Files
aiworker/DEVELOPMENT-WORKFLOW.md
Hector Ros db71705842 Complete documentation for future sessions
- CLAUDE.md for AI agents to understand the codebase
- GITEA-GUIDE.md centralizes all Gitea operations (API, Registry, Auth)
- DEVELOPMENT-WORKFLOW.md explains complete dev process
- ROADMAP.md, NEXT-SESSION.md for planning
- QUICK-REFERENCE.md, TROUBLESHOOTING.md for daily use
- 40+ detailed docs in /docs folder
- Backend as submodule from Gitea

Everything documented for autonomous operation.

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

428 lines
9.4 KiB
Markdown

# 🔄 Development Workflow - Cómo Trabajamos
Flujo completo de desarrollo usando Gitea, container registry y CI/CD automático.
---
## 📋 Overview del Workflow
```
Local Dev → Git Push → Gitea Actions → Docker Build → Registry Push → K8s Deploy
```
**Principios**:
-**CI/CD automático** - Cada push buildea automáticamente
-**Registry integrado** - Imágenes en Gitea, no Docker Hub
-**GitOps** - ArgoCD sincroniza desde Git
-**Sin Docker local** - Builds en el cluster
-**Preview automático** - Cada tarea tiene su environment
---
## 🛠️ Workflow Típico: Nueva Feature
### 1. Desarrollo Local
```bash
# Backend
cd backend
bun run dev # Hot reload activado
# Test localmente
curl http://localhost:3000/api/health
```
**Conexión a servicios K8s** (solo para desarrollo):
```bash
# Terminal 1: MariaDB
kubectl port-forward -n control-plane svc/mariadb 3306:3306
# Terminal 2: Redis
kubectl port-forward -n control-plane svc/redis 6379:6379
# Ahora el backend local puede conectar a DB/Redis en K8s
```
### 2. Commit y Push
```bash
git add .
git commit -m "Add feature X
Detailed description
Co-Authored-By: Claude Sonnet 4.5 (1M context) <noreply@anthropic.com>"
git push origin main
```
### 3. CI/CD Automático (Gitea Actions)
**Qué pasa automáticamente**:
1. Gitea recibe push
2. Workflow `.gitea/workflows/build.yml` se ejecuta
3. Runner en K8s (pod con Docker) buildea imagen
4. Push a `git.fuq.tv/admin/<repo>:latest`
5. Tag adicional con commit hash: `git.fuq.tv/admin/<repo>:<sha>`
**Monitorear**:
```bash
# Ver en UI
open https://git.fuq.tv/admin/aiworker-backend/actions
# Ver logs del runner
kubectl logs -n gitea-actions deployment/gitea-runner -c runner --tail=100 -f
```
**Tiempo típico**: 2-5 minutos (primer build más lento)
### 4. Verificar Imagen en Registry
```bash
# Ver en UI
open https://git.fuq.tv/admin/-/packages
# O via API
curl -H "Authorization: token 159a5de2a16d15f33e388b55b1276e431dbca3f3" \
https://git.fuq.tv/api/v1/packages/admin/container
```
**Debe aparecer**: `aiworker-backend` con tags `latest` y `<commit-hash>`
### 5. Deploy en K8s (manual por ahora, ArgoCD después)
```bash
# Aplicar manifests
kubectl apply -f k8s/backend/
# O update imagen específica
kubectl set image deployment/backend backend=git.fuq.tv/admin/aiworker-backend:latest -n control-plane
# Verificar rollout
kubectl rollout status deployment/backend -n control-plane
# Ver logs
kubectl logs -f deployment/backend -n control-plane
```
### 6. Verificar en Producción
```bash
# Health check
curl https://api.fuq.tv/api/health
# Test endpoints
curl https://api.fuq.tv/api/projects
```
---
## 🌿 Workflow: Feature Branch
### 1. Crear Branch
```bash
git checkout -b feature/nueva-funcionalidad
```
### 2. Desarrollar y Commit
```bash
# Hacer cambios
bun run dev # Test local
git add .
git commit -m "Implement nueva funcionalidad"
git push origin feature/nueva-funcionalidad
```
### 3. Crear Pull Request
**Opción A - UI**:
1. https://git.fuq.tv/admin/aiworker-backend
2. "New Pull Request"
3. Base: main ← Compare: feature/nueva-funcionalidad
**Opción B - API** (desde backend):
```typescript
const pr = await giteaClient.createPullRequest('admin', 'aiworker-backend', {
title: 'Nueva funcionalidad',
body: 'Descripción detallada',
head: 'feature/nueva-funcionalidad',
base: 'main'
})
```
### 4. Review y Merge
**Manual** (UI):
- Review code
- Click "Merge Pull Request"
**Automático** (via backend):
```typescript
await giteaClient.mergePullRequest('admin', 'aiworker-backend', prNumber, 'squash')
```
### 5. Deploy Automático post-Merge
Una vez mergeado a `main`, el CI/CD rebuildeará automáticamente.
---
## 🚀 Workflow: Deploy de Preview
Para cada tarea, se crea un preview environment aislado.
### Proceso Completo
```typescript
// 1. Agente completa tarea
// 2. Crea branch y PR (via MCP)
// 3. Backend crea preview deployment
const previewNamespace = `preview-task-${taskId.slice(0, 8)}`
// Crear namespace en K8s
await k8sClient.createNamespace(previewNamespace)
// Deploy app
await k8sClient.createDeployment({
namespace: previewNamespace,
name: 'app',
image: `git.fuq.tv/admin/aiworker-backend:${branchName}`,
// ... config
})
// Crear ingress
await k8sClient.createIngress({
namespace: previewNamespace,
host: `task-${taskId.slice(0, 8)}.r.fuq.tv`,
// ... config
})
// 4. Usuario accede a:
// https://task-abc12345.r.fuq.tv
// 5. Si aprueba → merge a staging
// 6. Cleanup automático después de 7 días
```
---
## 🎨 Workflow: Multi-Repo
Eventualmente tendremos múltiples repos:
```
/admin/aiworker-backend → Backend API
/admin/aiworker-frontend → Dashboard React
/admin/aiworker-agents → Agent Docker image
/admin/aiworker-gitops → ArgoCD manifests
/aiworker/<project-name> → Proyectos de usuarios
```
**Cada repo**:
- Tiene su propio `.gitea/workflows/build.yml`
- Buildea a `git.fuq.tv/<owner>/<repo>:<tag>`
- Deploy independiente
---
## 🔐 Autenticación en Diferentes Contextos
### 1. Git Clone/Push (HTTPS)
```bash
# Con token en URL (inseguro pero funciona)
git clone https://admin:159a5de2a16d15f33e388b55b1276e431dbca3f3@git.fuq.tv/admin/myrepo.git
# O configurar credential helper
git config --global credential.helper store
git clone https://git.fuq.tv/admin/myrepo.git
# Primera vez pedirá user/password, luego lo guarda
```
### 2. Docker Registry
```bash
docker login git.fuq.tv -u admin -p 7401126cfb56ab2aebba17755bdc968c20768c27
```
### 3. Kubernetes Pulls
**Secret ya creado**:
```bash
# En control-plane y agents
kubectl get secret gitea-registry -n control-plane
kubectl get secret gitea-registry -n agents
```
**Usar en deployment**:
```yaml
imagePullSecrets:
- name: gitea-registry
```
### 4. API Calls
**Header**:
```bash
curl -H "Authorization: token 159a5de2a16d15f33e388b55b1276e431dbca3f3" \
https://git.fuq.tv/api/v1/user/repos
```
### 5. Webhooks
**Secret** (para verificar requests):
```bash
# Configurar en webhook
"secret": "webhook-secret-aiworker-2026"
# Verificar en backend usando HMAC
```
---
## 📦 Build Strategies
### Estrategia Actual: Gitea Actions
**Ventajas**:
- ✅ Sin Docker local necesario
- ✅ Build en cluster (más recursos)
- ✅ Histórico de builds en UI
- ✅ Cacheo de layers
**Cómo funciona**:
```
Push → Gitea Actions → Runner Pod (DinD) → Docker build → Push to registry
```
**Configuración**:
- Runner: Pod en namespace `gitea-actions`
- Docker-in-Docker (DinD) para builds
- Volumenes compartidos para cache
### Alternativa Futura: ArgoCD Image Updater
Cuando esté configurado:
```
Push → Build → Registry → ArgoCD detecta → Auto-update K8s → Deploy
```
---
## 🎯 Checklist de Feature Completa
- [ ] Desarrollo local con `bun run dev`
- [ ] Test manual de endpoints
- [ ] Commit con mensaje descriptivo
- [ ] Push a Gitea
- [ ] Verificar build en Actions (verde ✅)
- [ ] Verificar imagen en registry
- [ ] Deploy en K8s (manual o ArgoCD)
- [ ] Verificar pods running
- [ ] Test en producción (`api.fuq.tv`)
- [ ] Verificar logs sin errores
---
## 🐛 Troubleshooting del Workflow
### Build Falla en Actions
```bash
# Ver logs del job
https://git.fuq.tv/admin/aiworker-backend/actions/runs/<run-id>
# Ver runner logs
kubectl logs -n gitea-actions deployment/gitea-runner -c runner --tail=200
# Problemas comunes:
# - Dockerfile error → Fix Dockerfile
# - Dependencias faltantes → Update package.json
# - Registry auth → Verificar REGISTRY_TOKEN secret
```
**Fix**: Corregir error, commit, push de nuevo.
### Build OK pero K8s no Pulla Imagen
```bash
# Verificar secret
kubectl get secret gitea-registry -n control-plane
# Verificar imagePullSecrets en deployment
kubectl get deployment backend -n control-plane -o yaml | grep imagePullSecrets
# Ver eventos
kubectl describe pod <pod-name> -n control-plane | grep -i pull
```
**Fix**: Recrear secret o agregar `imagePullSecrets` al deployment.
### Imagen en Registry pero versión vieja en K8s
```bash
# Force pull nueva imagen
kubectl rollout restart deployment/backend -n control-plane
# O delete pod para recrear
kubectl delete pod <pod-name> -n control-plane
```
**Nota**: Si usas tag `latest`, K8s cachea. Mejor usar tags específicos (`v1.0.0`, `main-abc1234`).
---
## 📊 Monitoring del Workflow
### CI/CD Health
```bash
# Runner status
kubectl get pods -n gitea-actions
# Workflows recientes
open https://git.fuq.tv/admin/aiworker-backend/actions
# Registry usage
open https://git.fuq.tv/admin/-/packages
```
### Deployments
```bash
# Backend
kubectl get pods -n control-plane
kubectl logs -f deployment/backend -n control-plane
# Frontend (cuando exista)
kubectl get pods -n control-plane
kubectl logs -f deployment/frontend -n control-plane
```
---
## 🎓 Best Practices
1. **Commits frecuentes** - Push pequeños, builds rápidos
2. **Tags semánticos** - `v1.0.0`, `v1.1.0` para releases
3. **Branch strategy** - `main` (prod), `develop` (staging), `feature/*` (features)
4. **PR reviews** - Siempre review antes de merge
5. **Registry cleanup** - Eliminar imágenes viejas periódicamente
6. **Logs** - Siempre verificar logs post-deploy
---
## 🔗 Referencias
- **Guía Gitea completa**: `GITEA-GUIDE.md`
- **Container Registry**: `docs/CONTAINER-REGISTRY.md` (puedes eliminar después)
- **API Gitea**: `docs/02-backend/gitea-integration.md` (código de ejemplo)
- **CI/CD**: `docs/06-deployment/ci-cd.md`
---
**✅ Con este workflow, el desarrollo es fluido: código local → push → build automático → deploy → verificar.**