Sistema completo de gestión de tokens para subagentes NEXUS v4.0: Nuevas directivas SIMCO: - SIMCO-SUBAGENTE.md: Protocolo para agentes en modo subagente - SIMCO-CCA-SUBAGENTE.md: CCA ligero para subagentes (~1,500 tokens) - SIMCO-CONTROL-TOKENS.md: Gestión de límites de tokens - SIMCO-DELEGACION-PARALELA.md: Delegación paralela Perfiles compact (~250 tokens cada uno): - PERFIL-BACKEND-COMPACT.md - PERFIL-FRONTEND-COMPACT.md - PERFIL-DATABASE-COMPACT.md - PERFIL-DEVOPS-COMPACT.md - PERFIL-ML-COMPACT.md - PERFIL-GENERIC-SUBAGENT.md Templates de delegación escalonados: - TEMPLATE-DELEGACION-MINIMA.md (~250 tokens) - TEMPLATE-DELEGACION-ESTANDAR.md (~600 tokens) - TEMPLATE-DELEGACION-COMPLETA.md (~1,800 tokens) Nuevos perfiles especializados: - PERFIL-MCP-ARCHITECT.md - PERFIL-MCP-DEVELOPER.md - PERFIL-RAG-ENGINEER.md - PERFIL-CICD-SPECIALIST.md - PERFIL-PRODUCTION-MANAGER.md - PERFIL-MONITORING-AGENT.md - PERFIL-SECRETS-MANAGER.md - PERFIL-PROPAGATION-TRACKER.md Checklists y documentación: - CHECKLIST-PRE-DELEGACION.md - Análisis y planes de implementación Métricas de mejora: - ~59% reducción de tokens por delegación - Perfiles compact: 69% más ligeros - CCA subagente: 85% más ligero 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
15 KiB
15 KiB
FASE 5: REFINAMIENTO DEL PLAN
Sistema: NEXUS v3.4 + SIMCO Fecha: 2026-01-04 Autor: Architecture-Analyst Version: 1.0.0
1. AJUSTES IDENTIFICADOS EN VALIDACION
1.1 Consolidación de Ubicación de Perfiles
Problema: KB-MANAGER está en core/orchestration/agents/perfiles/ mientras los demás están en orchestration/agents/perfiles/.
Decisión: Mantener separación actual:
orchestration/agents/perfiles/→ Perfiles operativos de workspacecore/orchestration/agents/perfiles/→ Perfiles core del sistema NEXUS
Acción: Los nuevos perfiles (PRODUCTION-MANAGER, SECRETS-MANAGER, etc.) van en orchestration/agents/perfiles/.
1.2 Agregar Secciones Estándar a Perfiles Nuevos
Cada perfil nuevo incluirá:
secciones_obligatorias:
- "## PROTOCOLO DE INICIALIZACION (CCA)"
- "## IDENTIDAD"
- "## CONTEXT REQUIREMENTS"
- "## RESPONSABILIDADES"
- "## DIRECTIVAS SIMCO A SEGUIR"
- "## COMANDOS FRECUENTES" # NUEVO
- "## ALIAS RELEVANTES"
- "## REFERENCIAS EXTENDIDAS"
2. REFINAMIENTO: PERFIL-PRODUCTION-MANAGER
2.1 Comandos Frecuentes Agregados
comandos_frecuentes:
pm2:
listar: "pm2 list"
logs: "pm2 logs {app-name}"
restart: "pm2 restart {app-name}"
reload: "pm2 reload {app-name} --update-env"
save: "pm2 save"
startup: "pm2 startup"
nginx:
test: "sudo nginx -t"
reload: "sudo systemctl reload nginx"
sites: "ls -la /etc/nginx/sites-enabled/"
logs: "sudo tail -f /var/log/nginx/error.log"
ssl:
certbot_new: "sudo certbot --nginx -d {domain}"
certbot_renew: "sudo certbot renew --dry-run"
check_expiry: "sudo certbot certificates"
ufw:
status: "sudo ufw status numbered"
allow: "sudo ufw allow {port}"
deny: "sudo ufw deny {port}"
postgres:
backup: "pg_dump -U {user} {db} > backup.sql"
restore: "psql -U {user} {db} < backup.sql"
2.2 Checklist de Deploy a Producción
pre_deploy:
- "[ ] Build exitoso en CI/CD"
- "[ ] Tests pasando"
- "[ ] .env.production actualizado"
- "[ ] Backup de BD realizado"
- "[ ] Ventana de mantenimiento comunicada"
deploy:
- "[ ] Pull de código en servidor"
- "[ ] npm install --production"
- "[ ] npm run build"
- "[ ] pm2 reload {app}"
- "[ ] nginx -t && systemctl reload nginx"
post_deploy:
- "[ ] Health check OK"
- "[ ] Logs sin errores"
- "[ ] Funcionalidad crítica verificada"
- "[ ] Rollback plan disponible"
3. REFINAMIENTO: PERFIL-SECRETS-MANAGER
3.1 Comandos Frecuentes
comandos_frecuentes:
validacion:
check_env: "diff .env.example .env | grep '<'"
find_hardcoded: "grep -r 'API_KEY\\|SECRET\\|PASSWORD' --include='*.ts' --include='*.js' src/"
verify_gitignore: "grep '.env' .gitignore"
generacion:
jwt_secret: "openssl rand -base64 64"
api_key: "openssl rand -hex 32"
password: "openssl rand -base64 16"
auditoria:
list_vars: "cat .env.example | grep -v '^#' | cut -d'=' -f1"
count_vars: "cat .env.example | grep -v '^#' | grep '=' | wc -l"
3.2 Template ENV-VARS-INVENTORY.yml
# Template para inventario de variables de entorno
proyecto: "{nombre}"
actualizado: "{fecha}"
archivo_ejemplo: ".env.example"
resumen:
total_variables: N
sensibles: N
ambientes: ["development", "staging", "production"]
categorias:
database:
- nombre: "DB_HOST"
tipo: "string"
ejemplo: "localhost"
sensible: false
ambientes: [dev, staging, prod]
- nombre: "DB_PASSWORD"
tipo: "string"
ejemplo: "***"
sensible: true
ambientes: [dev, staging, prod]
rotacion: "cada 90 días"
authentication:
- nombre: "JWT_SECRET"
tipo: "string"
ejemplo: "***"
sensible: true
generacion: "openssl rand -base64 64"
rotacion: "cada 90 días"
external_apis:
- nombre: "STRIPE_SECRET_KEY"
tipo: "string"
ejemplo: "sk_test_***"
sensible: true
documentacion: "https://dashboard.stripe.com/apikeys"
notas:
- "Nunca commitear .env"
- "Rotar secrets cada 90 días"
- "Usar valores diferentes por ambiente"
4. REFINAMIENTO: PERFIL-MONITORING-AGENT
4.1 Comandos Frecuentes
comandos_frecuentes:
prometheus:
status: "curl http://localhost:9090/-/healthy"
targets: "curl http://localhost:9090/api/v1/targets"
query: "curl 'http://localhost:9090/api/v1/query?query={metric}'"
grafana:
status: "curl http://localhost:9091/api/health"
dashboards: "curl http://localhost:9091/api/search"
pm2_metrics:
monit: "pm2 monit"
info: "pm2 info {app}"
metrics: "pm2 show {app}"
system:
disk: "df -h"
memory: "free -m"
cpu: "top -bn1 | head -5"
connections: "netstat -an | grep ESTABLISHED | wc -l"
4.2 Alertas Estándar por Proyecto
alertas_gamilit:
- nombre: "API Response Time"
metrica: "http_request_duration_seconds"
threshold: "> 2s warning, > 5s critical"
accion: "Notificar #gamilit-alerts"
- nombre: "WebSocket Connections"
metrica: "websocket_active_connections"
threshold: "> 1000 warning"
accion: "Escalar instancias"
alertas_trading:
- nombre: "Order Execution Latency"
metrica: "order_execution_ms"
threshold: "> 500ms warning, > 1s critical"
accion: "Notificar #trading-alerts"
- nombre: "ML Prediction Rate"
metrica: "ml_predictions_per_second"
threshold: "< 10 warning"
accion: "Verificar ml-engine"
alertas_erp:
- nombre: "Transaction Throughput"
metrica: "transactions_per_minute"
threshold: "< 50 warning"
accion: "Verificar database"
5. REFINAMIENTO: PERFIL-CICD-SPECIALIST
5.1 Templates de Pipeline
templates:
jenkins:
nestjs: |
pipeline {
agent any
stages {
stage('Checkout') { steps { checkout scm } }
stage('Install') { steps { sh 'npm ci' } }
stage('Lint') { steps { sh 'npm run lint' } }
stage('Test') { steps { sh 'npm test' } }
stage('Build') { steps { sh 'npm run build' } }
stage('Deploy') {
when { branch 'main' }
steps { sh './scripts/deploy.sh' }
}
}
}
express: |
pipeline {
agent any
stages {
stage('Checkout') { steps { checkout scm } }
stage('Install') { steps { sh 'npm ci' } }
stage('Lint') { steps { sh 'npm run lint' } }
stage('Test') { steps { sh 'npm test' } }
stage('Build') { steps { sh 'npm run build' } }
}
}
fastapi: |
pipeline {
agent any
stages {
stage('Checkout') { steps { checkout scm } }
stage('Setup Python') { steps { sh 'python -m venv venv && . venv/bin/activate && pip install -r requirements.txt' } }
stage('Lint') { steps { sh '. venv/bin/activate && ruff check .' } }
stage('Test') { steps { sh '. venv/bin/activate && pytest' } }
}
}
5.2 Comandos Frecuentes
comandos_frecuentes:
jenkins:
status: "curl -s http://jenkins.isem.dev/api/json | jq '.jobs[].name'"
build: "curl -X POST http://jenkins.isem.dev/job/{job}/build"
logs: "curl http://jenkins.isem.dev/job/{job}/lastBuild/consoleText"
github_actions:
list_runs: "gh run list --repo {owner}/{repo}"
view_run: "gh run view {run-id}"
rerun: "gh run rerun {run-id}"
6. REFINAMIENTO: PERFIL-PROPAGATION-TRACKER
6.1 Comandos Frecuentes
comandos_frecuentes:
version_check:
all_modules: "./devtools/scripts/propagation/check-module-versions.sh --all"
single_module: "./devtools/scripts/propagation/check-module-versions.sh {module}"
outdated: "./devtools/scripts/propagation/detect-outdated-projects.sh"
reports:
sync_status: "./devtools/scripts/propagation/generate-sync-report.sh"
history: "cat shared/knowledge-base/propagacion/REGISTRO-PROPAGACIONES.yml"
tracking:
update: "./devtools/scripts/propagation/update-trazabilidad.sh"
validate: "./devtools/scripts/propagation/validate-propagation-chain.sh {PROP-ID}"
6.2 Template TRAZABILIDAD-PROPAGACION.yml
# Template para trazabilidad de propagaciones
metadata:
version: "1.0.0"
updated: "{fecha}"
sistema: "NEXUS v3.4"
modulos:
auth:
version_catalog: "1.2.0"
adoptantes:
gamilit:
version: "1.2.0"
actualizado: "2026-01-04"
estado: "sincronizado"
erp_core:
version: "1.1.0"
actualizado: "2025-12-15"
estado: "desactualizado"
pendiente: "TASK-PROP-AUTH-001"
notifications:
version_catalog: "1.0.5"
adoptantes:
gamilit:
version: "1.0.5"
estado: "sincronizado"
resumen:
total_modulos: 11
total_adoptantes: 14
sincronizados: 12
desactualizados: 2
pendientes:
- "erp_core → auth 1.2.0"
- "trading → notifications 1.0.5"
7. TEMPLATES DE INVENTARIOS NUEVOS
7.1 PRODUCTION-INVENTORY.yml
# Template para inventario de producción
metadata:
version: "1.0.0"
updated: "{fecha}"
responsable: "@PERFIL_PRODUCTION_MANAGER"
servidores:
- nombre: "prod-01"
ip: "xxx.xxx.xxx.xxx"
rol: "app-server"
os: "Ubuntu 22.04"
specs: "4 vCPU, 8GB RAM"
servicios_pm2:
gamilit:
- nombre: "gamilit-api"
puerto: 3006
instancias: 2
memoria_max: "512M"
ecosystem: "/var/www/gamilit/ecosystem.config.js"
nginx_sites:
- dominio: "app.gamilit.com"
config: "/etc/nginx/sites-available/gamilit"
upstream: "localhost:3006"
ssl: true
cert_expiry: "2026-03-15"
certificados:
- dominio: "*.gamilit.com"
tipo: "wildcard"
proveedor: "letsencrypt"
expira: "2026-03-15"
auto_renew: true
ufw_rules:
- puerto: 80
accion: "allow"
motivo: "HTTP redirect"
- puerto: 443
accion: "allow"
motivo: "HTTPS"
- puerto: 22
accion: "allow from {office_ip}"
motivo: "SSH restringido"
7.2 CICD-PIPELINES-INVENTORY.yml
# Template para inventario de pipelines CI/CD
metadata:
version: "1.0.0"
updated: "{fecha}"
responsable: "@PERFIL_CICD_SPECIALIST"
pipelines:
gamilit:
tipo: "jenkins"
url: "https://jenkins.isem.dev/job/gamilit/"
branches:
- nombre: "main"
trigger: "push"
stages: ["checkout", "install", "lint", "test", "build", "deploy-prod"]
- nombre: "develop"
trigger: "push"
stages: ["checkout", "install", "lint", "test", "build", "deploy-staging"]
webhooks:
- github: "https://jenkins.isem.dev/github-webhook/"
ultimo_build:
numero: 123
estado: "SUCCESS"
fecha: "2026-01-04"
trading_platform:
tipo: "jenkins"
url: "https://jenkins.isem.dev/job/trading-platform/"
estructura: "monorepo"
sub_pipelines:
- nombre: "trading-api"
stages: ["checkout", "install", "lint", "test", "build"]
- nombre: "trading-ml"
stages: ["checkout", "setup-python", "lint", "test"]
- nombre: "trading-frontend"
stages: ["checkout", "install", "lint", "test", "build"]
7.3 MONITORING-CONFIG.yml
# Template para configuración de monitoreo
metadata:
version: "1.0.0"
updated: "{fecha}"
responsable: "@PERFIL_MONITORING_AGENT"
prometheus:
url: "http://localhost:9090"
scrape_interval: "15s"
targets:
- nombre: "gamilit-api"
url: "localhost:3006/metrics"
labels: {project: "gamilit", type: "api"}
- nombre: "trading-api"
url: "localhost:3081/metrics"
labels: {project: "trading", type: "api"}
grafana:
url: "http://localhost:9091"
dashboards:
- nombre: "Overview"
uid: "overview-001"
tags: ["general"]
- nombre: "Gamilit Performance"
uid: "gamilit-perf"
tags: ["gamilit"]
alertas:
canales:
- nombre: "slack-critical"
tipo: "slack"
webhook: "${SLACK_WEBHOOK_URL}"
severidad: ["critical"]
- nombre: "email-warnings"
tipo: "email"
destino: "alerts@isem.dev"
severidad: ["warning", "critical"]
reglas:
- nombre: "HighErrorRate"
expr: "rate(http_requests_total{status=~'5..'}[5m]) > 0.05"
for: "5m"
severidad: "critical"
notificar: ["slack-critical"]
8. ORDEN DE EJECUCION REFINADO (FASE 6)
fase_6_1:
nombre: "Infraestructura Base"
duracion_estimada: "Sesión 1"
crear:
perfiles:
- "orchestration/agents/perfiles/PERFIL-PRODUCTION-MANAGER.md"
- "orchestration/agents/perfiles/PERFIL-SECRETS-MANAGER.md"
inventarios:
- "orchestration/inventarios/PRODUCTION-INVENTORY.yml"
- "orchestration/inventarios/ENV-VARS-INVENTORY.yml"
validar:
- "Formato consistente con perfiles existentes"
- "Secciones obligatorias presentes"
fase_6_2:
nombre: "Observabilidad y CI/CD"
duracion_estimada: "Sesión 2"
crear:
perfiles:
- "orchestration/agents/perfiles/PERFIL-MONITORING-AGENT.md"
- "orchestration/agents/perfiles/PERFIL-CICD-SPECIALIST.md"
inventarios:
- "orchestration/inventarios/MONITORING-CONFIG.yml"
- "orchestration/inventarios/CICD-PIPELINES-INVENTORY.yml"
validar:
- "Comandos frecuentes funcionales"
- "Templates aplicables"
fase_6_3:
nombre: "Propagación y Actualizaciones"
duracion_estimada: "Sesión 3"
crear:
perfiles:
- "orchestration/agents/perfiles/PERFIL-PROPAGATION-TRACKER.md"
inventarios:
- "shared/knowledge-base/TRAZABILIDAD-PROPAGACION.yml"
actualizar:
- "orchestration/agents/perfiles/PERFIL-DEVOPS.md"
- "orchestration/agents/perfiles/PERFIL-DEVENV.md"
- "core/orchestration/agents/perfiles/PERFIL-KB-MANAGER.md"
validar:
- "Referencias cruzadas correctas"
- "No duplicación de responsabilidades"
fase_6_4:
nombre: "Especializaciones (Opcional)"
duracion_estimada: "Sesión 4"
crear:
- "projects/trading-platform/orchestration/agents/PERFIL-TRADING-ML-SPECIALIST.md"
- "projects/gamilit/orchestration/agents/PERFIL-GAMIFICATION-SPECIALIST.md"
notas:
- "Solo si hay tiempo"
- "Pueden crearse bajo demanda"
9. VALIDACION POST-REFINAMIENTO
9.1 Checklist de Calidad por Perfil
checklist_perfil:
estructura:
- "[ ] Tiene PROTOCOLO DE INICIALIZACION"
- "[ ] Tiene IDENTIDAD completa"
- "[ ] Tiene CONTEXT REQUIREMENTS"
- "[ ] Tiene RESPONSABILIDADES (hace/no hace)"
- "[ ] Tiene COMANDOS FRECUENTES"
- "[ ] Tiene ALIAS RELEVANTES"
contenido:
- "[ ] Responsabilidades no se solapan con otros perfiles"
- "[ ] Comandos son ejecutables"
- "[ ] Referencias a archivos existentes son correctas"
- "[ ] Versión y fecha actualizadas"
9.2 Checklist de Inventario
checklist_inventario:
- "[ ] YAML válido (yamllint)"
- "[ ] Metadata completa"
- "[ ] Referencias a perfiles correctas"
- "[ ] Datos ejemplo realistas"
Plan refinado y listo para ejecución.
Documento generado por: NEXUS v3.4 + SIMCO Próxima acción: FASE 6 - Ejecución del plan