Files
aiworker/NEXT-SESSION.md
Hector Ros e5e039504e Rename CLUSTER-READY → K8S-CLUSTER (more direct)
Also added:
- DEVELOPMENT-WORKFLOW.md - Complete dev process documented
- Updated all references across documentation

Documentation is now centralized and direct.

Co-Authored-By: Claude Sonnet 4.5 (1M context) <noreply@anthropic.com>
2026-01-20 00:44:29 +01:00

8.7 KiB

📋 Próxima Sesión - Checklist Ejecutable

Objetivo: Completar Backend API y MCP Server básico Tiempo estimado: 2-3 horas


PRE-REQUISITOS (Verificar antes de empezar)

# 1. Cluster funcionando
export KUBECONFIG=~/.kube/aiworker-config
kubectl get nodes
# Debe mostrar 6 nodos Ready

# 2. Servicios corriendo
kubectl get pods -n control-plane
# mariadb-0: Running
# redis-xxx: Running

kubectl get pods -n gitea
# gitea-0: Running

# 3. Backend local
cd backend
bun --version
# 1.3.6

# 4. Gitea accesible
curl -I https://git.fuq.tv
# HTTP/2 200

Si algo falla, consulta: K8S-CLUSTER.md y TROUBLESHOOTING.md


🎯 PASO 1: Verificar CI/CD (15 min)

1.1 Revisar último build

# Ver en Gitea Actions
open https://git.fuq.tv/admin/aiworker-backend/actions

Opciones:

  • Si build exitoso: Continuar a paso 2
  • Si build fallido: Ver logs, corregir, push de nuevo

1.2 Verificar imagen en registry

# Vía UI
open https://git.fuq.tv/admin/-/packages

# Vía API
curl https://git.fuq.tv/api/v1/packages/admin/container?type=container

Debe existir: aiworker-backend con tag latest

1.3 Si no hay imagen, build manual

# Desde un nodo del cluster (si Docker local no funciona)
ssh root@108.165.47.225  # worker-01

cd /tmp
git clone https://git.fuq.tv/admin/aiworker-backend.git
cd aiworker-backend

docker build -t git.fuq.tv/admin/aiworker-backend:latest .
docker login git.fuq.tv -u admin -p 7401126cfb56ab2aebba17755bdc968c20768c27
docker push git.fuq.tv/admin/aiworker-backend:latest

🎯 PASO 2: Implementar API Routes (45 min)

2.1 Crear estructura de routes

cd backend/src/api
mkdir routes

# Archivos a crear:
# - routes/projects.ts
# - routes/tasks.ts
# - routes/agents.ts
# - routes/index.ts

2.2 Implementar Projects API

Archivo: src/api/routes/projects.ts

Endpoints necesarios:

GET    /api/projects          // List all
GET    /api/projects/:id      // Get one
POST   /api/projects          // Create
PATCH  /api/projects/:id      // Update
DELETE /api/projects/:id      // Delete

Referencia: docs/02-backend/api-endpoints.md (líneas 15-80)

Conectar con Bun.serve():

// En src/index.ts
import { handleProjectRoutes } from './api/routes/projects'

if (url.pathname.startsWith('/api/projects')) {
  return handleProjectRoutes(req, url)
}

2.3 Implementar Tasks API

Archivo: src/api/routes/tasks.ts

Endpoints principales:

GET    /api/tasks             // List with filters
GET    /api/tasks/:id         // Get details
POST   /api/tasks             // Create
PATCH  /api/tasks/:id         // Update
POST   /api/tasks/:id/respond // Respond to question

2.4 Probar APIs localmente

# Terminal 1: Port-forward MariaDB
kubectl port-forward -n control-plane svc/mariadb 3306:3306 &

# Terminal 2: Port-forward Redis
kubectl port-forward -n control-plane svc/redis 6379:6379 &

# Terminal 3: Run backend
cd backend
bun run dev

# Terminal 4: Test
curl http://localhost:3000/api/health
curl http://localhost:3000/api/projects

🎯 PASO 3: MCP Server Básico (60 min)

3.1 Crear estructura MCP

mkdir -p src/services/mcp
# Archivos:
# - services/mcp/server.ts
# - services/mcp/tools.ts
# - services/mcp/handlers.ts

3.2 Implementar herramientas básicas

Herramientas mínimas para MVP:

  1. get_next_task - Obtener siguiente tarea
  2. update_task_status - Actualizar estado
  3. create_branch - Crear rama en Gitea
  4. create_pull_request - Crear PR

Referencia: docs/05-agents/mcp-tools.md

Template básico:

// src/services/mcp/server.ts
import { Server } from '@modelcontextprotocol/sdk/server/index.js'

export class MCPServer {
  private server: Server

  constructor() {
    this.server = new Server({
      name: 'aiworker-mcp',
      version: '1.0.0'
    }, {
      capabilities: { tools: {} }
    })

    this.setupHandlers()
  }

  // Implementar handlers...
}

3.3 Conectar MCP con Bun.serve()

