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

fix(update): detect layout, compare release tags in stable installs (#61) (#82)

The updater always compared against the main branch (rolling), so in
install.sh single-binary installs (stable releases) the banner appeared
permanently (main is always ahead) and the Update button never worked:
no deploy/update.sh to copy, no permissions to swap the binary in
/usr/local/bin, and the handler conflated 'already_updating' with
'update_copy_failed' into the same 409.

Layout detection: at construction the updater checks whether
deploy/update.sh exists alongside repoRoot. If it does, mode='rolling'
(git layout: compares against main HEAD, can self-apply via update.sh).
If not, mode='stable' (install.sh layout: compares against the latest
release tag via semver, cannot self-apply).

Backend changes:
- Updater.New takes a version arg (httpapi.Version) for stable comparison
- fetchLatest split into fetchLatestCommit (rolling) and fetchLatestRelease
  (stable, queries /releases/latest)
- compareSemver/parseSemver for tag-vs-version comparison (strips 'v'
  prefix and pre-release suffixes)
- Status exposes canApply and mode
- CanApply() method; handler returns 'update_unavailable' (not
  'already_updating') when the layout can't self-apply

Frontend changes:
- UpdateBanner and UpdateCheckInline show a 'View on GitHub' link instead
  of a dead Update button when canApply is false
- New i18n keys: update.getRelease, update.stableHint (es+en)

Tests: 5 new (stable comparison up/same/older, semver unit, canApply
detection). Existing tests updated for the 4th arg and rolling-mode setup.

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

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

@@ -789,6 +789,8 @@
   "update": {
     "available": "New version available: {{version}} — {{msg}}",
     "button": "Update",
+    "getRelease": "View on GitHub",
+    "stableHint": "Stable install: re-run install.sh to update",
     "updating": "Updating… {{step}}",
     "dismiss": "Dismiss notice",
     "step": {

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

@@ -790,6 +790,8 @@
   "update": {
     "available": "Nueva versión disponible: {{version}} — {{msg}}",
     "button": "Actualizar",
+    "getRelease": "Ver en GitHub",
+    "stableHint": "Instalación estable: re-ejecuta install.sh para actualizar",
     "updating": "Actualizando… {{step}}",
     "dismiss": "Descartar aviso",
     "step": {

+ 25 - 9
app/src/components/UpdateBanner.tsx

@@ -7,7 +7,7 @@
 import { useCallback, useEffect, useRef, useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { motion, AnimatePresence, useReducedMotion } from 'framer-motion'
-import { DownloadCloud, Loader2, X } from 'lucide-react'
+import { DownloadCloud, ExternalLink, Loader2, X } from 'lucide-react'
 import { useAuth } from '@/data/AuthContext'
 
 interface UpdateStatus {
@@ -15,6 +15,9 @@ interface UpdateStatus {
   latest: string | null
   latestMsg: string | null
   updateAvailable: boolean
+  canApply: boolean
+  mode: string
+  repo: string
   updating: false | { step: string }
   hasToken: boolean
 }
@@ -154,14 +157,27 @@ export function UpdateBanner() {
         </p>
         {!updating ? (
           <>
-            <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"
-            >
-              <DownloadCloud className="h-3.5 w-3.5" strokeWidth={2} />
-              {t('update.button')}
-            </button>
+            {status.canApply ? (
+              <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"
+              >
+                <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={() => status.latest && setDismissed(status.latest)}

+ 24 - 9
app/src/pages/Settings.tsx

@@ -10,6 +10,7 @@ import {
   ChevronDown,
   Copy,
   Download,
+  ExternalLink,
   FileText,
   FlaskConical,
   Github,
@@ -1525,6 +1526,8 @@ interface NetPulseUpdateStatus {
   latest: string | null
   latestMsg: string | null
   updateAvailable: boolean
+  canApply: boolean
+  repo: string
   updating: false | { step: string }
 }
 
@@ -1562,15 +1565,27 @@ function UpdateCheckInline() {
   return (
     <div className="flex flex-col gap-1">
       {status?.updateAvailable && status.latest ? (
-        <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"
-        >
-          <Download className="h-4 w-4 shrink-0" strokeWidth={1.75} aria-hidden="true" />
-          <span className="hidden sm:inline">{t('update.button')}</span>
-        </button>
+        status.canApply ? (
+          <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"
+          >
+            <Download className="h-4 w-4 shrink-0" strokeWidth={1.75} aria-hidden="true" />
+            <span className="hidden sm:inline">{t('update.button')}</span>
+          </button>
+        ) : (
+          <a
+            href={`https://github.com/${status.repo || 'gnacho/netpulse'}/releases`}
+            target="_blank"
+            rel="noreferrer"
+            className="inline-flex h-9 shrink-0 items-center gap-1.5 rounded-xl border border-border bg-elevated px-3 text-[13px] font-medium text-text-primary transition-colors hover:bg-hover"
+          >
+            <ExternalLink className="h-4 w-4 shrink-0" strokeWidth={1.75} aria-hidden="true" />
+            <span className="hidden sm:inline">{t('update.getRelease')}</span>
+          </a>
+        )
       ) : (
         <button
           type="button"

+ 4 - 2
server-go/cmd/netpulse/main.go

@@ -232,8 +232,10 @@ func run() error {
 	}
 	static := staticspa.New(staticDir)
 
-	// Actualizador: repoRoot = padre de serverRoot (paridad index.js:49-53)
-	upd := updater.New(filepath.Clean(filepath.Join(cfg.ServerRoot, "..")), cfg.GithubRepo, cfg.GithubToken)
+	// 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)
 
 	// Rearmer compartido (endpoint manual + supervisor de auto-rearme).
 	// El supervisor solo arranca con NETPULSE_AUTO_REARM=1 y en modo live

+ 7 - 2
server-go/internal/httpapi/update.go

@@ -26,9 +26,14 @@ func (s *server) registerUpdateRoutes(mux *http.ServeMux, u *updater.Updater) {
 		writeJSON(w, http.StatusOK, u.Check(ctx))
 	})))
 	mux.Handle("POST /api/update/apply", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		if !u.CanApply() {
+			// Layout install.sh (single-binary): sin deploy/update.sh ni
+			// permisos para swap del binario. El usuario debe re-ejecutar
+			// install.sh (la vía documentada para estables).
+			writeError(w, http.StatusConflict, "update_unavailable")
+			return
+		}
 		if !u.Apply() {
-			// already_updating (o update_copy_failed: mismo 409 que el JS,
-			// que solo devuelve false en ambos casos)
 			writeError(w, http.StatusConflict, "already_updating")
 			return
 		}

+ 136 - 13
server-go/internal/updater/updater.go

@@ -15,6 +15,7 @@ import (
 	"os/exec"
 	"path/filepath"
 	"regexp"
+	"strconv"
 	"strings"
 	"sync"
 	"time"
@@ -46,6 +47,8 @@ type Status struct {
 	Latest          *string `json:"latest"`
 	LatestMsg       *string `json:"latestMsg"`
 	UpdateAvailable bool    `json:"updateAvailable"`
+	CanApply        bool    `json:"canApply"`
+	Mode            string  `json:"mode"`
 	LastCheck       *int64  `json:"lastCheck"`
 	Updating        any     `json:"updating"` // false | {"step": ...}
 	Error           *string `json:"error"`
@@ -59,6 +62,9 @@ type Updater struct {
 	repoRoot string
 	repo     string
 	token    string
+	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)
 
 	mu           sync.Mutex
 	current      string
@@ -75,17 +81,38 @@ type Updater struct {
 	wg     sync.WaitGroup
 }
 
-// New crea el updater (repoRoot = padre de serverRoot, como index.js).
-func New(repoRoot, repo, token string) *Updater {
+// New crea el updater. version es el semver embebido (httpapi.Version) usado
+// para comparar contra el último release tag en modo estable. La detección de
+// 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 {
+	canApply := fileExists(filepath.Join(repoRoot, "deploy", "update.sh"))
+	mode := "stable"
+	if canApply {
+		mode = "rolling"
+	}
 	return &Updater{
 		repoRoot: repoRoot,
 		repo:     repo,
 		token:    token,
+		version:  version,
+		canApply: canApply,
+		mode:     mode,
 		current:  "desconocido",
 		stopCh:   make(chan struct{}),
 	}
 }
 
+// CanApply indica si el updater puede auto-aplicar en este layout.
+func (u *Updater) CanApply() bool { return u.canApply }
+
+func fileExists(path string) bool {
+	_, err := os.Stat(path)
+	return err == nil
+}
+
 func gitShort(repoRoot string) string {
 	if BuildCommit != "" {
 		return BuildCommit
@@ -97,8 +124,9 @@ func gitShort(repoRoot string) string {
 	return strings.TrimSpace(string(out))
 }
 
-// fetchLatest consulta el último commit de main (errores → {error: ...}).
-func (u *Updater) fetchLatest(ctx context.Context) (sha, msg string, errCode string) {
+// fetchLatestCommit consulta el último commit de main (modo rolling).
+// Errores → {error: ...}.
+func (u *Updater) fetchLatestCommit(ctx context.Context) (sha, msg string, errCode string) {
 	req, err := http.NewRequestWithContext(ctx, "GET",
 		fmt.Sprintf("%s/repos/%s/commits/main", APIBase, u.repo), nil)
 	if err != nil {
@@ -160,13 +188,102 @@ func (u *Updater) fetchLatest(ctx context.Context) (sha, msg string, errCode str
 	return sha, msg, ""
 }
 
-// Check fuerza un chequeo contra GitHub y devuelve el estado.
+// fetchLatestRelease consulta el último release tag (modo stable). Devuelve
+// tag_name (ej. "v2.7.3") y el nombre del release. Errores → {error: ...}.
+func (u *Updater) fetchLatestRelease(ctx context.Context) (tag, name string, errCode string) {
+	req, err := http.NewRequestWithContext(ctx, "GET",
+		fmt.Sprintf("%s/repos/%s/releases/latest", APIBase, u.repo), nil)
+	if err != nil {
+		return "", "", "network"
+	}
+	req.Header.Set("Accept", "application/vnd.github+json")
+	req.Header.Set("User-Agent", "netpulse-updater")
+	req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
+	if u.token != "" {
+		req.Header.Set("Authorization", "Bearer "+u.token)
+	}
+	client := &http.Client{Timeout: httpTimeout}
+	res, err := client.Do(req)
+	if err != nil {
+		if ctx.Err() != nil {
+			return "", "", "timeout"
+		}
+		return "", "", "network"
+	}
+	defer res.Body.Close()
+	if res.StatusCode == 401 || res.StatusCode == 403 || res.StatusCode == 404 {
+		if u.token != "" {
+			return "", "", fmt.Sprintf("github_%d", res.StatusCode)
+		}
+		return "", "", "no_token"
+	}
+	if res.StatusCode != 200 {
+		return "", "", fmt.Sprintf("github_%d", res.StatusCode)
+	}
+	var data struct {
+		TagName string `json:"tag_name"`
+		Name    string `json:"name"`
+	}
+	if err := json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&data); err != nil {
+		return "", "", "network"
+	}
+	tag = data.TagName
+	name = data.Name
+	if name == "" {
+		name = tag
+	}
+	return tag, name, ""
+}
+
+// compareSemver compara dos strings semver (con o sin prefijo "v").
+// Devuelve >0 si a > b, 0 si iguales, <0 si a < b. No-parseable → 0.
+func compareSemver(a, b string) int {
+	av := parseSemver(a)
+	bv := parseSemver(b)
+	for i := 0; i < 3; i++ {
+		if av[i] != bv[i] {
+			return av[i] - bv[i]
+		}
+	}
+	return 0
+}
+
+func parseSemver(s string) [3]int {
+	s = strings.TrimPrefix(s, "v")
+	parts := strings.SplitN(s, ".", 3)
+	var out [3]int
+	for i := 0; i < len(parts) && i < 3; i++ {
+		p := parts[i]
+		// descartar sufijos pre-release/build (-rc1, +build, etc.)
+		if idx := strings.IndexAny(p, "-+"); idx >= 0 {
+			p = p[:idx]
+		}
+		n, _ := strconv.Atoi(p)
+		out[i] = n
+	}
+	return out
+}
+
+// Check fuerza un chequeo contra GitHub y devuelve el estado. En modo
+// rolling compara contra el último commit de main; en modo estable contra
+// el último release tag (semver).
 func (u *Updater) Check(ctx context.Context) Status {
-	current := gitShort(u.repoRoot)
-	if current == "" {
-		current = "desconocido"
+	var current, latest, latestMsg, errCode string
+
+	if u.mode == "stable" {
+		current = u.version
+		if current == "" {
+			current = "desconocido"
+		}
+		latest, latestMsg, errCode = u.fetchLatestRelease(ctx)
+	} else {
+		current = gitShort(u.repoRoot)
+		if current == "" {
+			current = "desconocido"
+		}
+		latest, latestMsg, errCode = u.fetchLatestCommit(ctx)
 	}
-	sha, msg, errCode := u.fetchLatest(ctx)
+
 	now := time.Now().UnixMilli()
 
 	u.mu.Lock()
@@ -178,11 +295,15 @@ func (u *Updater) Check(ctx context.Context) Status {
 		return u.statusLocked()
 	}
 	u.err = nil
-	u.latest = &sha
-	u.latestMsg = &msg
-	u.updateAvail = sha != "" && current != "desconocido" && sha != current
+	u.latest = &latest
+	u.latestMsg = &latestMsg
+	if u.mode == "stable" {
+		u.updateAvail = latest != "" && current != "desconocido" && compareSemver(latest, current) > 0
+	} else {
+		u.updateAvail = latest != "" && current != "desconocido" && latest != current
+	}
 	if u.updateAvail {
-		fmt.Printf("[netpulse] nueva versión disponible: %s → %s (%s)\n", current, sha, msg)
+		fmt.Printf("[netpulse] nueva versión disponible: %s → %s (%s)\n", current, latest, latestMsg)
 	}
 	return u.statusLocked()
 }
@@ -326,6 +447,8 @@ func (u *Updater) statusLocked() Status {
 		Latest:          u.latest,
 		LatestMsg:       u.latestMsg,
 		UpdateAvailable: u.updateAvail,
+		CanApply:        u.canApply,
+		Mode:            u.mode,
 		LastCheck:       u.lastCheck,
 		Updating:        updating,
 		Error:           u.err,

+ 117 - 5
server-go/internal/updater/updater_test.go

@@ -34,10 +34,12 @@ func TestCheckUpdateAvailable(t *testing.T) {
 		w.Header().Set("Content-Type", "application/json")
 		fmt.Fprint(w, `{"sha":"abc1234deadbeef","commit":{"message":"feat: algo\n\nbody"}}`)
 	})
-	// repoRoot con git válido (commit distinto) para updateAvailable
+	// repoRoot con git válido (commit distinto) para updateAvailable.
+	// deploy/update.sh → modo rolling (compara contra main HEAD).
 	root := t.TempDir()
+	writeDeployScript(t, root)
 	writeGitHead(t, root)
-	u := New(root, "owner/netpulse", "")
+	u := New(root, "owner/netpulse", "", "2.0.0")
 	st := u.Check(context.Background())
 	if st.Error != nil {
 		t.Fatalf("error: %v", *st.Error)
@@ -51,6 +53,9 @@ func TestCheckUpdateAvailable(t *testing.T) {
 	if !st.UpdateAvailable {
 		t.Fatalf("debería haber update: %+v", st)
 	}
+	if !st.CanApply || st.Mode != "rolling" {
+		t.Fatalf("debería ser rolling/canApply: canApply=%v mode=%s", st.CanApply, st.Mode)
+	}
 	if st.Updating != false || st.HasToken || st.Repo != "owner/netpulse" {
 		t.Fatalf("shape: %+v", st)
 	}
@@ -63,20 +68,26 @@ func TestCheckNoToken(t *testing.T) {
 	withAPI(t, func(w http.ResponseWriter, r *http.Request) {
 		w.WriteHeader(http.StatusNotFound)
 	})
-	u := New(t.TempDir(), "owner/netpulse", "")
+	// 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")
 	st := u.Check(context.Background())
 	if st.Error == nil || *st.Error != "no_token" {
 		t.Fatalf("error: %v", st.Error)
 	}
+	if st.CanApply || st.Mode != "stable" {
+		t.Fatalf("debería ser stable/!canApply: canApply=%v mode=%s", st.CanApply, st.Mode)
+	}
 }
 
 func TestCheckMismaVersion(t *testing.T) {
 	root := t.TempDir()
+	writeDeployScript(t, root) // modo rolling
 	short := writeGitHead(t, root)
 	withAPI(t, func(w http.ResponseWriter, r *http.Request) {
 		fmt.Fprintf(w, `{"sha":"%sffffffffff","commit":{"message":"x"}}`, short)
 	})
-	u := New(root, "owner/netpulse", "")
+	u := New(root, "owner/netpulse", "", "2.0.0")
 	st := u.Check(context.Background())
 	if st.UpdateAvailable {
 		t.Fatal("no debería haber update")
@@ -110,6 +121,18 @@ func writeGitHead(t *testing.T, root string) string {
 	return strings.TrimSpace(string(out))
 }
 
+// writeDeployScript crea deploy/update.sh en root (marca el layout como
+// git/rolling: el updater detecta que puede auto-aplicar).
+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)
+	}
+}
+
 func TestApplyYaEnCursoYScript(t *testing.T) {
 	if !gitAvailable() {
 		t.Skip("git no disponible")
@@ -122,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", "")
+	u := New(root, "owner/netpulse", "", "2.0.0")
 	if !u.Apply() {
 		t.Fatal("apply debería arrancar")
 	}
@@ -146,3 +169,92 @@ func TestApplyYaEnCursoYScript(t *testing.T) {
 		t.Fatalf("lastLog: %+v", st)
 	}
 }
+
+func TestStableModeUpdateAvailable(t *testing.T) {
+	withAPI(t, func(w http.ResponseWriter, r *http.Request) {
+		if r.URL.Path != "/repos/owner/netpulse/releases/latest" {
+			t.Errorf("path: %s (modo estable debe consultar releases/latest)", r.URL.Path)
+		}
+		w.Header().Set("Content-Type", "application/json")
+		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")
+	st := u.Check(context.Background())
+	if st.Error != nil {
+		t.Fatalf("error: %v", *st.Error)
+	}
+	if !st.UpdateAvailable {
+		t.Fatal("debería haber update (2.7.2 < 2.7.3)")
+	}
+	if st.Latest == nil || *st.Latest != "v2.7.3" {
+		t.Fatalf("latest: %v", st.Latest)
+	}
+	if st.Current != "2.7.2" {
+		t.Fatalf("current: %s", st.Current)
+	}
+	if st.CanApply || st.Mode != "stable" {
+		t.Fatalf("debería ser stable/!canApply: canApply=%v mode=%s", st.CanApply, st.Mode)
+	}
+}
+
+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")
+	st := u.Check(context.Background())
+	if st.UpdateAvailable {
+		t.Fatal("no debería haber update (misma versión)")
+	}
+}
+
+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")
+	st := u.Check(context.Background())
+	if st.UpdateAvailable {
+		t.Fatal("no debería haber update (2.7.0 < 2.7.2)")
+	}
+}
+
+func TestCompareSemver(t *testing.T) {
+	cases := []struct {
+		a, b string
+		want int
+	}{
+		{"2.7.2", "2.7.2", 0},
+		{"v2.7.2", "2.7.2", 0},
+		{"v2.7.3", "v2.7.2", 1},
+		{"2.8.0", "2.7.9", 1},
+		{"3.0.0", "2.9.9", 1},
+		{"2.7.1", "2.7.2", -1},
+		{"2.6.9", "2.7.0", -1},
+		{"v2.7.2-rc1", "v2.7.2", 0}, // pre-release suffix descartado
+		{"1.0.0", "1.0", 0},         // minor faltante = 0
+	}
+	for _, c := range cases {
+		got := compareSemver(c.a, c.b)
+		// normalizar a -1/0/1 para comparar
+		if (c.want == 0 && got != 0) || (c.want > 0 && got <= 0) || (c.want < 0 && got >= 0) {
+			t.Errorf("compareSemver(%q, %q) = %d, want sign %d", c.a, c.b, got, c.want)
+		}
+	}
+}
+
+func TestCanApplyDetection(t *testing.T) {
+	// Sin deploy/update.sh → stable, !canApply
+	u1 := New(t.TempDir(), "owner/netpulse", "", "1.0.0")
+	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")
+	if !u2.CanApply() || u2.mode != "rolling" {
+		t.Fatal("con deploy/update.sh debería ser rolling/canApply")
+	}
+}