package propuesta import ( "context" "encoding/json" "net/http" "net/http/httptest" "reflect" "regexp" "strconv" "strings" "sync/atomic" "testing" "time" "cotizador/internal/config" "cotizador/internal/domain" ) // ─────────────────────────── economia.go ─────────────────────────── func TestCalcularRatio(t *testing.T) { // Sin valor anual / cero / negativo -> sin etiqueta ni division entre cero for _, val := range []float64{0, -5, -1000} { r := CalcularRatio(100000, val) if r.Ratio != 0 || r.Etiqueta != "" { t.Fatalf("valorAnual=%v: esperado Ratio=0 Etiqueta=\"\", obtuve %+v", val, r) } if r.Nota == "" { t.Fatalf("valorAnual=%v: esperaba Nota explicativa", val) } } casos := []struct { nombre string total float64 valor float64 etiqueta string ratio float64 }{ {"5% subcotizado", 50000, 1000000, "subcotizado", 0.05}, {"corte exacto 10% en_rango", 100000, 1000000, "en_rango", 0.1}, {"20% en_rango", 200000, 1000000, "en_rango", 0.2}, {"corte exacto 25% en_rango", 250000, 1000000, "en_rango", 0.25}, {"35% alto", 350000, 1000000, "alto", 0.35}, {"corte exacto 40% alto", 400000, 1000000, "alto", 0.4}, {"60% objecion_probable", 600000, 1000000, "objecion_probable", 0.6}, {"redondeo a 3 decimales", 123456, 1000000, "en_rango", 0.123}, } for _, tc := range casos { t.Run(tc.nombre, func(t *testing.T) { got := CalcularRatio(tc.total, tc.valor) if got.Etiqueta != tc.etiqueta { t.Fatalf("etiqueta: esperado %q, obtuve %q (ratio=%v)", tc.etiqueta, got.Etiqueta, got.Ratio) } if got.Ratio != tc.ratio { t.Fatalf("ratio: esperado %v, obtuve %v", tc.ratio, got.Ratio) } if got.Nota == "" { t.Fatalf("se esperaba Nota no vacia para %q", tc.etiqueta) } }) } } // ─────────────────────────── cliente_ia.go ─────────────────────────── func TestNuevoClienteIA(t *testing.T) { t.Run("rechaza clave faltante nombrando MINIMAX_API_KEY y ANTHROPIC_API_KEY", func(t *testing.T) { t.Setenv("MINIMAX_API_KEY", "") t.Setenv("ANTHROPIC_API_KEY", "") _, err := NuevoClienteIA(&config.Config{}) if err == nil { t.Fatal("esperaba error sin MINIMAX_API_KEY") } if !strings.Contains(err.Error(), "MINIMAX_API_KEY") || !strings.Contains(err.Error(), "ANTHROPIC_API_KEY") { t.Fatalf("mensaje debe mencionar MINIMAX_API_KEY y ANTHROPIC_API_KEY: %q", err.Error()) } }) t.Run("advierte explicitamente si solo ANTHROPIC_API_KEY esta definida", func(t *testing.T) { t.Setenv("MINIMAX_API_KEY", "") t.Setenv("ANTHROPIC_API_KEY", "sk-ant-solo-prueba") _, err := NuevoClienteIA(&config.Config{}) if err == nil { t.Fatal("esperaba error cuando solo ANTHROPIC_API_KEY esta definida") } if !strings.Contains(err.Error(), "ANTHROPIC_API_KEY") || !strings.Contains(err.Error(), "MINIMAX_API_KEY") { t.Fatalf("error debe advertir sobre ANTHROPIC_API_KEY: %q", err.Error()) } }) t.Run("defaults e ignorar ANTHROPIC_BASE_URL", func(t *testing.T) { t.Setenv("ANTHROPIC_BASE_URL", "https://api.anthropic.com") c, err := NuevoClienteIA(&config.Config{MinimaxAPIKey: "clave-prueba"}) if err != nil { t.Fatalf("error inesperado: %v", err) } if !strings.Contains(c.BaseURL, "api.minimax.io") { t.Fatalf("BaseURL esperado de MiniMax, obtuve %q", c.BaseURL) } if strings.Contains(c.BaseURL, "api.anthropic.com") { t.Fatalf("ANTHROPIC_BASE_URL no debe secuestrar BaseURL: %q", c.BaseURL) } if c.Model != "MiniMax-M3" { t.Fatalf("Model por defecto esperado MiniMax-M3, obtuve %q", c.Model) } }) t.Run("respeta MINIMAX_BASE_URL y MINIMAX_MODEL", func(t *testing.T) { c, err := NuevoClienteIA(&config.Config{ MinimaxAPIKey: "clave-prueba", MinimaxBaseURL: "https://ejemplo.local/anthropic/", MinimaxModel: "MiniMax-M2", }) if err != nil { t.Fatalf("error inesperado: %v", err) } if c.BaseURL != "https://ejemplo.local/anthropic" { t.Fatalf("BaseURL inesperado: %q", c.BaseURL) } if c.Model != "MiniMax-M2" { t.Fatalf("Model inesperado: %q", c.Model) } }) } func TestNormalizarRespuesta(t *testing.T) { casos := []struct { nombre string in any want any }{ { "desenvuelve {item: X} cuando item es la unica clave", map[string]any{"item": map[string]any{"a": 1}}, map[string]any{"a": 1}, }, { "desenvuelve dentro de arrays", []any{map[string]any{"item": map[string]any{"a": 1}}, map[string]any{"item": map[string]any{"a": 2}}}, []any{map[string]any{"a": 1}, map[string]any{"a": 2}}, }, { "desenvuelve en profundidad", map[string]any{"lista": []any{map[string]any{"item": map[string]any{"x": []any{map[string]any{"item": 5}}}}}}, map[string]any{"lista": []any{map[string]any{"x": []any{5}}}}, }, { "NO toca un objeto con item junto a otras claves", map[string]any{"item": 1, "otro": 2}, map[string]any{"item": 1, "otro": 2}, }, { "deja intactos valores simples", "texto", "texto", }, { "deja intacto nil", nil, nil, }, { "no altera un objeto normal", map[string]any{"a": 1, "b": []any{1, 2}}, map[string]any{"a": 1, "b": []any{1, 2}}, }, { "caso real: alcance envuelto", map[string]any{"alcance": []any{map[string]any{"item": map[string]any{"refPartida": "P01", "descripcionResultado": "x"}}}}, map[string]any{"alcance": []any{map[string]any{"refPartida": "P01", "descripcionResultado": "x"}}}, }, } for _, tc := range casos { t.Run(tc.nombre, func(t *testing.T) { got := NormalizarRespuesta(tc.in) if !reflect.DeepEqual(got, tc.want) { t.Fatalf("esperado %#v, obtuve %#v", tc.want, got) } }) } } func TestClienteIAToolCallingRetryYFeedback(t *testing.T) { var calls int32 var sawToolChoice, sawCacheControl, sawToolResultError bool srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { n := atomic.AddInt32(&calls, 1) if r.URL.Path != "/v1/messages" { t.Errorf("path inesperado: %s", r.URL.Path) } if r.Header.Get("x-api-key") != "test-key" { t.Errorf("x-api-key faltante o invalido: %q", r.Header.Get("x-api-key")) } var body map[string]any if err := json.NewDecoder(r.Body).Decode(&body); err != nil { t.Fatalf("body JSON invalido: %v", err) } if tc, ok := body["tool_choice"].(map[string]any); ok && tc["type"] == "tool" && tc["name"] == "registrar_hechos" { sawToolChoice = true } if sys, ok := body["system"].([]any); ok && len(sys) > 0 { if s0, ok := sys[0].(map[string]any); ok { if cc, ok := s0["cache_control"].(map[string]any); ok && cc["type"] == "ephemeral" { sawCacheControl = true } } } // Llamada 1: fallo transitorio 429 if n == 1 { w.WriteHeader(http.StatusTooManyRequests) _, _ = w.Write([]byte(`{"error":"rate_limit"}`)) return } // Llamada 2: devuelve tool_use invalido (cita muy corta -> dispara feedback loop) if n == 2 { w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{ "id": "msg_1", "type": "message", "role": "assistant", "content": []any{ map[string]any{ "type": "tool_use", "id": "tu_1", "name": "registrar_hechos", "input": map[string]any{ "citas": []any{map[string]any{"id": "C01", "textoLiteral": "corta", "quienLoDijo": "socio"}}, "hechos": []any{}, "materialesPendientes": []any{}, "decisionesPendientes": []any{}, "mencionesFueraDeAlcance": []any{}, "redFlags": []any{}, }, }, }, "usage": map[string]any{"input_tokens": 100, "output_tokens": 50, "cache_creation_input_tokens": 80}, }) return } // Llamada 3: verificar que llego tool_result con is_error=true y responder valido envuelto en {item:...} if msgs, ok := body["messages"].([]any); ok && len(msgs) >= 3 { if last, ok := msgs[len(msgs)-1].(map[string]any); ok { if blocks, ok := last["content"].([]any); ok { for _, b := range blocks { if bm, ok := b.(map[string]any); ok && bm["type"] == "tool_result" && bm["is_error"] == true { sawToolResultError = true } } } } } w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{ "id": "msg_2", "type": "message", "role": "assistant", "content": []any{ map[string]any{ "type": "tool_use", "id": "tu_2", "name": "registrar_hechos", "input": map[string]any{ "citas": []any{map[string]any{"item": map[string]any{ "id": "C01", "textoLiteral": "no llevamos control de quien contesta el whatsapp el fin de semana", "quienLoDijo": "el socio", }}}, "hechos": []any{}, "materialesPendientes": []any{}, "decisionesPendientes": []any{}, "mencionesFueraDeAlcance": []any{}, "redFlags": []any{}, }, }, }, "usage": map[string]any{"input_tokens": 120, "output_tokens": 60, "cache_read_input_tokens": 80}, }) })) defer srv.Close() cliente := &ClienteIA{ APIKey: "test-key", BaseURL: srv.URL, Model: "MiniMax-M3", HTTPClient: srv.Client(), Sleep: func(context.Context, time.Duration) error { return nil }, } res, err := cliente.LlamarConHerramienta(context.Background(), OpcionesLlamada{ System: []BloqueSystem{{Texto: SystemBase, Cachear: true}}, MensajeUsuario: "extrae hechos", Herramienta: Herramienta{ Nombre: "registrar_hechos", Descripcion: "test", InputSchema: SchemaHechos(), Validar: ValidarHechos, }, MaxIntentos: 3, MaxTokens: 1000, }) if err != nil { t.Fatalf("error inesperado: %v", err) } if !sawToolChoice { t.Fatal("esperaba tool_choice: {type: tool, name: registrar_hechos}") } if !sawCacheControl { t.Fatal("esperaba cache_control: {type: ephemeral}") } if !sawToolResultError { t.Fatal("esperaba feedback loop con tool_result is_error=true") } if res.Intentos != 2 { t.Fatalf("esperaba 2 intentos de validacion (mas 1 reintento HTTP 429), obtuve %d", res.Intentos) } if res.Uso.Entrada != 220 || res.Uso.Salida != 110 || res.Uso.CacheEscritura != 80 || res.Uso.CacheLectura != 80 { t.Fatalf("acumulacion de uso incorrecta: %+v", res.Uso) } } // ─────────────────────────── prompts.go & schemas ─────────────────────────── func TestSystemBaseCacheInvariants(t *testing.T) { anioActual := strconv.Itoa(time.Now().Year()) if strings.Contains(SystemBase, anioActual) { t.Fatalf("SystemBase no debe contener el anio actual (%s)", anioActual) } if regexp.MustCompile(`\d{4}-\d{2}-\d{2}`).MatchString(SystemBase) { t.Fatal("SystemBase no debe contener fechas ISO") } if regexp.MustCompile(`UJ\d{4}`).MatchString(SystemBase) { t.Fatal("SystemBase no debe contener folios de cotizacion") } if len(SystemBase) <= 2500 { t.Fatalf("SystemBase debe superar el minimo cacheable (>2500 chars), tiene %d", len(SystemBase)) } for _, p := range []string{"P1.", "P2.", "P3.", "P4.", "P5.", "P6.", "P7.", "P8."} { if !strings.Contains(SystemBase, p) { t.Fatalf("SystemBase debe declarar principio %s", p) } } for _, s := range []string{ "rojo:", "ambar:", "azul:", "verde:", "entre pares", "Bucefalo", "ningun otro CRM", "USD", "garantizado", "sinergias", "UNICAMENTE servicios digitales", "nombres de empleados", "MATERIAL ES POBRE", "contenido de valor", } { if !strings.Contains(SystemBase, s) { t.Fatalf("SystemBase debe contener %q", s) } } } func TestBloqueContextoYMensajesSinPrecios(t *testing.T) { sinNada := BloqueContexto(ContextoEntrada{Cliente: "Ana", Proyecto: "P"}) if !strings.Contains(sinNada, "No se entrego transcripcion") { t.Fatal("sin transcripcion debe declararlo explicitamente") } if strings.Contains(sinNada, "()") { t.Fatal("sin empresa no debe imprimir parentesis vacios") } conTodo := BloqueContexto(ContextoEntrada{ Transcripcion: "TRANS", Notas: "NOTAS", Observaciones: "OBS", Cliente: "Ana", Empresa: "ACME", Proyecto: "P", }) for _, needle := range []string{"TRANS", "NOTAS", "OBS", "(ACME)"} { if !strings.Contains(conTodo, needle) { t.Fatalf("BloqueContexto debe incluir %q", needle) } } econ := &EconomiaCotizacion{ Partidas: []PartidaEconomia{ {Ref: "P01", Nombre: "Sitio web", Fase: 1, TipoPago: "unico", Precio: 12345, TiempoEntrega: "2 semanas", ModeloCobro: "fijo"}, }, Totales: domain.TotalesCotizacion{ SubtotalUnico: 12345, IVAUnico: 1975.2, TotalUnico: 14320.2, TotalPrimerAnio: 14320.2, IncluyeIVA: true, }, Moneda: "MXN", } ctx := ContextoEntrada{Transcripcion: "t", Cliente: "Ana", Empresa: "ACME", Proyecto: "P"} hechos := map[string]any{"citas": []any{}, "hechos": []any{}} diag := map[string]any{"hallazgos": []any{}, "valorProblema": map[string]any{"dimensiones": []any{}, "notaMetodologia": ""}} m1 := MensajePaso1(ctx) m2 := MensajePaso2(ctx, hechos, econ) m3 := MensajePaso3(ctx, hechos, diag, econ) if !strings.Contains(m1, "registrar_hechos") || !strings.Contains(m1, "TEXTUALES") { t.Fatal("MensajePaso1 debe pedir registrar_hechos y citas TEXTUALES") } if !strings.Contains(m2, "registrar_diagnostico") { t.Fatal("MensajePaso2 debe pedir registrar_diagnostico") } if !strings.Contains(m3, "registrar_propuesta") { t.Fatal("MensajePaso3 debe pedir registrar_propuesta") } for nombre, msg := range map[string]string{"paso 2": m2, "paso 3": m3} { if strings.Contains(msg, "12345") || strings.Contains(msg, "14320") { t.Fatalf("%s NO puede filtrar precios o totales", nombre) } if !strings.Contains(msg, "P01") { t.Fatalf("%s SI debe incluir refPartida P01", nombre) } } } func TestToolSchemasZeroUJCPriceKeys(t *testing.T) { schemas := []map[string]any{SchemaHechos(), SchemaDiagnostico(), SchemaRedaccion()} rawBytes, err := json.Marshal(schemas) if err != nil { t.Fatalf("error serializando schemas: %v", err) } todos := string(rawBytes) prohibidos := []string{"precio", "total", "subtotal", "iva", "montoMinimo", "tarifaHora", "descuento"} for _, p := range prohibidos { if strings.Contains(todos, `"`+p+`"`) { t.Fatalf("ningun tool schema puede declarar propiedad de dinero UJC %q", p) } } if !strings.Contains(todos, `"montoAnualMXN"`) { t.Fatal("SchemaDiagnostico debe incluir montoAnualMXN (costo del problema del cliente)") } if strings.Contains(todos, `"$schema"`) { t.Fatal("los tool schemas no deben llevar $schema") } if strings.Contains(todos, `"calculo"`) { t.Fatal("la dimension de valorProblema debe ser plana, sin objeto calculo") } if !strings.Contains(todos, `"additionalProperties"`) || !strings.Contains(todos, `"description"`) { t.Fatal("los tool schemas deben conservar additionalProperties y description") } } func TestValidadoresSchemaPasos(t *testing.T) { // Hechos vacios validos (material pobre) if errs := ValidarHechos(map[string]any{ "citas": []any{}, "hechos": []any{}, "materialesPendientes": []any{}, "decisionesPendientes": []any{}, "mencionesFueraDeAlcance": []any{}, "redFlags": []any{}, }); len(errs) != 0 { t.Fatalf("hechos vacios deben ser validos: %v", errs) } // Diagnostico: omitir montoAnualMXN se tolera y rellena nil; con monto y <2 factores se rechaza dimSinMonto := map[string]any{ "tipo": "tiempo", "descripcion": "Horas perdidas en atencion", "factores": []any{}, "confianza": "por_validar", "hechos": []any{}, } diag := map[string]any{ "hallazgos": []any{map[string]any{ "id": "D01", "urgencia": "rojo", "titulo": "Titulo valido", "descripcion": strings.Repeat("x", 25), "confianza": "confirmado", "citas": []any{}, "hechos": []any{}, }}, "valorProblema": map[string]any{ "dimensiones": []any{dimSinMonto}, "notaMetodologia": "sin cifras", }, "resultados": []any{}, } if errs := ValidarDiagnostico(diag); len(errs) != 0 { t.Fatalf("diagnostico omitiendo montoAnualMXN debe validar: %v", errs) } if val, exists := dimSinMonto["montoAnualMXN"]; !exists || val != nil { t.Fatalf("omitir montoAnualMXN debe rellenar nil, obtuve exists=%v val=%v", exists, val) } // Con montoAnualMXN y solo 1 factor -> error dimUnFactor := map[string]any{ "tipo": "tiempo", "descripcion": "Horas perdidas en atencion", "factores": []any{map[string]any{"nombre": "a", "valor": 1.0, "confianza": "estimado"}}, "montoAnualMXN": 1.0, "confianza": "estimado", "hechos": []any{}, } diag["valorProblema"].(map[string]any)["dimensiones"] = []any{dimUnFactor} if errs := ValidarDiagnostico(diag); len(errs) == 0 { t.Fatal("esperaba rechazo al declarar montoAnualMXN con menos de 2 factores") } // Redaccion estricta rechaza propiedad desconocida `precioTotal` red := map[string]any{ "hero": map[string]any{"titulo": "Titulo valido", "subtitulo": strings.Repeat("x", 25)}, "citaDestacadaId": "C01", "alcance": []any{map[string]any{"refPartida": "P01", "descripcionResultado": strings.Repeat("x", 25)}}, "beneficios": []any{}, "exclusiones": []any{map[string]any{"texto": strings.Repeat("x", 20), "razon": "porque si"}}, "backlogEvolucion": []any{}, "notasInternas": []any{}, "precioTotal": 99999, } if errs := ValidarRedaccion(red); len(errs) == 0 { t.Fatal("ValidarRedaccion debe rechazar propiedades desconocidas") } } // ─────────────────────────── validacion.go ─────────────────────────── const citaPrueba = "no llevamos control de quien contesta el whatsapp el fin de semana" func econPrueba() *EconomiaCotizacion { return &EconomiaCotizacion{ Partidas: []PartidaEconomia{ {Ref: "P01", Nombre: "Sitio web", Fase: 1, TipoPago: "unico", Precio: 12000, TiempoEntrega: "2 semanas", ModeloCobro: "fijo"}, }, Totales: domain.TotalesCotizacion{ SubtotalUnico: 12000, IVAUnico: 1920, TotalUnico: 13920, TotalPrimerAnio: 13920, IncluyeIVA: true, }, Moneda: "MXN", } } func propuestaBase() map[string]any { return map[string]any{ "hechos": map[string]any{ "citas": []any{ map[string]any{"id": "C01", "textoLiteral": citaPrueba, "quienLoDijo": "el socio"}, }, "hechos": []any{ map[string]any{"id": "H01", "enunciado": "No hay control de la atencion", "confianza": "confirmado", "citas": []any{"C01"}}, }, "materialesPendientes": []any{map[string]any{"texto": "Accesos al dominio", "bloqueaEntrega": true}}, "decisionesPendientes": []any{map[string]any{"texto": "Definir responsable de atencion", "quienDecide": "el socio"}}, "mencionesFueraDeAlcance": []any{}, "redFlags": []any{}, }, "diagnostico": map[string]any{ "hallazgos": []any{ map[string]any{ "id": "D01", "urgencia": "rojo", "titulo": "Prospectos sin seguimiento", "descripcion": "Los mensajes del fin de semana se pierden.", "confianza": "confirmado", "citas": []any{"C01"}, "hechos": []any{"H01"}, }, }, "valorProblema": map[string]any{ "dimensiones": []any{ map[string]any{ "tipo": "tiempo", "descripcion": "Horas perdidas de atencion", "factores": []any{ map[string]any{"nombre": "horas por semana", "valor": 8.0, "confianza": "confirmado"}, map[string]any{"nombre": "semanas", "valor": 52.0, "confianza": "confirmado"}, map[string]any{"nombre": "costo por hora", "valor": 400.0, "confianza": "estimado"}, }, "montoAnualMXN": 166400.0, "confianza": "estimado", "hechos": []any{"H01"}, }, }, "notaMetodologia": "Ocho horas por semana a costo cargado.", }, "resultados": []any{ map[string]any{ "enunciado": "Ningun mensaje sin respuesta en mas de 24 horas", "metrica": "tiempo de respuesta", "lineaBase": nil, "periodoMedicion": "mensual", }, }, }, "redaccion": map[string]any{ "hero": map[string]any{ "titulo": "Propuesta de digitalizacion", "subtitulo": "Ordenar la atencion para dejar de perder prospectos.", }, "citaDestacadaId": "C01", "alcance": []any{ map[string]any{"refPartida": "P01", "descripcionResultado": "Un lugar a donde mandar a los prospectos que llegan de los anuncios."}, }, "beneficios": []any{ map[string]any{"etiqueta": "Respuesta", "texto": "Cada mensaje queda registrado y con responsable.", "hallazgoId": "D01"}, }, "exclusiones": []any{ map[string]any{"texto": "No incluye migrar el historico de pedidos de los ultimos 4 anos.", "razon": "Se evalua en fase 2."}, }, "backlogEvolucion": []any{}, "notasInternas": []any{"El socio es quien decide."}, }, } } func tieneRegla(avisos []Aviso, regla string) bool { for _, a := range avisos { if a.Regla == regla { return true } } return false } func severidadRegla(avisos []Aviso, regla string) string { for _, a := range avisos { if a.Regla == regla { return a.Severidad } } return "" } func TestNormalizarTexto(t *testing.T) { if got := NormalizarTexto("¿Cómo estás, Juan?"); got != "como estas juan" { t.Fatalf("esperado %q, obtuve %q", "como estas juan", got) } if got := NormalizarTexto(" a b "); got != "a b" { t.Fatalf("esperado %q, obtuve %q", "a b", got) } } func TestValidarPropuestaTodasLasReglas(t *testing.T) { econ := econPrueba() fuentes := "El socio dijo: " + citaPrueba + ". Nada mas." t.Run("propuesta limpia sin bloqueantes", func(t *testing.T) { avisos := ValidarPropuesta(propuestaBase(), econ, fuentes, "") if HayBloqueantes(avisos) { t.Fatalf("propuesta limpia no debe producir bloqueantes: %+v", avisos) } if len(avisos) != 0 { t.Fatalf("propuesta limpia no debe producir avisos: %+v", avisos) } }) t.Run("R0 fuga de notas internas 7-gramas", func(t *testing.T) { interno := "el socio pidio descuento antes de entender el alcance del proyecto completo" // Fuga en hero p := propuestaBase() p["redaccion"].(map[string]any)["hero"].(map[string]any)["subtitulo"] = "Contexto del proyecto: " + interno + "." av := ValidarPropuesta(p, econ, fuentes, interno) if !tieneRegla(av, "R0") || severidadRegla(av, "R0") != "bloqueante" { t.Fatalf("R0 debe bloquear fuga en hero: %+v", av) } // Fuga en hallazgo p = propuestaBase() p["diagnostico"].(map[string]any)["hallazgos"].([]any)[0].(map[string]any)["descripcion"] = "Observado: " + interno + "." av = ValidarPropuesta(p, econ, fuentes, interno) if !tieneRegla(av, "R0") { t.Fatalf("R0 debe revisar todos los campos visibles (hallazgo): %+v", av) } // Sin fuga -> ok if tieneRegla(ValidarPropuesta(propuestaBase(), econ, fuentes, interno), "R0") { t.Fatal("R0 no debe disparar si no hay fuga") } // En notasInternas del propio resultado -> NO se imprime, NO dispara R0 p = propuestaBase() p["redaccion"].(map[string]any)["notasInternas"] = []any{interno} if tieneRegla(ValidarPropuesta(p, econ, fuentes, interno), "R0") { t.Fatal("R0 no debe quejarse de notasInternas (no se imprimen)") } }) t.Run("R2 y R2b referencias de partidas", func(t *testing.T) { p := propuestaBase() p["redaccion"].(map[string]any)["alcance"].([]any)[0].(map[string]any)["refPartida"] = "P99" av := ValidarPropuesta(p, econ, fuentes, "") if !tieneRegla(av, "R2") || severidadRegla(av, "R2") != "bloqueante" { t.Fatalf("R2 debe bloquear partida inventada P99: %+v", av) } p = propuestaBase() p["redaccion"].(map[string]any)["alcance"] = []any{} av = ValidarPropuesta(p, econ, fuentes, "") if !tieneRegla(av, "R2b") || severidadRegla(av, "R2b") != "advertencia" { t.Fatalf("R2b debe advertir partida cotizada no descrita: %+v", av) } }) t.Run("R3 cita destacada existe y es literal", func(t *testing.T) { p := propuestaBase() p["redaccion"].(map[string]any)["citaDestacadaId"] = "C09" av := ValidarPropuesta(p, econ, fuentes, "") if !tieneRegla(av, "R3") || severidadRegla(av, "R3") != "bloqueante" { t.Fatalf("R3 debe bloquear cita inexistente: %+v", av) } p = propuestaBase() p["hechos"].(map[string]any)["citas"].([]any)[0].(map[string]any)["textoLiteral"] = "esto nunca lo dijo nadie en la reunion" av = ValidarPropuesta(p, econ, fuentes, "") if !tieneRegla(av, "R3") { t.Fatalf("R3 debe bloquear cita no literal: %+v", av) } // Tolera acentos, mayusculas y puntuacion p = propuestaBase() p["hechos"].(map[string]any)["citas"].([]any)[0].(map[string]any)["textoLiteral"] = "NO LLEVAMOS CONTROL, de quién contesta... el WhatsApp el fin de semana!" if tieneRegla(ValidarPropuesta(p, econ, fuentes, ""), "R3") { t.Fatal("R3 debe tolerar acentos, mayusculas y puntuacion") } }) t.Run("R4 confirmado sin evidencia", func(t *testing.T) { p := propuestaBase() h0 := p["diagnostico"].(map[string]any)["hallazgos"].([]any)[0].(map[string]any) h0["citas"] = []any{} h0["hechos"] = []any{} av := ValidarPropuesta(p, econ, fuentes, "") if !tieneRegla(av, "R4") || severidadRegla(av, "R4") != "advertencia" { t.Fatalf("R4 debe advertir hallazgo confirmado sin citas ni hechos: %+v", av) } }) t.Run("R5 aritmetica dentro de 2% y R5b sin factores confirmados", func(t *testing.T) { // No cuadra -> R5 bloqueante p := propuestaBase() dim := p["diagnostico"].(map[string]any)["valorProblema"].(map[string]any)["dimensiones"].([]any)[0].(map[string]any) dim["montoAnualMXN"] = 999999.0 av := ValidarPropuesta(p, econ, fuentes, "") if !tieneRegla(av, "R5") || severidadRegla(av, "R5") != "bloqueante" { t.Fatalf("R5 debe bloquear aritmetica inconsistente: %+v", av) } // Cuadra por suma dentro de 2% -> sin R5 p = propuestaBase() dim = p["diagnostico"].(map[string]any)["valorProblema"].(map[string]any)["dimensiones"].([]any)[0].(map[string]any) dim["factores"] = []any{ map[string]any{"nombre": "a", "valor": 10000.0, "confianza": "confirmado"}, map[string]any{"nombre": "b", "valor": 5000.0, "confianza": "estimado"}, } dim["montoAnualMXN"] = 15100.0 // diferencia < 1% if tieneRegla(ValidarPropuesta(p, econ, fuentes, ""), "R5") { t.Fatal("R5 debe aceptar suma dentro del margen de 2%") } // Sin cifra (nil) -> sin R5 ni R5b p = propuestaBase() dim = p["diagnostico"].(map[string]any)["valorProblema"].(map[string]any)["dimensiones"].([]any)[0].(map[string]any) dim["montoAnualMXN"] = nil dim["factores"] = []any{} av = ValidarPropuesta(p, econ, fuentes, "") if tieneRegla(av, "R5") || tieneRegla(av, "R5b") { t.Fatalf("sin montoAnualMXN no debe disparar R5 ni R5b: %+v", av) } // Solo estimados -> R5b advertencia p = propuestaBase() dim = p["diagnostico"].(map[string]any)["valorProblema"].(map[string]any)["dimensiones"].([]any)[0].(map[string]any) for _, f := range dim["factores"].([]any) { f.(map[string]any)["confianza"] = "estimado" } av = ValidarPropuesta(p, econ, fuentes, "") if !tieneRegla(av, "R5b") || severidadRegla(av, "R5b") != "advertencia" { t.Fatalf("R5b debe advertir cuando ningun factor es confirmado: %+v", av) } }) t.Run("R6 hallazgoId colgante", func(t *testing.T) { p := propuestaBase() p["redaccion"].(map[string]any)["beneficios"].([]any)[0].(map[string]any)["hallazgoId"] = "D99" av := ValidarPropuesta(p, econ, fuentes, "") if !tieneRegla(av, "R6") || severidadRegla(av, "R6") != "advertencia" { t.Fatalf("R6 debe advertir beneficio colgante: %+v", av) } }) t.Run("MARCA MONEDA GARANTIA PII", func(t *testing.T) { // MARCA p := propuestaBase() p["redaccion"].(map[string]any)["beneficios"].([]any)[0].(map[string]any)["texto"] = "Lo integramos con HubSpot sin problema alguno." av := ValidarPropuesta(p, econ, fuentes, "") if !tieneRegla(av, "MARCA") || severidadRegla(av, "MARCA") != "bloqueante" { t.Fatalf("MARCA debe bloquear otro CRM: %+v", av) } // MONEDA p = propuestaBase() p["redaccion"].(map[string]any)["hero"].(map[string]any)["subtitulo"] = "Una inversion de 1,800 USD al mes para tu negocio." av = ValidarPropuesta(p, econ, fuentes, "") if !tieneRegla(av, "MONEDA") || severidadRegla(av, "MONEDA") != "bloqueante" { t.Fatalf("MONEDA debe bloquear USD: %+v", av) } // GARANTIA p = propuestaBase() p["redaccion"].(map[string]any)["beneficios"].([]any)[0].(map[string]any)["texto"] = "Te garantizamos la posicion numero uno en Google." av = ValidarPropuesta(p, econ, fuentes, "") if !tieneRegla(av, "GARANTIA") || severidadRegla(av, "GARANTIA") != "bloqueante" { t.Fatalf("GARANTIA debe bloquear promesa garantizada: %+v", av) } // PII (advertencia, no bloqueante) p = propuestaBase() p["redaccion"].(map[string]any)["hero"].(map[string]any)["subtitulo"] = "El sueldo de quien atiende sale muy caro hoy en dia." av = ValidarPropuesta(p, econ, fuentes, "") if !tieneRegla(av, "PII") || severidadRegla(av, "PII") != "advertencia" || HayBloqueantes(av) { t.Fatalf("PII debe ser advertencia no bloqueante: %+v", av) } }) } // ─────────────────────────── pipeline.go ─────────────────────────── func TestEjecutarPipelineTresPasos(t *testing.T) { base := propuestaBase() var step int32 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { n := atomic.AddInt32(&step, 1) var toolName string var payload any switch n { case 1: toolName = "registrar_hechos" payload = base["hechos"] case 2: toolName = "registrar_diagnostico" payload = base["diagnostico"] case 3: toolName = "registrar_propuesta" payload = base["redaccion"] default: t.Fatalf("llamada inesperada #%d", n) } w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{ "id": "msg_" + strconv.Itoa(int(n)), "type": "message", "role": "assistant", "content": []any{ map[string]any{ "type": "tool_use", "id": "tu_" + strconv.Itoa(int(n)), "name": toolName, "input": payload, }, }, "usage": map[string]any{ "input_tokens": 100 * int(n), "output_tokens": 50 * int(n), "cache_read_input_tokens": 40, "cache_creation_input_tokens": 10, }, }) })) defer srv.Close() cliente := &ClienteIA{ APIKey: "test-key", BaseURL: srv.URL, Model: "MiniMax-M3", HTTPClient: srv.Client(), Sleep: func(context.Context, time.Duration) error { return nil }, } res, err := ejecutarPipeline( context.Background(), cliente, ContextoEntrada{ Transcripcion: "El socio dijo: " + citaPrueba + ".", Cliente: "Juan Perez", Empresa: "ACME", Proyecto: "MKT Digital", }, econPrueba(), "nota confidencial que no debe aparecer en la propuesta final jamas", ) if err != nil { t.Fatalf("error en pipeline: %v", err) } if res.Modelo != "MiniMax-M3" { t.Fatalf("Modelo esperado MiniMax-M3, obtuve %q", res.Modelo) } if HayBloqueantes(res.Avisos) { t.Fatalf("no esperaba bloqueantes en pipeline limpio: %+v", res.Avisos) } if res.Contenido["hechos"] == nil || res.Contenido["diagnostico"] == nil || res.Contenido["redaccion"] == nil { t.Fatalf("Contenido incompleto: %+v", res.Contenido) } totalUso, ok := res.Traza["totalUso"].(UsoTokens) if !ok || totalUso.Entrada != 600 || totalUso.Salida != 300 || totalUso.CacheLectura != 120 || totalUso.CacheEscritura != 30 { t.Fatalf("Traza totalUso incorrecta: %#v", res.Traza["totalUso"]) } }