Opciones:

  • A: Puerto separado (3100) para MCP
  • B: Ruta /mcp en mismo server

Recomendación: Opción A (puerto 3100)


🎯 PASO 4: Integración con Gitea (30 min)

4.1 Cliente API de Gitea

Archivo: src/services/gitea/client.ts

Operaciones necesarias:

- createRepo(name, description)
- createBranch(owner, repo, branch, from)
- createPullRequest(owner, repo, {title, body, head, base})
- mergePullRequest(owner, repo, number)

Usar:

  • Axios para HTTP requests
  • Base URL: https://git.fuq.tv/api/v1
  • Token: Variable de entorno GITEA_TOKEN

Referencia: docs/02-backend/gitea-integration.md (líneas 10-200)

4.2 Test de integración

# Crear un repo de prueba vía API
bun run src/test-gitea.ts

🎯 PASO 5: Deploy Backend en K8s (30 min)

5.1 Crear manifests

Directorio: k8s/backend/

Archivos necesarios:

# deployment.yaml
# service.yaml
# ingress.yaml
# secrets.yaml

Template deployment:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: backend
  namespace: control-plane
spec:
  replicas: 2
  selector:
    matchLabels:
      app: backend
  template:
    spec:
      imagePullSecrets:
      - name: gitea-registry
      containers:
      - name: backend
        image: git.fuq.tv/admin/aiworker-backend:latest
        ports:
        - containerPort: 3000
        - containerPort: 3100  # MCP
        env:
        - name: DB_HOST
          value: mariadb.control-plane.svc.cluster.local
        # ... más env vars

5.2 Crear secrets

kubectl create secret generic backend-secrets -n control-plane \
  --from-literal=jwt-secret=your-secret \
  --from-literal=anthropic-api-key=your-key

5.3 Deploy

kubectl apply -f k8s/backend/
kubectl get pods -n control-plane
kubectl logs -f deployment/backend -n control-plane

5.4 Crear Ingress

# Para api.fuq.tv
host: api.fuq.tv
backend: backend:3000

5.5 Verificar

curl https://api.fuq.tv/api/health

🎯 PASO 6: Test End-to-End (15 min)

6.1 Crear proyecto vía API

curl -X POST https://api.fuq.tv/api/projects \
  -H "Content-Type: application/json" \
  -d '{
    "name": "test-project",
    "description": "First project"
  }'

6.2 Crear tarea

curl -X POST https://api.fuq.tv/api/tasks \
  -H "Content-Type: application/json" \
  -d '{
    "projectId": "xxx",
    "title": "Test task",
    "description": "First automated task"
  }'

6.3 Verificar en DB

kubectl exec -n control-plane mariadb-0 -- \
  mariadb -uaiworker -pAiWorker2026_UserPass! aiworker \
  -e "SELECT * FROM projects; SELECT * FROM tasks;"

📝 NOTAS IMPORTANTES

Desarrollo Local vs K8s

Local (desarrollo):

  • Port-forward para MariaDB y Redis
  • bun run dev con hot-reload
  • Cambios rápidos

K8s (testing/producción):

  • Build → Push → Deploy
  • Migrations automáticas en startup
  • Logs con kubectl

Migrations

SIEMPRE automáticas en el código:

// src/index.ts
await runMigrations()  // Al inicio

NUNCA manuales con port-forward

Secrets

Desarrollo: .env (git-ignored) Producción: Kubernetes Secrets

kubectl create secret generic app-secrets -n namespace \
  --from-env-file=.env.production

🐛 TROUBLESHOOTING

Si backend no arranca

# Ver logs
kubectl logs -n control-plane deployment/backend

# Verificar DB connection
kubectl exec -n control-plane mariadb-0 -- \
  mariadb -uaiworker -pAiWorker2026_UserPass! -e "SELECT 1"

# Verificar Redis
kubectl exec -n control-plane deployment/redis -- redis-cli ping

Si Actions no funciona

# Ver runner
kubectl get pods -n gitea-actions
kubectl logs -n gitea-actions deployment/gitea-runner -c runner

# Restart runner
kubectl rollout restart deployment/gitea-runner -n gitea-actions

Si Ingress no resuelve

# Verificar DNS
dig api.fuq.tv +short
# Debe mostrar: 108.165.47.221 y 108.165.47.203

# Verificar certificado
kubectl get certificate -n control-plane

# Logs de Ingress
kubectl logs -n ingress-nginx deployment/ingress-nginx-controller --tail=50

CHECKLIST DE SESIÓN

Al final de cada sesión, verificar:

  • Código commitado y pusheado a Gitea
  • Build de CI/CD exitoso
  • Pods corriendo en K8s
  • Endpoints accesibles vía HTTPS
  • Documentación actualizada
  • Credenciales documentadas en lugar seguro
  • Tests básicos pasando

🎉 META

Completado: Infraestructura HA + Backend base Próximo hito: Backend API funcional + MCP Server Hito final: Sistema completo de agentes autónomos

¡Excelente progreso! Sigue el roadmap y lo tendrás listo pronto! 🚀