Przeglądaj źródła

fix(orchestr): drop NetGrip apply delegation (#1595)

Apply and rollback only use the agent apply command over SSE, with conditional transitions and a restore when delivery fails. MQTT propagation now creates one real plan per router, redacts the broker password in the stored plan and reports queued instead of applied.

Closes #1591
Nacho 1 miesiąc temu
rodzic
commit
cdf0eba4c7

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

@@ -1979,6 +1979,8 @@
       "test": "Test connection",
       "propagate": "Propagate to NetGrip",
       "propagateEmpty": "There are no NetGrip routers in the fleet to propagate to.",
+      "propagatePending": "sent, awaiting confirmation",
+      "propagateHint": "Sent is not applied: the plan closes when the agent reports the result. The real state is shown in Orchestration.",
       "running": "publishing",
       "notRunning": "stopped"
     },

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

@@ -1979,6 +1979,8 @@
       "test": "Probar conexión",
       "propagate": "Propagar a NetGrip",
       "propagateEmpty": "No hay routers NetGrip en la flota a los que propagar.",
+      "propagatePending": "enviado, pendiente de confirmación",
+      "propagateHint": "Enviado no es aplicado: el plan se cierra cuando el agente reporta el resultado. El estado real se ve en Orquestación.",
       "running": "publicando",
       "notRunning": "detenido"
     },

+ 29 - 15
app/src/components/MqttCard.tsx

@@ -1,6 +1,6 @@
 import { useState, useEffect, useCallback } from 'react'
 import { useTranslation } from 'react-i18next'
-import { Send, Loader2, Check, Eye, EyeOff, Radio, Share2 } from 'lucide-react'
+import { Send, Loader2, Check, Clock, Eye, EyeOff, Radio, Share2 } from 'lucide-react'
 import { Switch } from '@/components/ui/switch'
 import { InfoTip } from '@/components/InfoTip'
 
@@ -19,7 +19,14 @@ interface MqttConfig {
 interface PropagateResult {
   id: string
   name: string
-  delegated: boolean
+  // planId: plan real creado para este router en el servidor.
+  planId?: string
+  // queued: el comando quedó ENCOLADO en el agente. No significa aplicado:
+  // el plan se cierra cuando el agente reporta su resultado.
+  queued?: boolean
+  // delegated: alias histórico de queued (servidores antiguos).
+  delegated?: boolean
+  status?: string
   error?: string
 }
 
@@ -281,19 +288,26 @@ export default function MqttCard({ onSaved, bare = true }: { onSaved: () => void
           {results.length === 0 ? (
             <p>{t('settings.mqtt.propagateEmpty')}</p>
           ) : (
-            <ul className="space-y-0.5">
-              {results.map((r) => (
-                <li key={r.id} className="flex items-center gap-1.5">
-                  {r.delegated && !r.error ? (
-                    <Check className="h-3 w-3 text-ok" strokeWidth={2.5} />
-                  ) : (
-                    <span className="text-danger">!</span>
-                  )}
-                  <span>{r.name || r.id}</span>
-                  {r.error ? <span className="text-danger">({r.error})</span> : null}
-                </li>
-              ))}
-            </ul>
+            <>
+              <ul className="space-y-0.5">
+                {results.map((r) => (
+                  <li key={r.id} className="flex items-center gap-1.5">
+                    {r.error ? (
+                      <span className="text-danger">!</span>
+                    ) : (
+                      <Clock className="h-3 w-3 shrink-0 text-text-muted" strokeWidth={2} aria-hidden />
+                    )}
+                    <span>{r.name || r.id}</span>
+                    {r.error ? (
+                      <span className="text-danger">({r.error})</span>
+                    ) : r.queued || r.delegated ? (
+                      <span className="text-text-muted">{t('settings.mqtt.propagatePending')}</span>
+                    ) : null}
+                  </li>
+                ))}
+              </ul>
+              <p className="mt-1 text-text-muted">{t('settings.mqtt.propagateHint')}</p>
+            </>
           )}
         </div>
       )}

+ 1 - 1
docs/manual.en.md

@@ -623,7 +623,7 @@ The temperature, signal and latency thresholds that define health and alerts are
 
 ### Procedure: enable it
 
-The usual way is the **MQTT card in Settings**: turn it on, enter host, port and credentials, test the connection and save; it applies live, without a restart. From the same card you can **propagate the configuration to the NetGrip routers** in the fleet, so you do not configure them one by one.
+The usual way is the **MQTT card in Settings**: turn it on, enter host, port and credentials, test the connection and save; it applies live, without a restart. From the same card you can **propagate the configuration to the NetGrip routers** in the fleet, so you do not configure them one by one. Propagation creates one plan per router and only **queues** it on its agent: the card marks it as awaiting confirmation and the real outcome (applied or failed) shows up in Orchestration when the agent reports it.
 
 The alternative is environment variables (or the UCI options `mqtt_*` with the on-box install):
 

+ 1 - 1
docs/manual.es.md

@@ -623,7 +623,7 @@ Los umbrales de temperatura, señal y latencia que definen la salud y las alerta
 
 ### Procedimiento: activarlo
 
-La forma habitual es la **tarjeta MQTT de Ajustes**: la activas, pones host, puerto y credenciales, pruebas la conexión y guardas; se aplica en caliente, sin reiniciar. Desde esa misma tarjeta puedes **propagar la configuración a los routers NetGrip** de la flota, para no configurarlos uno a uno.
+La forma habitual es la **tarjeta MQTT de Ajustes**: la activas, pones host, puerto y credenciales, pruebas la conexión y guardas; se aplica en caliente, sin reiniciar. Desde esa misma tarjeta puedes **propagar la configuración a los routers NetGrip** de la flota, para no configurarlos uno a uno. La propagación crea un plan por router y al agente solo se le deja **encolado**: la tarjeta lo marca como pendiente de confirmación y el resultado real (aplicado o fallido) se ve en Orquestación cuando el agente lo reporta.
 
 La alternativa son las variables de entorno (o las opciones UCI `mqtt_*` en modo on-box):
 

+ 242 - 0
server-go/internal/httpapi/mqtt_propagate_test.go

@@ -0,0 +1,242 @@
+// mqtt_propagate_test.go — regresión F-06: POST /api/settings/mqtt/propagate
+// entrega la op mqtt.configure a cada router NetGrip por SSE, sin hablar HTTP
+// con sus executors. Cada router recibe un plan REAL (fila en orchestr_plans,
+// marcado applying antes del envío) y la respuesta dice "encolado", nunca
+// "aplicado".
+package httpapi_test
+
+import (
+	"bytes"
+	"encoding/json"
+	"io"
+	"net/http"
+	"strings"
+	"sync/atomic"
+	"testing"
+
+	"github.com/gnacho/netpulse/agent/executor"
+	"github.com/gnacho/netpulse/agent/probe"
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+)
+
+type propagateResult struct {
+	ID        string `json:"id"`
+	Name      string `json:"name"`
+	PlanID    string `json:"planId"`
+	Queued    bool   `json:"queued"`
+	Delegated bool   `json:"delegated"`
+	Status    string `json:"status"`
+	Error     string `json:"error"`
+}
+
+// propagateMQTT llama al endpoint y devuelve los resultados por id más el
+// cuerpo crudo (para comprobar que no se afirma que el plan se aplicó).
+func propagateMQTT(t *testing.T, ts *testServer, cookie string) (map[string]propagateResult, string) {
+	t.Helper()
+	req, _ := http.NewRequest("POST", ts.URL+"/api/settings/mqtt/propagate", nil)
+	req.Header.Set("Cookie", "session="+cookie)
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("propagate: %v", err)
+	}
+	defer res.Body.Close()
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("propagate: esperaba 200, got %d", res.StatusCode)
+	}
+	raw, err := io.ReadAll(res.Body)
+	if err != nil {
+		t.Fatalf("leer respuesta propagate: %v", err)
+	}
+	var body struct {
+		Results []propagateResult `json:"results"`
+	}
+	if err := json.Unmarshal(raw, &body); err != nil {
+		t.Fatalf("respuesta propagate: %v (%s)", err, raw)
+	}
+	out := map[string]propagateResult{}
+	for _, r := range body.Results {
+		if _, dup := out[r.ID]; dup {
+			t.Fatalf("router duplicado en la respuesta: %s", r.ID)
+		}
+		out[r.ID] = r
+	}
+	return out, string(raw)
+}
+
+func TestMQTTPropagateSendsOpsOverSSE(t *testing.T) {
+	ov := &adapters.Overview{Routers: []adapters.Router{
+		{ID: "flint2", Name: "Flint 2"},
+		{ID: "rt2", Name: "RT2"},
+		{ID: "rt1", Name: "RT1"}, // agente nativo: no participa
+	}}
+	ts, reg := newSSEPlanServer(t, ov)
+	netgripMock, hits := countingNetGripMock(t)
+	host := netgripMock.Listener.Addr().String()
+	addPlanRouter(t, ts, "flint2", host, true, "netgrip-secret")
+	addPlanRouter(t, ts, "rt2", host, false, "netgrip-secret")
+	addPlanRouter(t, ts, "rt1", host, false, "netgrip-secret")
+	// flint2 y rt2 con agente conectado; rt1 es nativo y queda fuera.
+	setAgentToken(t, ts, "flint2", "agent-token")
+	setAgentToken(t, ts, "rt2", "agent-token")
+	reg.Ingest(&probe.Payload{Router: "flint2", Kind: "netgrip", Version: "0.77.3"})
+	reg.Ingest(&probe.Payload{Router: "rt2", Kind: "netgrip", Version: "0.77.3"})
+	reg.Ingest(&probe.Payload{Router: "rt1", Kind: "native", Version: "3.0.26"})
+
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	flintEvents := connectAgentStream(t, ts.URL, "flint2")
+	rt2Events := connectAgentStream(t, ts.URL, "rt2")
+
+	results, raw := propagateMQTT(t, ts, cookie)
+
+	if strings.Contains(raw, `"applied"`) {
+		t.Errorf("la propagación solo encola: la respuesta no puede afirmar que se aplicó: %s", raw)
+	}
+	if got := atomic.LoadInt32(hits); got != 0 {
+		t.Fatalf("NetGrip recibió %d peticiones HTTP; la propagación debe ir por SSE", got)
+	}
+	if len(results) != 2 {
+		t.Fatalf("esperaba 2 routers NetGrip en el resultado, got %+v", results)
+	}
+	if _, ok := results["rt1"]; ok {
+		t.Error("rt1 es agente nativo: no debe aparecer en la propagación")
+	}
+
+	// El agente conectado recibe la op mqtt.configure con el broker del server.
+	streams := map[string]<-chan agentEvent{"flint2": flintEvents, "rt2": rt2Events}
+	planIDs := map[string]string{}
+	for id, r := range results {
+		if r.Error != "" {
+			t.Errorf("%s: error inesperado %q", id, r.Error)
+		}
+		if !r.Queued || !r.Delegated {
+			t.Errorf("%s: se entregó al agente, esperaba queued/delegated true, got %+v", id, r)
+		}
+		// La respuesta habla de encolado, no de aplicación.
+		if r.Status != "queued" {
+			t.Errorf("%s: estado esperado queued, got %+v", id, r)
+		}
+		if r.PlanID == "" {
+			t.Fatalf("%s: la respuesta debe llevar el planId real", id)
+		}
+		planIDs[id] = r.PlanID
+
+		// El plan existe de verdad y está en curso (applying), no inventado.
+		p := readPlan(t, ts, r.PlanID)
+		if p.Status != "applying" {
+			t.Errorf("%s: el plan debe quedar applying, got %s", id, p.Status)
+		}
+		if p.Resource != "mqtt" {
+			t.Errorf("%s: recurso del plan: got %q, want mqtt", id, p.Resource)
+		}
+		if p.CreatedBy != "admin" {
+			t.Errorf("%s: createdBy del plan: got %q, want admin", id, p.CreatedBy)
+		}
+		if !bytes.Contains([]byte(p.Diff), []byte("mqtt.configure")) {
+			t.Errorf("%s: el diff persistido no lleva la op mqtt.configure: %s", id, p.Diff)
+		}
+		if !bytes.Contains([]byte(p.Desired), []byte("broker.test")) {
+			t.Errorf("%s: el desired persistido no lleva el broker: %s", id, p.Desired)
+		}
+		// La contraseña del broker no se duplica en la tabla de planes.
+		if bytes.Contains([]byte(p.Diff), []byte("broker-pass")) ||
+			bytes.Contains([]byte(p.Desired), []byte("broker-pass")) {
+			t.Errorf("%s: la contraseña del broker no debe persistirse en el plan", id)
+		}
+
+		ev := waitAgentEvent(t, streams[id], "apply")
+		var payload struct {
+			PlanID string        `json:"plan_id"`
+			Ops    []executor.Op `json:"ops"`
+		}
+		if err := json.Unmarshal([]byte(ev.data), &payload); err != nil {
+			t.Fatalf("%s: payload SSE apply inválido (%q): %v", id, ev.data, err)
+		}
+		if payload.PlanID != r.PlanID {
+			t.Errorf("%s: plan_id SSE got %q, want %q", id, payload.PlanID, r.PlanID)
+		}
+		if len(payload.Ops) != 1 || payload.Ops[0].Kind != "mqtt.configure" {
+			t.Fatalf("%s: ops SSE: %+v", id, payload.Ops)
+		}
+		if got := payload.Ops[0].Args["host"]; got != "broker.test" {
+			t.Errorf("%s: broker en la op: got %q, want broker.test", id, got)
+		}
+		// El secreto viaja al agente (por el canal autenticado), aunque no se
+		// guarde en el plan.
+		if got := payload.Ops[0].Args["pass"]; got != "broker-pass" {
+			t.Errorf("%s: la op enviada debe llevar la contraseña real, got %q", id, got)
+		}
+	}
+	if planIDs["flint2"] == planIDs["rt2"] {
+		t.Fatalf("cada router necesita su propio plan, ambos comparten %q", planIDs["flint2"])
+	}
+
+	// El agente confirma: el plan de ese router pasa a applied.
+	if code, raw := postApplyResult(t, ts.URL, "flint2", "agent-token", planIDs["flint2"],
+		executor.ApplyResult{Status: "applied"}); code != http.StatusOK {
+		t.Fatalf("apply-result: esperaba 200, got %d: %s", code, raw)
+	}
+	if got := planStatus(t, ts, planIDs["flint2"]); got != "applied" {
+		t.Fatalf("el plan confirmado por el agente debe quedar applied, got %s", got)
+	}
+}
+
+// TestMQTTPropagateWithoutAgentIsHonest: sin agente conectado no se simula
+// éxito: la respuesta lo dice y el plan no queda en curso.
+func TestMQTTPropagateWithoutAgentIsHonest(t *testing.T) {
+	ov := &adapters.Overview{Routers: []adapters.Router{{ID: "flint2", Name: "Flint 2"}}}
+	ts, reg := newSSEPlanServer(t, ov)
+	addPlanRouter(t, ts, "flint2", "192.0.2.10", true, "")
+	reg.Ingest(&probe.Payload{Router: "flint2", Kind: "netgrip", Version: "0.77.3"})
+
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	results, _ := propagateMQTT(t, ts, cookie)
+
+	r, ok := results["flint2"]
+	if !ok {
+		t.Fatalf("falta flint2 en la respuesta: %+v", results)
+	}
+	if r.Queued || r.Delegated || r.Status == "queued" {
+		t.Errorf("sin agente conectado no se puede afirmar que se encoló: %+v", r)
+	}
+	if r.Error != "agent_not_connected" {
+		t.Errorf("error esperado agent_not_connected, got %+v", r)
+	}
+	if r.PlanID == "" {
+		t.Fatal("la respuesta debe identificar el plan creado para el intento")
+	}
+	if got := planStatus(t, ts, r.PlanID); got != "pending" {
+		t.Errorf("un envío fallido no puede dejar el plan en curso, got %s", got)
+	}
+}
+
+// TestMQTTPropagateDoesNotPersistBrokerPassword revisa la copia persistida
+// del plan: el secreto viaja por SSE, no se guarda en orchestr_plans.
+func TestMQTTPropagateDoesNotPersistBrokerPassword(t *testing.T) {
+	ov := &adapters.Overview{Routers: []adapters.Router{{ID: "flint2", Name: "Flint 2"}}}
+	ts, reg := newSSEPlanServer(t, ov)
+	addPlanRouter(t, ts, "flint2", "192.0.2.10", true, "")
+	reg.Ingest(&probe.Payload{Router: "flint2", Kind: "netgrip", Version: "0.77.3"})
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	connectAgentStream(t, ts.URL, "flint2")
+
+	results, _ := propagateMQTT(t, ts, cookie)
+	r := results["flint2"]
+	if r.PlanID == "" {
+		t.Fatalf("sin planId en la respuesta: %+v", r)
+	}
+
+	// La fila completa, tal cual queda en la base de datos.
+	var desired, diff, result string
+	if err := ts.db.QueryRow(
+		`SELECT desired, diff, COALESCE(result, '') FROM orchestr_plans WHERE id = ?`,
+		r.PlanID).Scan(&desired, &diff, &result); err != nil {
+		t.Fatalf("select plan: %v", err)
+	}
+	blob := strings.Join([]string{desired, diff, result}, "\n")
+	if strings.Contains(blob, "broker-pass") {
+		t.Fatalf("la contraseña del broker quedó persistida en el plan:\n%s", blob)
+	}
+	if !strings.Contains(diff, "mqtt.configure") {
+		t.Errorf("el plan debe registrar la op enviada: %s", diff)
+	}
+}

