docs: actualizar README.md y STATUS.md con estado actual y plan

Co-authored-by: aider (openrouter/openai/gpt-5) <aider@aider.chat>
pull/1/head
borja 2 months ago
parent 939cf1ac9f
commit a8afa74ff5

@ -95,7 +95,7 @@ Estado: la tabla response_queue ya está creada e incluida en los tests de DB.
- Basic `/tarea` command detection (`src/server.ts`) and processing structure (`src/services/command.ts` - logic is placeholder). - Basic `/tarea` command detection (`src/server.ts`) and processing structure (`src/services/command.ts` - logic is placeholder).
- Task data models (`src/tasks/model.ts`). - Task data models (`src/tasks/model.ts`).
- Basic task creation service stub (`src/tasks/service.ts` - needs `created_by` and assignment logic). - Basic task creation service stub (`src/tasks/service.ts` - needs `created_by` and assignment logic).
- Response queue structure (`src/services/response-queue.ts` - `process` method is empty). - Response queue persistente con workers en background y envío vía Evolution API (`src/services/response-queue.ts`).
- Environment variable validation (`src/server.ts`, `src/services/webhook-manager.ts`). - Environment variable validation (`src/server.ts`, `src/services/webhook-manager.ts`).
- Health check endpoint (`/health`). - Health check endpoint (`/health`).
- **User validation integration**: Normalization and `ensureUserExists` are now fully integrated in the main message handling flow (`src/server.ts`). - **User validation integration**: Normalization and `ensureUserExists` are now fully integrated in the main message handling flow (`src/server.ts`).
@ -103,10 +103,9 @@ Estado: la tabla response_queue ya está creada e incluida en los tests de DB.
- **Database isolation in unit tests**: Implemented using in-memory instances to avoid conflicts between tests. - **Database isolation in unit tests**: Implemented using in-memory instances to avoid conflicts between tests.
### Incomplete / Missing Core Functionality ### Incomplete / Missing Core Functionality
- **User/Group Validation Integration:** Although normalization (`normalizeWhatsAppId`) and user creation (`ensureUserExists`) functions exist, they are **not yet integrated** into the main request handling flow in `src/server.ts` to validate senders or automatically add users on first message. Similarly, the active group cache from `group-sync.ts` is **not yet used** in `src/server.ts` to filter messages from inactive/unknown groups. - **Filtro de grupos activos:** La sincronización existe y hay caché; queda por reforzar el uso del filtro de grupos activos en `src/server.ts` si se requiere un bloqueo más estricto.
- **Core Command Logic:** Actual processing of `/tarea nueva` (parsing args, calling `TaskService`) is missing in `CommandService`. Other commands (`mostrar`, `completar`) not implemented. - **Core Command Logic:** Actual processing of `/tarea nueva` (parsing args, calling `TaskService`) is missing in `CommandService`. Other commands (`mostrar`, `completar`) not implemented.
- **Task Service Implementation:** `TaskService` needs updating to handle `created_by`, assignments, and potentially methods for listing/completing tasks. - **Task Service Implementation:** `TaskService` needs updating to handle `created_by`, assignments, and potentially methods for listing/completing tasks.
- **Response Sending:** `ResponseQueue` does not yet send messages back via the Evolution API.
- **Database Migrations:** No system in place to manage schema changes. - **Database Migrations:** No system in place to manage schema changes.
- **Robust Error Handling:** Comprehensive error handling, logging, and transaction management need improvement, especially around API calls and DB operations. - **Robust Error Handling:** Comprehensive error handling, logging, and transaction management need improvement, especially around API calls and DB operations.
@ -158,21 +157,20 @@ bun test
- [x] **Integrate Validation in Server:** (`src/server.ts`) Use normalization, `ensureUserExists`, and active group check before processing commands. - [x] **Integrate Validation in Server:** (`src/server.ts`) Use normalization, `ensureUserExists`, and active group check before processing commands.
- [x] **Implement DB isolation in tests:** (`tests/unit/services/group-sync.test.ts`) Use in-memory instances to avoid conflicts. - [x] **Implement DB isolation in tests:** (`tests/unit/services/group-sync.test.ts`) Use in-memory instances to avoid conflicts.
### Phase 2: Implement `/tarea nueva` Command (High Priority) ### Phase 2: Refinar `/tarea nueva` (Alta prioridad)
- [ ] **Update `TaskService.createTask`:** (`src/tasks/service.ts`) Handle `created_by` and assignments (including adding assigned users via `ensureUserExists`). - [ ] Completar `TaskService.createTask` con `created_by` y asignaciones (incluyendo `ensureUserExists` para asignados) y transacción atómica.
- [ ] **Implement `/tarea nueva` Logic:** (`src/services/command.ts`) Parse description, due date, mentions; call `TaskService`; generate response messages. - [ ] Mejorar `CommandService` para parsear menciones y devolver el id de la tarea creada y resumen de asignados.
### Phase 3: Implement Response Sending (High Priority) ### Phase 3: Comandos adicionales y refinamientos (Alta prioridad)
- [ ] **Implement `ResponseQueue.process`:** (`src/services/response-queue.ts`) Send queued messages via Evolution API's send endpoint. - [ ] Implementar `/tarea mostrar [group|mine]` para listar pendientes.
- [ ] **Trigger Queue Processing:** (`src/server.ts`) Call `ResponseQueue.process()` after command handling. - [ ] Implementar `/tarea completar <task_id>` con validaciones básicas.
- [ ] **Persist Response Queue in Database:** (`src/services/response-queue.ts`, `src/db.ts`) Add table for queued responses to avoid loss on server restart (important for reliability). - [ ] Soportar mensajes de texto extendido y captions de media (además de conversation).
### Phase 4: Further Commands & Refinements (Medium Priority) ### Phase 4: Fiabilidad de la cola y observabilidad (Media)
- [ ] Implement `/tarea mostrar [group|mine]` command. - [ ] Añadir reintentos con backoff exponencial y jitter.
- [ ] Implement `/tarea completar <task_id>` command. - [ ] Recuperar ítems en estado `processing` tras reinicios (lease o expiración y requeue).
- [ ] Add Database Migrations system. - [ ] Métricas y logging mejorado (contadores de enviados/fallidos, tiempos).
- [ ] Improve Error Handling & Logging (API calls, DB transactions). - [ ] Limpieza/retención de historiales.
- [ ] Refine Group Sync (Delta updates).
### Phase 5: Advanced Features (Low Priority) ### Phase 5: Advanced Features (Low Priority)
- [ ] Add task reminders system. - [ ] Add task reminders system.
@ -183,7 +181,7 @@ bun test
## 🔑 Key Considerations & Caveats ## 🔑 Key Considerations & Caveats
* **WhatsApp ID Normalization:** Crucial for consistently identifying users and groups. Needs careful implementation to handle edge cases. (Utility function exists). * **WhatsApp ID Normalization:** Crucial for consistently identifying users and groups. Needs careful implementation to handle edge cases. (Utility function exists).
* **Response Latency:** Sending responses requires an API call back to Evolution. Ensure the `ResponseQueue` processing is efficient. * **Response Latency:** Sending responses requires an API call back to Evolution. Ensure the `ResponseQueue` processing is efficient.
* **Response Queue Persistence:** Currently in-memory; consider persisting in DB to prevent message loss on restarts (added to Phase 3 roadmap). * **Cola de respuestas:** Persistente en DB; pendiente añadir reintentos/backoff y limpieza/retención.
* **Group Sync:** The current full sync might be slow or rate-limited with many groups. Delta updates are recommended long-term. * **Group Sync:** The current full sync might be slow or rate-limited with many groups. Delta updates are recommended long-term.
* **Error Handling:** Failures in command processing or response sending should be logged clearly and potentially reported back to the user. Database operations should use transactions for atomicity (especially task+assignment creation). * **Error Handling:** Failures in command processing or response sending should be logged clearly and potentially reported back to the user. Database operations should use transactions for atomicity (especially task+assignment creation).
* **State Management:** The current design is stateless. Complex interactions might require state persistence later. * **State Management:** The current design is stateless. Complex interactions might require state persistence later.

