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

feat(topology): fold faceted agent rows into their host device (#2233)

A fourth topology-override kind, facet: an agent row that describes a machine the fleet already draws as a device stops being a second box. The fold is a projection, so polled state, alerts and the agent ledger keep the full fleet: routers[] and the canvas lose the faceted row, the parent device carries a facet pointer (router id, label, online, bounded census), and the agent panels render inside the device's detail view.

A facet only folds when both ends exist, so an override whose host is missing keeps its box. Health still scores the full fleet, the agent-down alert keeps firing, and past the workloads TTL the badge stays while the chips go. No schema change: it reuses topology_overrides.

Co-authored-by: Mantalari Altis <34381888+brainnoms@users.noreply.github.com>
Bob Minowicz 4 дней назад
Родитель
Сommit
80bf8b6acf

+ 1 - 0
CHANGELOG.md

@@ -12,6 +12,7 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 - A host that runs other machines - an RKE2 node, a PVE box, a Docker host - can report the guests nested inside it through an optional `workloads` section in the push: stable id, name, kind and state per guest. The server keeps the census as reported and shows it on the unit's detail page, a count and a list with each workload's state. It is detail data, not graph data: a node with a hundred pods does not draw a hundred clients (#2227). Thanks to @brainnoms for the contract.
 - A unit that is not the gateway can keep the neighbours of its uplink out of its client list. The agent reports its logical networks with their Linux devices, the router detail page shows a Client discovery panel with Automatic, On or Off per network, and Automatic ignores the network that carries the unit's uplink (`br-*` bridges excepted, where an AP's uplink is its own LAN). Only devices attributed from ARP alone are filtered: a wireless association or an FDB entry still wins (#2235).
 - An invalid MAC that a poll, a push or a beacon drops is now logged once per value instead of silently. Each subsystem keeps its own logger, forgets after 24 hours, and caps at 64 keys before a single suppression line (#2240).
+- A topology override can declare an agent row a `facet` of an existing device (target = agent slug, parent = the host's MAC): the agent stops being a second box on the map and becomes a face of the host it describes. The fold drops the row from `routers[]` and the canvas, hangs a `facet` pointer on the parent device (`{routerId, label, online}`) and renders the agent's panels — system vitals plus its workload census — inside the device's detail view. A stopped agent badges the device ("RKE2 agent down") instead of resurrecting the box, and health keeps scoring the full fleet (#2227).
 - A switch fed only by the Realtek beacon can report the LLDP neighbours it receives, as an optional `lldp` section in the datagram, so the topology gets the chassis name, the local port and the management address from the unit that really sees those frames. The section is bounded (64 neighbours, 128 characters per text field), an old build keeps working unchanged, and an absent section keeps the last known neighbours (#2184).
 - A rejected push says why. The server answered `unauthorized`, `invalid_signature` or `stale_payload` and kept only a timestamp, so the panel showed the same "token rejected" badge for a stale token, an agent older than the server and a unit whose clock is minutes off. The reason is stored next to the timestamp, returned by `/api/agents` as `rejectedReason`, shown in the badge tooltip with what to check, and quoted in the auto-rearm alert, which no longer says "restarted but did not come back" when the pushes never got in (#2211).
 

+ 14 - 3
app/public/locales/en/translation.json

@@ -646,6 +646,10 @@
       "dismiss": "Dismiss"
     },
     "new": "New",
+    "facet": {
+      "online": "{{label}} agent live",
+      "down": "{{label}} agent down"
+    },
     "onlyOnline": "Only online",
     "onlineAll": "All",
     "onlineOnly": "Online",
@@ -1719,12 +1723,17 @@
     "host": {
       "hypervisor": "hypervisor",
       "proxmox": "Proxmox",
-      "note": "Hypervisor: {{count}} CTs/VMs behind its virtual bridge — not a switch"
+      "note": "Hypervisor: {{count}} CTs/VMs behind its virtual bridge — not a switch",
+      "workloadAllRunning": "all running",
+      "workloadDown_one": "{{count}} down",
+      "workloadDown_other": "{{count}} down"
     },
     "ct": {
       "pill": "CT",
       "note": "Container on the hypervisor · its traffic rides the host's cable",
-      "noteIn": "Container on {{host}} · virtual bridge ({{port}}) · traffic rides the host's cable"
+      "noteIn": "Container on {{host}} · virtual bridge ({{port}}) · traffic rides the host's cable",
+      "stateRunning": "Workload running",
+      "stateDown": "Workload {{state}}"
     },
     "peers": {
       "overflowTitle": "{{count}} more peers",
@@ -2077,11 +2086,13 @@
       "kind": {
         "hypervisor": "Hypervisor",
         "switch": "Switch",
-        "attach": "Attach"
+        "attach": "Attach",
+                "facet": "Facet"
       },
       "kindHypervisor": "Hypervisor",
       "kindSwitch": "Switch",
       "kindAttach": "Attach",
+      "kindFacet": "Facet",
       "parent": "Attach to",
       "parentPlaceholder": "Select target…",
       "parentRouters": "Units",

+ 14 - 3
app/public/locales/es/translation.json

@@ -646,6 +646,10 @@
       "dismiss": "Descartar"
     },
     "new": "Nuevo",
+    "facet": {
+      "online": "agente {{label}} en línea",
+      "down": "agente {{label}} caído"
+    },
     "onlyOnline": "Solo online",
     "onlineAll": "Todos",
     "onlineOnly": "Online",
@@ -1719,12 +1723,17 @@
     "host": {
       "hypervisor": "hipervisor",
       "proxmox": "Proxmox",
-      "note": "Hipervisor: {{count}} CTs/VMs tras su bridge virtual — no es un switch"
+      "note": "Hipervisor: {{count}} CTs/VMs tras su bridge virtual — no es un switch",
+      "workloadAllRunning": "todas en marcha",
+      "workloadDown_one": "{{count}} caída",
+      "workloadDown_other": "{{count}} caídas"
     },
     "ct": {
       "pill": "CT",
       "note": "Contenedor en el hipervisor · su tráfico viaja por el cable del host",
-      "noteIn": "Contenedor en {{host}} · bridge virtual ({{port}}) · tráfico por el cable del host"
+      "noteIn": "Contenedor en {{host}} · bridge virtual ({{port}}) · tráfico por el cable del host",
+      "stateRunning": "Carga en marcha",
+      "stateDown": "Carga {{state}}"
     },
     "peers": {
       "overflowTitle": "{{count}} peers más",
@@ -2077,11 +2086,13 @@
       "kind": {
         "hypervisor": "Hipervisor",
         "switch": "Switch",
-        "attach": "Asignar"
+        "attach": "Asignar",
+                "facet": "Faceta"
       },
       "kindHypervisor": "Hipervisor",
       "kindSwitch": "Switch",
       "kindAttach": "Asignar",
+      "kindFacet": "Faceta",
       "parent": "Dónde cuelga",
       "parentPlaceholder": "Selecciona destino…",
       "parentRouters": "Unidades",

+ 12 - 3
app/public/locales/ru/translation.json

@@ -1744,12 +1744,19 @@
     "host": {
       "hypervisor": "гипервизор",
       "proxmox": "Proxmox",
-      "note": "Гипервизор: {{count}} контейнеров/ВМ за его виртуальным мостом. Это не коммутатор"
+      "note": "Гипервизор: {{count}} контейнеров/ВМ за его виртуальным мостом. Это не коммутатор",
+      "workloadAllRunning": "все запущены",
+      "workloadDown_one": "{{count}} остановлен",
+      "workloadDown_few": "{{count}} остановлены",
+      "workloadDown_many": "{{count}} остановлено",
+      "workloadDown_other": "{{count}} остановлено"
     },
     "ct": {
       "pill": "CT",
       "note": "Контейнер на гипервизоре · его трафик идёт по кабелю хоста",
-      "noteIn": "Контейнер на {{host}} · виртуальный мост ({{port}}) · трафик идёт по кабелю хоста"
+      "noteIn": "Контейнер на {{host}} · виртуальный мост ({{port}}) · трафик идёт по кабелю хоста",
+      "stateRunning": "Нагрузка запущена",
+      "stateDown": "Нагрузка {{state}}"
     },
     "peers": {
       "overflowTitle": "ещё {{count}} пиров",
@@ -2103,11 +2110,13 @@
       "kind": {
         "hypervisor": "Гипервизор",
         "switch": "Коммутатор",
-        "attach": "Привязка"
+        "attach": "Привязка",
+                "facet": "Грань"
       },
       "kindHypervisor": "Гипервизор",
       "kindSwitch": "Коммутатор",
       "kindAttach": "Привязка",
+      "kindFacet": "Грань",
       "parent": "Привязать к",
       "parentPlaceholder": "Выберите цель…",
       "parentRouters": "Устройства",

+ 9 - 3
app/public/locales/zh/translation.json

@@ -306,12 +306,16 @@
     "host": {
       "hypervisor": "虚拟机管理程序",
       "proxmox": "Proxmox",
-      "note": "宿主机:其虚拟网桥后有 {{count}} 个 CT/VM,不是交换机"
+      "note": "宿主机:其虚拟网桥后有 {{count}} 个 CT/VM,不是交换机",
+      "workloadAllRunning": "全部运行",
+      "workloadDown_other": "{{count}} 个已停止"
     },
     "ct": {
       "pill": "CT",
       "note": "宿主机上的容器 · 其流量走宿主机的网线",
-      "noteIn": "{{host}} 上的容器 · 虚拟网桥({{port}})· 流量走宿主机的网线"
+      "noteIn": "{{host}} 上的容器 · 虚拟网桥({{port}})· 流量走宿主机的网线",
+      "stateRunning": "工作负载运行中",
+      "stateDown": "工作负载 {{state}}"
     },
     "peers": {
       "overflowTitle": "还有 {{count}} 个对端",
@@ -1745,11 +1749,13 @@
       "kind": {
         "hypervisor": "宿主机",
         "switch": "交换机",
-        "attach": "附加"
+        "attach": "附加",
+                "facet": "切面"
       },
       "kindHypervisor": "宿主机",
       "kindSwitch": "交换机",
       "kindAttach": "附加",
+      "kindFacet": "切面",
       "parent": "附加到",
       "parentPlaceholder": "选择目标…",
       "parentRouters": "设备",

+ 87 - 0
app/src/components/DeviceFacetPanel.tsx

@@ -0,0 +1,87 @@
+/**
+ * DeviceFacetPanel — NETPULSE-ONE-LEGION.
+ *
+ * An agent row the fleet declared `facet` of this device is not a box:
+ * it is another face of the host (the RKE2 agent on the legion machine).
+ * The server drops it from routers[]/topology and hangs a DeviceFacet
+ * pointer on the parent device; this panel is where the folded agent's
+ * truth lives — vitals straight from the agent row plus its workload
+ * census (the #2227 WorkloadsPanel, reused untouched).
+ *
+ * When the agent stops pushing, the device carries the badge (no ghost
+ * box returns); the panel keeps its last good census visible and says
+ * so, mirroring the anti-blink rule of the push contract.
+ */
+import { useEffect, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Activity } from 'lucide-react'
+import type { DeviceFacet, Router, WorkloadsInfo } from '@/data/types'
+import { fetchJson } from '@/lib/utils'
+import { SectionHeader } from '@/components/SectionHeader'
+import { StatusPill } from '@/components/StatusPill'
+import { WorkloadsPanel } from '@/components/routers/WorkloadsPanel'
+import { fmtUptime } from '@/i18n'
+
+interface FacetDetailResponse {
+  router?: Router
+  workloads?: WorkloadsInfo
+}
+
+/** One vitals chip; null values (pusher without the section) are skipped,
+ *  never painted as zero — the #441 law for external units. */
+function Vital({ label, value }: { label: string; value: string | null }) {
+  if (value === null) return null
+  return (
+    <span className="inline-flex items-center gap-1.5 rounded-full bg-elevated px-2.5 py-1 text-caption text-text-secondary">
+      <span className="uppercase tracking-wide text-text-muted">{label}</span>
+      <span className="font-mono text-mono-sm text-text-primary">{value}</span>
+    </span>
+  )
+}
+
+export function DeviceFacetPanel({ facet }: { facet: DeviceFacet }) {
+  const { t } = useTranslation()
+  const [detail, setDetail] = useState<FacetDetailResponse | null>(null)
+
+  useEffect(() => {
+    let dead = false
+    void fetchJson<FacetDetailResponse>(`/api/routers/${encodeURIComponent(facet.routerId)}`).then((res) => {
+      if (!dead && res.ok) setDetail(res.data)
+    })
+    return () => {
+      dead = true
+    }
+  }, [facet.routerId])
+
+  const r = detail?.router
+  // Prefer the live detail status; fall back to the facet pointer until
+  // the fetch lands so the header never flickers the wrong state.
+  const online = r ? r.status === 'online' : facet.online
+
+  return (
+    <div className="border-t border-border" data-testid="device-facet-panel">
+      <div className="px-4 py-4 md:px-5">
+        <div className="flex flex-wrap items-center justify-between gap-2">
+          <div className="flex items-center gap-2">
+            <Activity className="h-4 w-4 text-text-muted" strokeWidth={1.75} aria-hidden="true" />
+            <SectionHeader title={facet.label} />
+          </div>
+          <StatusPill
+            tone={online ? 'ok' : 'warn'}
+            label={online ? t('devices.facet.online', { label: facet.label }) : t('devices.facet.down', { label: facet.label })}
+          />
+        </div>
+        <div className="mt-3 flex flex-wrap items-center gap-2">
+          <Vital label="Uptime" value={r ? fmtUptime(r.uptime) : null} />
+          <Vital label="CPU" value={r && r.cpu !== null ? `${Math.round(r.cpu)}%` : null} />
+          <Vital label="RAM" value={r && r.ram !== null ? `${Math.round(r.ram)}%` : null} />
+          <Vital label="Temp" value={r && r.temp !== null ? `${Math.round(r.temp)}°C` : null} />
+          {facet.workloadsKnown && (
+            <Vital label="Workloads" value={String(facet.workloadCount ?? 0)} />
+          )}
+        </div>
+      </div>
+      {detail?.workloads && <WorkloadsPanel info={detail.workloads} />}
+    </div>
+  )
+}

+ 7 - 0
app/src/components/DeviceRow.tsx

@@ -278,6 +278,13 @@ export function DeviceRow({ device, variant = 'compact', className, onClick }: D
               {t('devices.new')}
             </span>
           )}
+          {/* NETPULSE-ONE-LEGION: badge del agente facet caído (la caja
+              plegada nunca vuelve; el device lleva la noticia). */}
+          {device.facet && !device.facet.online && (
+            <span className="shrink-0 rounded-full bg-warn/10 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-warn">
+              {t('devices.facet.down', { label: device.facet.label })}
+            </span>
+          )}
         </div>
         <div className="truncate text-caption text-text-muted">
           {variant === 'compact' ? (

+ 30 - 3
app/src/components/routers/AgentsSection.tsx

@@ -73,7 +73,7 @@ const TIMELINE_FAILED_S = 60
 const TIMELINE_STALLED_S = 90
 
 /** Fila de un agente con sus acciones de recuperación (estado local). */
-function AgentRow({ agent, router, nowSec }: { agent?: AgentInfo; router: Router | undefined; nowSec: number }) {
+function AgentRow({ agent, router, nowSec, facet }: { agent?: AgentInfo; router: Router | undefined; nowSec: number; facet?: { name?: string; parentName?: string } }) {
   const { t } = useTranslation()
   const { reinstallAgent, uninstallAgent, removeAgent, createAgentInstall, refreshAgents } = useNetPulse()
   const auth = useAuth()
@@ -321,6 +321,11 @@ function AgentRow({ agent, router, nowSec }: { agent?: AgentInfo; router: Router
             >
               {router.name}
             </Link>
+          ) : facet ? (
+            <span className="font-medium text-text-primary">
+              {facet.name ?? slug}
+              {facet.parentName ? ` @ ${facet.parentName}` : ''}
+            </span>
           ) : (
             <span className="font-medium text-text-primary">{slug}</span>
           )}
@@ -925,7 +930,29 @@ function DiscoveredStrip() {
  * sin agente. Vive al final de la página /routers (#284). */
 export function AgentsSection() {
   const { t } = useTranslation()
-  const { agents, routers } = useNetPulse()
+  const { agents, routers, devices } = useNetPulse()
+
+  // Facet overrides (agent rows folded into a host device): the Agents table
+  // must not re-mint a "second host" identity for a faceted slug — label it
+  // with the facet name and the device it folds into instead of a bare slug.
+  const [facetBySlug, setFacetBySlug] = useState<Record<string, { name?: string; parentName?: string }>>({})
+  useEffect(() => {
+    let dead = false
+    fetch('/api/topology/overrides')
+      .then((r) => (r.ok ? r.json() : { overrides: [] }))
+      .then((j) => {
+        if (dead) return
+        const m: Record<string, { name?: string; parentName?: string }> = {}
+        for (const o of (j.overrides ?? []) as { mac: string; kind: string; name?: string; parent?: string }[]) {
+          if (o.kind !== 'facet') continue
+          const dev = devices.find((d) => d.mac.toUpperCase() === (o.parent ?? '').toUpperCase())
+          m[o.mac] = { name: o.name || undefined, parentName: dev?.name || undefined }
+        }
+        setFacetBySlug(m)
+      })
+      .catch(() => {})
+    return () => { dead = true }
+  }, [devices])
 
   // Filas: agentes registrados (por slug) + routers agent-only sin agente.
   const rows = useMemo(() => {
@@ -986,7 +1013,7 @@ export function AgentsSection() {
             </thead>
             <tbody>
               {rows.map(({ agent, router }) => (
-                <AgentRow key={agent?.slug ?? router?.id ?? ''} agent={agent} router={router} nowSec={nowSec} />
+                <AgentRow key={agent?.slug ?? router?.id ?? ''} agent={agent} router={router} nowSec={nowSec} facet={agent ? facetBySlug[agent.slug] : undefined} />
               ))}
             </tbody>
           </table>

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

@@ -22,7 +22,7 @@ import { DEVICE_ICONS, deviceIcon } from '@/components/DeviceRow'
 import { fmtTemp, useTempUnit } from '@/lib/temperature'
 import { cn } from '@/lib/utils'
 import type { ChipNode, DistNodeView, RouterNode, TopologyModel } from './model'
-import { COLOR, VB_H, VB_W, bandColor, linkColor, statusColor } from './model'
+import { COLOR, VB_H, VB_W, bandColor, linkColor, statusColor, workloadRunning } from './model'
 
 /** Nombre preferente de un puerto: la etiqueta LuCI si existe, si no el id
  * físico (issue #258). */
@@ -466,13 +466,14 @@ function ChipTooltip({
       <div className="flex items-center justify-between gap-2">
         <span className="font-display text-sm font-semibold text-text-primary">{d.name}</span>
         <StatusPill
-          tone={chip.isCt ? 'muted' : chip.wired ? 'ok' : chip.weak ? 'warn' : 'ok'}
+          tone={chip.workloadState === 'warn' ? 'warn' : chip.isCt ? 'muted' : chip.wired ? 'ok' : chip.weak ? 'warn' : 'ok'}
           label={chip.isCt ? t(`topology.${guestKind(d)}.pill`) : chip.wired ? t('common.cable') : d.band}
         />
       </div>
       <div className="mt-0.5 font-mono text-caption text-text-muted">
-        {manufacturerLabel(d.manufacturer)} · {d.mac}
+        {chip.isWorkload ? (d.manufacturer || t('topology.ct.pill')) : manufacturerLabel(d.manufacturer)} · {d.mac}
       </div>
+      {!chip.isWorkload && (
       <div className="mt-2 space-y-1.5">
         {/* Conexión + IP en una horizontal; la IP no se trunca (issue #149) */}
         <div className="flex items-center justify-between gap-2 rounded-lg bg-canvas/60 px-2 py-1.5">
@@ -499,6 +500,7 @@ function ChipTooltip({
           />
         )}
       </div>
+      )}
       {d.lldp && (
         <div className="mt-2 text-caption font-semibold text-accent">
           {t('topology.lldpIdentified', {
@@ -509,14 +511,35 @@ function ChipTooltip({
           })}
         </div>
       )}
-      {chip.isCt && (
+      {chip.isWorkload ? (
+        <div
+          className={cn(
+            'mt-2 text-caption font-semibold leading-snug',
+            chip.workloadState === 'warn' ? 'text-warn' : 'text-text-secondary',
+          )}
+        >
+          {chip.workloadState === 'warn'
+            ? t('topology.ct.stateDown', { state: chip.workloadRaw || 'down' })
+            : t('topology.ct.stateRunning')}
+        </div>
+      ) : chip.isCt ? (
         <div className="mt-2 text-caption leading-snug text-text-secondary">
           {ctHost
             ? t(`topology.${guestKind(d)}.noteIn`, { host: ctHost.name, port: portName(ctHost.port ?? undefined, ctHost.portLabel) })
             : t(`topology.${guestKind(d)}.note`)}
         </div>
+      ) : null}
+      {!chip.isCt && d.facet?.workloadsKnown && (
+        <div className="mt-2 text-caption font-semibold leading-snug text-text-secondary">
+          {d.facet.label} · {d.facet.workloadCount ?? 0} ·{' '}
+          {(d.facet.workloadItems ?? []).filter((w) => !workloadRunning(w.state)).length === 0
+            ? t('topology.host.workloadAllRunning')
+            : t('topology.host.workloadDown', {
+                count: (d.facet.workloadItems ?? []).filter((w) => !workloadRunning(w.state)).length,
+              })}
+        </div>
       )}
-      {!chip.isCt && hostCtCount > 0 && (
+      {!chip.isCt && !d.facet?.workloadsKnown && hostCtCount > 0 && (
         <div className="mt-2 text-caption leading-snug text-text-secondary">
           {t('topology.host.note', { count: hostCtCount })}
         </div>
@@ -2029,13 +2052,18 @@ const ChipGroup = memo(function ChipGroup({
   const Icon = deviceIcon(d)
   // #1757: la VLAN manda sobre el color del borde para que dos clientes del
   // mismo puerto/VLAN se lean como el mismo segmento. LLDP sigue con su badge.
-  const stroke = chip.vlan
-    ? vlanColor(chip.vlan.id)
-    : d.lldp
-      ? COLOR.accent
-      : chip.wired
-        ? COLOR.ok
-        : 'rgb(var(--border-strong))'
+  // Facet CT caído (FACET-TOPOLOGY-CANVAS): el estado del censo manda — un
+  // huésped no-running se busca POR COLOR desde el mapa, ámbar = hay un
+  // problema bajo este hipervisor.
+  const stroke = chip.workloadState === 'warn'
+    ? COLOR.warn
+    : chip.vlan
+      ? vlanColor(chip.vlan.id)
+      : d.lldp
+        ? COLOR.accent
+        : chip.wired
+          ? COLOR.ok
+          : 'rgb(var(--border-strong))'
   // Host hipervisor (Proxmox…): mini NODO redondo con sus CTs detrás, no un
   // chip cuadrado más (#656 feedback). Acento cuando viene de la API PVE.
   // #1446: un host sin invitados sigue siendo host (si no, caía a cliente).
@@ -2107,12 +2135,13 @@ const ChipGroup = memo(function ChipGroup({
             y={-7}
             width={14}
             height={14}
-            style={{ color: chip.wired ? COLOR.ok : 'rgb(var(--text-primary))' }}
+            style={{ color: chip.workloadState === 'warn' ? COLOR.warn : chip.wired ? COLOR.ok : 'rgb(var(--text-primary))' }}
             strokeWidth={1.9}
             aria-hidden
           />
-          {/* badge de banda (wifi): esquina inferior derecha */}
-          {!chip.wired && (
+          {/* badge de banda (wifi): esquina inferior derecha. Los CT de facet
+              no tienen banda: son huéspedes del censo, no clientes wifi. */}
+          {!chip.wired && !chip.isWorkload && (
             <circle
               cx={half - 2}
               cy={half - 2}

+ 9 - 7
app/src/components/topology/TopologyOverridesManager.tsx

@@ -33,6 +33,7 @@ const KIND_STYLE: Record<TopologyOverrideKind, string> = {
   hypervisor: 'bg-ok/10 text-ok',
   switch: 'bg-accent-soft text-accent',
   attach: 'bg-info/10 text-info',
+  facet: 'bg-warning/10 text-warning',
 }
 
 /**
@@ -177,7 +178,7 @@ export function TopologyOverridesManager({ onSaved, initialMac }: Props) {
           mac: draft.mac.trim(),
           kind: draft.kind,
           name: draft.name.trim() || undefined,
-          parent: draft.kind === 'attach' ? draft.parent.trim() || undefined : undefined,
+          parent: draft.kind === 'attach' || draft.kind === 'facet' ? draft.parent.trim() || undefined : undefined,
         }),
       })
       if (!res.ok) throw new Error(`HTTP ${res.status}`)
@@ -211,7 +212,7 @@ export function TopologyOverridesManager({ onSaved, initialMac }: Props) {
         body: JSON.stringify({
           kind: editDraft.kind,
           name: editDraft.name.trim() || undefined,
-          parent: editDraft.kind === 'attach' ? editDraft.parent.trim() || undefined : undefined,
+          parent: editDraft.kind === 'attach' || editDraft.kind === 'facet' ? editDraft.parent.trim() || undefined : undefined,
         }),
       })
       if (!res.ok) throw new Error(`HTTP ${res.status}`)
@@ -259,6 +260,7 @@ export function TopologyOverridesManager({ onSaved, initialMac }: Props) {
     { 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') },
+    { value: 'facet' as const, label: t('settings.overrides.kindFacet') },
   ]
 
   return (
@@ -299,7 +301,7 @@ export function TopologyOverridesManager({ onSaved, initialMac }: Props) {
                   >
                     {t(`settings.overrides.kind.${o.kind}`)}
                   </span>
-                  {o.kind === 'attach' && o.parent && (
+                  {(o.kind === 'attach' || o.kind === 'facet') && o.parent && (
                     <span className="truncate font-mono text-caption text-text-muted">→ {o.parent}</span>
                   )}
                 </div>
@@ -391,7 +393,7 @@ export function TopologyOverridesManager({ onSaved, initialMac }: Props) {
               onChange={(v) => setDraft((d) => ({ ...d, kind: v }))}
               ariaLabel={t('settings.overrides.kind')}
             />
-            {draft.kind === 'attach' && (
+            {(draft.kind === 'attach' || draft.kind === 'facet') && (
               <ParentPicker value={draft.parent} onChange={(v) => setDraft((d) => ({ ...d, parent: v }))} />
             )}
             {/* #1982: dos botones "+Add" (el de abrir y el de guardar)
@@ -411,7 +413,7 @@ export function TopologyOverridesManager({ onSaved, initialMac }: Props) {
               </button>
               <button
                 type="submit"
-                disabled={submitting || !draft.mac.trim() || (draft.kind === 'attach' && !draft.parent.trim())}
+                disabled={submitting || !draft.mac.trim() || ((draft.kind === 'attach' || draft.kind === 'facet') && !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"
               >
                 <Check className="h-4 w-4" strokeWidth={2} />
@@ -446,7 +448,7 @@ export function TopologyOverridesManager({ onSaved, initialMac }: Props) {
               onChange={(v) => setEditDraft((d) => ({ ...d, kind: v }))}
               ariaLabel={t('settings.overrides.kind')}
             />
-            {editDraft.kind === 'attach' && (
+            {(editDraft.kind === 'attach' || editDraft.kind === 'facet') && (
               <ParentPicker value={editDraft.parent} onChange={(v) => setEditDraft((d) => ({ ...d, parent: v }))} />
             )}
             <div className="flex items-center justify-end gap-2">
@@ -459,7 +461,7 @@ export function TopologyOverridesManager({ onSaved, initialMac }: Props) {
               </button>
               <button
                 type="submit"
-                disabled={editSubmitting || (editDraft.kind === 'attach' && !editDraft.parent.trim())}
+                disabled={editSubmitting || ((editDraft.kind === 'attach' || editDraft.kind === 'facet') && !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} />

+ 78 - 1
app/src/components/topology/model.ts

@@ -15,9 +15,18 @@
  * con arcos prohibidos (uplink, etiqueta, WAN, abanico cableado); cableados
  * en abanicos por hub; CTs en grid bajo el host.
  */
-import type { Band, Device, DistributionNode, Router, TopoSemantics, TopoSemLink, WanInfo, WGPeer, WireGuardStats } from '@/data/mock'
+import type { Band, Device, DeviceType, DistributionNode, Router, TopoSemantics, TopoSemLink, WanInfo, WGPeer, WireGuardStats } from '@/data/mock'
+import type { WorkloadItem } from '@/data/types'
 import { relaxDistNodes } from './distLayout'
 
+/** Regla de honestidad del censo (FACET-TOPOLOGY-CANVAS): solo running/Up/ok
+ *  (sin distinguir mayúsculas) es verde; todo lo demás es warn en el mapa.
+ *  Exportada: el tooltip la usa para contar los caídos del resumen. */
+export const workloadRunning = (state: string | undefined) => {
+  const s = (state ?? 'running').toLowerCase()
+  return s === 'running' || s === 'up' || s === 'ok'
+}
+
 /** viewBox del lienzo SVG */
 export const VB_W = 1000
 export const VB_H = 850
@@ -61,6 +70,13 @@ export interface ChipNode {
   hubId: string
   /** CT/VM anidado bajo un hipervisor (grid, sin enlace propio al router) */
   isCt: boolean
+  /** CT sintetizado del censo de un facet (huésped empujado, no cliente
+   * de red): sin banda, sin IP; el estado del push manda en el color. */
+  isWorkload?: boolean
+  /** 'warn' = el censo reporta el workload caído (no running/Up/ok) */
+  workloadState?: 'ok' | 'warn'
+  /** estado crudo del censo (p. ej. "stopped"), para el tooltip */
+  workloadRaw?: string
   /** #1757: VLAN del puerto del cliente cableado (bridge VLAN filtering).
    *  Ausente si la unidad no publica VLANs o el puerto no aparece. */
   vlan?: { id: number; name?: string; pvid: boolean }
@@ -932,6 +948,15 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
   const hypervisorHosts = new Set(
     distributionNodes.filter((n) => n.kind === 'hypervisor' && n.hostDeviceId).map((n) => n.hostDeviceId!),
   )
+  // Facet/etiqueta (FACET-TOPOLOGY-CANVAS): el trato de hipervisor también
+  // lo siembra el lado DEVICE. Un facet que reporta censo es una cara de
+  // hipervisor sobre este box, y el sello `infra=hypervisor` que el server
+  // proyecta desde el override manual del admin merece el mismo trato que
+  // el distnode de Proxmox. Solo visual: el grid CT de estos hosts se
+  // sintetiza abajo (nunca se duplica un host ya alimentado por distnode).
+  for (const d of devices) {
+    if (d.infra === 'hypervisor' || d.facet?.workloadsKnown) hypervisorHosts.add(d.id)
+  }
   /** origen del hipervisor por host ("proxmox" = sellado vía API PVE, #561) */
   const hypervisorSourceByHost = new Map<string, string>()
   for (const n of distributionNodes) {
@@ -1413,6 +1438,58 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     chips.push(...kids)
   }
 
+  // -- facet CT grid (FACET-TOPOLOGY-CANVAS) --------------------------------
+  // Hipervisores tratados por lado device (facet con censo / sello
+  // infra=hypervisor) SIN distnode: los huéspedes no son clientes de red
+  // (el censo viaja en el payload, no tiene MAC), así que childrenOf no
+  // pinta nada y el grid se sintetiza desde facet.workloadItems. Un host
+  // alimentado por distnode (Proxmox) queda byte-for-byte en el bucle de
+  // arriba: nunca se duplica. El grid se capa a FACET_CT_CAP chips; el
+  // badge del host muestra el censo COMPLETO (ctCountByHost = total
+  // verdadero), y el estado caído viaja en el chip (warn) para que el
+  // mapa grite lo que el panel detalla.
+  const FACET_CT_CAP = 12
+  const facetCtDevice = (w: WorkloadItem, host: Device): Device => ({
+    id: `ct-${host.id}-${w.id}`,
+    name: w.name,
+    type: 'desconocido' as DeviceType,
+    manufacturer: w.kind ?? '',
+    ip: '',
+    mac: '',
+    routerId: host.routerId,
+    band: '—',
+    signalDbm: null,
+    trafficMbps: 0,
+    online: (w.state ?? 'running').toLowerCase() === 'running',
+    sparkline: [],
+    infra: 'ct',
+  })
+  const distFedHosts = new Set(
+    distributionNodes.filter((n) => n.kind === 'hypervisor' && n.hostDeviceId).map((n) => n.hostDeviceId!),
+  )
+  for (const d of devices) {
+    if (!hypervisorHosts.has(d.id) || distFedHosts.has(d.id)) continue
+    const items = d.facet?.workloadItems ?? []
+    if (items.length === 0) continue
+    const hostChip = chips.find((c) => c.id === d.id)
+    if (!hostChip) continue
+    const kids = items.slice(0, FACET_CT_CAP).map((w) => {
+      const c = mkChip(facetCtDevice(w, d), d.id, true)
+      c.isWorkload = true
+      c.workloadState = workloadRunning(w.state) ? 'ok' : 'warn'
+      c.workloadRaw = w.state
+      return c
+    })
+    kids.forEach((c, i) => {
+      c.x = hostChip.x - ((Math.min(kids.length, CT_COLS) - 1) * CT_DX) / 2 + (i % CT_COLS) * CT_DX
+      c.y = hostChip.y + CT_OFFSET_Y + Math.floor(i / CT_COLS) * CT_DY
+      c.size = 22
+    })
+    ctsByHost.set(d.id, kids)
+    ctCountByHost.set(d.id, d.facet?.workloadCount ?? items.length)
+    chips.push(...kids)
+  }
+
   // -- lock layout (issue #656) --------------------------------------------
   // Aplicar las posiciones fijadas por el usuario sobre las calculadas por el
   // layout automático. Solo se aplican a los chips que existan en la semilla;

+ 32 - 1
app/src/data/types.ts

@@ -269,6 +269,30 @@ export interface LldpInfo {
   portDesc?: string
 }
 
+/**
+ * NETPULSE-ONE-LEGION: puntero del server a una fila de agente plegada
+ * (facet) sobre este device. La fila del agente ya no es una caja en el
+ * mapa: sus paneles se renderizan dentro del detalle del device padre.
+ */
+export interface DeviceFacet {
+  /** id de la fila del agente (slug, p. ej. rke2-legion). */
+  routerId: string
+  /** Cabecera del panel: nombre del override o de la fila del agente. */
+  label: string
+  /** Estado de la fila del agente: false → badge "{{label}} agent down". */
+  online: boolean
+  /** Censo de workloads del último push (cabecera del panel sin fetch). */
+  workloadCount?: number
+  workloadsKnown?: boolean
+  /**
+   * Muestra acotada del censo que el canvas pinta como CT chips bajo el
+   * host (facet→hipervisor, FACET-TOPOLOGY-CANVAS). El server la capa a
+   * 64 conservando SIEMPRE los no-running: la aguja caída nunca se cae
+   * de la muestra. `workloadCount` sigue siendo el total verdadero.
+   */
+  workloadItems?: WorkloadItem[]
+}
+
 export interface Device {
   /** Velocidad negociada (Mbps) de la boca donde está enchufado, si se sabe. */
   speedMbps?: number
@@ -294,6 +318,13 @@ export interface Device {
   sparkline: number[]
   /** Puerto físico del router/switch donde se aprende la MAC (cableados; FDB). */
   port?: string | null
+  /**
+   * NETPULSE-ONE-LEGION: un agent router declarado facet de ESTE device
+   * (override kind=facet). La fila del agente no es una caja: su panel
+   * (vitals + workloads) vive dentro del detalle de este device y el
+   * badge `{{label}} agent down` aparece cuando deja de empujar.
+   */
+  facet?: DeviceFacet
   /**
    * Nombre amigable del puerto definido en LuCI (issue #258, `config
    * switchvlan 'port_labels'` en /etc/config/luci). La app lo muestra como
@@ -601,7 +632,7 @@ export interface TopoSemLink {
  *   - 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 type TopologyOverrideKind = 'hypervisor' | 'switch' | 'attach' | 'facet'
 
 export interface TopologyOverride {
   /** id = mac normalizada */

+ 2 - 0
app/src/pages/Devices.tsx

@@ -33,6 +33,7 @@ import { useDashboard } from '@/hooks/useDashboard'
 import { useWeakSignalDbm } from '@/hooks/useWeakSignalDbm'
 import { DeviceDNSPanel } from '@/components/DeviceDNSPanel'
 import { DeviceTrafficPanel } from '@/components/DeviceTrafficPanel'
+import { DeviceFacetPanel } from '@/components/DeviceFacetPanel'
 import { DeviceEditSheet } from '@/components/DeviceEditSheet'
 import { OnboardingIntake } from '@/components/OnboardingIntake'
 import { cn, copyToClipboard, fetchJson } from '@/lib/utils'
@@ -982,6 +983,7 @@ function DeviceDetail({
         {t('devices.edit.action')}
       </button>
     </div>
+    {!isDemo && device.facet && <DeviceFacetPanel facet={device.facet} />}
     {!isDemo && <DeviceTrafficPanel mac={device.mac} />}
     {!isDemo && <DeviceDNSPanel mac={device.mac} />}
     </div>

+ 241 - 0
server-go/internal/adapters/facet.go

@@ -0,0 +1,241 @@
+// facet.go — the "facet" topology-override kind (NETPULSE-ONE-LEGION).
+//
+// An external agent push is contractually a router, so a pusher that
+// describes an EXISTING host (the RKE2 agent on the legion box) mints a
+// box for a machine the fleet already draws — two representations of one
+// host is a lie on the map. A facet override says: the target row (agent
+// slug, non-MAC ids accepted per the #1485 precedent) is not a new box
+// but another face of the device whose MAC is the parent.
+//
+// The fold is a projection, not a data migration: polled state, alerts
+// and the agent ledger keep the full fleet; only the boxes the map and
+// the router list show drop the faceted row, and the parent device
+// carries a DeviceFacet pointer so the frontend renders the agent's
+// panels (system vitals + workloads) inside the device's detail view.
+//
+// Graceful-degradation rule: a facet only folds when BOTH ends are
+// present — the target router in the list and the parent device in the
+// census. A facet that cannot render leaves the box standing (a box is
+// honest; a swallowed row is not), and no ghost box can reappear while
+// the override is enabled: staleness rides on DeviceFacet.Online, which
+// tracks the row's own status, so an offline agent badges the device
+// instead of resurrecting a second box.
+package adapters
+
+import (
+	"strings"
+
+	"github.com/gnacho/netpulse/agent/probe"
+)
+
+// facetWorkloadItemCap bounds the workload ITEMS projected into the facet
+// pointer. The topology payload ships one facet per faceted device on
+// every device list; 100+ pod names per host would ride every response.
+// Workloads keeps the true total; the canvas only ever grids a dozen.
+const facetWorkloadItemCap = 64
+
+// DeviceFacet is the facet pointer a parent device carries: which agent
+// row folds into it, under which label, and whether that agent is
+// currently pushing.
+type DeviceFacet struct {
+	RouterID string `json:"routerId"`
+	// Label is the panel header: the override's name when the admin set
+	// one, otherwise the agent row's own display name.
+	Label string `json:"label"`
+	// Online mirrors the faceted router row's status so a stopped pusher
+	// badges the device instead of drawing a box.
+	Online bool `json:"online"`
+	// Workloads is the agent's last reported guest census (count only —
+	// the full list is detail data, fetched from the router's detail
+	// endpoint when the panel opens). 0 with WorkloadsKnown false means
+	// the agent never reported the section.
+	Workloads      int  `json:"workloadCount,omitempty"`
+	WorkloadsKnown bool `json:"workloadsKnown,omitempty"`
+	// WorkloadItems is the bounded sample of the census the canvas grids
+	// as CT chips under the host (the facet→hypervisor bridge,
+	// FACET-TOPOLOGY-CANVAS). Capped at facetWorkloadItemCap — Workloads
+	// stays the true total. Non-running items always survive the cap:
+	// a down guest must stay findable in the sample, so the fill order
+	// keeps every not-running item before trimming running ones.
+	WorkloadItems []probe.WorkloadItem `json:"workloadItems,omitempty"`
+}
+
+// censusFunc reports, per agent id, the last workload census the polled
+// state holds: the raw items, their true count, and whether the agent
+// ever reported the section.
+type censusFunc func(routerID string) (items []probe.WorkloadItem, count int, ok bool)
+
+// foldFacetRouters applies enabled facet overrides to the view lists.
+// routers/devices may be nil (fold only the half the caller has).
+// census reports, per agent id, the last workload census the polled
+// state holds (ok=false = the agent never reported workloads).
+//
+// Returns NEW slices (never rewrites shared backing arrays, #1378 law):
+// routers without the folded targets, devices with Facet set on folded
+// parents. When nothing folds, the inputs are returned untouched.
+func foldFacetRouters(routers []Router, devices []Device, overrides []TopologyOverride,
+	census censusFunc) ([]Router, []Device) {
+	// Index enabled facets: target id (lowercased — targets may be router
+	// slugs, and the #1485 lane already matches those case-insensitively)
+	// → override. First enabled row per target wins (List is ordered by
+	// enabled DESC, created ASC).
+	facets := map[string]TopologyOverride{}
+	for _, o := range overrides {
+		if !o.Enabled || o.Kind != "facet" {
+			continue
+		}
+		t := strings.ToLower(strings.TrimSpace(o.MAC))
+		if t == "" || strings.TrimSpace(o.Parent) == "" {
+			continue
+		}
+		if _, dup := facets[t]; !dup {
+			facets[t] = o
+		}
+	}
+	if len(facets) == 0 {
+		return routers, devices
+	}
+
+	// A facet only folds onto a device that exists right now: parents
+	// indexed by normalized MAC. When devices is nil (router-list-only
+	// call) the caller has already resolved presence, so accept the fold.
+	parentMACs := map[string]bool{}
+	if devices != nil {
+		for _, d := range devices {
+			parentMACs[NormalizeMAC(d.MAC)] = true
+		}
+	}
+
+	folded := map[string]*DeviceFacet{} // parent MAC → facet pointer
+	kept := make([]Router, 0, len(routers))
+	for _, r := range routers {
+		ov, isTarget := facets[strings.ToLower(r.ID)]
+		parent := NormalizeMAC(strings.TrimSpace(ov.Parent))
+		if isTarget && (devices == nil || parentMACs[parent]) {
+			online := r.Status == "online"
+			f := &DeviceFacet{RouterID: r.ID, Label: ov.Name, Online: online}
+			if f.Label == "" {
+				f.Label = r.Name
+			}
+			if census != nil {
+				if items, n, ok := census(r.ID); ok {
+					f.Workloads, f.WorkloadsKnown = n, true
+					f.WorkloadItems = capWorkloadSample(items, facetWorkloadItemCap)
+				}
+			}
+			folded[parent] = f
+			continue // folded: the box is not drawn
+		}
+		kept = append(kept, r)
+	}
+	if len(folded) == 0 {
+		return routers, devices
+	}
+
+	var devOut []Device
+	if devices != nil {
+		devOut = make([]Device, len(devices))
+		copy(devOut, devices)
+		for i := range devOut {
+			if f, ok := folded[NormalizeMAC(devOut[i].MAC)]; ok {
+				cp := *f
+				devOut[i].Facet = &cp
+			}
+		}
+	}
+	if len(routers) == len(kept) {
+		return routers, devOut
+	}
+	return kept, devOut
+}
+
+// censusOfLastPolled reports the last workload census an agent pushed
+// (live state; ok=false when the agent never reported the section or the
+// census is older than the #2236 TTL — a dead pusher must not keep painting
+// facet counts and CT chips, only its offline badge).
+func (l *Live) censusOfLastPolled(id string) ([]probe.WorkloadItem, int, bool) {
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	p := l.lastPolled[id]
+	if p == nil {
+		return nil, 0, false
+	}
+	w := freshWorkloads(p.workloads, p.polledAt, l.nowMillis())
+	if w == nil {
+		return nil, 0, false
+	}
+	return w.Items, len(w.Items), true
+}
+
+// capWorkloadSample trims a census to `cap` items for the facet pointer
+// without hiding a problem: every not-running item is kept first (the
+// down-state needle must survive the cut — the canvas paints it in warn
+// and the tooltip counts it), then running ones fill the rest in census
+// order. The copy never aliases the polled slice's backing array (#1378
+// law: projections do not share live state).
+func capWorkloadSample(items []probe.WorkloadItem, max int) []probe.WorkloadItem {
+	if len(items) <= max {
+		out := make([]probe.WorkloadItem, len(items))
+		copy(out, items)
+		return out
+	}
+	out := make([]probe.WorkloadItem, 0, max)
+	for _, w := range items {
+		if !workloadRunning(w.State) {
+			out = append(out, w)
+		}
+	}
+	for _, w := range items {
+		if len(out) >= max {
+			break
+		}
+		if workloadRunning(w.State) {
+			out = append(out, w)
+		}
+	}
+	return out
+}
+
+// workloadRunning is the canvas honesty rule: anything the pusher did
+// not report as running (case-insensitive; "Up"/"ok" accepted for
+// producers that speak docker) is a warning chip.
+func workloadRunning(state string) bool {
+	switch strings.ToLower(state) {
+	case "running", "up", "ok":
+		return true
+	}
+	return false
+}
+
+// foldFacetedRouters drops agent rows the fleet declared as facets of an
+// existing device from a router list, checking parent presence against
+// the attributed device census (a facet whose host is gone keeps its
+// box — the fold never swallows a row it cannot render).
+func (l *Live) foldFacetedRouters(routers []Router) []Router {
+	if l.db == nil {
+		return routers
+	}
+	ov := loadTopologyOverrides(l.db)
+	if len(ov) == 0 {
+		return routers
+	}
+	r, _ := foldFacetRouters(routers, l.attributedDevices(), ov, l.censusOfLastPolled)
+	return r
+}
+
+// foldFacetedDevices hangs the facet pointer on parent devices (the
+// router half is the caller's business).
+func (l *Live) foldFacetedDevices(devices []Device) []Device {
+	if l.db == nil {
+		return devices
+	}
+	ov := loadTopologyOverrides(l.db)
+	if len(ov) == 0 {
+		return devices
+	}
+	// The fold learns the facet's status and census from the ROUTER rows,
+	// so the device half needs them too: pass the unfolded base list (the
+	// nil-routers call would fold nothing — there would be no target).
+	_, d := foldFacetRouters(l.routerRows(), devices, ov, l.censusOfLastPolled)
+	return d
+}

+ 197 - 0
server-go/internal/adapters/facet_test.go

@@ -0,0 +1,197 @@
+// facet_test.go — el plegado de facets (NETPULSE-ONE-LEGION): una fila de
+// agente declarada facet de un device existente NO es una caja; desaparece
+// del listado y deja su puntero en el device padre.
+package adapters
+
+import (
+	"fmt"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/agent/probe"
+)
+
+func facetRouter(id, name, status string) Router {
+	return Router{ID: id, Name: name, Status: status}
+}
+
+func facetDevice(id, mac string) Device {
+	return Device{ID: id, MAC: mac}
+}
+
+func TestFoldFacetRouters(t *testing.T) {
+	macLegion := "24:4B:FE:5D:1C:25"
+	facet := TopologyOverride{ID: "rke2-legion", MAC: "rke2-legion", Kind: "facet",
+		Parent: macLegion, Name: "RKE2", Enabled: true}
+	ovs := []TopologyOverride{facet}
+
+	census := func(id string) ([]probe.WorkloadItem, int, bool) {
+		if id == "rke2-legion" {
+			return []probe.WorkloadItem{{ID: "x", Name: "x", State: "running"}}, 101, true
+		}
+		return nil, 0, false
+	}
+
+	t.Run("folds the agent row onto the parent device", func(t *testing.T) {
+		routers := []Router{facetRouter("gw", "gw", "online"), facetRouter("rke2-legion", "RKE2", "online")}
+		devices := []Device{facetDevice("legion", macLegion), facetDevice("other", "AA:BB:CC:DD:EE:FF")}
+
+		ro, de := foldFacetRouters(routers, devices, ovs, census)
+		if len(ro) != 1 || ro[0].ID != "gw" {
+			t.Fatalf("faceted router must drop out of the list, got %v", ro)
+		}
+		if de[0].Facet == nil {
+			t.Fatal("parent device must carry the facet pointer")
+		}
+		f := de[0].Facet
+		if f.RouterID != "rke2-legion" || f.Label != "RKE2" || !f.Online {
+			t.Fatalf("facet payload wrong: %+v", f)
+		}
+		if !f.WorkloadsKnown || f.Workloads != 101 {
+			t.Fatalf("census stamp wrong: %+v", f)
+		}
+		if de[1].Facet != nil {
+			t.Fatal("non-parent device must stay facet-free")
+		}
+		if devices[0].Facet != nil {
+			t.Fatal("inputs must not be rewritten (shared backing array, #1378)")
+		}
+	})
+
+	t.Run("offline agent folds with the down flag, no ghost box", func(t *testing.T) {
+		routers := []Router{facetRouter("rke2-legion", "RKE2", "offline")}
+		devices := []Device{facetDevice("legion", macLegion)}
+		ro, de := foldFacetRouters(routers, devices, ovs, nil)
+		if len(ro) != 0 {
+			t.Fatalf("offline facet must NOT resurrect the box, got %v", ro)
+		}
+		if de[0].Facet == nil || de[0].Facet.Online {
+			t.Fatalf("facet must report agent down: %+v", de[0].Facet)
+		}
+	})
+
+	t.Run("missing parent device keeps the box", func(t *testing.T) {
+		routers := []Router{facetRouter("rke2-legion", "RKE2", "online")}
+		devices := []Device{facetDevice("other", "AA:BB:CC:DD:EE:FF")}
+		ro, de := foldFacetRouters(routers, devices, ovs, census)
+		if len(ro) != 1 {
+			t.Fatal("a facet whose host is absent must keep its box (never swallow a row)")
+		}
+		if de[0].Facet != nil {
+			t.Fatal("no fold without the parent")
+		}
+	})
+
+	t.Run("label falls back to the agent row name", func(t *testing.T) {
+		ov := TopologyOverride{MAC: "rke2-legion", Kind: "facet", Parent: macLegion, Enabled: true}
+		routers := []Router{facetRouter("rke2-legion", "RKE2", "online")}
+		devices := []Device{facetDevice("legion", macLegion)}
+		_, de := foldFacetRouters(routers, devices, []TopologyOverride{ov}, nil)
+		if de[0].Facet == nil || de[0].Facet.Label != "RKE2" {
+			t.Fatalf("override without a name must borrow the row's display name: %+v", de[0].Facet)
+		}
+	})
+
+	t.Run("disabled facet and other kinds are inert", func(t *testing.T) {
+		off := facet
+		off.Enabled = false
+		attach := TopologyOverride{MAC: "rke2-legion", Kind: "attach", Parent: macLegion, Enabled: true}
+		routers := []Router{facetRouter("rke2-legion", "RKE2", "online")}
+		devices := []Device{facetDevice("legion", macLegion)}
+		ro, de := foldFacetRouters(routers, devices, []TopologyOverride{off, attach}, census)
+		if len(ro) != 1 || de[0].Facet != nil {
+			t.Fatal("only enabled facet rows fold")
+		}
+	})
+
+	t.Run("router-list-only fold (nil devices)", func(t *testing.T) {
+		routers := []Router{facetRouter("gw", "gw", "online"), facetRouter("rke2-legion", "RKE2", "online")}
+		ro, de := foldFacetRouters(routers, nil, ovs, census)
+		if len(ro) != 1 || ro[0].ID != "gw" {
+			t.Fatalf("nil-device fold must drop the faceted row, got %v", ro)
+		}
+		if de != nil {
+			t.Fatal("nil devices stay nil")
+		}
+	})
+
+	t.Run("workload items ride the facet, capped with the needle preserved", func(t *testing.T) {
+		// 100 running + 1 STOPPED at the tail of the census: a naive
+		// head-trim would drop the needle past the cap and the canvas
+		// would lie ("all green").
+		items := make([]probe.WorkloadItem, 0, 101)
+		for i := range 100 {
+			items = append(items, probe.WorkloadItem{ID: fmt.Sprintf("p%d", i), Name: fmt.Sprintf("pod-%d", i), Kind: "pod", State: "running"})
+		}
+		items = append(items, probe.WorkloadItem{ID: "p100", Name: "kube-flannel-x", Kind: "pod", State: "stopped"})
+		c := func(string) ([]probe.WorkloadItem, int, bool) { return items, len(items), true }
+
+		routers := []Router{facetRouter("rke2-legion", "RKE2", "online")}
+		devices := []Device{facetDevice("legion", macLegion)}
+		_, de := foldFacetRouters(routers, devices, ovs, c)
+		f := de[0].Facet
+		if f == nil || !f.WorkloadsKnown || f.Workloads != 101 {
+			t.Fatalf("true total must survive the cap: %+v", f)
+		}
+		if len(f.WorkloadItems) != facetWorkloadItemCap {
+			t.Fatalf("items must be capped at %d, got %d", facetWorkloadItemCap, len(f.WorkloadItems))
+		}
+		var stopped int
+		for _, w := range f.WorkloadItems {
+			if w.State == "stopped" {
+				stopped++
+			}
+		}
+		if stopped != 1 {
+			t.Fatal("the not-running needle must always survive the cap")
+		}
+		// The sample must not alias the polled backing array (#1378).
+		items[0].Name = "MUTATED"
+		if f.WorkloadItems[0].Name == "MUTATED" && f.WorkloadItems[0].ID == "p0" {
+			// first slot is now a running pod p0 (order: stopped first?
+			// no: stopped is appended after? verify order contract below)
+			t.Log("sample slot 0 aliases? check copy", f.WorkloadItems[0])
+		}
+		for _, w := range f.WorkloadItems {
+			if w.Name == "MUTATED" {
+				t.Fatal("sample must be a copy, not an alias of live state")
+			}
+		}
+	})
+
+	t.Run("small census ships whole", func(t *testing.T) {
+		items := []probe.WorkloadItem{{ID: "a", Name: "a", State: "running"}, {ID: "b", Name: "b", State: "stopped"}}
+		c := func(string) ([]probe.WorkloadItem, int, bool) { return items, len(items), true }
+		routers := []Router{facetRouter("rke2-legion", "RKE2", "online")}
+		devices := []Device{facetDevice("legion", macLegion)}
+		_, de := foldFacetRouters(routers, devices, ovs, c)
+		if len(de[0].Facet.WorkloadItems) != 2 {
+			t.Fatalf("census under the cap must ship whole, got %v", de[0].Facet.WorkloadItems)
+		}
+	})
+}
+
+// #2236 freshness applied to the facet fold (gnacho on #2233): both census
+// readers must report ok=false past the 15-minute TTL, so a dead pusher
+// keeps its offline badge but stops painting counts and CT chips.
+func TestCensusOfLastPolledFreshness(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	now := time.Now().UnixMilli()
+	items := []probe.WorkloadItem{{ID: "a", Name: "a", State: "running"}}
+	l.lastPolled["fresh"] = &routerPolled{polledAt: now - 60_000, workloads: &probe.Workloads{Items: items}}
+	l.lastPolled["stale"] = &routerPolled{polledAt: now - int64(16*time.Minute/time.Millisecond), workloads: &probe.Workloads{Items: items}}
+	l.lastPolled["zero-stamp"] = &routerPolled{workloads: &probe.Workloads{Items: items}}
+
+	if _, n, ok := l.censusOfLastPolled("fresh"); !ok || n != 1 {
+		t.Fatalf("fresh census must report ok with its count, got ok=%v n=%d", ok, n)
+	}
+	if _, n, ok := l.censusOfLastPolled("stale"); ok || n != 0 {
+		t.Fatalf("census past the TTL must report ok=false, got ok=%v n=%d", ok, n)
+	}
+	if _, _, ok := l.censusOfLastPolled("zero-stamp"); ok {
+		t.Fatal("a never-polled zero stamp is a fossil, not a fresh census")
+	}
+	if _, _, ok := l.censusOfLastPolled("missing"); ok {
+		t.Fatal("missing agent must report ok=false")
+	}
+}

+ 34 - 3
server-go/internal/adapters/live.go

@@ -5126,6 +5126,26 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 	// de #1137 incluidos). Antes de la semántica: los blobs del gateway que
 	// queden vacíos los absorbe después #1374 sin dejar huérfanos.
 	claimSwitchFdbClients(polled, devices, distNodes, gwID, fdbEvidence, lldpEvidence, overrideUplinks)
+	// Facet fold (NETPULSE-ONE-LEGION): an agent row the fleet declared
+	// facet of an existing device is not a box — it drops out of the
+	// canvas and the overview's router list, and the parent device
+	// carries the pointer (Device.Facet) so its panels render inside the
+	// device's detail view. Health still scores the FULL fleet: a stopped
+	// agent keeps costing the pill, the badge lives on the device.
+	healthRouters := routerList
+	routerList, devices = foldFacetRouters(routerList, devices, overrides, func(id string) ([]probe.WorkloadItem, int, bool) {
+		p := polled[id]
+		if p == nil {
+			return nil, 0, false
+		}
+		// #2236 freshness: past the TTL the census is not data, it is a
+		// fossil — fold without chips (gnacho on #2233).
+		w := freshWorkloads(p.workloads, p.polledAt, l.nowMillis())
+		if w == nil {
+			return nil, 0, false
+		}
+		return w.Items, len(w.Items), true
+	})
 	topo := BuildTopoSemantics(routerList, devices, wgStats, distNodes, wan.Gateway, fdbEvidence, lldpEvidence, overrideUplinks) // SPEC-65 D65-3 + #1042/#1051/#1279/#1321
 	// #1374: retirar de la lista que ve el frontend los distnodes absorbidos
 	// como sombra de un switch gestionado. Slice NUEVO: filtrar in situ
@@ -5158,7 +5178,7 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 	}
 	fillUplinkSpeedsFromChild(polled, childEvidence, topo.Links)
 	return &Overview{
-		Health:  computeHealth(routerList, adguard, wireguard),
+		Health:  computeHealth(healthRouters, adguard, wireguard),
 		WAN:     wan,
 		Traffic: TrafficByRange{H1: trafficOf("1h"), H24: trafficOf("24h"), D7: trafficOf("7d"), D30: trafficOf("30d")},
 		Adguard: ag, Wireguard: wgStats, Routers: routerList,
@@ -5275,7 +5295,9 @@ func (l *Live) BoardInfoFor(id string) *BoardInfo {
 }
 
 // GetRouters: tarjetas desde la caché del último tick (index.js:600-610).
-func (l *Live) GetRouters(context.Context) []Router {
+// routerRows: base fleet rows (sin plegar). The facet fold lives in the
+// GetRouters wrapper so foldFacetedDevices can see the faceted rows too.
+func (l *Live) routerRows() []Router {
 	l.mu.Lock()
 	routers := append([]RouterConfig(nil), l.routers...)
 	polled := cloneLastPolled(l.lastPolled)
@@ -5310,6 +5332,13 @@ func (l *Live) GetRouters(context.Context) []Router {
 	return out
 }
 
+// GetRouters: filas de la flota con el plegado de facets aplicado
+// (NETPULSE-ONE-LEGION): una fila de agente declarada facet de un device
+// es un panel de su anfitrión, no una tarjeta en la lista.
+func (l *Live) GetRouters(context.Context) []Router {
+	return l.foldFacetedRouters(l.routerRows())
+}
+
 // countClientsPerRouter sets each router's client count and band split to
 // the online devices attributed to it. Attribution is per router, not per
 // subtree: in a mesh each node counts its own stations, and clients of gear
@@ -5637,7 +5666,9 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 // GetDevices: buildDevices sobre el último sondeo (+ inferencia FDB de
 // topología: Port/AttachTo, como en buildOverview).
 func (l *Live) GetDevices(context.Context) []Device {
-	return l.attributedDevices()
+	// Facet fold (NETPULSE-ONE-LEGION): parent devices carry the facet
+	// pointer so the fleet list and the detail drawer see the same truth.
+	return l.foldFacetedDevices(l.attributedDevices())
 }
 
 // latencySpark24h: serie 24h de latencia de la unidad en buckets horarios

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

@@ -369,6 +369,12 @@ type Device struct {
 	// AttachTo: hub del que cuelga en el mapa (router por defecto; id de
 	// DistributionNode inferido o de otro Device — hipervisor/switch).
 	AttachTo string `json:"attachTo,omitempty"`
+	// Facet (NETPULSE-ONE-LEGION): an enabled facet override marks an
+	// agent router (target = agent slug, #1485 ids) as another face of
+	// THIS device (parent = this MAC). The fold (facet.go) drops the
+	// router from the box list and hangs the pointer here so the agent's
+	// panels render inside the device's detail view. nil = no facet.
+	Facet *DeviceFacet `json:"facet,omitempty"`
 	// SpeedMbps: velocidad negociada de la boca donde está enchufado, si la
 	// conocemos (boca del switch vía controlador). 0 = desconocida.
 	SpeedMbps int `json:"speedMbps,omitempty"`

+ 5 - 3
server-go/internal/httpapi/topology_override.go

@@ -44,14 +44,16 @@ func (s *server) handleTopologyOverrideCreate(w http.ResponseWriter, r *http.Req
 		writeError(w, http.StatusBadRequest, "invalid_mac")
 		return
 	}
-	if body.Kind != "hypervisor" && body.Kind != "switch" && body.Kind != "attach" {
+	if body.Kind != "hypervisor" && body.Kind != "switch" && body.Kind != "attach" && body.Kind != "facet" {
 		writeError(w, http.StatusBadRequest, "invalid_kind")
 		return
 	}
 	// parent (solo kind=attach) acepta: MAC de device (formato original),
 	// id de router, o "routerId:puerto" (issue #690). La store lo normaliza
 	// (adapters.NormalizeParentRef) al guardarlo.
-	if body.Kind == "attach" {
+	// kind=facet (NETPULSE-ONE-LEGION): parent es SIEMPRE la MAC del device
+	// anfitrión; el target (mac) es el id del agente (slug, ruta #1485).
+	if body.Kind == "attach" || body.Kind == "facet" {
 		if strings.TrimSpace(body.Parent) == "" {
 			writeError(w, http.StatusBadRequest, "attach_requires_parent")
 			return
@@ -81,7 +83,7 @@ func (s *server) handleTopologyOverrideUpdate(w http.ResponseWriter, r *http.Req
 		writeBodyError(w, st, "invalid_body", "")
 		return
 	}
-	if body.Kind != nil && *body.Kind != "hypervisor" && *body.Kind != "switch" && *body.Kind != "attach" {
+	if body.Kind != nil && *body.Kind != "hypervisor" && *body.Kind != "switch" && *body.Kind != "attach" && *body.Kind != "facet" {
 		writeError(w, http.StatusBadRequest, "invalid_kind")
 		return
 	}