+ 80 - 7
server-go/internal/httpapi/mqtt_settings.go

@@ -4,6 +4,8 @@
 package httpapi
 
 import (
+	"encoding/json"
+	"log"
 	"net/http"
 	"strconv"
 	"time"
@@ -11,8 +13,14 @@ import (
 	"github.com/gnacho/netpulse/agent/executor"
 	"github.com/gnacho/netpulse/server-go/internal/auth"
 	"github.com/gnacho/netpulse/server-go/internal/mqttpub"
+	"github.com/gnacho/netpulse/server-go/internal/orchestr"
 )
 
+// mqttRedactedPass sustituye la contraseña del broker en la copia del plan que
+// se persiste: el secreto viaja al agente por el canal autenticado (SSE), pero
+// no se duplica en orchestr_plans ni en el historial de auditoría.
+const mqttRedactedPass = "<redacted>"
+
 type mqttConfigResponse struct {
 	Enabled     bool   `json:"enabled"`
 	Host        string `json:"host"`
@@ -24,7 +32,7 @@ type mqttConfigResponse struct {
 	Running     bool   `json:"running"`
 }
 
-func (s *server) registerMQTTRoutes(mux *http.ServeMux, mgr *mqttpub.Manager) {
+func (s *server) registerMQTTRoutes(mux *http.ServeMux, mgr *mqttpub.Manager, orchMgr *orchestr.Manager) {
 	adapter := &dbKVAdapter{db: s.db.DB}
 
 	mux.Handle("GET /api/settings/mqtt", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -124,12 +132,21 @@ func (s *server) registerMQTTRoutes(mux *http.ServeMux, mgr *mqttpub.Manager) {
 	})))
 
 	// propagate envía la configuración del broker a cada router NetGrip de la
-	// flota (op mqtt.configure vía su executor), para no configurarlos a mano.
+	// flota (op mqtt.configure) por SSE, al agente embebido en su NetGrip.
+	//
+	// Cada router recibe un plan REAL (fila en orchestr_plans, marcado
+	// applying antes del envío) y se identifica en la respuesta con su planId.
+	// La respuesta solo afirma que el comando quedó ENCOLADO en el agente: el
+	// resultado real llega después por POST /api/agents/{slug}/apply-result.
 	mux.Handle("POST /api/settings/mqtt/propagate", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		if mgr == nil {
 			writeError(w, http.StatusServiceUnavailable, "mqtt_unavailable")
 			return
 		}
+		if orchMgr == nil {
+			writeError(w, http.StatusServiceUnavailable, "orchestr_unavailable")
+			return
+		}
 		cfg := mgr.Config()
 		if !cfg.Enabled {
 			writeError(w, http.StatusBadRequest, "mqtt_disabled", "MQTT está desactivado en este servidor")
@@ -140,6 +157,15 @@ func (s *server) registerMQTTRoutes(mux *http.ServeMux, mgr *mqttpub.Manager) {
 			writeError(w, http.StatusServiceUnavailable, "no_overview")
 			return
 		}
+		if s.agentHub == nil {
+			writeError(w, http.StatusServiceUnavailable, "no_agent_hub")
+			return
+		}
+		actor := ""
+		if user := auth.UserFromContext(r.Context()); user != nil {
+			actor = user.Username
+		}
+		intervalSec := int(cfg.Interval.Seconds())
 		op := executor.Op{
 			Kind: "mqtt.configure",
 			Args: map[string]string{
@@ -148,21 +174,68 @@ func (s *server) registerMQTTRoutes(mux *http.ServeMux, mgr *mqttpub.Manager) {
 				"port":     strconv.Itoa(cfg.Port),
 				"user":     cfg.User,
 				"pass":     cfg.Pass,
-				"interval": strconv.Itoa(int(cfg.Interval.Seconds())),
+				"interval": strconv.Itoa(intervalSec),
 			},
 			Desc: "MQTT: aplicar el broker de NetPulse",
 		}
-		planID := "mqtt-propagate-" + strconv.FormatInt(time.Now().Unix(), 10)
+		// Copia persistida del op: el secreto se redacta (el agente recibe el
+		// valor real por el stream autenticado).
+		opPersisted := op
+		opPersisted.Args = map[string]string{}
+		for k, v := range op.Args {
+			opPersisted.Args[k] = v
+		}
+		if cfg.Pass != "" {
+			opPersisted.Args["pass"] = mqttRedactedPass
+		}
+		// Estado deseado persistido: la configuración del broker sin secreto.
+		desiredJSON, _ := json.Marshal(map[string]any{
+			"enabled":     true,
+			"host":        cfg.Host,
+			"port":        cfg.Port,
+			"user":        cfg.User,
+			"instance":    cfg.Instance,
+			"intervalSec": intervalSec,
+			"passSet":     cfg.Pass != "",
+		})
+
 		results := []map[string]any{}
 		for _, rt := range ov.Routers {
 			if s.agentKindOf(rt.ID) != "netgrip" {
 				continue
 			}
-			ok, err := s.applyViaNetGrip(rt.ID, planID, []executor.Op{op})
-			res := map[string]any{"id": rt.ID, "name": rt.Name, "delegated": ok}
+			res := map[string]any{
+				"id": rt.ID, "name": rt.Name,
+				"queued": false, "delegated": false, "status": "not_queued",
+			}
+			plan, err := orchMgr.CreatePlan(rt.ID, "mqtt", desiredJSON, []executor.Op{opPersisted}, actor)
 			if err != nil {
-				res["error"] = err.Error()
+				log.Printf("[netpulse] mqtt propagate: no se pudo crear el plan de %s: %v", rt.ID, err)
+				res["error"] = "plan_error"
+				results = append(results, res)
+				continue
+			}
+			res["planId"] = plan.ID
+			// El estado se fija ANTES de enviar: si el agente responde al
+			// instante, su resultado encuentra el plan en applying.
+			if err := orchMgr.SetApplying(plan.ID, actor); err != nil {
+				log.Printf("[netpulse] mqtt propagate: no se pudo marcar applying el plan %s: %v", plan.ID, err)
+				res["error"] = "plan_error"
+				results = append(results, res)
+				continue
+			}
+			data, _ := json.Marshal(map[string]any{"plan_id": plan.ID, "ops": []executor.Op{op}})
+			if !s.agentHub.Send(rt.ID, "apply", json.RawMessage(data)) {
+				// No se entregó: el plan vuelve a pending (no se simula éxito).
+				s.restorePlan(orchMgr, plan.ID, "applying", "pending", actor, "sse delivery failed")
+				res["error"] = "agent_not_connected"
+				results = append(results, res)
+				continue
 			}
+			res["queued"] = true
+			// delegated: alias histórico de queued (compatibilidad de campo).
+			res["delegated"] = true
+			res["status"] = "queued"
 			results = append(results, res)
 		}
 		writeJSON(w, http.StatusOK, map[string]any{"results": results})

+ 63 - 150
server-go/internal/httpapi/orchestr.go

@@ -8,17 +8,11 @@
 package httpapi
 
 import (
-	"bytes"
 	"encoding/json"
 	"errors"
 	"fmt"
-	"io"
 	"log"
-	"net"
 	"net/http"
-	"net/url"
-	"strings"
-	"time"
 
 	"github.com/gnacho/netpulse/agent/executor"
 	"github.com/gnacho/netpulse/server-go/internal/auth"
@@ -146,11 +140,9 @@ func (s *server) registerOrchestrRoutes(mux *http.ServeMux, mgr *orchestr.Manage
 	//
 	// Calcula el "desired inverso" del módulo (p. ej. AdGuard: si el plan era
 	// enabled=true, el inverso es enabled=false), vuelve a sondear el router
-	// (para detectar el escenario actual) y envía las Ops inversas. #397: si el
-	// router tiene executor token de NetGrip, se delegan las Ops inversas a su
-	// API local (snapshot+healthcheck+rollback probados); si NetGrip no está
-	// configurado o no responde, se envían al agente vía SSE como antes. El
-	// resultado SSE llega por POST /api/agents/{slug}/apply-result.
+	// (para detectar el escenario actual) y envía las Ops inversas al agente
+	// por el comando apply (el único que el agente ejecuta). El resultado real
+	// llega por POST /api/agents/{slug}/apply-result.
 	mux.Handle("POST /api/plans/{id}/rollback", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		id := r.PathValue("id")
 		plan, err := mgr.GetPlan(id)
@@ -174,40 +166,42 @@ func (s *server) registerOrchestrRoutes(mux *http.ServeMux, mgr *orchestr.Manage
 			s.writeModuleErr(w, err)
 			return
 		}
+		// Mismo envoltorio de ownership que un apply: las ops inversas tocan
+		// secciones que NetPulse marcó como gestionadas.
+		diff = orchestr.WrapOwnership(diff)
 		user := auth.UserFromContext(r.Context())
 		actor := ""
 		if user != nil {
 			actor = user.Username
 		}
-		// #397: delegar el rollback al executor de NetGrip si está configurado
-		// (mismo criterio que el apply). Éxito → SetRollingBack + SetResult;
-		// la máquina de estados traduce el resultado applied a rolled_back
-		// cuando el estado previo es rolling_back.
-		if ok, ngErr := s.applyViaNetGrip(plan.RouterID, plan.ID, diff); ngErr != nil {
-			writeError(w, http.StatusBadGateway, "netgrip_error", ngErr.Error())
+		if s.agentHub == nil {
+			writeError(w, http.StatusServiceUnavailable, "no_agent_hub")
 			return
-		} else if ok {
-			if err := mgr.SetRollingBack(id, actor); err != nil {
-				log.Printf("[netpulse] error marcando plan rolling_back vía NetGrip: %v", err)
+		}
+		// El agente solo implementa el comando "apply" (payload plan_id +
+		// ops), así que el rollback reutiliza ESE comando con las ops
+		// inversas. El estado rolling_back se fija ANTES de enviar y hace que
+		// SetResult traduzca el resultado applied del agente a rolled_back.
+		if err := mgr.SetRollingBack(id, actor); err != nil {
+			if errors.Is(err, orchestr.ErrPlanNotFound) {
+				writeError(w, http.StatusNotFound, "not_found")
+				return
 			}
-			if err := mgr.SetResult(id, netgripApplyResult()); err != nil {
-				log.Printf("[netpulse] error asentando rollback vía NetGrip: %v", err)
+			if errors.Is(err, orchestr.ErrInvalidTransition) {
+				writeError(w, http.StatusConflict, "plan_not_applied",
+					"El plan cambió de estado antes de revertir")
+				return
 			}
-			writeJSON(w, http.StatusAccepted, map[string]string{"status": "rolling_back", "planId": id})
-			return
-		}
-		if s.agentHub == nil {
-			writeError(w, http.StatusServiceUnavailable, "no_agent_hub")
+			writeError(w, http.StatusInternalServerError, "plan_error")
 			return
 		}
-		applyData, _ := json.Marshal(map[string]any{"plan_id": id, "ops": diff})
-		sent := s.agentHub.Send(plan.RouterID, "rollback", json.RawMessage(applyData))
-		if !sent {
+		cmdData, _ := json.Marshal(map[string]any{"plan_id": id, "ops": diff})
+		if !s.agentHub.Send(plan.RouterID, "apply", json.RawMessage(cmdData)) {
+			s.restorePlan(mgr, id, "rolling_back", "applied", actor, "sse delivery failed")
 			writeError(w, http.StatusServiceUnavailable, "agent_not_connected",
 				"El agente no está conectado vía SSE")
 			return
 		}
-		mgr.SetRollingBack(id, actor)
 		writeJSON(w, http.StatusAccepted, map[string]string{"status": "rolling_back", "planId": id})
 	})))
 
@@ -238,6 +232,11 @@ func (s *server) registerOrchestrRoutes(mux *http.ServeMux, mgr *orchestr.Manage
 			return
 		}
 		if err := mgr.SetResult(body.PlanID, body.Result); err != nil {
+			if errors.Is(err, orchestr.ErrPlanNotFound) {
+				// Un plan que no existe no se arregla reintentando: 404, no 500.
+				writeError(w, http.StatusNotFound, "not_found", "El plan no existe en este servidor")
+				return
+			}
 			writeError(w, http.StatusInternalServerError, "update_error")
 			return
 		}
@@ -257,8 +256,11 @@ func (s *server) registerOrchestrRoutes(mux *http.ServeMux, mgr *orchestr.Manage
 	})))
 }
 
-// applyPlanHandler aplica un plan pendiente, intentando NetGrip primero y
-// fallback a SSE. Escribe la respuesta HTTP y no devuelve nada.
+// applyPlanHandler aplica un plan pendiente enviando sus Ops al agente del
+// router vía SSE (evento apply). El estado applying se fija ANTES de enviar:
+// un agente que aplica y reporta al instante no puede encontrar el plan
+// todavía pendiente. Si el envío no se entrega, se deshace la transición con
+// auditoría y se responde 503 (nunca 202 de éxito). No devuelve nada.
 func (s *server) applyPlanHandler(w http.ResponseWriter, r *http.Request, mgr *orchestr.Manager, id string) {
 	plan, err := mgr.GetPlan(id)
 	if err != nil {
@@ -269,34 +271,46 @@ func (s *server) applyPlanHandler(w http.ResponseWriter, r *http.Request, mgr *o
 		writeError(w, http.StatusConflict, "plan_not_pending", "El plan ya fue aplicado o está en curso")
 		return
 	}
-	// Intentar delegar en NetGrip si el router tiene executor token.
-	if ok, err := s.applyViaNetGrip(plan.RouterID, plan.ID, plan.Diff); err != nil {
-		writeError(w, http.StatusBadGateway, "netgrip_error", err.Error())
-		return
-	} else if ok {
-		mgr.SetApplying(plan.ID)
-		if err := mgr.SetResult(plan.ID, netgripApplyResult()); err != nil {
-			log.Printf("[netpulse] error marcando plan aplicado vía NetGrip: %v", err)
-		}
-		writeJSON(w, http.StatusAccepted, map[string]string{"status": "applying", "planId": id})
-		return
-	}
 	if s.agentHub == nil {
 		writeError(w, http.StatusServiceUnavailable, "no_agent_hub")
 		return
 	}
-	// Fallback: enviar Ops al agente vía SSE.
+	actor := ""
+	if user := auth.UserFromContext(r.Context()); user != nil {
+		actor = user.Username
+	}
+	if err := mgr.SetApplying(id, actor); err != nil {
+		if errors.Is(err, orchestr.ErrPlanNotFound) {
+			writeError(w, http.StatusNotFound, "not_found")
+			return
+		}
+		if errors.Is(err, orchestr.ErrInvalidTransition) {
+			writeError(w, http.StatusConflict, "plan_not_pending", "El plan cambió de estado antes de aplicar")
+			return
+		}
+		writeError(w, http.StatusInternalServerError, "plan_error")
+		return
+	}
 	applyData, _ := json.Marshal(map[string]any{"plan_id": id, "ops": plan.Diff})
-	sent := s.agentHub.Send(plan.RouterID, "apply", json.RawMessage(applyData))
-	if !sent {
+	if !s.agentHub.Send(plan.RouterID, "apply", json.RawMessage(applyData)) {
+		s.restorePlan(mgr, id, "applying", "pending", actor, "sse delivery failed")
 		writeError(w, http.StatusServiceUnavailable, "agent_not_connected",
 			"El agente no está conectado vía SSE")
 		return
 	}
-	mgr.SetApplying(id)
 	writeJSON(w, http.StatusAccepted, map[string]string{"status": "applying", "planId": id})
 }
 
+// restorePlan deshace una transición transitoria cuando el envío al agente no
+// se entregó. El UPDATE va condicionado al estado de partida, así que no pisa
+// un resultado que el agente ya haya reportado; si la restauración choca con
+// ese caso, solo queda registrado en el log.
+func (s *server) restorePlan(mgr *orchestr.Manager, id, from, to, actor, reason string) {
+	if err := mgr.RestoreTransition(id, from, to, actor, reason); err != nil {
+		log.Printf("[netpulse] orchestr: no se pudo restaurar el plan %s (%s -> %s): %v", id, from, to, err)
+	}
+}
+
 func bearerToken(r *http.Request) string {
 	const prefix = "Bearer "
 	t := r.Header.Get("Authorization")
@@ -591,104 +605,3 @@ func invertDesired(resource string, desired json.RawMessage) (json.RawMessage, e
 		return nil, fmt.Errorf("rollback no soportado para el módulo %q", resource)
 	}
 }
-
-// applyViaNetGrip intenta ejecutar un plan en el NetGrip del router.
-// Devuelve (true, nil) si NetGrip aceptó y ejecutó las ops; (false, nil) si
-// no hay NetGrip configurado o no responde (fallback a SSE); (false, error)
-// si NetGrip devolvió error explícito.
-// netgripExecutorToken devuelve el token del executor de un router NetGrip:
-// primero de la kv (lo deja la subida del backup de configuración) y, si
-// falta, lo lee por SSH y lo guarda (#838).
-func (s *server) netgripExecutorToken(routerID string) string {
-	token := ""
-	if s.db != nil {
-		_ = s.db.QueryRow(
-			"SELECT value FROM kv WHERE key = ?", "netgrip.executor_token."+routerID,
-		).Scan(&token)
-	}
-	if token != "" || s.pool == nil {
-		return token
-	}
-	host := s.hostOfRouter(routerID)
-	if host == "" {
-		return ""
-	}
-	out, err := s.pool.Run(host, "cat /etc/netgrip/executor-token", 10*time.Second)
-	if err != nil {
-		return ""
-	}
-	token = strings.TrimSpace(out)
-	if token != "" && s.db != nil {
-		_, _ = s.db.Exec(
-			`INSERT INTO kv (key, value) VALUES (?, ?)
-			 ON CONFLICT(key) DO UPDATE SET value=excluded.value`,
-			"netgrip.executor_token."+routerID, token)
-	}
-	return token
-}
-
-func (s *server) applyViaNetGrip(routerID string, planID string, ops []executor.Op) (bool, error) {
-	sshHost := s.hostOfRouter(routerID)
-	if sshHost == "" {
-		return false, nil
-	}
-	// hostOfRouter devuelve "host:puerto_ssh" (SSHAddr, issue #605); NetGrip
-	// habla por HTTP en un puerto propio (8080), así que necesitamos solo el
-	// host. Cae por si el pool ya entrega un host pelado.
-	host := sshHost
-	if h, _, err := net.SplitHostPort(sshHost); err == nil {
-		host = h
-	}
-	execToken := s.netgripExecutorToken(routerID)
-	if execToken == "" {
-		return false, nil
-	}
-
-	addr := host
-	if !strings.Contains(addr, ":") {
-		addr = addr + ":8080"
-	}
-	u := url.URL{Scheme: "http", Host: addr, Path: "/api/executor/apply"}
-	body, _ := json.Marshal(map[string]any{"ops": ops})
-	req, err := http.NewRequest("POST", u.String(), bytes.NewReader(body))
-	if err != nil {
-		return false, err
-	}
-	req.Header.Set("Content-Type", "application/json")
-	req.Header.Set("Authorization", "Bearer "+execToken)
-	req.Header.Set("X-Plan-ID", planID)
-
-	client := &http.Client{Timeout: 30 * time.Second}
-	resp, err := client.Do(req)
-	if err != nil {
-		log.Printf("[netpulse] NetGrip no responde en %s: %v", u.Host, err)
-		return false, nil
-	}
-	defer resp.Body.Close()
-
-	if resp.StatusCode != http.StatusOK {
-		b, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
-		log.Printf("[netpulse] NetGrip respondió %d: %s", resp.StatusCode, string(b))
-		return false, nil
-	}
-	var res struct {
-		Ok    bool   `json:"ok"`
-		Error string `json:"error,omitempty"`
-	}
-	if err := json.NewDecoder(io.LimitReader(resp.Body, 4096)).Decode(&res); err != nil {
-		log.Printf("[netpulse] NetGrip respondió JSON inválido: %v", err)
-		return false, nil
-	}
-	if !res.Ok {
-		return false, fmt.Errorf("netgrip: %s", res.Error)
-	}
-	return true, nil
-}
-
-// netgripApplyResult simula un resultado de apply para marcar un plan como
-// aplicado cuando NetGrip ejecutó las ops.
-func netgripApplyResult() executor.ApplyResult {
-	return executor.ApplyResult{
-		Status: "applied",
-	}
-}

+ 500 - 0
server-go/internal/httpapi/orchestr_apply_result_test.go

@@ -0,0 +1,500 @@
+// orchestr_apply_result_test.go — ciclo completo de un plan real:
+// POST /api/plans -> apply (marca applying ANTES de enviar) -> el agente
+// reporta por POST /api/agents/{slug}/apply-result -> applied / rolled_back,
+// y los caminos honestos cuando el plan no existe o el envío SSE falla.
+package httpapi_test
+
+import (
+	"bytes"
+	"encoding/json"
+	"io"
+	"net/http"
+	"sync"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/agent/executor"
+)
+
+// planRow es el estado persistido de un plan.
+type planRow struct {
+	Status    string
+	Resource  string
+	CreatedBy string
+	Desired   string
+	Diff      string
+	AppliedAt *int64
+	Result    *string
+}
+
+func readPlan(t *testing.T, ts *testServer, id string) planRow {
+	t.Helper()
+	var p planRow
+	if err := ts.db.QueryRow(
+		`SELECT status, resource, created_by, desired, diff, applied_at, result
+		 FROM orchestr_plans WHERE id = ?`, id).Scan(
+		&p.Status, &p.Resource, &p.CreatedBy, &p.Desired, &p.Diff, &p.AppliedAt, &p.Result); err != nil {
+		t.Fatalf("select plan %s: %v", id, err)
+	}
+	return p
+}
+
+// createPlanViaAPI crea un plan real con diff explícito (sin probe SSH).
+func createPlanViaAPI(t *testing.T, base, cookie, routerID, resource string, ops []executor.Op) string {
+	t.Helper()
+	body, _ := json.Marshal(map[string]any{
+		"routerId": routerID,
+		"resource": resource,
+		"diff":     ops,
+	})
+	req, _ := http.NewRequest("POST", base+"/api/plans", bytes.NewReader(body))
+	req.Header.Set("Cookie", "session="+cookie)
+	req.Header.Set("Content-Type", "application/json")
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("create plan: %v", err)
+	}
+	defer res.Body.Close()
+	raw, _ := io.ReadAll(res.Body)
+	if res.StatusCode != http.StatusCreated {
+		t.Fatalf("create plan: esperaba 201, got %d: %s", res.StatusCode, raw)
+	}
+	var plan struct {
+		ID string `json:"id"`
+	}
+	if err := json.Unmarshal(raw, &plan); err != nil {
+		t.Fatalf("plan JSON: %v (%s)", err, raw)
+	}
+	if plan.ID == "" {
+		t.Fatalf("el plan creado llegó sin id: %s", raw)
+	}
+	return plan.ID
+}
+
+// createPlanFromDesired crea un plan real dejando que el módulo calcule el
+// diff (el probe SSH es fakeProbeSSH, sin red), de modo que desired y diff
+// quedan persistidos y el rollback puede invertirse.
+func createPlanFromDesired(t *testing.T, base, cookie, routerID, resource string, desired any) string {
+	t.Helper()
+	body, _ := json.Marshal(map[string]any{
+		"routerId": routerID,
+		"resource": resource,
+		"desired":  desired,
+	})
+	req, _ := http.NewRequest("POST", base+"/api/plans", bytes.NewReader(body))
+	req.Header.Set("Cookie", "session="+cookie)
+	req.Header.Set("Content-Type", "application/json")
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("create plan: %v", err)
+	}
+	defer res.Body.Close()
+	raw, _ := io.ReadAll(res.Body)
+	if res.StatusCode != http.StatusCreated {
+		t.Fatalf("create plan: esperaba 201, got %d: %s", res.StatusCode, raw)
+	}
+	var plan struct {
+		ID string `json:"id"`
+	}
+	if err := json.Unmarshal(raw, &plan); err != nil {
+		t.Fatalf("plan JSON: %v (%s)", err, raw)
+	}
+	if plan.ID == "" {
+		t.Fatalf("el plan creado llegó sin id: %s", raw)
+	}
+	return plan.ID
+}
+
+func postApply(t *testing.T, base, cookie, planID string) (int, []byte) {
+	t.Helper()
+	req, _ := http.NewRequest("POST", base+"/api/plans/"+planID+"/apply", nil)
+	req.Header.Set("Cookie", "session="+cookie)
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("apply: %v", err)
+	}
+	defer res.Body.Close()
+	raw, _ := io.ReadAll(res.Body)
+	return res.StatusCode, raw
+}
+
+func postRollback(t *testing.T, base, cookie, planID string) (int, []byte) {
+	t.Helper()
+	req, _ := http.NewRequest("POST", base+"/api/plans/"+planID+"/rollback", nil)
+	req.Header.Set("Cookie", "session="+cookie)
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("rollback: %v", err)
+	}
+	defer res.Body.Close()
+	raw, _ := io.ReadAll(res.Body)
+	return res.StatusCode, raw
+}
+
+// tryPostApplyResult hace el POST sin tocar *testing.T (se usa desde la
+// goroutine del hook del stream).
+func tryPostApplyResult(base, slug, token, planID string, result executor.ApplyResult) (int, []byte, error) {
+	body, err := json.Marshal(map[string]any{"planId": planID, "result": result})
+	if err != nil {
+		return 0, nil, err
+	}
+	req, err := http.NewRequest("POST", base+"/api/agents/"+slug+"/apply-result", bytes.NewReader(body))
+	if err != nil {
+		return 0, nil, err
+	}
+	req.Header.Set("Authorization", "Bearer "+token)
+	req.Header.Set("Content-Type", "application/json")
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		return 0, nil, err
+	}
+	defer res.Body.Close()
+	raw, err := io.ReadAll(res.Body)
+	if err != nil {
+		return res.StatusCode, nil, err
+	}
+	return res.StatusCode, raw, nil
+}
+
+// postApplyResult es lo que hace el agente al terminar de aplicar las ops.
+func postApplyResult(t *testing.T, base, slug, token, planID string, result executor.ApplyResult) (int, []byte) {
+	t.Helper()
+	code, raw, err := tryPostApplyResult(base, slug, token, planID, result)
+	if err != nil {
+		t.Fatalf("apply-result: %v", err)
+	}
+	return code, raw
+}
+
+// waitPlanStatus espera (con deadline) a que el plan llegue a un estado.
+func waitPlanStatus(t *testing.T, ts *testServer, id, want string) {
+	t.Helper()
+	deadline := time.Now().Add(5 * time.Second)
+	for {
+		got := planStatus(t, ts, id)
+		if got == want {
+			return
+		}
+		if time.Now().After(deadline) {
+			t.Fatalf("plan %s: esperaba %q, sigue en %q", id, want, got)
+		}
+		time.Sleep(20 * time.Millisecond)
+	}
+}
+
+func auditActionsOf(t *testing.T, ts *testServer, planID string) []string {
+	t.Helper()
+	rows, err := ts.db.Query(`SELECT action FROM orchestr_audit WHERE plan_id = ? ORDER BY id`, planID)
+	if err != nil {
+		t.Fatalf("audit: %v", err)
+	}
+	defer rows.Close()
+	var out []string
+	for rows.Next() {
+		var a string
+		if err := rows.Scan(&a); err != nil {
+			t.Fatalf("scan audit: %v", err)
+		}
+		out = append(out, a)
+	}
+	return out
+}
+
+func containsAction(actions []string, want string) bool {
+	for _, a := range actions {
+		if a == want {
+			return true
+		}
+	}
+	return false
+}
+
+// TestApplyResultMarksPlanApplied: el agente reporta el resultado y el plan
+// queda applied con applied_at y el resultado persistidos.
+func TestApplyResultMarksPlanApplied(t *testing.T) {
+	ts, _ := newSSEPlanServer(t, nil)
+	addPlanRouter(t, ts, "flint2", "192.0.2.10", true, "")
+	setAgentToken(t, ts, "flint2", "agent-token")
+
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	planID := createPlanViaAPI(t, ts.URL, cookie, "flint2", "guestwifi", []executor.Op{
+		{Kind: "uci_commit", Args: map[string]string{"config": "wireless"}, Desc: "commit wireless"},
+	})
+
+	code, raw := postApplyResult(t, ts.URL, "flint2", "agent-token", planID, executor.ApplyResult{
+		Status: "applied", DurationMs: 12,
+	})
+	if code != http.StatusOK {
+		t.Fatalf("apply-result: esperaba 200, got %d: %s", code, raw)
+	}
+
+	p := readPlan(t, ts, planID)
+	if p.Status != "applied" {
+		t.Fatalf("estado del plan: got %q, want applied", p.Status)
+	}
+	if p.AppliedAt == nil {
+		t.Error("el plan aplicado debe llevar applied_at")
+	}
+	if p.Result == nil || !bytes.Contains([]byte(*p.Result), []byte(`"applied"`)) {
+		t.Errorf("el resultado del agente debe persistirse, got %v", p.Result)
+	}
+	if acts := auditActionsOf(t, ts, planID); !containsAction(acts, "applied") {
+		t.Errorf("se esperaba auditoría \"applied\", got %v", acts)
+	}
+}
+
+// TestApplyResultUnknownPlanIsNotFound: un plan inexistente es un error del
+// cliente (404), no un 500 de "update_error" que el agente reintenta diez veces.
+func TestApplyResultUnknownPlanIsNotFound(t *testing.T) {
+	ts, _ := newSSEPlanServer(t, nil)
+	addPlanRouter(t, ts, "flint2", "192.0.2.10", true, "")
+	setAgentToken(t, ts, "flint2", "agent-token")
+
+	code, raw := postApplyResult(t, ts.URL, "flint2", "agent-token", "plan-que-no-existe",
+		executor.ApplyResult{Status: "applied"})
+	if code != http.StatusNotFound {
+		t.Fatalf("apply-result con plan inexistente: esperaba 404, got %d: %s", code, raw)
+	}
+	var body struct {
+		Error string `json:"error"`
+	}
+	if err := json.Unmarshal(raw, &body); err != nil {
+		t.Fatalf("cuerpo de error: %v (%s)", err, raw)
+	}
+	if body.Error != "not_found" {
+		t.Errorf("código de error: got %q, want not_found", body.Error)
+	}
+}
+
+// TestApplyResultRejectsBadAgentToken: el token del agente se sigue exigiendo.
+func TestApplyResultRejectsBadAgentToken(t *testing.T) {
+	ts, _ := newSSEPlanServer(t, nil)
+	addPlanRouter(t, ts, "flint2", "192.0.2.10", true, "")
+	setAgentToken(t, ts, "flint2", "agent-token")
+
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	planID := createPlanViaAPI(t, ts.URL, cookie, "flint2", "guestwifi", []executor.Op{
+		{Kind: "uci_commit", Args: map[string]string{"config": "wireless"}, Desc: "commit wireless"},
+	})
+
+	code, raw := postApplyResult(t, ts.URL, "flint2", "token-equivocado", planID,
+		executor.ApplyResult{Status: "applied"})
+	if code != http.StatusUnauthorized {
+		t.Fatalf("apply-result con token inválido: esperaba 401, got %d: %s", code, raw)
+	}
+	if got := planStatus(t, ts, planID); got != "pending" {
+		t.Fatalf("un token inválido no puede tocar el plan, got %s", got)
+	}
+}
+
+// TestPlanLifecycleApplyAndRollbackReportedByAgent recorre el ciclo completo
+// con un plan real creado por la API: apply-result lo deja applied, el
+// rollback manda las ops inversas por SSE y el nuevo apply-result lo cierra
+// como rolled_back (no se queda en rolling_back).
+func TestPlanLifecycleApplyAndRollbackReportedByAgent(t *testing.T) {
+	ts, _ := newSSEPlanServer(t, nil)
+	addPlanRouter(t, ts, "flint2", "192.0.2.10", true, "")
+	setAgentToken(t, ts, "flint2", "agent-token")
+
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	events := connectAgentStream(t, ts.URL, "flint2")
+
+	planID := createPlanFromDesired(t, ts.URL, cookie, "flint2", "guestwifi", map[string]any{
+		"enabled": true, "ssid": "NetPulse-Guest", "allowNonGateway": false,
+	})
+
+	if code, raw := postApply(t, ts.URL, cookie, planID); code != http.StatusAccepted {
+		t.Fatalf("apply: esperaba 202, got %d: %s", code, raw)
+	}
+	ev := waitAgentEvent(t, events, "apply")
+	if !bytes.Contains([]byte(ev.data), []byte(planID)) {
+		t.Fatalf("el evento SSE no lleva el plan real: %s", ev.data)
+	}
+	if code, raw := postApplyResult(t, ts.URL, "flint2", "agent-token", planID,
+		executor.ApplyResult{Status: "applied"}); code != http.StatusOK {
+		t.Fatalf("apply-result: esperaba 200, got %d: %s", code, raw)
+	}
+	if got := planStatus(t, ts, planID); got != "applied" {
+		t.Fatalf("tras el apply-result: esperaba applied, got %s", got)
+	}
+
+	if code, raw := postRollback(t, ts.URL, cookie, planID); code != http.StatusAccepted {
+		t.Fatalf("rollback: esperaba 202, got %d: %s", code, raw)
+	}
+	ev = waitAgentEvent(t, events, "apply")
+	var payload struct {
+		PlanID string        `json:"plan_id"`
+		Ops    []executor.Op `json:"ops"`
+	}
+	if err := json.Unmarshal([]byte(ev.data), &payload); err != nil {
+		t.Fatalf("payload SSE del rollback: %v (%s)", err, ev.data)
+	}
+	if payload.PlanID != planID {
+		t.Errorf("plan_id del rollback: got %q, want %q", payload.PlanID, planID)
+	}
+	if got := planStatus(t, ts, planID); got != "rolling_back" {
+		t.Fatalf("el rollback en curso debe quedar rolling_back, got %s", got)
+	}
+
+	// El agente termina el rollback y reporta: el plan NO se queda colgado.
+	if code, raw := postApplyResult(t, ts.URL, "flint2", "agent-token", planID,
+		executor.ApplyResult{Status: "applied"}); code != http.StatusOK {
+		t.Fatalf("apply-result del rollback: esperaba 200, got %d: %s", code, raw)
+	}
+	if got := planStatus(t, ts, planID); got != "rolled_back" {
+		t.Fatalf("tras el rollback: esperaba rolled_back, got %s", got)
+	}
+	acts := auditActionsOf(t, ts, planID)
+	if !containsAction(acts, "rollback") || !containsAction(acts, "rolled_back") {
+		t.Errorf("la auditoría debe registrar rollback y rolled_back, got %v", acts)
+	}
+}
+
+// TestApplyMarksApplyingBeforeAgentSeesEvent: con un agente que responde al
+// instante (el apply-result entra mientras el servidor aún está escribiendo el
+// evento), el plan no se queda en applying: el estado applying se fija ANTES
+// de enviar, así que SetResult no pisa un resultado que ya llegó.
+func TestApplyMarksApplyingBeforeAgentSeesEvent(t *testing.T) {
+	var (
+		mu       sync.Mutex
+		planID   string
+		base     string
+		hookCode int
+		hookBody []byte
+		hookErr  error
+		hooks    int
+	)
+	onApply := func() {
+		mu.Lock()
+		id, url := planID, base
+		hooks++
+		mu.Unlock()
+		if id == "" || url == "" {
+			return
+		}
+		code, raw, err := tryPostApplyResult(url, "flint2", "agent-token", id,
+			executor.ApplyResult{Status: "applied", DurationMs: 3})
+		mu.Lock()
+		hookCode, hookBody, hookErr = code, raw, err
+		mu.Unlock()
+	}
+
+	ts, _ := newSSEPlanServer(t, nil, withHandlerWrap(withStreamHook(streamHookFastAgent, onApply)))
+	base = ts.URL
+	addPlanRouter(t, ts, "flint2", "192.0.2.10", true, "")
+	setAgentToken(t, ts, "flint2", "agent-token")
+
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	connectAgentStream(t, ts.URL, "flint2")
+
+	created := createPlanViaAPI(t, ts.URL, cookie, "flint2", "guestwifi", []executor.Op{
+		{Kind: "uci_commit", Args: map[string]string{"config": "wireless"}, Desc: "commit wireless"},
+	})
+	mu.Lock()
+	planID = created
+	mu.Unlock()
+
+	if code, raw := postApply(t, ts.URL, cookie, planID); code != http.StatusAccepted {
+		t.Fatalf("apply: esperaba 202, got %d: %s", code, raw)
+	}
+
+	mu.Lock()
+	got := hooks
+	code, body, err := hookCode, hookBody, hookErr
+	mu.Unlock()
+	if got == 0 {
+		t.Fatal("el agente rápido no llegó a responder dentro del envío")
+	}
+	if err != nil {
+		t.Fatalf("apply-result del agente rápido: %v", err)
+	}
+	if code != http.StatusOK {
+		t.Fatalf("apply-result del agente rápido: esperaba 200, got %d: %s", code, body)
+	}
+	// El resultado del agente es el último estado; nunca se queda en applying.
+	waitPlanStatus(t, ts, planID, "applied")
+}
+
+// TestApplyRestoresPendingWhenSSEDeliveryFails: si la escritura del evento
+// falla, el plan vuelve a pending (estado honesto), se audita la
+// restauración y la respuesta es un 503, nunca un 202 de éxito.
+func TestApplyRestoresPendingWhenSSEDeliveryFails(t *testing.T) {
+	ts, _ := newSSEPlanServer(t, nil, withHandlerWrap(withStreamHook(streamHookFailOnApply, nil)))
+	addPlanRouter(t, ts, "flint2", "192.0.2.10", true, "")
+
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	connectAgentStream(t, ts.URL, "flint2")
+
+	planID := createPlanViaAPI(t, ts.URL, cookie, "flint2", "guestwifi", []executor.Op{
+		{Kind: "uci_commit", Args: map[string]string{"config": "wireless"}, Desc: "commit wireless"},
+	})
+
+	code, raw := postApply(t, ts.URL, cookie, planID)
+	if code != http.StatusServiceUnavailable {
+		t.Fatalf("apply con el stream roto: esperaba 503, got %d: %s", code, raw)
+	}
+	if got := planStatus(t, ts, planID); got != "pending" {
+		t.Fatalf("tras fallar el envío el plan debe volver a pending, got %s", got)
+	}
+	if acts := auditActionsOf(t, ts, planID); !containsAction(acts, "restore") {
+		t.Errorf("la restauración debe quedar auditada, got %v", acts)
+	}
+}
+
+// TestApplyKeepsPlanPendingWithoutAgent: sin agente conectado no hay plan en
+// curso ni 202: el plan sigue pendiente y se puede reintentar.
+func TestApplyKeepsPlanPendingWithoutAgent(t *testing.T) {
+	ts, _ := newSSEPlanServer(t, nil)
+	addPlanRouter(t, ts, "flint2", "192.0.2.10", true, "")
+
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	planID := createPlanViaAPI(t, ts.URL, cookie, "flint2", "guestwifi", []executor.Op{
+		{Kind: "uci_commit", Args: map[string]string{"config": "wireless"}, Desc: "commit wireless"},
+	})
+
+	code, raw := postApply(t, ts.URL, cookie, planID)
+	if code != http.StatusServiceUnavailable {
+		t.Fatalf("apply sin agente: esperaba 503, got %d: %s", code, raw)
+	}
+	if got := planStatus(t, ts, planID); got != "pending" {
+		t.Fatalf("sin agente el plan debe seguir pending, got %s", got)
+	}
+}
+
+// TestRollbackRestoresAppliedWhenSSEDeliveryFails: si el envío del rollback
+// falla, el plan vuelve a applied (no se queda rolling_back para siempre).
+func TestRollbackRestoresAppliedWhenSSEDeliveryFails(t *testing.T) {
+	// La primera entrega (apply) va bien; la segunda (rollback) se rompe.
+	ts, _ := newSSEPlanServer(t, nil, withHandlerWrap(withStreamHookFailAt(streamHookFailOnApply, nil, 2)))
+	addPlanRouter(t, ts, "flint2", "192.0.2.10", true, "")
+	setAgentToken(t, ts, "flint2", "agent-token")
+
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	events := connectAgentStream(t, ts.URL, "flint2")
+
+	planID := createPlanFromDesired(t, ts.URL, cookie, "flint2", "guestwifi", map[string]any{
+		"enabled": true, "ssid": "NetPulse-Guest", "allowNonGateway": false,
+	})
+	if code, raw := postApply(t, ts.URL, cookie, planID); code != http.StatusAccepted {
+		t.Fatalf("apply: esperaba 202, got %d: %s", code, raw)
+	}
+	waitAgentEvent(t, events, "apply")
+	if code, raw := postApplyResult(t, ts.URL, "flint2", "agent-token", planID,
+		executor.ApplyResult{Status: "applied"}); code != http.StatusOK {
+		t.Fatalf("apply-result: got %d: %s", code, raw)
+	}
+	if got := planStatus(t, ts, planID); got != "applied" {
+		t.Fatalf("tras el apply: esperaba applied, got %s", got)
+	}
+
+	code, raw := postRollback(t, ts.URL, cookie, planID)
+	if code != http.StatusServiceUnavailable {
+		t.Fatalf("rollback con el stream roto: esperaba 503, got %d: %s", code, raw)
+	}
+	if got := planStatus(t, ts, planID); got != "applied" {
+		t.Fatalf("tras fallar el envío el plan debe volver a applied, got %s", got)
+	}
+	if acts := auditActionsOf(t, ts, planID); !containsAction(acts, "restore") {
+		t.Errorf("la restauración debe quedar auditada, got %v", acts)
+	}
+}

+ 30 - 69
server-go/internal/httpapi/orchestr_apply_test.go

@@ -1,75 +1,26 @@
-// orchestr_apply_test.go — tests del endpoint /api/orchestr/apply (#451).
+// orchestr_apply_test.go — tests del endpoint /api/orchestr/apply (#451) con
+// el contrato F-06: las ops (ya envueltas con ownership) van al agente por
+// SSE y no hay ninguna petición HTTP al executor de NetGrip.
 package httpapi_test
 
 import (
 	"bytes"
-	"crypto/sha256"
-	"encoding/hex"
 	"encoding/json"
 	"io"
 	"net/http"
-	"net/http/httptest"
+	"sync/atomic"
 	"testing"
 
 	"github.com/gnacho/netpulse/agent/executor"
-	"github.com/gnacho/netpulse/server-go/internal/routerstore"
 )
 
 func TestOrchestrApplyCreatesAndAppliesPlan(t *testing.T) {
-	ts := makeTestServer(t)
-
-	var receivedOps []executor.Op
-	netgripMock := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
-		if r.URL.Path != "/api/executor/apply" {
-			http.NotFound(w, r)
-			return
-		}
-		if auth := r.Header.Get("Authorization"); auth != "Bearer netgrip-secret" {
-			http.Error(w, "unauthorized", http.StatusUnauthorized)
-			return
-		}
-		var body struct {
-			Ops []executor.Op `json:"ops"`
-		}
-		if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&body); err != nil {
-			http.Error(w, err.Error(), http.StatusBadRequest)
-			return
-		}
-		receivedOps = body.Ops
-		w.Header().Set("Content-Type", "application/json")
-		w.WriteHeader(http.StatusOK)
-		_ = json.NewEncoder(w).Encode(map[string]bool{"ok": true})
-	}))
-	defer netgripMock.Close()
-
-	host := netgripMock.Listener.Addr().String()
-	_, err := routerstore.AddRouter(ts.db.DB, routerstore.AddInput{
-		Name:      "Flint 2",
-		Host:      host,
-		Type:      "openwrt",
-		IsGateway: true,
-	})
-	if err != nil {
-		t.Fatalf("add router: %v", err)
-	}
-	_, err = ts.db.Exec("UPDATE routers SET id = ? WHERE host = ?", "flint2", host)
-	if err != nil {
-		t.Fatalf("update router id: %v", err)
-	}
-
-	sum := sha256.Sum256([]byte("agent-token"))
-	_, err = ts.db.Exec("INSERT INTO kv (key, value) VALUES (?, ?)", "agent.token.flint2", hex.EncodeToString(sum[:]))
-	if err != nil {
-		t.Fatalf("insert agent token: %v", err)
-	}
-	_, err = ts.db.Exec(
-		"INSERT INTO kv (key, value) VALUES (?, ?)",
-		"netgrip.executor_token.flint2", "netgrip-secret")
-	if err != nil {
-		t.Fatalf("insert executor token: %v", err)
-	}
+	ts, _ := newSSEPlanServer(t, nil)
+	netgripMock, hits := countingNetGripMock(t)
+	addPlanRouter(t, ts, "flint2", netgripMock.Listener.Addr().String(), true, "netgrip-secret")
 
 	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	events := connectAgentStream(t, ts.URL, "flint2")
 
 	ops := []executor.Op{{
 		Kind: "uci_set",
@@ -94,27 +45,37 @@ func TestOrchestrApplyCreatesAndAppliesPlan(t *testing.T) {
 		b, _ := io.ReadAll(res.Body)
 		t.Fatalf("apply: esperaba 202, got %d: %s", res.StatusCode, string(b))
 	}
+	if got := atomic.LoadInt32(hits); got != 0 {
+		t.Fatalf("NetGrip recibió %d peticiones HTTP; el apply debe ir por SSE", got)
+	}
 
-	// Verificar que el plan se creó y que NetGrip recibió ownership.
-	if len(receivedOps) < 3 {
-		t.Fatalf("NetGrip debería recibir al menos 3 ops, got %d", len(receivedOps))
+	// El agente recibe el plan completo, con las ops de ownership delante.
+	ev := waitAgentEvent(t, events, "apply")
+	var payload struct {
+		PlanID string        `json:"plan_id"`
+		Ops    []executor.Op `json:"ops"`
+	}
+	if err := json.Unmarshal([]byte(ev.data), &payload); err != nil {
+		t.Fatalf("payload SSE apply inválido (%q): %v", ev.data, err)
+	}
+	if len(payload.Ops) < 3 {
+		t.Fatalf("el agente debería recibir al menos 3 ops, got %d", len(payload.Ops))
 	}
-	if receivedOps[0].Kind != "ownership_mode" || receivedOps[0].Args["enforce"] != "true" {
-		t.Errorf("op[0] debería ser ownership_mode enforce=true, got %+v", receivedOps[0])
+	if payload.Ops[0].Kind != "ownership_mode" || payload.Ops[0].Args["enforce"] != "true" {
+		t.Errorf("op[0] debería ser ownership_mode enforce=true, got %+v", payload.Ops[0])
 	}
-	if receivedOps[1].Kind != "uci_set_managed" {
-		t.Errorf("op[1] debería ser uci_set_managed, got %+v", receivedOps[1])
+	if payload.Ops[1].Kind != "uci_set_managed" {
+		t.Errorf("op[1] debería ser uci_set_managed, got %+v", payload.Ops[1])
 	}
 
 	var planID string
 	if err := ts.db.QueryRow("SELECT id FROM orchestr_plans ORDER BY created_at DESC LIMIT 1").Scan(&planID); err != nil {
 		t.Fatalf("select plan: %v", err)
 	}
-	var status string
-	if err := ts.db.QueryRow("SELECT status FROM orchestr_plans WHERE id = ?", planID).Scan(&status); err != nil {
-		t.Fatalf("select status: %v", err)
+	if payload.PlanID != planID {
+		t.Errorf("plan_id SSE: got %q, want %q", payload.PlanID, planID)
 	}
-	if status != "applied" {
-		t.Fatalf("plan status: esperaba applied, got %s", status)
+	if got := planStatus(t, ts, planID); got != "applying" {
+		t.Fatalf("plan status: esperaba applying, got %s", got)
 	}
 }

+ 133 - 108
server-go/internal/httpapi/orchestr_netgrip_rollback_test.go

@@ -1,32 +1,23 @@
-// orchestr_netgrip_rollback_test.go — regresión #397: el rollback delega al
-// executor de NetGrip cuando el router tiene executor token, y el plan queda
-// rolled_back (SetRollingBack + SetResult).
+// orchestr_netgrip_rollback_test.go — regresión F-06: el rollback va SIEMPRE
+// al agente vía SSE (comando apply con las ops inversas, que es el único que
+// el agente ejecuta) y no habla HTTP con NetGrip. El plan queda rolling_back
+// hasta que el agente reporta, y entonces se cierra como rolled_back.
 package httpapi_test
 
 import (
 	"encoding/json"
 	"io"
 	"net/http"
-	"net/http/httptest"
 	"strings"
+	"sync/atomic"
 	"testing"
 	"time"
 
 	"github.com/gnacho/netpulse/agent/executor"
-	"github.com/gnacho/netpulse/server-go/internal/adapters"
-	"github.com/gnacho/netpulse/server-go/internal/apitoken"
-	"github.com/gnacho/netpulse/server-go/internal/auth"
-	"github.com/gnacho/netpulse/server-go/internal/config"
-	"github.com/gnacho/netpulse/server-go/internal/configbackup"
-	"github.com/gnacho/netpulse/server-go/internal/db"
-	"github.com/gnacho/netpulse/server-go/internal/httpapi"
-	"github.com/gnacho/netpulse/server-go/internal/orchestr"
-	"github.com/gnacho/netpulse/server-go/internal/routerstore"
-	"github.com/gnacho/netpulse/server-go/internal/sse"
 )
 
 // fakeProbeSSH responde al probe de guestwifi con secciones vacías (sin guest
-// configurado) y registra las llamadas.
+// configurado) y no hace SSH real.
 type fakeProbeSSH struct{}
 
 func (fakeProbeSSH) Run(host, cmd string, _ time.Duration) (string, error) {
@@ -36,104 +27,40 @@ func (fakeProbeSSH) Run(host, cmd string, _ time.Duration) (string, error) {
 	return "", nil
 }
 
-func TestRollbackDelegatesToNetGrip(t *testing.T) {
-	// Server a medida: igual que makeTestServer pero con Pool (fakeProbeSSH)
-	// para que computeModuleDiff pueda sondear el escenario sin SSH real.
-	dataDir := t.TempDir()
-	cfg, err := config.Load(map[string]string{
-		"AUTH_USER": "admin", "AUTH_PASS": "test123456",
-		"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)
-	}
-	t.Cleanup(func() { d.Close() })
-	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)
-	}
-	if err := apitoken.EnsureSchema(d); err != nil {
-		t.Fatalf("api_tokens schema: %v", err)
-	}
-	configBackup, err := configbackup.NewStore(d)
-	if err != nil {
-		t.Fatalf("config backup store: %v", err)
-	}
-	reg := adapters.NewAgentRegistry(90 * time.Second)
-	hub := sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil })
-	handler := httpapi.NewHandler(httpapi.Deps{
-		Config: cfg, DB: d, Adapter: adapters.NewDemo(), Hub: hub, Secret: secret,
-		Agents: reg, Pool: fakeProbeSSH{}, Started: time.Now(),
-		TokenStore:   apitoken.NewStore(d, secret),
-		ConfigBackup: configBackup,
-		Orchestr:     orchestr.New(d),
-	})
-	srv := httptest.NewServer(handler)
-	t.Cleanup(srv.Close)
-
-	// Mock de NetGrip: registra las ops recibidas.
-	var receivedOps []executor.Op
-	netgripMock := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
-		if r.URL.Path != "/api/executor/apply" {
-			http.NotFound(w, r)
-			return
-		}
-		if auth := r.Header.Get("Authorization"); auth != "Bearer netgrip-secret" {
-			http.Error(w, "unauthorized", http.StatusUnauthorized)
-			return
-		}
-		var body struct {
-			Ops []executor.Op `json:"ops"`
+// opKey identifica una op por tipo + argumentos relevantes, para comparar la
+// secuencia exacta sin depender de Desc (texto libre).
+func opKey(op executor.Op) string {
+	keys := []string{"config", "section", "option", "value", "name", "action", "enforce", "type"}
+	parts := []string{op.Kind}
+	for _, k := range keys {
+		if v, ok := op.Args[k]; ok {
+			parts = append(parts, k+"="+v)
 		}
-		if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&body); err != nil {
-			http.Error(w, err.Error(), http.StatusBadRequest)
-			return
-		}
-		receivedOps = body.Ops
-		w.Header().Set("Content-Type", "application/json")
-		w.WriteHeader(http.StatusOK)
-		_ = json.NewEncoder(w).Encode(map[string]bool{"ok": true})
-	}))
-	defer netgripMock.Close()
-
-	// Router gateway apuntando al mock + executor token en kv.
-	host := netgripMock.Listener.Addr().String()
-	if _, err := routerstore.AddRouter(d.DB, routerstore.AddInput{
-		Name: "Flint 2", Host: host, Type: "openwrt", IsGateway: true,
-	}); err != nil {
-		t.Fatalf("add router: %v", err)
-	}
-	if _, err := d.Exec("UPDATE routers SET id = ? WHERE host = ?", "flint2", host); err != nil {
-		t.Fatalf("update router id: %v", err)
-	}
-	if _, err := d.Exec(
-		"INSERT INTO kv (key, value) VALUES (?, ?)",
-		"netgrip.executor_token.flint2", "netgrip-secret"); err != nil {
-		t.Fatalf("insert executor token: %v", err)
 	}
+	return strings.Join(parts, " ")
+}
+
+func TestRollbackSendsInverseOpsOverSSE(t *testing.T) {
+	ts, _ := newSSEPlanServer(t, nil)
+	netgripMock, hits := countingNetGripMock(t)
+	addPlanRouter(t, ts, "flint2", netgripMock.Listener.Addr().String(), true, "netgrip-secret")
+	setAgentToken(t, ts, "flint2", "agent-token")
 
-	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	events := connectAgentStream(t, ts.URL, "flint2")
 
 	// Plan guestwifi YA APLICADO con enabled=true (el rollback lo invierte).
-	planID := "plan-roll-01"
+	planID := "plan-roll-sse"
 	opsJSON, _ := json.Marshal([]executor.Op{{Kind: "uci_set", Args: map[string]string{"key": "guestwifi.guest.enabled"}, Desc: "enable guest"}})
-	if _, err := d.Exec(
+	if _, err := ts.db.Exec(
 		`INSERT INTO orchestr_plans (id, router_id, resource, desired, diff, status, created_by, created_at, applied_at, result)
 		 VALUES (?, ?, 'guestwifi', ?, ?, 'applied', 'admin', ?, ?, '{"status":"applied"}')`,
 		planID, "flint2", `{"enabled":true,"allowNonGateway":false}`, string(opsJSON),
-		time.Now().UnixMilli(), time.Now().UnixMilli()); err != nil {
+		time.Now().Unix(), time.Now().Unix()); err != nil {
 		t.Fatalf("insert plan: %v", err)
 	}
 
-	// Rollback.
-	req, _ := http.NewRequest("POST", srv.URL+"/api/plans/"+planID+"/rollback", nil)
+	req, _ := http.NewRequest("POST", ts.URL+"/api/plans/"+planID+"/rollback", nil)
 	req.Header.Set("Cookie", "session="+cookie)
 	res, err := http.DefaultClient.Do(req)
 	if err != nil {
@@ -145,14 +72,112 @@ func TestRollbackDelegatesToNetGrip(t *testing.T) {
 		t.Fatalf("rollback: esperaba 202, got %d: %s", res.StatusCode, string(b))
 	}
 
-	if len(receivedOps) == 0 {
-		t.Fatal("NetGrip no recibió las ops inversas del rollback")
+	if got := atomic.LoadInt32(hits); got != 0 {
+		t.Fatalf("NetGrip recibió %d peticiones HTTP; el rollback debe ir por SSE", got)
+	}
+	if got := planStatus(t, ts, planID); got != "rolling_back" {
+		t.Fatalf("plan status: esperaba rolling_back, got %s", got)
+	}
+
+	ev := waitAgentEvent(t, events, "apply")
+	var payload struct {
+		PlanID string        `json:"plan_id"`
+		Ops    []executor.Op `json:"ops"`
+	}
+	if err := json.Unmarshal([]byte(ev.data), &payload); err != nil {
+		t.Fatalf("payload SSE del rollback inválido (%q): %v", ev.data, err)
+	}
+	if payload.PlanID != planID {
+		t.Errorf("plan_id SSE: got %q, want %q", payload.PlanID, planID)
+	}
+
+	// El rollback manda el modo de ownership delante (igual que un apply) y
+	// después EXACTAMENTE las ops que deshacen el guest: borra la sección de
+	// red guest y recarga, sin volver a crear ni a configurar nada.
+	want := []string{
+		"ownership_mode enforce=true",
+		"uci_set_managed config=network section=guest",
+		"uci_commit config=wireless",
+		"uci_delete_section config=network section=guest",
+		"uci_commit config=network",
+		"uci_commit config=firewall",
+		"service name=network action=reload",
+		"service name=firewall action=reload",
+	}
+	if len(payload.Ops) != len(want) {
+		t.Fatalf("ops inversas: esperaba %d, got %d: %+v", len(want), len(payload.Ops), payload.Ops)
+	}
+	for i, op := range payload.Ops {
+		if got := opKey(op); got != want[i] {
+			t.Fatalf("op[%d]: got %q, want %q", i, got, want[i])
+		}
+		if strings.Contains(opKey(op), "wifi-iface") {
+			t.Errorf("op[%d] recrea la wifi-iface guest: %+v", i, op)
+		}
+	}
+	for _, op := range payload.Ops {
+		if op.Kind == "uci_add" || op.Kind == "uci_set_named" || op.Kind == "uci_set" {
+			t.Fatalf("el rollback no debe crear ni fijar opciones: %+v", op)
+		}
+	}
+
+	// El agente confirma el rollback: el plan se cierra como rolled_back (no
+	// se queda en rolling_back para siempre).
+	if code, raw := postApplyResult(t, ts.URL, "flint2", "agent-token", planID,
+		executor.ApplyResult{Status: "applied"}); code != http.StatusOK {
+		t.Fatalf("apply-result del rollback: esperaba 200, got %d: %s", code, raw)
+	}
+	if got := planStatus(t, ts, planID); got != "rolled_back" {
+		t.Fatalf("tras el rollback: esperaba rolled_back, got %s", got)
+	}
+	acts := auditActionsOf(t, ts, planID)
+	if !containsAction(acts, "rollback") || !containsAction(acts, "rolled_back") {
+		t.Errorf("la auditoría debe registrar rollback y rolled_back, got %v", acts)
+	}
+}
+
+// TestRollbackRejectsPlanNotApplied: solo se revierte lo aplicado, y el plan
+// no cambia de estado si la petición no procede.
+func TestRollbackRejectsPlanNotApplied(t *testing.T) {
+	ts, _ := newSSEPlanServer(t, nil)
+	addPlanRouter(t, ts, "flint2", "192.0.2.10", true, "")
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	planID := createPlanViaAPI(t, ts.URL, cookie, "flint2", "guestwifi", []executor.Op{
+		{Kind: "uci_commit", Args: map[string]string{"config": "wireless"}, Desc: "commit wireless"},
+	})
+	code, raw := postRollback(t, ts.URL, cookie, planID)
+	if code != http.StatusConflict {
+		t.Fatalf("rollback de un plan pendiente: esperaba 409, got %d: %s", code, raw)
+	}
+	if got := planStatus(t, ts, planID); got != "pending" {
+		t.Fatalf("el plan debe seguir pending, got %s", got)
+	}
+}
+
+// TestRollbackWithoutAgentKeepsPlanApplied: si el agente no está, no se puede
+// dejar el plan en rolling_back (eso lo dejaría colgado sin nadie que lo cierre).
+func TestRollbackWithoutAgentKeepsPlanApplied(t *testing.T) {
+	ts, _ := newSSEPlanServer(t, nil)
+	addPlanRouter(t, ts, "flint2", "192.0.2.10", true, "")
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	planID := "plan-roll-no-agent"
+	opsJSON, _ := json.Marshal([]executor.Op{{Kind: "uci_commit", Args: map[string]string{"config": "wireless"}, Desc: "commit wireless"}})
+	if _, err := ts.db.Exec(
+		`INSERT INTO orchestr_plans (id, router_id, resource, desired, diff, status, created_by, created_at, applied_at, result)
+		 VALUES (?, ?, 'guestwifi', ?, ?, 'applied', 'admin', ?, ?, '{"status":"applied"}')`,
+		planID, "flint2", `{"enabled":true,"allowNonGateway":false}`, string(opsJSON),
+		time.Now().Unix(), time.Now().Unix()); err != nil {
+		t.Fatalf("insert plan: %v", err)
 	}
-	var status string
-	if err := d.QueryRow("SELECT status FROM orchestr_plans WHERE id = ?", planID).Scan(&status); err != nil {
-		t.Fatalf("select plan status: %v", err)
+
+	// Sin agente conectado por SSE.
+	code, raw := postRollback(t, ts.URL, cookie, planID)
+	if code != http.StatusServiceUnavailable {
+		t.Fatalf("rollback sin agente: esperaba 503, got %d: %s", code, raw)
 	}
-	if status != "rolled_back" {
-		t.Fatalf("plan status: esperaba rolled_back, got %s", status)
+	if got := planStatus(t, ts, planID); got != "applied" {
+		t.Fatalf("un rollback no entregado no puede mover el plan, got %s", got)
 	}
 }

+ 309 - 69
server-go/internal/httpapi/orchestr_netgrip_test.go

@@ -1,113 +1,353 @@
-// orchestr_netgrip_test.go — tests de delegación de apply a NetGrip (#339).
+// orchestr_netgrip_test.go — regresión F-06: aplicar un plan va SIEMPRE al
+// agente por SSE. El servidor no habla HTTP con NetGrip ni manda su executor
+// token, así que un NetGrip HTTP accesible recibe cero peticiones.
 package httpapi_test
 
 import (
-	"crypto/sha256"
-	"encoding/hex"
+	"bufio"
+	"context"
 	"encoding/json"
 	"io"
 	"net/http"
 	"net/http/httptest"
+	"strings"
+	"sync/atomic"
 	"testing"
 	"time"
 
 	"github.com/gnacho/netpulse/agent/executor"
+	"github.com/gnacho/netpulse/agent/probe"
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/apitoken"
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/config"
+	"github.com/gnacho/netpulse/server-go/internal/configbackup"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/httpapi"
+	"github.com/gnacho/netpulse/server-go/internal/mqttpub"
+	"github.com/gnacho/netpulse/server-go/internal/orchestr"
 	"github.com/gnacho/netpulse/server-go/internal/routerstore"
+	"github.com/gnacho/netpulse/server-go/internal/sse"
 )
 
-func TestApplyDelegatesToNetGrip(t *testing.T) {
-	ts := makeTestServer(t)
+// serverOption ajusta el servidor de test antes de arrancarlo.
+type serverOption func(*serverOptions)
 
-	var receivedOps []executor.Op
-	netgripMock := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
-		if r.URL.Path != "/api/executor/apply" {
-			http.NotFound(w, r)
+type serverOptions struct {
+	wrap func(http.Handler) http.Handler
+}
+
+// withHandlerWrap envuelve el handler completo: lo usan los tests que
+// necesitan interceptar el stream SSE del agente (agente que responde al
+// instante o conexión que se rompe a mitad del envío).
+func withHandlerWrap(wrap func(http.Handler) http.Handler) serverOption {
+	return func(o *serverOptions) { o.wrap = wrap }
+}
+
+// newSSEPlanServer monta un servidor con AgentHub (auth siempre válida),
+// registry de agentes, manager MQTT y overview opcional, de modo que los
+// tests puedan conectar un agente falso y comprobar lo que recibe por SSE.
+func newSSEPlanServer(t *testing.T, ov *adapters.Overview, opts ...serverOption) (*testServer, *adapters.AgentRegistry) {
+	t.Helper()
+	dataDir := t.TempDir()
+	cfg, err := config.Load(map[string]string{
+		"AUTH_USER": "admin", "AUTH_PASS": "test123456",
+		"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)
+	}
+	if err := apitoken.EnsureSchema(d); err != nil {
+		t.Fatalf("api_tokens schema: %v", err)
+	}
+	configBackup, err := configbackup.NewStore(d)
+	if err != nil {
+		t.Fatalf("config backup store: %v", err)
+	}
+	reg := adapters.NewAgentRegistry(0)
+	hub := sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil })
+	agentHub := sse.NewAgentHub(func(_, _ string) bool { return true })
+	mqttMgr := mqttpub.NewManager(mqttpub.Config{
+		Enabled: true, Host: "broker.test", Port: 1883,
+		User: "netpulse", Pass: "broker-pass", Instance: "netpulse",
+		Interval: 60 * time.Second,
+	}, "test", nil, false)
+	handler := httpapi.NewHandler(httpapi.Deps{
+		Config: cfg, DB: d, Adapter: adapters.NewDemo(), Hub: hub, Secret: secret,
+		Agents: reg, Pool: fakeProbeSSH{}, Started: time.Now(),
+		TokenStore:   apitoken.NewStore(d, secret),
+		ConfigBackup: configBackup,
+		Orchestr:     orchestr.New(d),
+		AgentHub:     agentHub,
+		MQTT:         mqttMgr,
+		LastOverview: func() *adapters.Overview { return ov },
+	})
+	var so serverOptions
+	for _, opt := range opts {
+		opt(&so)
+	}
+	var served http.Handler = handler
+	if so.wrap != nil {
+		served = so.wrap(handler)
+	}
+	srv := httptest.NewServer(served)
+	ts := &testServer{Server: srv, db: d, secret: secret}
+	t.Cleanup(func() {
+		srv.Close()
+		d.Close()
+	})
+	return ts, reg
+}
+
+// addPlanRouter inserta un router con ID fijo y, si tiene, el executor token
+// de NetGrip en kv: con el código anterior eso bastaba para delegar por HTTP.
+func addPlanRouter(t *testing.T, ts *testServer, id, host string, gateway bool, executorToken string) {
+	t.Helper()
+	if _, err := routerstore.AddRouter(ts.db.DB, routerstore.AddInput{
+		Name: "Flota " + id, Host: host, Type: "openwrt", IsGateway: gateway,
+	}); err != nil {
+		t.Fatalf("add router %s: %v", id, err)
+	}
+	if _, err := ts.db.Exec("UPDATE routers SET id = ? WHERE name = ?", id, "Flota "+id); err != nil {
+		t.Fatalf("update router id %s: %v", id, err)
+	}
+	if executorToken != "" {
+		if _, err := ts.db.Exec(
+			"INSERT INTO kv (key, value) VALUES (?, ?)",
+			"netgrip.executor_token."+id, executorToken); err != nil {
+			t.Fatalf("insert executor token %s: %v", id, err)
+		}
+	}
+}
+
+// countingNetGripMock emula el executor HTTP de NetGrip y cuenta peticiones.
+// El contrato F-06 exige que la cuenta se quede a cero y que el token no salga.
+func countingNetGripMock(t *testing.T) (*httptest.Server, *int32) {
+	t.Helper()
+	var hits int32
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		atomic.AddInt32(&hits, 1)
+		http.Error(w, "NetPulse no debe delegar por HTTP", http.StatusTeapot)
+	}))
+	t.Cleanup(srv.Close)
+	return srv, &hits
+}
+
+// agentEvent es un evento SSE recibido del stream del agente.
+type agentEvent struct {
+	name string
+	data string
+}
+
+// connectAgentStream abre el stream SSE del agente y devuelve el canal de
+// eventos. Espera al evento "connected" para que el hub ya tenga la conexión
+// registrada antes de disparar el comando.
+func connectAgentStream(t *testing.T, base, slug string) <-chan agentEvent {
+	t.Helper()
+	ctx, cancel := context.WithCancel(context.Background())
+	t.Cleanup(cancel)
+	events := make(chan agentEvent, 16)
+	go func() {
+		defer close(events)
+		req, err := http.NewRequestWithContext(ctx, "GET", base+"/api/agents/"+slug+"/stream", nil)
+		if err != nil {
 			return
 		}
-		if auth := r.Header.Get("Authorization"); auth != "Bearer netgrip-secret" {
-			http.Error(w, "unauthorized", http.StatusUnauthorized)
+		req.Header.Set("Authorization", "Bearer agent-token")
+		res, err := http.DefaultClient.Do(req)
+		if err != nil {
 			return
 		}
-		var body struct {
-			Ops []executor.Op `json:"ops"`
+		defer res.Body.Close()
+		br := bufio.NewReader(res.Body)
+		name := ""
+		for {
+			line, err := br.ReadString('\n')
+			if err != nil {
+				return
+			}
+			line = strings.TrimRight(line, "\r\n")
+			switch {
+			case strings.HasPrefix(line, "event: "):
+				name = strings.TrimPrefix(line, "event: ")
+			case strings.HasPrefix(line, "data: "):
+				events <- agentEvent{name: name, data: strings.TrimPrefix(line, "data: ")}
+			}
 		}
-		if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&body); err != nil {
-			http.Error(w, err.Error(), http.StatusBadRequest)
-			return
+	}()
+	select {
+	case ev, ok := <-events:
+		if !ok || ev.name != "connected" {
+			t.Fatalf("stream SSE: esperaba connected, got %+v", ev)
 		}
-		receivedOps = body.Ops
-		w.Header().Set("Content-Type", "application/json")
-		w.WriteHeader(http.StatusOK)
-		_ = json.NewEncoder(w).Encode(map[string]bool{"ok": true})
-	}))
-	defer netgripMock.Close()
-
-	// Insertar router apuntando al mock de NetGrip (host:puerto).
-	host := netgripMock.Listener.Addr().String()
-	_, err := routerstore.AddRouter(ts.db.DB, routerstore.AddInput{
-		Name:      "Flint 2",
-		Host:      host,
-		Type:      "openwrt",
-		IsGateway: true,
-	})
-	if err != nil {
-		t.Fatalf("add router: %v", err)
-	}
-	// Forzar ID conocido para el plan.
-	_, err = ts.db.Exec("UPDATE routers SET id = ? WHERE host = ?", "flint2", host)
-	if err != nil {
-		t.Fatalf("update router id: %v", err)
+	case <-time.After(5 * time.Second):
+		t.Fatal("el stream SSE del agente no llegó a conectar")
 	}
+	return events
+}
 
-	// Guardar token de agente y executor token de NetGrip.
-	sum := sha256.Sum256([]byte("agent-token"))
-	_, err = ts.db.Exec("INSERT INTO kv (key, value) VALUES (?, ?)", "agent.token.flint2", hex.EncodeToString(sum[:]))
-	if err != nil {
-		t.Fatalf("insert agent token: %v", err)
+// waitAgentEvent descarta heartbeats y eventos intermedios hasta `name`.
+func waitAgentEvent(t *testing.T, events <-chan agentEvent, name string) agentEvent {
+	t.Helper()
+	deadline := time.After(5 * time.Second)
+	for {
+		select {
+		case ev, ok := <-events:
+			if !ok {
+				t.Fatalf("stream SSE cerrado esperando el evento %q", name)
+			}
+			if ev.name == name {
+				return ev
+			}
+		case <-deadline:
+			t.Fatalf("timeout esperando el evento SSE %q", name)
+		}
 	}
-	_, err = ts.db.Exec(
-		"INSERT INTO kv (key, value) VALUES (?, ?)",
-		"netgrip.executor_token.flint2", "netgrip-secret")
-	if err != nil {
-		t.Fatalf("insert executor token: %v", err)
+}
+
+// planStatus lee el estado persistido de un plan.
+func planStatus(t *testing.T, ts *testServer, id string) string {
+	t.Helper()
+	var status string
+	if err := ts.db.QueryRow("SELECT status FROM orchestr_plans WHERE id = ?", id).Scan(&status); err != nil {
+		t.Fatalf("select plan status: %v", err)
 	}
+	return status
+}
+
+func TestApplySendsOpsOverSSEWithoutNetGripHTTP(t *testing.T) {
+	ts, reg := newSSEPlanServer(t, nil)
+	netgripMock, hits := countingNetGripMock(t)
+
+	// Router "NetGrip": host del mock + executor token en kv. Con el código
+	// anterior, aplicar delegaba aquí por HTTP con el Bearer del executor.
+	addPlanRouter(t, ts, "flint2", netgripMock.Listener.Addr().String(), true, "netgrip-secret")
+	reg.Ingest(&probe.Payload{Router: "flint2", Kind: "netgrip", Version: "0.77.3"})
 
 	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	events := connectAgentStream(t, ts.URL, "flint2")
 
-	// Crear plan directamente (evita sondeo SSH).
-	planID := "plan-" + hex.EncodeToString(sum[:])[:8]
+	planID := "plan-apply-sse"
 	ops := []executor.Op{{Kind: "uci_set", Args: map[string]string{"key": "guestwifi.guest.enabled"}, Desc: "enable guest"}}
 	opsJSON, _ := json.Marshal(ops)
-	_, err = ts.db.Exec(
+	if _, err := ts.db.Exec(
 		`INSERT INTO orchestr_plans (id, router_id, resource, desired, diff, status, created_by, created_at)
-		 VALUES (?, ?, ?, ?, ?, 'pending', 'admin', ?)`,
-		planID, "flint2", "guestwifi", `{}`, string(opsJSON), time.Now().UnixMilli())
-	if err != nil {
+		 VALUES (?, ?, 'guestwifi', '{}', ?, 'pending', 'admin', ?)`,
+		planID, "flint2", string(opsJSON), time.Now().UnixMilli()); err != nil {
 		t.Fatalf("insert plan: %v", err)
 	}
 
-	// Aplicar plan.
-	req2, _ := http.NewRequest("POST", ts.URL+"/api/plans/"+planID+"/apply", nil)
-	req2.Header.Set("Cookie", "session="+cookie)
-	res2, err := http.DefaultClient.Do(req2)
+	req, _ := http.NewRequest("POST", ts.URL+"/api/plans/"+planID+"/apply", nil)
+	req.Header.Set("Cookie", "session="+cookie)
+	res, err := http.DefaultClient.Do(req)
 	if err != nil {
 		t.Fatalf("apply: %v", err)
 	}
-	defer res2.Body.Close()
-	if res2.StatusCode != http.StatusAccepted {
-		b, _ := io.ReadAll(res2.Body)
-		t.Fatalf("apply: %d %s", res2.StatusCode, string(b))
+	defer res.Body.Close()
+	if res.StatusCode != http.StatusAccepted {
+		b, _ := io.ReadAll(res.Body)
+		t.Fatalf("apply: esperaba 202, got %d: %s", res.StatusCode, string(b))
 	}
 
-	if len(receivedOps) != 1 || receivedOps[0].Kind != "uci_set" {
-		t.Fatalf("NetGrip no recibió la op esperada: %+v", receivedOps)
+	// Ninguna petición al executor HTTP de NetGrip (ni con token).
+	if got := atomic.LoadInt32(hits); got != 0 {
+		t.Fatalf("NetGrip recibió %d peticiones HTTP; el apply debe ir por SSE", got)
+	}
+	// El plan queda en curso: lo asienta el resultado real del agente.
+	if got := planStatus(t, ts, planID); got != "applying" {
+		t.Fatalf("plan status: esperaba applying, got %s", got)
 	}
 
-	var status string
-	if err := ts.db.QueryRow("SELECT status FROM orchestr_plans WHERE id = ?", planID).Scan(&status); err != nil {
-		t.Fatalf("select plan status: %v", err)
+	ev := waitAgentEvent(t, events, "apply")
+	var payload struct {
+		PlanID string        `json:"plan_id"`
+		Ops    []executor.Op `json:"ops"`
+	}
+	if err := json.Unmarshal([]byte(ev.data), &payload); err != nil {
+		t.Fatalf("payload SSE apply inválido (%q): %v", ev.data, err)
+	}
+	if payload.PlanID != planID {
+		t.Errorf("plan_id SSE: got %q, want %q", payload.PlanID, planID)
+	}
+	if len(payload.Ops) != 1 || payload.Ops[0].Kind != "uci_set" {
+		t.Fatalf("ops SSE: %+v", payload.Ops)
 	}
-	if status != "applied" {
-		t.Fatalf("plan status: esperaba applied, got %s", status)
+}
+
+// streamHookMode decide cómo se comporta el wrapper del stream SSE del agente.
+type streamHookMode int
+
+const (
+	// streamHookNone: stream normal (solo cuenta lo que pasa).
+	streamHookNone streamHookMode = iota
+	// streamHookFastAgent: en cuanto el servidor escribe el evento "apply",
+	// el agente responde su apply-result ANTES de que Send devuelva. Es el
+	// caso real de un agente que aplica rápido y reporta al instante.
+	streamHookFastAgent
+	// streamHookFailOnApply: la escritura del evento "apply" falla (el agente
+	// se cayó a mitad del envío). Send debe devolver false.
+	streamHookFailOnApply
+)
+
+// hookedStreamWriter intercepta el stream SSE del agente.
+type hookedStreamWriter struct {
+	http.ResponseWriter
+	mode    streamHookMode
+	onApply func()
+	failAt  int
+	seen    *int32
+}
+
+func (w *hookedStreamWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }
+
+func (w *hookedStreamWriter) Flush() {
+	_ = http.NewResponseController(w.ResponseWriter).Flush()
+}
+
+func (w *hookedStreamWriter) Write(b []byte) (int, error) {
+	isApply := strings.Contains(string(b), "event: apply")
+	idx := int32(0)
+	if isApply && w.seen != nil {
+		idx = atomic.AddInt32(w.seen, 1)
+	}
+	if isApply && w.mode == streamHookFailOnApply && (w.failAt == 0 || int(idx) == w.failAt) {
+		return 0, io.ErrClosedPipe
+	}
+	n, err := w.ResponseWriter.Write(b)
+	if err == nil && isApply && w.mode == streamHookFastAgent {
+		w.Flush()
+		if w.onApply != nil {
+			w.onApply()
+		}
+	}
+	return n, err
+}
+
+// withStreamHook envuelve el handler para interceptar el stream del agente.
+// failAt > 0 limita el fallo al n-ésimo evento apply (1 = el primero).
+func withStreamHook(mode streamHookMode, onApply func()) func(http.Handler) http.Handler {
+	return withStreamHookFailAt(mode, onApply, 0)
+}
+
+func withStreamHookFailAt(mode streamHookMode, onApply func(), failAt int) func(http.Handler) http.Handler {
+	var seen int32
+	return func(h http.Handler) http.Handler {
+		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+			if strings.HasSuffix(r.URL.Path, "/stream") {
+				w = &hookedStreamWriter{ResponseWriter: w, mode: mode, onApply: onApply, failAt: failAt, seen: &seen}
+			}
+			h.ServeHTTP(w, r)
+		})
 	}
 }

+ 1 - 1
server-go/internal/httpapi/server.go

@@ -573,7 +573,7 @@ func NewHandler(d Deps) http.Handler {
 	s.registerOrchestrRoutes(mux, d.Orchestr)
 
 	// --- Ajustes MQTT (#838; solo admin) ---
-	s.registerMQTTRoutes(mux, d.MQTT)
+	s.registerMQTTRoutes(mux, d.MQTT, d.Orchestr)
 
 	// --- Ajustes globales en kv (issue #121: orchestration opt-in) ---
 	s.registerSettingsRoutes(mux)

+ 95 - 23
server-go/internal/orchestr/orchestr.go

@@ -5,8 +5,10 @@ package orchestr
 
 import (
 	"crypto/rand"
+	"database/sql"
 	"encoding/hex"
 	"encoding/json"
+	"errors"
 	"fmt"
 	"time"
 
@@ -14,18 +16,28 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/db"
 )
 
+// Errores del ciclo de vida del plan.
+var (
+	// ErrPlanNotFound: no hay ningún plan con ese id (p. ej. el agente
+	// reporta un plan de una base de datos que se recreó).
+	ErrPlanNotFound = errors.New("plan_not_found")
+	// ErrInvalidTransition: el plan no está en el estado del que parte la
+	// transición pedida. No se hacen UPDATE a ciegas.
+	ErrInvalidTransition = errors.New("invalid_plan_transition")
+)
+
 // Plan es un plan de orquestación: desired state → diff (Ops) → apply.
 type Plan struct {
-	ID        string             `json:"id"`
-	RouterID  string             `json:"routerId"`
-	Resource  string             `json:"resource"`
-	Desired   json.RawMessage    `json:"desired"`
-	Diff      []executor.Op      `json:"diff"`
-	Status    string             `json:"status"` // pending|applying|applied|failed|rolled_back
-	CreatedBy string             `json:"createdBy"`
-	CreatedAt int64              `json:"createdAt"`
-	AppliedAt *int64             `json:"appliedAt,omitempty"`
-	Result    *ApplyResult       `json:"result,omitempty"`
+	ID        string          `json:"id"`
+	RouterID  string          `json:"routerId"`
+	Resource  string          `json:"resource"`
+	Desired   json.RawMessage `json:"desired"`
+	Diff      []executor.Op   `json:"diff"`
+	Status    string          `json:"status"` // pending|applying|applied|failed|rolled_back
+	CreatedBy string          `json:"createdBy"`
+	CreatedAt int64           `json:"createdAt"`
+	AppliedAt *int64          `json:"appliedAt,omitempty"`
+	Result    *ApplyResult    `json:"result,omitempty"`
 	// Method NO se persiste: es metadato de la respuesta del POST /api/plans
 	// que indica el escenario detectado (apk|opkg|none|binary) para que el
 	// frontend lo muestre. Vacío en GET /api/plans/{id}.
@@ -98,39 +110,99 @@ func (m *Manager) GetPlan(id string) (*Plan, error) {
 	return &p, nil
 }
 
-// SetApplying marca el plan como en ejecución.
-func (m *Manager) SetApplying(id string) error {
-	_, err := m.db.Exec(`UPDATE orchestr_plans SET status = 'applying' WHERE id = ?`, id)
-	return err
+// SetApplying marca el plan como en ejecución (pending → applying).
+// Devuelve ErrInvalidTransition si el plan ya no está pendiente, de modo que
+// un apply repetido o fuera de orden no puede mover el estado a ciegas.
+func (m *Manager) SetApplying(id, actor string) error {
+	return m.transition(id, "pending", "applying", "applying", actor, "apply requested")
 }
 
-// SetRollingBack marca el plan como en revertido en curso (un admin disparó
-// POST /api/plans/{id}/rollback). Registra auditoría.
+// SetRollingBack marca el plan como revertido en curso (applied →
+// rolling_back) porque un admin disparó POST /api/plans/{id}/rollback.
+// Solo se acepta desde applied: revertir algo que no se aplicó no tiene
+// sentido y dejaría el plan colgado. Registra auditoría.
 func (m *Manager) SetRollingBack(id, actor string) error {
-	_, err := m.db.Exec(`UPDATE orchestr_plans SET status = 'rolling_back' WHERE id = ?`, id)
+	return m.transition(id, "applied", "rolling_back", "rollback", actor, "manual rollback triggered")
+}
+
+// RestoreTransition deshace una transición transitoria cuando el envío al
+// agente no llegó a entregarse (p. ej. applying → pending si el SSE falló).
+// El UPDATE va condicionado al estado de partida, así que nunca pisa un
+// resultado que el agente ya haya reportado. Registra auditoría "restore".
+func (m *Manager) RestoreTransition(id, from, to, actor, reason string) error {
+	switch {
+	case from != "applying" && from != "rolling_back":
+		return fmt.Errorf("%w: no se restaura desde %q", ErrInvalidTransition, from)
+	case to != "pending" && to != "applied":
+		return fmt.Errorf("%w: no se restaura a %q", ErrInvalidTransition, to)
+	}
+	detail := from + " -> " + to
+	if reason != "" {
+		detail += ": " + reason
+	}
+	return m.transition(id, from, to, "restore", actor, detail)
+}
+
+// transition mueve el plan de `from` a `to` solo si sigue en `from`
+// (UPDATE condicional, nunca a ciegas) y deja una línea de auditoría.
+func (m *Manager) transition(id, from, to, action, actor, detail string) error {
+	res, err := m.db.Exec(`UPDATE orchestr_plans SET status = ? WHERE id = ? AND status = ?`, to, id, from)
+	if err != nil {
+		return err
+	}
+	n, err := res.RowsAffected()
 	if err != nil {
 		return err
 	}
-	m.audit(id, "rollback", actor, "manual rollback triggered")
+	if n == 0 {
+		var cur string
+		switch err := m.db.QueryRow(`SELECT status FROM orchestr_plans WHERE id = ?`, id).Scan(&cur); {
+		case errors.Is(err, sql.ErrNoRows):
+			return ErrPlanNotFound
+		case err != nil:
+			return err
+		}
+		return fmt.Errorf("%w: estado %q, se esperaba %q", ErrInvalidTransition, cur, from)
+	}
+	m.audit(id, action, actor, detail)
 	return nil
 }
 
 // SetResult actualiza el plan con el resultado del agente y registra auditoría.
-// Si el plan estaba en 'rolling_back', traduce el resultado del agente al
-// estado semántico del plan (applied → rolled_back, fallido → failed).
+// El estado final depende del estado de partida: si el plan estaba en
+// 'rolling_back', el apply con las ops inversas se traduce a rolled_back;
+// si el rollback en sí falló, queda failed. Nunca deja rolling_back.
 func (m *Manager) SetResult(id string, res ApplyResult) error {
 	var prev string
 	if err := m.db.QueryRow(`SELECT status FROM orchestr_plans WHERE id = ?`, id).Scan(&prev); err != nil {
+		if errors.Is(err, sql.ErrNoRows) {
+			return ErrPlanNotFound
+		}
 		return err
 	}
+	if res.Status == "" {
+		res.Status = "failed"
+		if res.Error == "" {
+			res.Error = "el agente no reportó estado"
+		}
+	}
 	final := res.Status
-	if prev == "rolling_back" {
+	switch prev {
+	case "rolled_back":
+		// rolled_back es terminal: un apply-result duplicado o tardío no
+		// puede resucitar un plan que ya se revirtió.
+		final = "rolled_back"
+	case "rolling_back":
 		switch res.Status {
-		case "applied":
+		case "applied", "rolled_back":
 			final = "rolled_back"
-		case "rolled_back":
+		case "failed":
 			final = "failed" // el propio rollback no pudo revertir
 		}
+	case "applying":
+		if res.Status == "rolled_back" {
+			final = "rolled_back"
+		}
 	}
 	resJSON, _ := json.Marshal(res)
 	now := time.Now().Unix()

+ 293 - 0
server-go/internal/orchestr/orchestr_transitions_test.go

@@ -0,0 +1,293 @@
+// orchestr_transitions_test.go: ciclo de vida del plan. Cada transición se
+// valida contra el estado de partida y deja auditoría. Si el envío por SSE
+// falla, el handler restaura el estado anterior con una transición condicional
+// (RestoreTransition), nunca con un UPDATE ciego que pise el resultado que el
+// agente ya hubiera reportado.
+package orchestr
+
+import (
+	"encoding/json"
+	"errors"
+	"testing"
+
+	"github.com/gnacho/netpulse/agent/executor"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+func newTestManager(t *testing.T) (*Manager, *db.DB) {
+	t.Helper()
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	t.Cleanup(func() { d.Close() })
+	return New(d), d
+}
+
+func newTestPlan(t *testing.T, m *Manager) *Plan {
+	t.Helper()
+	plan, err := m.CreatePlan("flint2", "guestwifi", json.RawMessage(`{"enabled":true}`),
+		[]executor.Op{{Kind: "uci_commit", Args: map[string]string{"config": "wireless"}, Desc: "commit wireless"}},
+		"admin")
+	if err != nil {
+		t.Fatalf("create plan: %v", err)
+	}
+	return plan
+}
+
+func auditActions(t *testing.T, d *db.DB, planID string) []string {
+	t.Helper()
+	rows, err := d.Query(`SELECT action FROM orchestr_audit WHERE plan_id = ? ORDER BY id`, planID)
+	if err != nil {
+		t.Fatalf("audit: %v", err)
+	}
+	defer rows.Close()
+	var out []string
+	for rows.Next() {
+		var a string
+		if err := rows.Scan(&a); err != nil {
+			t.Fatalf("scan audit: %v", err)
+		}
+		out = append(out, a)
+	}
+	return out
+}
+
+func requireStatus(t *testing.T, m *Manager, planID, want string) {
+	t.Helper()
+	p, err := m.GetPlan(planID)
+	if err != nil {
+		t.Fatalf("get plan: %v", err)
+	}
+	if p.Status != want {
+		t.Fatalf("estado del plan: got %q, want %q", p.Status, want)
+	}
+}
+
+func TestSetApplyingOnlyFromPending(t *testing.T) {
+	m, d := newTestManager(t)
+	plan := newTestPlan(t, m)
+
+	if err := m.SetApplying(plan.ID, "admin"); err != nil {
+		t.Fatalf("SetApplying desde pending: %v", err)
+	}
+	requireStatus(t, m, plan.ID, "applying")
+	if got := auditActions(t, d, plan.ID); len(got) == 0 || got[len(got)-1] != "applying" {
+		t.Errorf("se esperaba una entrada de auditoría \"applying\", got %v", got)
+	}
+
+	// Repetir la transición sobre un plan que ya está en marcha debe fallar
+	// (no es un UPDATE a ciegas) y no debe mover el estado.
+	err := m.SetApplying(plan.ID, "admin")
+	if !errors.Is(err, ErrInvalidTransition) {
+		t.Fatalf("SetApplying sobre applying: esperaba ErrInvalidTransition, got %v", err)
+	}
+	requireStatus(t, m, plan.ID, "applying")
+}
+
+func TestSetApplyingRejectsAppliedPlan(t *testing.T) {
+	m, _ := newTestManager(t)
+	plan := newTestPlan(t, m)
+	if err := m.SetApplying(plan.ID, "admin"); err != nil {
+		t.Fatalf("SetApplying: %v", err)
+	}
+	if err := m.SetResult(plan.ID, ApplyResult{Status: "applied"}); err != nil {
+		t.Fatalf("SetResult: %v", err)
+	}
+	requireStatus(t, m, plan.ID, "applied")
+
+	if err := m.SetApplying(plan.ID, "admin"); !errors.Is(err, ErrInvalidTransition) {
+		t.Fatalf("SetApplying sobre applied: esperaba ErrInvalidTransition, got %v", err)
+	}
+	requireStatus(t, m, plan.ID, "applied")
+}
+
+func TestSetRollingBackOnlyFromApplied(t *testing.T) {
+	m, d := newTestManager(t)
+	plan := newTestPlan(t, m)
+
+	// pending no se puede revertir.
+	if err := m.SetRollingBack(plan.ID, "admin"); !errors.Is(err, ErrInvalidTransition) {
+		t.Fatalf("SetRollingBack sobre pending: esperaba ErrInvalidTransition, got %v", err)
+	}
+	requireStatus(t, m, plan.ID, "pending")
+
+	if err := m.SetApplying(plan.ID, "admin"); err != nil {
+		t.Fatalf("SetApplying: %v", err)
+	}
+	if err := m.SetResult(plan.ID, ApplyResult{Status: "applied"}); err != nil {
+		t.Fatalf("SetResult: %v", err)
+	}
+	if err := m.SetRollingBack(plan.ID, "admin"); err != nil {
+		t.Fatalf("SetRollingBack desde applied: %v", err)
+	}
+	requireStatus(t, m, plan.ID, "rolling_back")
+	actions := auditActions(t, d, plan.ID)
+	if actions[len(actions)-1] != "rollback" {
+		t.Errorf("se esperaba auditoría \"rollback\", got %v", actions)
+	}
+
+	// Repetir el rollback no puede volver a mover el estado.
+	if err := m.SetRollingBack(plan.ID, "admin"); !errors.Is(err, ErrInvalidTransition) {
+		t.Fatalf("SetRollingBack repetido: esperaba ErrInvalidTransition, got %v", err)
+	}
+	requireStatus(t, m, plan.ID, "rolling_back")
+}
+
+func TestRestoreTransitionOnlyRevertsMatchingState(t *testing.T) {
+	m, d := newTestManager(t)
+	plan := newTestPlan(t, m)
+	if err := m.SetApplying(plan.ID, "admin"); err != nil {
+		t.Fatalf("SetApplying: %v", err)
+	}
+
+	// El envío por SSE falló: se deshace la transición y queda pendiente.
+	if err := m.RestoreTransition(plan.ID, "applying", "pending", "admin", "sse delivery failed"); err != nil {
+		t.Fatalf("RestoreTransition: %v", err)
+	}
+	requireStatus(t, m, plan.ID, "pending")
+	if got := auditActions(t, d, plan.ID); got[len(got)-1] != "restore" {
+		t.Errorf("se esperaba auditoría \"restore\", got %v", got)
+	}
+
+	// Ya no hay nada que restaurar: repetirlo es un error, no un no-op ciego.
+	if err := m.RestoreTransition(plan.ID, "applying", "pending", "admin", "retry"); !errors.Is(err, ErrInvalidTransition) {
+		t.Fatalf("RestoreTransition repetido: esperaba ErrInvalidTransition, got %v", err)
+	}
+	requireStatus(t, m, plan.ID, "pending")
+}
+
+func TestRestoreTransitionDoesNotClobberAgentResult(t *testing.T) {
+	m, _ := newTestManager(t)
+	plan := newTestPlan(t, m)
+	if err := m.SetApplying(plan.ID, "admin"); err != nil {
+		t.Fatalf("SetApplying: %v", err)
+	}
+	// El agente responde antes de que el handler se dé cuenta de que el
+	// envío falló: el resultado manda y la restauración no puede pisarlo.
+	if err := m.SetResult(plan.ID, ApplyResult{Status: "applied"}); err != nil {
+		t.Fatalf("SetResult: %v", err)
+	}
+	if err := m.RestoreTransition(plan.ID, "applying", "pending", "admin", "sse delivery failed"); !errors.Is(err, ErrInvalidTransition) {
+		t.Fatalf("RestoreTransition tras applied: esperaba ErrInvalidTransition, got %v", err)
+	}
+	requireStatus(t, m, plan.ID, "applied")
+}
+
+func TestSetResultMapsStatesHonestly(t *testing.T) {
+	cases := []struct {
+		name    string
+		prepare func(m *Manager, id string) error
+		result  ApplyResult
+		want    string
+	}{
+		{
+			name:    "applying + applied -> applied",
+			prepare: func(m *Manager, id string) error { return m.SetApplying(id, "admin") },
+			result:  ApplyResult{Status: "applied"},
+			want:    "applied",
+		},
+		{
+			name:    "applying + failed -> failed",
+			prepare: func(m *Manager, id string) error { return m.SetApplying(id, "admin") },
+			result:  ApplyResult{Status: "failed", Error: "uci_commit exit 1"},
+			want:    "failed",
+		},
+		{
+			name: "rolling_back + applied -> rolled_back",
+			prepare: func(m *Manager, id string) error {
+				if err := m.SetApplying(id, "admin"); err != nil {
+					return err
+				}
+				if err := m.SetResult(id, ApplyResult{Status: "applied"}); err != nil {
+					return err
+				}
+				return m.SetRollingBack(id, "admin")
+			},
+			result: ApplyResult{Status: "applied"},
+			want:   "rolled_back",
+		},
+		{
+			name: "rolling_back + rolled_back -> rolled_back",
+			prepare: func(m *Manager, id string) error {
+				if err := m.SetApplying(id, "admin"); err != nil {
+					return err
+				}
+				if err := m.SetResult(id, ApplyResult{Status: "applied"}); err != nil {
+					return err
+				}
+				return m.SetRollingBack(id, "admin")
+			},
+			result: ApplyResult{Status: "rolled_back"},
+			want:   "rolled_back",
+		},
+		{
+			name: "rolling_back + failed -> failed",
+			prepare: func(m *Manager, id string) error {
+				if err := m.SetApplying(id, "admin"); err != nil {
+					return err
+				}
+				if err := m.SetResult(id, ApplyResult{Status: "applied"}); err != nil {
+					return err
+				}
+				return m.SetRollingBack(id, "admin")
+			},
+			result: ApplyResult{Status: "failed", Error: "uci rollback falló"},
+			want:   "failed",
+		},
+	}
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			m, _ := newTestManager(t)
+			plan := newTestPlan(t, m)
+			if err := tc.prepare(m, plan.ID); err != nil {
+				t.Fatalf("prepare: %v", err)
+			}
+			if err := m.SetResult(plan.ID, tc.result); err != nil {
+				t.Fatalf("SetResult: %v", err)
+			}
+			requireStatus(t, m, plan.ID, tc.want)
+			p, err := m.GetPlan(plan.ID)
+			if err != nil {
+				t.Fatalf("get plan: %v", err)
+			}
+			if p.AppliedAt == nil {
+				t.Error("el resultado debe sellar applied_at")
+			}
+			if p.Result == nil || p.Result.Status != tc.result.Status {
+				t.Errorf("el resultado del agente debe persistirse, got %+v", p.Result)
+			}
+		})
+	}
+}
+
+func TestSetResultUnknownPlan(t *testing.T) {
+	m, _ := newTestManager(t)
+	if err := m.SetResult("no-existe", ApplyResult{Status: "applied"}); !errors.Is(err, ErrPlanNotFound) {
+		t.Fatalf("SetResult con plan inexistente: esperaba ErrPlanNotFound, got %v", err)
+	}
+}
+
+func TestSetResultKeepsRolledBackTerminal(t *testing.T) {
+	m, _ := newTestManager(t)
+	plan := newTestPlan(t, m)
+	if err := m.SetApplying(plan.ID, "admin"); err != nil {
+		t.Fatalf("SetApplying: %v", err)
+	}
+	if err := m.SetResult(plan.ID, ApplyResult{Status: "applied"}); err != nil {
+		t.Fatalf("SetResult: %v", err)
+	}
+	if err := m.SetRollingBack(plan.ID, "admin"); err != nil {
+		t.Fatalf("SetRollingBack: %v", err)
+	}
+	if err := m.SetResult(plan.ID, ApplyResult{Status: "applied"}); err != nil {
+		t.Fatalf("SetResult (rollback): %v", err)
+	}
+	requireStatus(t, m, plan.ID, "rolled_back")
+
+	// Reintento tardío del apply-result del apply original: no revive el plan.
+	if err := m.SetResult(plan.ID, ApplyResult{Status: "applied"}); err != nil {
+		t.Fatalf("SetResult tardío: %v", err)
+	}
+	requireStatus(t, m, plan.ID, "rolled_back")
+}