@ -15,38 +15,44 @@
- **Webhooks** - **Webhooks**
- Registro/verificación con Evolution API - Registro/verificación con Evolution API
- Manejo básico de eventos (MESSAGES_UPSERT) - Manejo básico de eventos (MESSAGES_UPSERT)
- Normalización del nombre del evento del webhook (soporta MESSAGES_UPSERT/messages.upsert)
- **Cola de Respuestas**
- Persistencia en DB y envío real a Evolution API
- Workers en background activos
- **Comandos** - **Comandos**
- Detección de /tarea - Detección de /tarea
- Parser básico de acciones/fechas - Parser básico de acciones/fechas
- **Testing**
- Suite completa de tests unitarios
- Todos los tests pasan (97 pass, 0 fail)
- **Validaciones de Usuario** - **Validaciones de Usuario**
- Integración completa de normalización y `ensureUserExists` en el flujo principal de mensajes - Integración completa de normalización y `ensureUserExists` en el flujo principal de mensajes
- Tests de integración para validaciones de usuarios - Tests de integración para validaciones de usuarios
- **Testing**
- Suite completa de tests unitarios
- Todos los tests pasan (97 pass, 0 fail)
- **Aislamiento de Base de Datos en Pruebas** - **Aislamiento de Base de Datos en Pruebas**
- Uso de instancias en memoria para evitar conflictos entre tests - Uso de instancias en memoria para evitar conflictos entre tests
## ⚠️ Funcionalidades Pendientes ## ⚠️ Funcionalidades Pendientes
- **Gestión de Tareas** - **Gestión de Tareas**
- Operaciones CRUD incompletas (solo creación) - Completar persistencia de creación (añadir `created_by` y asignaciones)
- Falta listar/completar/eliminar tareas - Listar/completar/eliminar tareas
- **Cola de Respuestas** - **Cola de Respuestas**
- Sin integración con Evolution API - Reintentos con backoff y jitter
- No envía mensajes realmente - Recuperación de ítems en estado `processing` tras caídas
- **Persistencia en DB en progreso** (importante para evitar pérdida de mensajes en reinicios) - Métricas/observabilidad y limpieza/retención
- **Validaciones** - **Validaciones**
- Permisos de usuario no implementados - Permisos de usuario no implementados
- Sin verificación de pertenencia a grupos - Verificación de pertenencia a grupos (si se requiere política estricta)
- **Comandos** - **Comandos**
- Acciones de tareas no implementadas (crear/listar) - Implementar `/tarea mostrar` y `/tarea completar`
- **Migraciones**
- Sistema de migraciones de esquema
## ➡️ Próximos Pasos Prioritarios ## ➡️ Próximos Pasos Prioritarios
1. Adaptar ResponseQueue.add a persistente (insert en DB) 1. Completar persistencia de tareas: `created_by` y asignaciones con `ensureUserExists`.
2. Implementar worker continuo básico (N workers, sin reintentos, sin orden estricto) 2. Implementar comandos: `/tarea mostrar` y `/tarea completar`.
3. Integrar el worker en server.start (desactivado en entorno de test) 3. Extender soporte de entrada: `extendedTextMessage` y captions de media.
4. Añadir tests unitarios de la cola con mocks de fetch 4. Mejoras de fiabilidad de la cola: reintentos con backoff y recuperación de `processing`.
5. Iteración siguiente: reintentos con backoff exponencial y mejoras de observabilidad 5. Métricas/observabilidad básicas y plan de migraciones de DB.
## 🔧 Archivos Clave a Modificar ## 🔧 Archivos Clave a Modificar
- `src/services/response-queue.ts` - `src/services/response-queue.ts`

Loading…
Cancel
Save