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

feat(update): history, readiness checks and post-update confirmation (#178)

* feat(update): track apply history in SQLite (#159)

* feat(update): readiness checks before apply (#160)

* feat(update): post-update confirmation toast (#161)

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 месяцев назад
Родитель
Сommit
e92598d045

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

@@ -984,6 +984,31 @@
       "frontend-build": "building the UI",
       "restart": "restarting the service",
       "done": "done, reloading"
+    },
+    "checks": {
+      "title": "Pre-flight checks",
+      "ready": "Ready to update",
+      "notReady": "Review the checks before updating",
+      "disk": "Disk space",
+      "git": "Clean working tree",
+      "network": "GitHub reachable",
+      "concurrent": "No update in progress",
+      "ok": "OK",
+      "fail": "Failed"
+    },
+    "confirmed": "Updated to {{sha}}",
+    "history": {
+      "title": "Update history",
+      "empty": "No updates recorded yet",
+      "from": "From",
+      "to": "To",
+      "date": "Date",
+      "initiatedBy": "Started by",
+      "status": "Status",
+      "duration": "Duration",
+      "success": "Success",
+      "failed": "Failed",
+      "running": "Running"
     }
   },
   "demo": {

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

@@ -984,6 +984,31 @@
       "frontend-build": "compilando la interfaz",
       "restart": "reiniciando el servicio",
       "done": "completado, recargando"
+    },
+    "checks": {
+      "title": "Comprobaciones previas",
+      "ready": "Todo listo para actualizar",
+      "notReady": "Revisa las comprobaciones antes de actualizar",
+      "disk": "Espacio en disco",
+      "git": "Working tree limpio",
+      "network": "Conexión con GitHub",
+      "concurrent": "Sin actualización en curso",
+      "ok": "OK",
+      "fail": "Fallo"
+    },
+    "confirmed": "Actualizado a {{sha}}",
+    "history": {
+      "title": "Historial de actualizaciones",
+      "empty": "Sin actualizaciones registradas",
+      "from": "Desde",
+      "to": "Hasta",
+      "date": "Fecha",
+      "initiatedBy": "Iniciado por",
+      "status": "Estado",
+      "duration": "Duración",
+      "success": "Correcto",
+      "failed": "Falló",
+      "running": "En curso"
     }
   },
   "demo": {

+ 4 - 0
app/src/components/Layout.tsx

@@ -27,6 +27,7 @@ import { CommandPalette } from '@/components/CommandPalette'
 import { HealthRing } from '@/components/HealthRing'
 import { ThemeToggle } from '@/components/ThemeToggle'
 import { UpdateBanner } from '@/components/UpdateBanner'
+import { UpdateConfirmToast } from '@/components/UpdateConfirmToast'
 import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from '@/components/ui/sheet'
 import { cn, exitDemo } from '@/lib/utils'
 
@@ -659,6 +660,9 @@ function Shell() {
         <main className="mx-auto w-full max-w-[1400px] px-4 pb-24 pt-4 md:px-6 md:pb-10 md:pt-6">
           {isDemo && <DemoBanner />}
           <UpdateBanner />
+          {/* Confirmación post-update (issue #161): toast al cargar si el
+              último apply llegó a arrancar con el commit nuevo. */}
+          <UpdateConfirmToast />
           {/* Pull-to-refresh (issue #139): gesto móvil recarga la vista para
               coger un deploy nuevo sin reabrir la app. Solo actúa en touch y
               con scroll arriba; no interfiere con carruseles/tablas. */}

+ 48 - 37
app/src/components/UpdateBanner.tsx

@@ -9,6 +9,7 @@ import { useTranslation } from 'react-i18next'
 import { motion, AnimatePresence, useReducedMotion } from 'framer-motion'
 import { DownloadCloud, ExternalLink, Loader2, X } from 'lucide-react'
 import { useAuth } from '@/data/AuthContext'
+import { ReadinessPanel, type UpdateReadiness } from '@/components/UpdateReadiness'
 
 interface UpdateStatus {
   current: string
@@ -20,6 +21,7 @@ interface UpdateStatus {
   repo: string
   updating: false | { step: string }
   hasToken: boolean
+  readiness?: UpdateReadiness | null
 }
 
 const POLL_MS = 60 * 60 * 1000
@@ -138,6 +140,7 @@ export function UpdateBanner() {
 
   const updating = Boolean(status.updating)
   const step = status.updating ? status.updating.step : 'start'
+  const ready = status.readiness ? status.readiness.ready : true
 
   return (
     <AnimatePresence>
@@ -147,48 +150,56 @@ export function UpdateBanner() {
         exit={{ opacity: 0, y: -8 }}
         transition={{ duration: 0.25, ease: 'easeOut' }}
         role="status"
-        className="mb-4 flex items-center gap-3 rounded-xl border border-accent/40 bg-accent-soft px-4 py-2.5"
+        className="mb-4 flex flex-col gap-2"
       >
-        <DownloadCloud className="h-4 w-4 shrink-0 text-accent" strokeWidth={1.75} />
-        <p className="min-w-0 flex-1 truncate text-sm text-text-primary">
-          {updating
-            ? t('update.updating', { step: t(`update.step.${step}`) })
-            : t('update.available', { version: status.latest, msg: status.latestMsg ?? '' })}
-        </p>
-        {!updating ? (
-          <>
-            {status.canApply ? (
+        <div className="flex items-center gap-3 rounded-xl border border-accent/40 bg-accent-soft px-4 py-2.5">
+          <DownloadCloud className="h-4 w-4 shrink-0 text-accent" strokeWidth={1.75} />
+          <p className="min-w-0 flex-1 truncate text-sm text-text-primary">
+            {updating
+              ? t('update.updating', { step: t(`update.step.${step}`) })
+              : t('update.available', { version: status.latest, msg: status.latestMsg ?? '' })}
+          </p>
+          {!updating ? (
+            <>
+              {status.canApply ? (
+                <button
+                  type="button"
+                  onClick={() => void apply()}
+                  disabled={!ready}
+                  className="flex shrink-0 items-center gap-1.5 rounded-lg bg-accent px-3 py-1.5 text-xs font-semibold text-canvas transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50"
+                >
+                  <DownloadCloud className="h-3.5 w-3.5" strokeWidth={2} />
+                  {t('update.button')}
+                </button>
+              ) : (
+                <a
+                  href={`https://github.com/${status.repo || 'gnacho/netpulse'}/releases`}
+                  target="_blank"
+                  rel="noreferrer"
+                  title={t('update.stableHint')}
+                  className="flex shrink-0 items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-xs font-semibold text-text-primary transition-colors hover:bg-surface-2"
+                >
+                  <ExternalLink className="h-3.5 w-3.5" strokeWidth={2} />
+                  {t('update.getRelease')}
+                </a>
+              )}
               <button
                 type="button"
-                onClick={() => void apply()}
-                className="flex shrink-0 items-center gap-1.5 rounded-lg bg-accent px-3 py-1.5 text-xs font-semibold text-canvas transition-opacity hover:opacity-90"
+                onClick={() => status.latest && setDismissed(status.latest)}
+                aria-label={t('update.dismiss')}
+                className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg text-text-muted transition-colors hover:text-text-primary"
               >
-                <DownloadCloud className="h-3.5 w-3.5" strokeWidth={2} />
-                {t('update.button')}
+                <X className="h-4 w-4" strokeWidth={1.75} />
               </button>
-            ) : (
-              <a
-                href={`https://github.com/${status.repo || 'gnacho/netpulse'}/releases`}
-                target="_blank"
-                rel="noreferrer"
-                title={t('update.stableHint')}
-                className="flex shrink-0 items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-xs font-semibold text-text-primary transition-colors hover:bg-surface-2"
-              >
-                <ExternalLink className="h-3.5 w-3.5" strokeWidth={2} />
-                {t('update.getRelease')}
-              </a>
-            )}
-            <button
-              type="button"
-              onClick={() => status.latest && setDismissed(status.latest)}
-              aria-label={t('update.dismiss')}
-              className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg text-text-muted transition-colors hover:text-text-primary"
-            >
-              <X className="h-4 w-4" strokeWidth={1.75} />
-            </button>
-          </>
-        ) : (
-          <Loader2 className="h-4 w-4 shrink-0 animate-spin text-accent" strokeWidth={1.75} />
+            </>
+          ) : (
+            <Loader2 className="h-4 w-4 shrink-0 animate-spin text-accent" strokeWidth={1.75} />
+          )}
+        </div>
+        {/* Pre-flight checks (issue #160): se muestran antes de permitir aplicar
+            y deshabilitan el botón si alguno falla. */}
+        {!updating && status.canApply && status.readiness && (
+          <ReadinessPanel readiness={status.readiness} compact className="mx-0.5" />
         )}
       </motion.div>
     </AnimatePresence>

+ 92 - 0
app/src/components/UpdateConfirmToast.tsx

@@ -0,0 +1,92 @@
+/**
+ * UpdateConfirmToast — confirmación post-update (issue #161): tras aplicar y
+ * reiniciar, el backend expone `pendingApply` en /api/update/status solo si
+ * el commit actual cambió respecto al marcador pre-update. Este componente
+ * lo lee al cargar (admin), muestra un toast "Actualizado a <sha>" y hace el
+ * ack (POST /api/update/pending-confirm) para que sea una sola vez.
+ */
+import { useEffect, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { motion, AnimatePresence, useReducedMotion } from 'framer-motion'
+import { CheckCircle2, X } from 'lucide-react'
+import { useAuth } from '@/data/AuthContext'
+
+const AUTO_DISMISS_MS = 8000
+
+interface PendingApply {
+  from: string
+  to: string
+}
+
+export function UpdateConfirmToast() {
+  const { t } = useTranslation()
+  const reduce = useReducedMotion()
+  const auth = useAuth()
+  const [pending, setPending] = useState<PendingApply | null>(null)
+  const ackedRef = useRef(false)
+
+  // Leer la confirmación al cargar (solo admin).
+  useEffect(() => {
+    if (auth?.role !== 'admin') return
+    let cancelled = false
+    void (async () => {
+      try {
+        const res = await fetch('/api/update/status')
+        if (!res.ok) return
+        const json = (await res.json()) as { pendingApply?: PendingApply | null }
+        if (!cancelled && json.pendingApply) setPending(json.pendingApply)
+      } catch {
+        /* sin status: sin confirmación */
+      }
+    })()
+    return () => {
+      cancelled = true
+    }
+  }, [auth?.role])
+
+  // Ack tras mostrar (una sola vez): el backend descarta la confirmación.
+  useEffect(() => {
+    if (!pending || ackedRef.current) return
+    ackedRef.current = true
+    void fetch('/api/update/pending-confirm', { method: 'POST' }).catch(() => {
+      /* si el ack falla, el toast reaparece en la próxima carga (backend la
+         mantiene hasta confirmar) */
+    })
+  }, [pending])
+
+  // Auto-cierre.
+  useEffect(() => {
+    if (!pending) return
+    const id = window.setTimeout(() => setPending(null), AUTO_DISMISS_MS)
+    return () => window.clearTimeout(id)
+  }, [pending])
+
+  if (!pending) return null
+
+  return (
+    <div className="pointer-events-none fixed inset-x-0 bottom-24 z-50 flex justify-center px-4 md:bottom-8" aria-live="polite">
+      <AnimatePresence>
+        <motion.div
+          key={pending.to}
+          initial={reduce ? false : { opacity: 0, y: 16, scale: 0.95 }}
+          animate={{ opacity: 1, y: 0, scale: 1 }}
+          exit={reduce ? false : { opacity: 0, y: 8, scale: 0.95 }}
+          transition={{ duration: 0.25, ease: 'easeOut' }}
+          role="status"
+          className="flex items-center gap-2 rounded-xl border border-border-strong bg-elevated py-2 pl-3 pr-2 text-sm font-medium text-text-primary shadow-soft"
+        >
+          <CheckCircle2 className="h-4 w-4 shrink-0 text-ok" strokeWidth={1.75} />
+          <span>{t('update.confirmed', { sha: pending.to })}</span>
+          <button
+            type="button"
+            onClick={() => setPending(null)}
+            aria-label={t('update.dismiss')}
+            className="flex h-6 w-6 shrink-0 items-center justify-center rounded-lg text-text-muted transition-colors hover:text-text-primary"
+          >
+            <X className="h-4 w-4" strokeWidth={1.75} />
+          </button>
+        </motion.div>
+      </AnimatePresence>
+    </div>
+  )
+}

+ 83 - 0
app/src/components/UpdateReadiness.tsx

@@ -0,0 +1,83 @@
+/**
+ * UpdateReadiness — panel de pre-flight checks del updater (issue #160):
+ * muestra cada check (disco, git, red, concurrencia) con su estado ok/fail y
+ * un resumen ready/notReady. Lo usan UpdateBanner y UpdateCheckInline.
+ */
+import { useTranslation } from 'react-i18next'
+import { CircleCheck, CircleX, ShieldCheck, ShieldAlert } from 'lucide-react'
+import { cn } from '@/lib/utils'
+
+export interface ReadinessCheck {
+  ok: boolean
+  detail?: string
+}
+
+export interface UpdateReadiness {
+  disk: ReadinessCheck
+  git: ReadinessCheck
+  network: ReadinessCheck
+  concurrent: ReadinessCheck
+  ready: boolean
+}
+
+const CHECKS = ['disk', 'git', 'network', 'concurrent'] as const
+
+export function ReadinessPanel({
+  readiness,
+  compact,
+  className,
+}: {
+  readiness: UpdateReadiness
+  compact?: boolean
+  className?: string
+}) {
+  const { t } = useTranslation()
+  const ready = readiness.ready
+  return (
+    <div
+      role="group"
+      aria-label={t('update.checks.title')}
+      className={cn(
+        'flex flex-col gap-2 rounded-xl border border-border bg-surface p-3',
+        compact && 'gap-1.5 p-2.5',
+        className,
+      )}
+    >
+      <div className="flex items-center gap-1.5">
+        {ready ? (
+          <ShieldCheck className="h-4 w-4 shrink-0 text-ok" strokeWidth={1.75} aria-hidden="true" />
+        ) : (
+          <ShieldAlert className="h-4 w-4 shrink-0 text-rose-500" strokeWidth={1.75} aria-hidden="true" />
+        )}
+        <span
+          className={cn(
+            'text-xs font-semibold',
+            ready ? 'text-text-primary' : 'text-rose-500',
+          )}
+        >
+          {ready ? t('update.checks.ready') : t('update.checks.notReady')}
+        </span>
+      </div>
+      <ul className={cn('flex flex-col gap-1', compact && 'gap-0.5')}>
+        {CHECKS.map((k) => {
+          const c = readiness[k]
+          return (
+            <li key={k} className="flex items-center gap-1.5 text-caption">
+              {c.ok ? (
+                <CircleCheck className="h-3.5 w-3.5 shrink-0 text-ok" strokeWidth={2} aria-hidden="true" />
+              ) : (
+                <CircleX className="h-3.5 w-3.5 shrink-0 text-rose-500" strokeWidth={2} aria-hidden="true" />
+              )}
+              <span className="text-text-secondary">{t(`update.checks.${k}`)}</span>
+              {c.detail && (
+                <span className="truncate text-text-muted" title={c.detail}>
+                  {c.detail}
+                </span>
+              )}
+            </li>
+          )
+        })}
+      </ul>
+    </div>
+  )
+}

+ 106 - 3
app/src/pages/Settings.tsx

@@ -19,6 +19,7 @@ import {
   Github,
   HardDrive,
   Heart,
+  History,
   KeyRound,
   LogOut,
   MonitorSmartphone,
@@ -43,6 +44,7 @@ import type { LucideIcon } from 'lucide-react'
 import { HealthRing } from '@/components/HealthRing'
 import { SegmentedControl } from '@/components/SegmentedControl'
 import { TopologyOverridesManager } from '@/components/topology/TopologyOverridesManager'
+import { ReadinessPanel, type UpdateReadiness } from '@/components/UpdateReadiness'
 import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog'
 import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
 import { Slider } from '@/components/ui/slider'
@@ -52,6 +54,7 @@ import { useAuth } from '@/data/AuthContext'
 import { getVapidKey, postPushSubscribe, postPushUnsubscribe, pushContext, urlBase64ToUint8Array } from '@/data/push'
 import { useServicesVisibility } from '@/hooks/useServicesVisibility'
 import type { ServicesVisibility } from '@/hooks/useServicesVisibility'
+import { relTimeFromTs } from '@/i18n'
 import { cn, exitDemo } from '@/lib/utils'
 import { ACCENTS, type AccentId, type ThemeMode } from '@/lib/theme-boot'
 import pkg from '../../package.json'
@@ -1873,7 +1876,8 @@ function DemoCard({ onSaved }: { reduce?: boolean; onSaved: () => void }) {
 
 /** Widget inline de "Comprobar actualizaciones" para la AdminBar. Usa los
  *  endpoints /api/update/status y /api/update/apply (misma lógica que
- *  UpdateBanner, sin banner): al pulsar comprueba y muestra estado compacto. */
+ *  UpdateBanner, sin banner): al pulsar comprueba y muestra estado compacto.
+ *  Con readiness (issue #160): los checks previos bloquean el botón. */
 interface NetPulseUpdateStatus {
   current: string
   latest: string | null
@@ -1882,6 +1886,7 @@ interface NetPulseUpdateStatus {
   canApply: boolean
   repo: string
   updating: false | { step: string }
+  readiness?: UpdateReadiness | null
 }
 
 function UpdateCheckInline() {
@@ -1915,6 +1920,8 @@ function UpdateCheckInline() {
     }
   }
 
+  const ready = status?.readiness ? status.readiness.ready : true
+
   return (
     <div className="flex flex-col gap-1">
       {status?.updateAvailable && status.latest ? (
@@ -1922,8 +1929,8 @@ function UpdateCheckInline() {
           <button
             type="button"
             onClick={() => void apply()}
-            disabled={busy}
-            className="inline-flex h-9 shrink-0 items-center gap-1.5 rounded-xl border border-accent bg-accent-soft px-3 text-[13px] font-medium text-accent transition-colors hover:brightness-105 disabled:opacity-60"
+            disabled={busy || !ready}
+            className="inline-flex h-9 shrink-0 items-center gap-1.5 rounded-xl border border-accent bg-accent-soft px-3 text-[13px] font-medium text-accent transition-colors hover:brightness-105 disabled:cursor-not-allowed disabled:opacity-60"
           >
             <Download className="h-4 w-4 shrink-0" strokeWidth={1.75} aria-hidden="true" />
             <span className="hidden sm:inline">{t('update.button')}</span>
@@ -1961,6 +1968,94 @@ function UpdateCheckInline() {
           {t('settings.about.updateError')}
         </span>
        ) : null}
+      {status?.updateAvailable && status.canApply && status.readiness && (
+        <div className="mt-2 w-[260px]">
+          <ReadinessPanel readiness={status.readiness} compact />
+        </div>
+      )}
+    </div>
+  )
+}
+
+/** Historial de actualizaciones (issue #159): tabla con los últimos applies
+ *  (SHA from→to, fecha, estado, duración) servida por GET /api/updates/history. */
+interface UpdateHistoryRow {
+  id: number
+  ts: number
+  action: string
+  channel: string
+  versionFrom?: string
+  versionTo?: string
+  initiatedBy: string
+  status: string
+  durationMs?: number
+  error?: string
+}
+
+function UpdateHistoryCard() {
+  const { t } = useTranslation()
+  const [rows, setRows] = useState<UpdateHistoryRow[] | null>(null)
+
+  const load = useCallback(async () => {
+    try {
+      const res = await fetch('/api/updates/history')
+      if (!res.ok) return
+      const json = (await res.json()) as { history?: UpdateHistoryRow[] }
+      setRows(json.history ?? [])
+    } catch {
+      /* sin historial: la tarjeta muestra el estado vacío */
+    }
+  }, [])
+
+  useEffect(() => { void load() }, [load])
+
+  const statusLabel = (s: string) =>
+    s === 'success' ? t('update.history.success') : s === 'failed' ? t('update.history.failed') : t('update.history.running')
+  const statusCls = (s: string) =>
+    s === 'success' ? 'text-ok' : s === 'failed' ? 'text-rose-500' : 'text-amber-600 dark:text-amber-400'
+
+  return (
+    <div className="rounded-2xl border border-border bg-surface p-4 md:p-5">
+      <div className="mb-3 flex items-center gap-2">
+        <History className="h-4 w-4 text-accent" strokeWidth={1.75} aria-hidden="true" />
+        <h3 className="text-sm font-semibold text-text-primary">{t('update.history.title')}</h3>
+      </div>
+      {rows === null ? (
+        <p className="text-xs text-text-muted">{t('settings.about.checking')}</p>
+      ) : rows.length === 0 ? (
+        <p className="text-xs text-text-secondary">{t('update.history.empty')}</p>
+      ) : (
+        <div className="overflow-x-auto">
+          <table className="w-full min-w-[540px] text-left text-xs">
+            <thead>
+              <tr className="border-b border-border text-text-muted">
+                <th className="py-2 pr-3 font-medium">{t('update.history.date')}</th>
+                <th className="py-2 pr-3 font-medium">{t('update.history.from')}</th>
+                <th className="py-2 pr-3 font-medium">{t('update.history.to')}</th>
+                <th className="py-2 pr-3 font-medium">{t('update.history.initiatedBy')}</th>
+                <th className="py-2 pr-3 font-medium">{t('update.history.duration')}</th>
+                <th className="py-2 font-medium">{t('update.history.status')}</th>
+              </tr>
+            </thead>
+            <tbody>
+              {rows.map((r) => (
+                <tr key={r.id} className="border-b border-border/60 last:border-0">
+                  <td className="whitespace-nowrap py-2 pr-3 text-text-secondary">
+                    {relTimeFromTs(r.ts) ?? new Date(r.ts).toLocaleString()}
+                  </td>
+                  <td className="py-2 pr-3 font-mono text-text-primary">{r.versionFrom ?? '—'}</td>
+                  <td className="py-2 pr-3 font-mono text-text-primary">{r.versionTo ?? '—'}</td>
+                  <td className="py-2 pr-3 text-text-secondary">{r.initiatedBy || '—'}</td>
+                  <td className="py-2 pr-3 text-text-secondary">
+                    {r.durationMs != null ? `${(r.durationMs / 1000).toFixed(1)} s` : '—'}
+                  </td>
+                  <td className={cn('py-2 font-semibold', statusCls(r.status))}>{statusLabel(r.status)}</td>
+                </tr>
+              ))}
+            </tbody>
+          </table>
+        </div>
+      )}
     </div>
   )
 }
@@ -3198,6 +3293,14 @@ export default function Settings() {
           </div>
         )}
 
+        {/* Historial de actualizaciones (issue #159) — solo admin y modo live;
+            el updater es un mecanismo de auto-aplicación que no existe en demo */}
+        {!isDemo && auth?.role === 'admin' && (
+          <div className="lg:col-span-12">
+            <UpdateHistoryCard />
+          </div>
+        )}
+
         {/* Gestión de routers — solo admin y con backend (modo live); la API
             exige rol admin en las mutaciones (auditoría v2.4.0 §2, #7) */}
         {!isDemo && auth?.role === 'admin' && (

+ 1 - 1
server-go/cmd/netpulse/main.go

@@ -259,7 +259,7 @@ func run() error {
 	// Actualizador: repoRoot = padre de serverRoot (paridad index.js:49-53).
 	// La versión embebida (httpapi.Version) se usa para comparar contra el
 	// último release tag en modo estable (layout install.sh).
-	upd := updater.New(filepath.Clean(filepath.Join(cfg.ServerRoot, "..")), cfg.GithubRepo, cfg.GithubToken, httpapi.Version)
+	upd := updater.New(filepath.Clean(filepath.Join(cfg.ServerRoot, "..")), cfg.GithubRepo, cfg.GithubToken, httpapi.Version, dbHandle.DB)
 
 	// Fase 10: motor de orquestación (plan→apply→state).
 	orchMgr := orchestr.New(dbHandle)

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

@@ -191,8 +191,27 @@ CREATE TABLE IF NOT EXISTS topology_overrides (
   updated_at INTEGER NOT NULL
 );
 CREATE INDEX IF NOT EXISTS idx_topo_overrides_mac ON topology_overrides(mac);
+
+-- Historial de actualizaciones (issue #159): registro de cada apply del
+-- updater. En canal rolling main version_from/to son SHAs de commit.
+CREATE TABLE IF NOT EXISTS update_history (
+  id           INTEGER PRIMARY KEY AUTOINCREMENT,
+  event_id     TEXT NOT NULL,
+  ts           INTEGER NOT NULL,
+  action       TEXT NOT NULL,
+  channel      TEXT NOT NULL,
+  version_from TEXT,
+  version_to   TEXT,
+  initiated_by TEXT NOT NULL DEFAULT '',
+  status       TEXT NOT NULL DEFAULT 'running',
+  duration_ms  INTEGER,
+  backup_path  TEXT,
+  error        TEXT
+);
+CREATE INDEX IF NOT EXISTS idx_update_history_ts ON update_history(ts DESC);
 `
 
+
 // DB envuelve *sql.DB con los jobs y helpers de paridad.
 type DB struct {
 	*sql.DB

+ 20 - 3
server-go/internal/httpapi/update.go

@@ -1,9 +1,11 @@
 // update.go — rutas /api/update/* (paridad src/routes/update.js, SPEC §2.18,
 // solo admin):
 //
-//	GET  /api/update/status → estado actual
-//	POST /api/update/check  → fuerza un chequeo contra GitHub
-//	POST /api/update/apply  → aplica la actualización (202 | 409)
+//	GET  /api/update/status          → estado actual (incl. readiness + pendingApply)
+//	POST /api/update/check           → fuerza un chequeo contra GitHub
+//	POST /api/update/apply           → aplica la actualización (202 | 409)
+//	GET  /api/updates/history        → historial de updates (issue #159)
+//	POST /api/update/pending-confirm → descarta la confirmación post-update (issue #161)
 package httpapi
 
 import (
@@ -39,4 +41,19 @@ func (s *server) registerUpdateRoutes(mux *http.ServeMux, u *updater.Updater) {
 		}
 		writeJSON(w, http.StatusAccepted, u.Status())
 	})))
+	// Historial de updates (issue #159): los últimos N registros, por ahora
+	// sin paginar (cota de 200 en ListHistory).
+	mux.Handle("GET /api/updates/history", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		history, err := updater.ListHistory(s.db.DB, 50)
+		if err != nil {
+			writeError(w, http.StatusInternalServerError, "history_error")
+			return
+		}
+		writeJSON(w, http.StatusOK, map[string]any{"history": history})
+	})))
+	// Descarta la confirmación post-update tras mostrarla (issue #161).
+	mux.Handle("POST /api/update/pending-confirm", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		u.AckPending()
+		w.WriteHeader(http.StatusNoContent)
+	})))
 }

+ 32 - 0
server-go/internal/httpapi/update_apply_test.go

@@ -0,0 +1,32 @@
+// update_apply_test.go — regresión del gate de apply (layout estable).
+package httpapi_test
+
+import (
+	"encoding/json"
+	"net/http"
+	"testing"
+)
+
+func TestApplyUnavailableOnStableLayout(t *testing.T) {
+	// Sin deploy/update.sh → modo estable: POST /api/update/apply → 409.
+	root := t.TempDir()
+	ts := makeTestServerWithUpdater(t, root)
+	cookie := adminCookie(t, ts)
+	req, _ := http.NewRequest("POST", ts.URL+"/api/update/apply", nil)
+	req.Header.Set("Cookie", "session="+cookie)
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer res.Body.Close()
+	if res.StatusCode != 409 {
+		t.Fatalf("apply estable: got %d want 409", res.StatusCode)
+	}
+	var body map[string]any
+	if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
+		t.Fatal(err)
+	}
+	if body["error"] != "update_unavailable" {
+		t.Errorf("error: %+v", body)
+	}
+}

+ 134 - 0
server-go/internal/httpapi/update_helpers_test.go

@@ -0,0 +1,134 @@
+// update_helpers_test.go — helpers de los tests del módulo updater
+// (issues #159, #160, #161): servidor con updater rolling (repo git +
+// deploy/update.sh) y BD real.
+package httpapi_test
+
+import (
+	"net/http/httptest"
+	"os"
+	"os/exec"
+	"path/filepath"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/config"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/httpapi"
+	"github.com/gnacho/netpulse/server-go/internal/sse"
+	"github.com/gnacho/netpulse/server-go/internal/updater"
+)
+
+func gitAvailable() bool { _, err := exec.LookPath("git"); return err == nil }
+
+// writeGitHead crea un repo git mínimo con un commit y devuelve su short SHA.
+func writeGitHead(t *testing.T, root string) string {
+	t.Helper()
+	if !gitAvailable() {
+		t.Skip("git no disponible")
+	}
+	run := func(args ...string) {
+		cmd := exec.Command("git", append([]string{"-C", root}, args...)...)
+		if out, err := cmd.CombinedOutput(); err != nil {
+			t.Fatalf("git %v: %v %s", args, err, out)
+		}
+	}
+	run("init", "-q")
+	run("config", "user.email", "t@t")
+	run("config", "user.name", "t")
+	if err := os.WriteFile(filepath.Join(root, "f"), []byte("x"), 0o644); err != nil {
+		t.Fatal(err)
+	}
+	run("add", ".")
+	run("commit", "-qm", "init")
+	out, err := exec.Command("git", "-C", root, "rev-parse", "--short", "HEAD").Output()
+	if err != nil {
+		t.Fatal(err)
+	}
+	return strings.TrimSpace(string(out))
+}
+
+// writeDeployScript crea deploy/update.sh en root (layout rolling).
+func writeDeployScript(t *testing.T, root string) {
+	t.Helper()
+	if err := os.MkdirAll(filepath.Join(root, "deploy"), 0o755); err != nil {
+		t.Fatal(err)
+	}
+	if err := os.WriteFile(filepath.Join(root, "deploy", "update.sh"), []byte("#!/bin/bash\ntrue\n"), 0o755); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// gitCreaSegundoCommit añade un segundo commit al repo de `root` y devuelve
+// su short SHA (simula que un update movió el HEAD).
+func gitCreaSegundoCommit(t *testing.T, root string) string {
+	t.Helper()
+	run := func(args ...string) {
+		cmd := exec.Command("git", append([]string{"-C", root}, args...)...)
+		if out, err := cmd.CombinedOutput(); err != nil {
+			t.Fatalf("git %v: %v %s", args, err, out)
+		}
+	}
+	if err := os.WriteFile(filepath.Join(root, "f2"), []byte("y"), 0o644); err != nil {
+		t.Fatal(err)
+	}
+	run("add", ".")
+	run("commit", "-qm", "second")
+	out, err := exec.Command("git", "-C", root, "rev-parse", "--short", "HEAD").Output()
+	if err != nil {
+		t.Fatal(err)
+	}
+	return strings.TrimSpace(string(out))
+}
+
+// makeTestServerWithUpdater: app real con updater (repoRoot; si tiene
+// deploy/update.sh el updater es rolling) y BD real.
+func makeTestServerWithUpdater(t *testing.T, repoRoot string) *testServer {
+	t.Helper()
+	auth.SetTrustProxy(true)
+	t.Cleanup(func() { auth.SetTrustProxy(false) })
+	dataDir := t.TempDir()
+	cfg, err := config.Load(map[string]string{
+		"AUTH_USER": "admin", "AUTH_PASS": "test1234",
+		"DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
+	}, dataDir)
+	if err != nil {
+		t.Fatalf("config: %v", err)
+	}
+	d, err := db.Open(dataDir)
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	secret, err := auth.EnsureSessionSecret(d, cfg)
+	if err != nil {
+		t.Fatalf("secret: %v", err)
+	}
+	if err := auth.EnsureUsers(d, cfg); err != nil {
+		t.Fatalf("users: %v", err)
+	}
+	adapter := adapters.NewDemo()
+	hub := sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil })
+	up := updater.New(repoRoot, "owner/netpulse", "", "2.0.0", d.DB)
+	handler := httpapi.NewHandler(httpapi.Deps{
+		Config: cfg, DB: d, Adapter: adapter, Hub: hub, Secret: secret,
+		Started: time.Now(), Updater: up,
+	})
+	srv := httptest.NewServer(handler)
+	ts := &testServer{Server: srv, db: d, secret: secret}
+	t.Cleanup(func() {
+		srv.Close()
+		d.Close()
+	})
+	return ts
+}
+
+func adminCookie(t *testing.T, ts *testServer) string {
+	t.Helper()
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test1234")
+	if cookie == "" {
+		t.Fatal("login admin falló")
+	}
+	return cookie
+}

+ 60 - 0
server-go/internal/httpapi/update_history_test.go

@@ -0,0 +1,60 @@
+// update_history_test.go — GET /api/updates/history (issue #159).
+package httpapi_test
+
+import (
+	"testing"
+	"time"
+)
+
+func TestUpdateHistoryEndpoint(t *testing.T) {
+	if !gitAvailable() {
+		t.Skip("git no disponible")
+	}
+	root := t.TempDir()
+	writeDeployScript(t, root)
+	writeGitHead(t, root)
+	ts := makeTestServerWithUpdater(t, root)
+
+	// Sembrar una entrada directamente (como la escribiría el updater).
+	if _, err := ts.db.Exec(
+		`INSERT INTO update_history
+		   (event_id, ts, action, channel, version_from, version_to, initiated_by, status)
+		 VALUES ('upd-123', ?, 'apply', 'rolling', 'aaa1111', 'bbb2222', 'admin', 'success')`,
+		time.Now().UnixMilli()); err != nil {
+		t.Fatal(err)
+	}
+
+	cookie := adminCookie(t, ts)
+	res := get(t, ts.URL, "/api/updates/history", cookie)
+	if res.StatusCode != 200 {
+		t.Fatalf("status: got %d want 200", res.StatusCode)
+	}
+	body := readJSON(t, res)
+	hist, ok := body["history"].([]any)
+	if !ok || len(hist) == 0 {
+		t.Fatalf("history: %+v", body)
+	}
+	first := hist[0].(map[string]any)
+	if first["eventId"] != "upd-123" || first["status"] != "success" ||
+		first["versionFrom"] != "aaa1111" || first["versionTo"] != "bbb2222" {
+		t.Errorf("entrada: %+v", first)
+	}
+	if first["initiatedBy"] != "admin" {
+		t.Errorf("initiatedBy: %+v", first["initiatedBy"])
+	}
+}
+
+func TestUpdateHistoryRequiresAdmin(t *testing.T) {
+	if !gitAvailable() {
+		t.Skip("git no disponible")
+	}
+	root := t.TempDir()
+	writeDeployScript(t, root)
+	writeGitHead(t, root)
+	ts := makeTestServerWithUpdater(t, root)
+	admin := adminCookie(t, ts)
+	userCookie := createUserAndLogin(t, ts.URL, admin, "viewer", "clave12345", "user")
+	if got := get(t, ts.URL, "/api/updates/history", userCookie).StatusCode; got != 403 {
+		t.Errorf("GET history como user: got %d want 403", got)
+	}
+}

+ 101 - 0
server-go/internal/httpapi/update_pending_test.go

@@ -0,0 +1,101 @@
+// update_pending_test.go — confirmación post-update y POST pending-confirm
+// (issue #161).
+package httpapi_test
+
+import (
+	"fmt"
+	"net/http"
+	"net/http/httptest"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/config"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/httpapi"
+	"github.com/gnacho/netpulse/server-go/internal/sse"
+	"github.com/gnacho/netpulse/server-go/internal/updater"
+)
+
+func TestPendingConfirmEndpoint(t *testing.T) {
+	if !gitAvailable() {
+		t.Skip("git no disponible")
+	}
+	root := t.TempDir()
+	writeDeployScript(t, root)
+	old := writeGitHead(t, root)
+	newSHA := gitCreaSegundoCommit(t, root)
+
+	// Server con la BD sembrada ANTES de crear el updater (como un arranque
+	// real): el marcador se procesa en updater.New.
+	auth.SetTrustProxy(true)
+	t.Cleanup(func() { auth.SetTrustProxy(false) })
+	dataDir := t.TempDir()
+	cfg, err := config.Load(map[string]string{
+		"AUTH_USER": "admin", "AUTH_PASS": "test1234",
+		"DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
+	}, dataDir)
+	if err != nil {
+		t.Fatalf("config: %v", err)
+	}
+	d, err := db.Open(dataDir)
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	if _, err := d.Exec(
+		`INSERT INTO kv (key, value) VALUES ('update.pending_apply', ?)
+		 ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
+		fmt.Sprintf(`{"from":%q,"to":%q}`, old, newSHA)); err != nil {
+		t.Fatal(err)
+	}
+	secret, err := auth.EnsureSessionSecret(d, cfg)
+	if err != nil {
+		t.Fatalf("secret: %v", err)
+	}
+	if err := auth.EnsureUsers(d, cfg); err != nil {
+		t.Fatalf("users: %v", err)
+	}
+	adapter := adapters.NewDemo()
+	hub := sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil })
+	up := updater.New(root, "owner/netpulse", "", "2.0.0", d.DB)
+	if up.Status().PendingApply == nil {
+		t.Fatal("pendingApply debería confirmarse al arrancar con el marcador")
+	}
+	handler := httpapi.NewHandler(httpapi.Deps{
+		Config: cfg, DB: d, Adapter: adapter, Hub: hub, Secret: secret,
+		Started: time.Now(), Updater: up,
+	})
+	srv := httptest.NewServer(handler)
+	t.Cleanup(func() {
+		srv.Close()
+		d.Close()
+	})
+	ts := &testServer{Server: srv, db: d, secret: secret}
+
+	cookie := adminCookie(t, ts)
+	body := readJSON(t, get(t, ts.URL, "/api/update/status", cookie))
+	pa, ok := body["pendingApply"].(map[string]any)
+	if !ok {
+		t.Fatalf("pendingApply ausente en status: %+v", body)
+	}
+	if pa["from"] != old || pa["to"] != newSHA {
+		t.Errorf("pendingApply: %+v, want from=%s to=%s", pa, old, newSHA)
+	}
+
+	// POST pending-confirm → 204 y pendingApply desaparece.
+	req, _ := http.NewRequest("POST", ts.URL+"/api/update/pending-confirm", nil)
+	req.Header.Set("Cookie", "session="+cookie)
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatal(err)
+	}
+	res.Body.Close()
+	if res.StatusCode != 204 {
+		t.Fatalf("pending-confirm: got %d want 204", res.StatusCode)
+	}
+	body2 := readJSON(t, get(t, ts.URL, "/api/update/status", cookie))
+	if _, ok := body2["pendingApply"]; ok {
+		t.Errorf("pendingApply debería desaparecer tras confirmar: %+v", body2)
+	}
+}

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

@@ -0,0 +1,41 @@
+// update_readiness_test.go — readiness en /api/update/status (issue #160).
+package httpapi_test
+
+import (
+	"testing"
+)
+
+func TestUpdateStatusExposesReadiness(t *testing.T) {
+	if !gitAvailable() {
+		t.Skip("git no disponible")
+	}
+	root := t.TempDir()
+	writeDeployScript(t, root)
+	writeGitHead(t, root)
+	ts := makeTestServerWithUpdater(t, root)
+	cookie := adminCookie(t, ts)
+	res := get(t, ts.URL, "/api/update/status", cookie)
+	if res.StatusCode != 200 {
+		t.Fatalf("status: got %d want 200", res.StatusCode)
+	}
+	body := readJSON(t, res)
+	r, ok := body["readiness"].(map[string]any)
+	if !ok {
+		t.Fatalf("readiness ausente: %+v", body)
+	}
+	ready, _ := r["ready"].(bool)
+	if !ready {
+		t.Errorf("ready false: %+v", r)
+	}
+	for _, k := range []string{"disk", "git", "network", "concurrent"} {
+		ck, ok := r[k].(map[string]any)
+		if !ok {
+			t.Errorf("check %s ausente: %+v", k, r)
+			continue
+		}
+		okv, _ := ck["ok"].(bool)
+		if !okv {
+			t.Errorf("check %s = %+v, want ok", k, ck)
+		}
+	}
+}

+ 134 - 0
server-go/internal/updater/history.go

@@ -0,0 +1,134 @@
+// history.go — historial de actualizaciones (issue #159): tabla SQLite
+// update_history con un registro por apply. Al lanzar el update se inserta
+// una entrada 'running'; la goroutine que vigila el script la finaliza a
+// success/failed con duración. Si el servicio se reinicia a mitad (el script
+// de update toca .restart-me), la entrada queda 'running' y el siguiente
+// arranque la marca como fallida (finalizeInterrupted).
+package updater
+
+import (
+	"crypto/rand"
+	"database/sql"
+	"encoding/hex"
+	"fmt"
+	"time"
+)
+
+// HistoryEntry es un registro de update_history. En el canal rolling main
+// version_from/to son SHAs cortos de commit; en estable, tags semver.
+type HistoryEntry struct {
+	ID          int64   `json:"id"`
+	EventID     string  `json:"eventId"`
+	TS          int64   `json:"ts"`
+	Action      string  `json:"action"`
+	Channel     string  `json:"channel"`
+	VersionFrom *string `json:"versionFrom,omitempty"`
+	VersionTo   *string `json:"versionTo,omitempty"`
+	InitiatedBy string  `json:"initiatedBy"`
+	Status      string  `json:"status"` // running | success | failed
+	DurationMS  *int64  `json:"durationMs,omitempty"`
+	BackupPath  *string `json:"backupPath,omitempty"`
+	Error       *string `json:"error,omitempty"`
+}
+
+// newEventID genera un event_id único para el historial.
+func newEventID() string {
+	var b [8]byte
+	_, _ = rand.Read(b[:])
+	return fmt.Sprintf("upd-%d-%s", time.Now().UnixMilli(), hex.EncodeToString(b[:]))
+}
+
+// recordStart inserta la entrada 'running' del apply y devuelve su id.
+// Devuelve -1 si no hay BD (historial deshabilitado, p. ej. en tests).
+func (u *Updater) recordStart(from string, to *string, initiatedBy string) int64 {
+	if u.db == nil {
+		return -1
+	}
+	res, err := u.db.Exec(
+		`INSERT INTO update_history
+		   (event_id, ts, action, channel, version_from, version_to, initiated_by, status)
+		 VALUES (?, ?, ?, ?, ?, ?, ?, 'running')`,
+		newEventID(), time.Now().UnixMilli(), "apply", u.mode, from, to, initiatedBy)
+	if err != nil {
+		fmt.Printf("[netpulse] no se pudo registrar el historial de update: %v\n", err)
+		return -1
+	}
+	id, _ := res.LastInsertId()
+	return id
+}
+
+// finishHistory finaliza una entrada (success/failed) con duración y error.
+func (u *Updater) finishHistory(id int64, status, errStr string, dur time.Duration) {
+	if u.db == nil || id < 0 {
+		return
+	}
+	ms := dur.Milliseconds()
+	var errVal any
+	if errStr != "" {
+		errVal = errStr
+	}
+	if _, err := u.db.Exec(
+		`UPDATE update_history SET status = ?, duration_ms = ?, error = ? WHERE id = ?`,
+		status, ms, errVal, id); err != nil {
+		fmt.Printf("[netpulse] no se pudo finalizar el historial de update: %v\n", err)
+	}
+}
+
+// finalizeInterrupted marca como fallidas las entradas 'running' que quedaron
+// de un apply interrumpido por el reinicio del servicio.
+func (u *Updater) finalizeInterrupted() {
+	if u.db == nil {
+		return
+	}
+	msg := "interrupted_by_restart"
+	if _, err := u.db.Exec(
+		`UPDATE update_history SET status = 'failed', error = ? WHERE status = 'running'`, msg); err != nil {
+		fmt.Printf("[netpulse] no se pudo finalizar historial interrumpido: %v\n", err)
+	}
+}
+
+// ListHistory devuelve los últimos `limit` registros de update_history
+// (issue #159), más reciente primero. Cota de 200 por petición.
+func ListHistory(db *sql.DB, limit int) ([]HistoryEntry, error) {
+	if limit <= 0 || limit > 200 {
+		limit = 50
+	}
+	rows, err := db.Query(`
+		SELECT id, event_id, ts, action, channel, version_from, version_to,
+		       initiated_by, status, duration_ms, backup_path, error
+		FROM update_history
+		ORDER BY ts DESC
+		LIMIT ?`, limit)
+	if err != nil {
+		return nil, err
+	}
+	defer rows.Close()
+	out := []HistoryEntry{}
+	for rows.Next() {
+		var e HistoryEntry
+		var from, to, backup, errStr sql.NullString
+		var dur sql.NullInt64
+		if err := rows.Scan(&e.ID, &e.EventID, &e.TS, &e.Action, &e.Channel,
+			&from, &to, &e.InitiatedBy, &e.Status, &dur, &backup, &errStr); err != nil {
+			return nil, err
+		}
+		if from.Valid {
+			e.VersionFrom = &from.String
+		}
+		if to.Valid {
+			e.VersionTo = &to.String
+		}
+		if dur.Valid {
+			ms := dur.Int64
+			e.DurationMS = &ms
+		}
+		if backup.Valid {
+			e.BackupPath = &backup.String
+		}
+		if errStr.Valid {
+			e.Error = &errStr.String
+		}
+		out = append(out, e)
+	}
+	return out, rows.Err()
+}

+ 97 - 0
server-go/internal/updater/pending.go

@@ -0,0 +1,97 @@
+// pending.go — confirmación post-update (issue #161): antes de aplicar se
+// persiste un marcador from→to en kv; en el siguiente arranque se compara el
+// commit actual. Si cambió → se expone la confirmación (toast "Actualizado a
+// <sha>" en el frontend); si no → se limpia en silencio (el apply falló). El
+// marcador se borra en ambos casos, así que la confirmación es de una sola vez.
+package updater
+
+import (
+	"database/sql"
+	"encoding/json"
+	"fmt"
+)
+
+// pendingApplyKey es la clave kv del marcador pre-update.
+const pendingApplyKey = "update.pending_apply"
+
+// PendingApply es el marcador from→to y, tras un arranque con confirmación,
+// el valor expuesto en /api/update/status (campo `pendingApply`). To es el
+// SHA que quedó corriendo tras el arranque confirmado.
+type PendingApply struct {
+	From string `json:"from"`
+	To   string `json:"to"`
+}
+
+// persistPendingApply guarda el marcador en kv (best-effort; sin BD → no-op).
+func (u *Updater) persistPendingApply(from string, to *string) {
+	if u.db == nil {
+		return
+	}
+	p := PendingApply{From: from}
+	if to != nil {
+		p.To = *to
+	}
+	data, err := json.Marshal(p)
+	if err != nil {
+		return
+	}
+	if _, err := u.db.Exec(
+		`INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
+		pendingApplyKey, string(data)); err != nil {
+		fmt.Printf("[netpulse] no se pudo persistir el marcador de update: %v\n", err)
+	}
+}
+
+// clearPendingApply borra el marcador (apply falló o ya confirmado).
+func (u *Updater) clearPendingApply() {
+	if u.db == nil {
+		return
+	}
+	_, _ = u.db.Exec(`DELETE FROM kv WHERE key = ?`, pendingApplyKey)
+}
+
+// readPendingApply lee el marcador del kv (false si no existe o es inválido).
+func readPendingApply(db *sql.DB) (PendingApply, bool) {
+	var v string
+	if err := db.QueryRow("SELECT value FROM kv WHERE key = ?", pendingApplyKey).Scan(&v); err != nil {
+		return PendingApply{}, false
+	}
+	var p PendingApply
+	if json.Unmarshal([]byte(v), &p) != nil || p.From == "" {
+		return PendingApply{}, false
+	}
+	return p, true
+}
+
+// loadPendingApply se ejecuta al crear el updater (cada arranque): finaliza
+// historial interrumpido y procesa el marcador pendiente si lo hay.
+func (u *Updater) loadPendingApply() {
+	if u.db == nil {
+		return
+	}
+	u.finalizeInterrupted()
+	p, ok := readPendingApply(u.db)
+	if !ok {
+		return
+	}
+	defer u.clearPendingApply()
+	if u.mode != "rolling" {
+		return // layout estable: sin auto-apply, no hay nada que confirmar
+	}
+	now := gitShort(u.repoRoot)
+	if now == "" || now == p.From {
+		return // sin cambio o commit desconocido → silencioso
+	}
+	u.mu.Lock()
+	u.pendingApply = &PendingApply{From: p.From, To: now}
+	u.mu.Unlock()
+	fmt.Printf("[netpulse] update confirmado: %s → %s\n", p.From, now)
+}
+
+// AckPending confirma y descarta el pendingApply en memoria (una sola vez:
+// el frontend lo muestra y llama a POST /api/update/pending-confirm).
+func (u *Updater) AckPending() {
+	u.mu.Lock()
+	u.pendingApply = nil
+	u.mu.Unlock()
+}

+ 149 - 0
server-go/internal/updater/readiness.go

@@ -0,0 +1,149 @@
+// readiness.go — pre-flight checks del apply (issue #160): espacio en disco
+// para descarga+backup, working tree de git limpio, red hacia GitHub y sin
+// update concurrente. Se expone en /api/update/status (campo `readiness`) y
+// el frontend bloquea el botón de aplicar si algo falla.
+//
+// El cómputo se cachea readinessTTL: el network check hace una petición HTTP
+// y no debe bloquear el polling de status (2,5 s durante el apply).
+package updater
+
+import (
+	"context"
+	"fmt"
+	"net/http"
+	"os/exec"
+	"strings"
+	"syscall"
+	"time"
+)
+
+const (
+	// readinessTTL: cuánto tiempo se sirve el readiness cacheado (el network
+	// check toca red; no recalcular en cada poll de status).
+	readinessTTL = 30 * time.Second
+	// readinessNetTimeout: tope para el check de red hacia GitHub.
+	readinessNetTimeout = 5 * time.Second
+)
+
+// minDiskFreeBytes es el espacio libre mínimo exigido en repoRoot (descarga
+// del binario de CI ~40 MB + backup del binario actual + margen de build).
+// Var de paquete para poder bajarlo en tests.
+var minDiskFreeBytes int64 = 500 * 1024 * 1024
+
+// CheckResult es el resultado de un check individual.
+type CheckResult struct {
+	OK     bool   `json:"ok"`
+	Detail string `json:"detail,omitempty"`
+}
+
+// Readiness agrupa los pre-flight checks del apply (issue #160).
+type Readiness struct {
+	Disk       CheckResult `json:"disk"`
+	Git        CheckResult `json:"git"`
+	Network    CheckResult `json:"network"`
+	Concurrent CheckResult `json:"concurrent"`
+	Ready      bool        `json:"ready"`
+}
+
+// Readiness devuelve los checks (cacheados readinessTTL). Nil si el layout no
+// permite auto-apply (modo estable install.sh): el frontend ya muestra el
+// enlace a releases en vez del botón de aplicar.
+func (u *Updater) Readiness() *Readiness {
+	if !u.canApply {
+		return nil
+	}
+	u.mu.Lock()
+	if u.readiness != nil && time.Since(u.readinessAt) < readinessTTL {
+		r := u.readiness
+		u.mu.Unlock()
+		return r
+	}
+	u.mu.Unlock()
+
+	r := u.computeReadiness()
+
+	u.mu.Lock()
+	u.readiness = &r
+	u.readinessAt = time.Now()
+	u.mu.Unlock()
+	return &r
+}
+
+// computeReadiness ejecuta los 4 checks sin cache.
+func (u *Updater) computeReadiness() Readiness {
+	r := Readiness{
+		Disk:       u.checkDisk(),
+		Git:        u.checkGit(),
+		Network:    u.checkNetwork(),
+		Concurrent: u.checkConcurrent(),
+	}
+	r.Ready = u.canApply && r.Disk.OK && r.Git.OK && r.Network.OK && r.Concurrent.OK
+	return r
+}
+
+// checkDisk verifica espacio libre en repoRoot (donde se backupa el binario
+// y se trabaja durante el update).
+func (u *Updater) checkDisk() CheckResult {
+	path := u.repoRoot
+	if path == "" {
+		path = "."
+	}
+	var st syscall.Statfs_t
+	if err := syscall.Statfs(path, &st); err != nil {
+		return CheckResult{OK: false, Detail: "no se pudo leer el espacio en disco"}
+	}
+	free := int64(st.Bavail) * int64(st.Bsize)
+	if free < minDiskFreeBytes {
+		return CheckResult{
+			OK:     false,
+			Detail: fmt.Sprintf("%d MB libres, se necesitan %d", free/(1<<20), minDiskFreeBytes/(1<<20)),
+		}
+	}
+	return CheckResult{OK: true, Detail: fmt.Sprintf("%d MB libres", free/(1<<20))}
+}
+
+// checkGit verifica que el working tree está limpio (update.sh hace
+// git reset --hard: cualquier cambio sin commitear se perdería).
+func (u *Updater) checkGit() CheckResult {
+	if u.mode != "rolling" {
+		return CheckResult{OK: true, Detail: "no aplica (layout estable)"}
+	}
+	out, err := exec.Command("git", "-C", u.repoRoot, "status", "--porcelain").Output()
+	if err != nil {
+		return CheckResult{OK: false, Detail: "no se pudo leer el estado de git"}
+	}
+	if len(strings.TrimSpace(string(out))) > 0 {
+		return CheckResult{OK: false, Detail: "hay cambios sin commitear"}
+	}
+	return CheckResult{OK: true}
+}
+
+// checkNetwork comprueba que GitHub es alcanzable (cualquier respuesta HTTP
+// cuenta: un 4xx también significa que hay conectividad).
+func (u *Updater) checkNetwork() CheckResult {
+	ctx, cancel := context.WithTimeout(context.Background(), readinessNetTimeout)
+	defer cancel()
+	req, err := http.NewRequestWithContext(ctx, "GET", APIBase, nil)
+	if err != nil {
+		return CheckResult{OK: false, Detail: "URL de API inválida"}
+	}
+	req.Header.Set("User-Agent", "netpulse-updater")
+	client := &http.Client{Timeout: readinessNetTimeout}
+	res, err := client.Do(req)
+	if err != nil {
+		return CheckResult{OK: false, Detail: "no se pudo contactar con GitHub"}
+	}
+	res.Body.Close()
+	return CheckResult{OK: true}
+}
+
+// checkConcurrent verifica que no hay ya un update en curso (mismo flag que
+// Apply usa para devolver 409 already_updating).
+func (u *Updater) checkConcurrent() CheckResult {
+	u.mu.Lock()
+	defer u.mu.Unlock()
+	if u.updatingStep != nil {
+		return CheckResult{OK: false, Detail: "hay una actualización en curso"}
+	}
+	return CheckResult{OK: true}
+}

+ 70 - 11
server-go/internal/updater/updater.go

@@ -7,6 +7,7 @@ package updater
 
 import (
 	"context"
+	"database/sql"
 	"encoding/json"
 	"fmt"
 	"io"
@@ -55,6 +56,12 @@ type Status struct {
 	LastLog         *string `json:"lastLog"`
 	Repo            string  `json:"repo"`
 	HasToken        bool    `json:"hasToken"`
+	// Readiness: pre-flight checks del apply (issue #160). Null en layout
+	// estable (sin auto-apply) o hasta el primer Status().
+	Readiness *Readiness `json:"readiness,omitempty"`
+	// PendingApply: confirmación de que el último update aplicó y el servicio
+	// arrancó con el commit nuevo (issue #161). Null sin confirmación.
+	PendingApply *PendingApply `json:"pendingApply,omitempty"`
 }
 
 // Updater mantiene el estado y los timers (como createUpdater).
@@ -65,6 +72,9 @@ type Updater struct {
 	version  string // semver embebido (httpapi.Version) para comparar en estable
 	canApply bool   // true si existe deploy/update.sh (layout git)
 	mode     string // "rolling" (git layout) | "stable" (install.sh)
+	// db: SQLite para historial (#159) y marcador pendingApply (#161). nil →
+	// persistencia deshabilitada (tests sin BD).
+	db *sql.DB
 
 	mu           sync.Mutex
 	current      string
@@ -77,6 +87,14 @@ type Updater struct {
 	lastLog      *string
 	err          *string
 
+	// readiness cacheado (issue #160): el network check toca red y no debe
+	// bloquear el polling de status.
+	readiness   *Readiness
+	readinessAt time.Time
+
+	// pendingApply en memoria (issue #161): confirmación post-update.
+	pendingApply *PendingApply
+
 	stopCh chan struct{}
 	wg     sync.WaitGroup
 }
@@ -86,23 +104,28 @@ type Updater struct {
 // layout es automática: si existe deploy/update.sh junto a repoRoot, el modo
 // es "rolling" (compara contra main HEAD y puede auto-aplicar); si no, es
 // "stable" (compara contra release tags y NO puede auto-aplicar — el usuario
-// debe re-ejecutar install.sh).
-func New(repoRoot, repo, token, version string) *Updater {
+// debe re-ejecutar install.sh). db puede ser nil (persistencia deshabilitada).
+func New(repoRoot, repo, token, version string, db *sql.DB) *Updater {
 	canApply := fileExists(filepath.Join(repoRoot, "deploy", "update.sh"))
 	mode := "stable"
 	if canApply {
 		mode = "rolling"
 	}
-	return &Updater{
+	u := &Updater{
 		repoRoot: repoRoot,
 		repo:     repo,
 		token:    token,
 		version:  version,
 		canApply: canApply,
 		mode:     mode,
+		db:       db,
 		current:  "desconocido",
 		stopCh:   make(chan struct{}),
 	}
+	// Issue #161: procesar el marcador pendiente (confirmación post-update)
+	// y finalizar historial interrumpido en cada arranque.
+	u.loadPendingApply()
+	return u
 }
 
 // CanApply indica si el updater puede auto-aplicar en este layout.
@@ -310,9 +333,16 @@ func (u *Updater) Check(ctx context.Context) Status {
 
 var stepRe = regexp.MustCompile(`STEP:(\w+)`)
 
-// Apply lanza update.sh en segundo plano. Devuelve false si ya hay una
-// actualización en curso (→ 409 already_updating) o si no se pudo copiar.
-func (u *Updater) Apply() bool {
+// Apply lanza update.sh en segundo plano (iniciado manualmente desde la UI,
+// rol admin). Devuelve false si ya hay una actualización en curso (→ 409
+// already_updating) o si no se pudo copiar.
+func (u *Updater) Apply() bool { return u.ApplyBy("admin") }
+
+// ApplyBy lanza update.sh en segundo plano con el iniciador dado ("admin"
+// manual o "auto" para el rolling main). Antes de lanzar registra la entrada
+// 'running' del historial (#159) y persiste el marcador pendingApply (#161);
+// la goroutine finaliza ambos según el resultado del script.
+func (u *Updater) ApplyBy(initiatedBy string) bool {
 	u.mu.Lock()
 	if u.updatingStep != nil {
 		u.mu.Unlock()
@@ -323,6 +353,23 @@ func (u *Updater) Apply() bool {
 	u.updatingLog = ""
 	u.mu.Unlock()
 
+	// Historial + marcador: version_from es el commit actual, version_to el
+	// objetivo (latest de GitHub si ya se consultó).
+	from := u.current
+	if from == "" || from == "desconocido" {
+		from = gitShort(u.repoRoot)
+	}
+	u.mu.Lock()
+	var to *string
+	if u.latest != nil {
+		c := *u.latest
+		to = &c
+	}
+	u.mu.Unlock()
+	historyID := u.recordStart(from, to, initiatedBy)
+	u.persistPendingApply(from, to)
+	startedAt := time.Now()
+
 	tmpScript := filepath.Join(os.TempDir(), fmt.Sprintf("netpulse-update-%d.sh", time.Now().UnixMilli()))
 	src, err := os.ReadFile(filepath.Join(u.repoRoot, "deploy", "update.sh"))
 	if err == nil {
@@ -334,6 +381,7 @@ func (u *Updater) Apply() bool {
 		code := "update_copy_failed"
 		u.err = &code
 		u.mu.Unlock()
+		u.finishHistory(historyID, "failed", code, time.Since(startedAt))
 		fmt.Printf("[netpulse] no se pudo copiar update.sh: %v\n", err)
 		return false
 	}
@@ -345,6 +393,7 @@ func (u *Updater) Apply() bool {
 		u.mu.Lock()
 		u.updatingStep = nil
 		u.mu.Unlock()
+		u.finishHistory(historyID, "failed", "update_pipe_failed", time.Since(startedAt))
 		return false
 	}
 	cmd.Stderr = &tailWriter{u: u}
@@ -352,6 +401,7 @@ func (u *Updater) Apply() bool {
 		u.mu.Lock()
 		u.updatingStep = nil
 		u.mu.Unlock()
+		u.finishHistory(historyID, "failed", "update_start_failed", time.Since(startedAt))
 		return false
 	}
 	u.wg.Add(1)
@@ -368,6 +418,7 @@ func (u *Updater) Apply() bool {
 			}
 		}
 		waitErr := cmd.Wait()
+		dur := time.Since(startedAt)
 		u.mu.Lock()
 		defer u.mu.Unlock()
 		if waitErr == nil {
@@ -376,18 +427,22 @@ func (u *Updater) Apply() bool {
 			log := u.updatingLog
 			u.lastLog = &log
 			u.updateAvail = false
+			u.finishHistory(historyID, "success", "", dur)
 		} else {
+			code := "update_exit_-1"
 			if ee, ok := waitErr.(*exec.ExitError); ok {
 				log := u.updatingLog
 				u.lastLog = &log
 				u.updatingStep = nil
-				code := fmt.Sprintf("update_exit_%d", ee.ExitCode())
+				code = fmt.Sprintf("update_exit_%d", ee.ExitCode())
 				u.err = &code
 			} else {
 				u.updatingStep = nil
-				code := "update_exit_-1"
 				u.err = &code
 			}
+			u.finishHistory(historyID, "failed", code, dur)
+			// Issue #161: el apply falló → sin confirmación post-update.
+			u.clearPendingApply()
 		}
 	}()
 	return true
@@ -422,11 +477,14 @@ func (w *tailWriter) Write(p []byte) (int, error) {
 	return len(p), nil
 }
 
-// Status devuelve el estado actual (shape de la API).
+// Status devuelve el estado actual (shape de la API), incluyendo readiness
+// (issue #160) y la confirmación pendingApply (issue #161).
 func (u *Updater) Status() Status {
 	u.mu.Lock()
-	defer u.mu.Unlock()
-	return u.statusLocked()
+	st := u.statusLocked()
+	u.mu.Unlock()
+	st.Readiness = u.Readiness()
+	return st
 }
 
 func (u *Updater) statusLocked() Status {
@@ -455,6 +513,7 @@ func (u *Updater) statusLocked() Status {
 		LastLog:         lastLog,
 		Repo:            u.repo,
 		HasToken:        u.token != "",
+		PendingApply:    u.pendingApply,
 	}
 }
 

+ 80 - 0
server-go/internal/updater/updater_helpers_test.go

@@ -0,0 +1,80 @@
+// updater_helpers_test.go — helpers compartidos de los tests de operaciones
+// nuevas del updater (readiness #160, historial #159, pendingApply #161).
+package updater
+
+import (
+	"database/sql"
+	"fmt"
+	"os"
+	"os/exec"
+	"path/filepath"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+// openDB abre una BD real temporal (schema completo) para los tests.
+func openDB(t *testing.T) *sql.DB {
+	t.Helper()
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	t.Cleanup(func() { d.Close() })
+	return d.DB
+}
+
+// writeSlowScript crea deploy/update.sh que duerme 1 s antes de salir 0.
+func writeSlowScript(t *testing.T, root string) {
+	t.Helper()
+	if err := os.MkdirAll(filepath.Join(root, "deploy"), 0o755); err != nil {
+		t.Fatal(err)
+	}
+	script := "#!/bin/bash\nsleep 1\ntrue\n"
+	if err := os.WriteFile(filepath.Join(root, "deploy", "update.sh"), []byte(script), 0o755); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// waitDone espera a que el update acabe (updating false o step done).
+func waitDone(t *testing.T, u *Updater) {
+	t.Helper()
+	deadline := time.Now().Add(5 * time.Second)
+	for {
+		st := u.Status()
+		if m, ok := st.Updating.(progress); ok && m.Step == "done" {
+			return
+		}
+		if st.Updating == false {
+			return
+		}
+		if time.Now().After(deadline) {
+			t.Fatalf("timeout esperando fin del apply: %+v", st)
+		}
+		time.Sleep(50 * time.Millisecond)
+	}
+}
+
+// gitRootCreaSegundoCommit añade un segundo commit al repo de `root` y
+// devuelve su short SHA. Útil para simular que un update movió el HEAD.
+func gitRootCreaSegundoCommit(t *testing.T, root string) string {
+	t.Helper()
+	run := func(args ...string) {
+		cmd := exec.Command("git", append([]string{"-C", root}, args...)...)
+		if out, err := cmd.CombinedOutput(); err != nil {
+			t.Fatalf("git %v: %v %s", args, err, out)
+		}
+	}
+	if err := os.WriteFile(filepath.Join(root, "f2"), []byte(fmt.Sprintf("y-%d", time.Now().UnixNano())), 0o644); err != nil {
+		t.Fatal(err)
+	}
+	run("add", ".")
+	run("commit", "-qm", "second")
+	out, err := exec.Command("git", "-C", root, "rev-parse", "--short", "HEAD").Output()
+	if err != nil {
+		t.Fatal(err)
+	}
+	return strings.TrimSpace(string(out))
+}

+ 134 - 0
server-go/internal/updater/updater_history_test.go

@@ -0,0 +1,134 @@
+// updater_history_test.go — historial de updates en SQLite (issue #159):
+// la entrada se registra al aplicar y se finaliza con el resultado del script.
+package updater
+
+import (
+	"context"
+	"fmt"
+	"net/http"
+	"os"
+	"path/filepath"
+	"testing"
+	"time"
+)
+
+func TestHistoryRecordedOnApply(t *testing.T) {
+	if !gitAvailable() {
+		t.Skip("git no disponible")
+	}
+	root := t.TempDir()
+	short := writeGitHead(t, root)
+	if err := os.MkdirAll(filepath.Join(root, "deploy"), 0o755); err != nil {
+		t.Fatal(err)
+	}
+	if err := os.WriteFile(filepath.Join(root, "deploy", "update.sh"),
+		[]byte("#!/bin/bash\necho STEP:fetch\nsleep 0.1\ntrue\n"), 0o755); err != nil {
+		t.Fatal(err)
+	}
+	withAPI(t, func(w http.ResponseWriter, r *http.Request) {
+		w.Header().Set("Content-Type", "application/json")
+		fmt.Fprint(w, `{"sha":"abc1234deadbeef","commit":{"message":"feat: algo"}}`)
+	})
+	dbh := openDB(t)
+	u := New(root, "owner/netpulse", "", "2.0.0", dbh)
+	u.Check(context.Background()) // fija current + latest
+	if !u.Apply() {
+		t.Fatal("apply debería arrancar")
+	}
+	waitDone(t, u)
+
+	hist, err := ListHistory(dbh, 10)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(hist) == 0 {
+		t.Fatal("sin historial tras el apply")
+	}
+	e := hist[0]
+	if e.Status != "success" {
+		t.Errorf("status: %s (entry %+v)", e.Status, e)
+	}
+	if e.InitiatedBy != "admin" {
+		t.Errorf("initiatedBy: %s", e.InitiatedBy)
+	}
+	if e.Channel != "rolling" {
+		t.Errorf("channel: %s", e.Channel)
+	}
+	if e.VersionFrom == nil || *e.VersionFrom != short {
+		t.Errorf("versionFrom: %v, want %s", e.VersionFrom, short)
+	}
+	if e.VersionTo == nil || *e.VersionTo != "abc1234" {
+		t.Errorf("versionTo: %v, want abc1234", e.VersionTo)
+	}
+	if e.DurationMS == nil {
+		t.Error("durationMs no debería ser nil")
+	}
+	if e.Error != nil {
+		t.Errorf("error inesperado: %v", *e.Error)
+	}
+}
+
+func TestHistoryFailedOnApplyError(t *testing.T) {
+	if !gitAvailable() {
+		t.Skip("git no disponible")
+	}
+	root := t.TempDir()
+	writeGitHead(t, root)
+	if err := os.MkdirAll(filepath.Join(root, "deploy"), 0o755); err != nil {
+		t.Fatal(err)
+	}
+	if err := os.WriteFile(filepath.Join(root, "deploy", "update.sh"),
+		[]byte("#!/bin/bash\necho STEP:fetch\nexit 3\n"), 0o755); err != nil {
+		t.Fatal(err)
+	}
+	dbh := openDB(t)
+	u := New(root, "owner/netpulse", "", "2.0.0", dbh)
+	if !u.Apply() {
+		t.Fatal("apply debería arrancar")
+	}
+	waitDone(t, u)
+
+	hist, _ := ListHistory(dbh, 10)
+	if len(hist) == 0 {
+		t.Fatal("sin historial")
+	}
+	e := hist[0]
+	if e.Status != "failed" {
+		t.Errorf("status: %s, want failed (%+v)", e.Status, e)
+	}
+	if e.Error == nil || *e.Error != "update_exit_3" {
+		t.Errorf("error: %v, want update_exit_3", e.Error)
+	}
+}
+
+func TestHistoryInterruptedFinalizedOnStartup(t *testing.T) {
+	if !gitAvailable() {
+		t.Skip("git no disponible")
+	}
+	root := t.TempDir()
+	writeDeployScript(t, root)
+	writeGitHead(t, root)
+	dbh := openDB(t)
+	// Entrada 'running' residual: simula un apply cortado por el reinicio.
+	if _, err := dbh.Exec(
+		`INSERT INTO update_history (event_id, ts, action, channel, initiated_by, status)
+		 VALUES ('upd-test', ?, 'apply', 'rolling', 'admin', 'running')`,
+		time.Now().UnixMilli()); err != nil {
+		t.Fatal(err)
+	}
+	New(root, "owner/netpulse", "", "2.0.0", dbh) // arranque → finaliza la pendiente
+	hist, err := ListHistory(dbh, 10)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(hist) == 0 {
+		t.Fatal("sin historial")
+	}
+	e := hist[0]
+	if e.Status != "failed" {
+		t.Errorf("status: %s, want failed (%+v)", e.Status, e)
+	}
+	if e.Error == nil || *e.Error != "interrupted_by_restart" {
+		t.Errorf("error: %v, want interrupted_by_restart", e.Error)
+	}
+}

+ 88 - 0
server-go/internal/updater/updater_pending_test.go

@@ -0,0 +1,88 @@
+// updater_pending_test.go — confirmación post-update (issue #161): marcador
+// from→to persistido antes de aplicar, comparado en el siguiente arranque.
+package updater
+
+import (
+	"database/sql"
+	"encoding/json"
+	"testing"
+)
+
+// seedPending inserta el marcador pendingApply en kv.
+func seedPending(t *testing.T, dbh *sql.DB, from, to string) {
+	t.Helper()
+	data, _ := json.Marshal(PendingApply{From: from, To: to})
+	if _, err := dbh.Exec(
+		`INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
+		pendingApplyKey, string(data)); err != nil {
+		t.Fatal(err)
+	}
+}
+
+func TestPendingApplyConfirmedOnNewCommit(t *testing.T) {
+	if !gitAvailable() {
+		t.Skip("git no disponible")
+	}
+	root := t.TempDir()
+	writeDeployScript(t, root)
+	old := writeGitHead(t, root)
+	newShort := gitRootCreaSegundoCommit(t, root)
+	if newShort == old {
+		t.Fatal("los SHAs deberían diferir tras un commit nuevo")
+	}
+	dbh := openDB(t)
+	seedPending(t, dbh, old, newShort)
+
+	u := New(root, "owner/netpulse", "", "2.0.0", dbh) // "arranque"
+	st := u.Status()
+	if st.PendingApply == nil {
+		t.Fatalf("pendingApply debería confirmar el update: %+v", st)
+	}
+	if st.PendingApply.From != old || st.PendingApply.To != newShort {
+		t.Errorf("pendingApply: %+v, want from=%s to=%s", st.PendingApply, old, newShort)
+	}
+	// Ack → descartada de una sola vez.
+	u.AckPending()
+	if u.Status().PendingApply != nil {
+		t.Fatal("tras ack, pendingApply debería ser nil")
+	}
+	if _, ok := readPendingApply(dbh); ok {
+		t.Fatal("el marcador debería estar borrado tras confirmar")
+	}
+}
+
+func TestPendingApplyClearedSilentlyWhenUnchanged(t *testing.T) {
+	if !gitAvailable() {
+		t.Skip("git no disponible")
+	}
+	root := t.TempDir()
+	writeDeployScript(t, root)
+	short := writeGitHead(t, root)
+	dbh := openDB(t)
+	// Marcador con from == HEAD actual: el update no cambió nada → silencio.
+	seedPending(t, dbh, short, "targetsha")
+
+	u := New(root, "owner/netpulse", "", "2.0.0", dbh)
+	st := u.Status()
+	if st.PendingApply != nil {
+		t.Fatalf("sin cambio no debería confirmar: %+v", st.PendingApply)
+	}
+	if _, ok := readPendingApply(dbh); ok {
+		t.Fatal("el marcador debería borrarse en silencio")
+	}
+}
+
+func TestPendingApplyIgnoredOnStableLayout(t *testing.T) {
+	// Layout estable (sin deploy/update.sh): el marcador se limpia sin
+	// confirmación (no hay auto-apply en este layout).
+	root := t.TempDir()
+	dbh := openDB(t)
+	seedPending(t, dbh, "oldsha", "newsha")
+	u := New(root, "owner/netpulse", "", "2.0.0", dbh)
+	if u.Status().PendingApply != nil {
+		t.Fatal("en layout estable no debería confirmar")
+	}
+	if _, ok := readPendingApply(dbh); ok {
+		t.Fatal("el marcador debería borrarse")
+	}
+}

+ 127 - 0
server-go/internal/updater/updater_readiness_test.go

@@ -0,0 +1,127 @@
+// updater_readiness_test.go — pre-flight checks del apply (issue #160).
+package updater
+
+import (
+	"fmt"
+	"net/http"
+	"os"
+	"path/filepath"
+	"testing"
+)
+
+func TestReadinessAllOK(t *testing.T) {
+	if !gitAvailable() {
+		t.Skip("git no disponible")
+	}
+	root := t.TempDir()
+	writeDeployScript(t, root)
+	writeGitHead(t, root)
+	withAPI(t, func(w http.ResponseWriter, r *http.Request) {
+		w.Header().Set("Content-Type", "application/json")
+		fmt.Fprint(w, `{"sha":"abc1234deadbeef","commit":{"message":"feat: algo"}}`)
+	})
+	u := New(root, "owner/netpulse", "", "2.0.0", nil)
+	r := u.Readiness()
+	if r == nil {
+		t.Fatal("readiness nil en layout rolling")
+	}
+	if !r.Disk.OK {
+		t.Errorf("disk: %+v", r.Disk)
+	}
+	if !r.Git.OK {
+		t.Errorf("git: %+v", r.Git)
+	}
+	if !r.Network.OK {
+		t.Errorf("network: %+v", r.Network)
+	}
+	if !r.Concurrent.OK {
+		t.Errorf("concurrent: %+v", r.Concurrent)
+	}
+	if !r.Ready {
+		t.Errorf("ready false: %+v", r)
+	}
+}
+
+func TestReadinessGitDirty(t *testing.T) {
+	if !gitAvailable() {
+		t.Skip("git no disponible")
+	}
+	root := t.TempDir()
+	writeDeployScript(t, root)
+	writeGitHead(t, root)
+	// Ensuciar el working tree: el update hace git reset --hard y lo perdería.
+	if err := os.WriteFile(filepath.Join(root, "untracked.txt"), []byte("x"), 0o644); err != nil {
+		t.Fatal(err)
+	}
+	withAPI(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
+	u := New(root, "owner/netpulse", "", "2.0.0", nil)
+	r := u.Readiness()
+	if r.Git.OK {
+		t.Errorf("git debería fallar con cambios sin commitear: %+v", r.Git)
+	}
+	if r.Ready {
+		t.Error("ready debería ser false con git sucio")
+	}
+}
+
+func TestReadinessConcurrent(t *testing.T) {
+	root := t.TempDir()
+	writeSlowScript(t, root)
+	u := New(root, "owner/netpulse", "", "2.0.0", nil)
+	if !u.Apply() {
+		t.Fatal("apply debería arrancar")
+	}
+	defer waitDone(t, u)
+	r := u.Readiness()
+	if r.Concurrent.OK {
+		t.Errorf("concurrent debería fallar durante el apply: %+v", r.Concurrent)
+	}
+	if r.Ready {
+		t.Error("ready debería ser false durante el apply")
+	}
+}
+
+func TestReadinessDiskInsufficient(t *testing.T) {
+	root := t.TempDir()
+	writeDeployScript(t, root)
+	old := minDiskFreeBytes
+	minDiskFreeBytes = 1 << 62 // umbral imposible de cumplir
+	t.Cleanup(func() { minDiskFreeBytes = old })
+	u := New(root, "owner/netpulse", "", "2.0.0", nil)
+	r := u.Readiness()
+	if r.Disk.OK {
+		t.Errorf("disk debería fallar con umbral imposible: %+v", r.Disk)
+	}
+}
+
+func TestReadinessNetworkDown(t *testing.T) {
+	root := t.TempDir()
+	writeDeployScript(t, root)
+	old := APIBase
+	APIBase = "http://127.0.0.1:1" // puerto cerrado → conexión rechazada
+	t.Cleanup(func() { APIBase = old })
+	u := New(root, "owner/netpulse", "", "2.0.0", nil)
+	r := u.Readiness()
+	if r.Network.OK {
+		t.Errorf("network debería fallar con endpoint muerto: %+v", r.Network)
+	}
+}
+
+// Status incluye el readiness (issue #160).
+func TestStatusExponeReadiness(t *testing.T) {
+	if !gitAvailable() {
+		t.Skip("git no disponible")
+	}
+	root := t.TempDir()
+	writeDeployScript(t, root)
+	writeGitHead(t, root)
+	withAPI(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
+	u := New(root, "owner/netpulse", "", "2.0.0", nil)
+	st := u.Status()
+	if st.Readiness == nil {
+		t.Fatal("status debería exponer readiness")
+	}
+	if !st.Readiness.Ready {
+		t.Errorf("ready esperado: %+v", st.Readiness)
+	}
+}

+ 9 - 9
server-go/internal/updater/updater_test.go

@@ -39,7 +39,7 @@ func TestCheckUpdateAvailable(t *testing.T) {
 	root := t.TempDir()
 	writeDeployScript(t, root)
 	writeGitHead(t, root)
-	u := New(root, "owner/netpulse", "", "2.0.0")
+	u := New(root, "owner/netpulse", "", "2.0.0", nil)
 	st := u.Check(context.Background())
 	if st.Error != nil {
 		t.Fatalf("error: %v", *st.Error)
@@ -70,7 +70,7 @@ func TestCheckNoToken(t *testing.T) {
 	})
 	// Sin deploy/update.sh → modo estable. El 404 llega tanto a /releases/latest
 	// como a /commits/main; el error es el mismo.
-	u := New(t.TempDir(), "owner/netpulse", "", "2.0.0")
+	u := New(t.TempDir(), "owner/netpulse", "", "2.0.0", nil)
 	st := u.Check(context.Background())
 	if st.Error == nil || *st.Error != "no_token" {
 		t.Fatalf("error: %v", st.Error)
@@ -87,7 +87,7 @@ func TestCheckMismaVersion(t *testing.T) {
 	withAPI(t, func(w http.ResponseWriter, r *http.Request) {
 		fmt.Fprintf(w, `{"sha":"%sffffffffff","commit":{"message":"x"}}`, short)
 	})
-	u := New(root, "owner/netpulse", "", "2.0.0")
+	u := New(root, "owner/netpulse", "", "2.0.0", nil)
 	st := u.Check(context.Background())
 	if st.UpdateAvailable {
 		t.Fatal("no debería haber update")
@@ -145,7 +145,7 @@ func TestApplyYaEnCursoYScript(t *testing.T) {
 	if err := os.WriteFile(filepath.Join(root, "deploy", "update.sh"), []byte(script), 0o755); err != nil {
 		t.Fatal(err)
 	}
-	u := New(root, "owner/netpulse", "", "2.0.0")
+	u := New(root, "owner/netpulse", "", "2.0.0", nil)
 	if !u.Apply() {
 		t.Fatal("apply debería arrancar")
 	}
@@ -179,7 +179,7 @@ func TestStableModeUpdateAvailable(t *testing.T) {
 		fmt.Fprint(w, `{"tag_name":"v2.7.3","name":"v2.7.3"}`)
 	})
 	// Sin deploy/update.sh → modo estable. Versión embebida 2.7.2 < 2.7.3.
-	u := New(t.TempDir(), "owner/netpulse", "", "2.7.2")
+	u := New(t.TempDir(), "owner/netpulse", "", "2.7.2", nil)
 	st := u.Check(context.Background())
 	if st.Error != nil {
 		t.Fatalf("error: %v", *st.Error)
@@ -202,7 +202,7 @@ func TestStableModeNoUpdateWhenSameVersion(t *testing.T) {
 	withAPI(t, func(w http.ResponseWriter, r *http.Request) {
 		fmt.Fprint(w, `{"tag_name":"v2.7.2","name":"v2.7.2"}`)
 	})
-	u := New(t.TempDir(), "owner/netpulse", "", "2.7.2")
+	u := New(t.TempDir(), "owner/netpulse", "", "2.7.2", nil)
 	st := u.Check(context.Background())
 	if st.UpdateAvailable {
 		t.Fatal("no debería haber update (misma versión)")
@@ -213,7 +213,7 @@ func TestStableModeNoUpdateWhenOlder(t *testing.T) {
 	withAPI(t, func(w http.ResponseWriter, r *http.Request) {
 		fmt.Fprint(w, `{"tag_name":"v2.7.0","name":"v2.7.0"}`)
 	})
-	u := New(t.TempDir(), "owner/netpulse", "", "2.7.2")
+	u := New(t.TempDir(), "owner/netpulse", "", "2.7.2", nil)
 	st := u.Check(context.Background())
 	if st.UpdateAvailable {
 		t.Fatal("no debería haber update (2.7.0 < 2.7.2)")
@@ -246,14 +246,14 @@ func TestCompareSemver(t *testing.T) {
 
 func TestCanApplyDetection(t *testing.T) {
 	// Sin deploy/update.sh → stable, !canApply
-	u1 := New(t.TempDir(), "owner/netpulse", "", "1.0.0")
+	u1 := New(t.TempDir(), "owner/netpulse", "", "1.0.0", nil)
 	if u1.CanApply() || u1.mode != "stable" {
 		t.Fatal("sin deploy/update.sh debería ser stable/!canApply")
 	}
 	// Con deploy/update.sh → rolling, canApply
 	root := t.TempDir()
 	writeDeployScript(t, root)
-	u2 := New(root, "owner/netpulse", "", "1.0.0")
+	u2 := New(root, "owner/netpulse", "", "1.0.0", nil)
 	if !u2.CanApply() || u2.mode != "rolling" {
 		t.Fatal("con deploy/update.sh debería ser rolling/canApply")
 	}