workspace/ANALISIS-WORKSPACE-COMPLETO.md
Adrian Flores Cortes e360b88612
Some checks are pending
CI Pipeline / changes (push) Waiting to run
CI Pipeline / core (push) Blocked by required conditions
CI Pipeline / trading-backend (push) Blocked by required conditions
CI Pipeline / trading-data-service (push) Blocked by required conditions
CI Pipeline / trading-frontend (push) Blocked by required conditions
CI Pipeline / erp-core (push) Blocked by required conditions
CI Pipeline / erp-mecanicas (push) Blocked by required conditions
CI Pipeline / gamilit-backend (push) Blocked by required conditions
CI Pipeline / gamilit-frontend (push) Blocked by required conditions
changes on erp
2025-12-18 06:25:52 -06:00

974 lines
32 KiB
Markdown

# ANALISIS COMPLETO DEL WORKSPACE - FABRICA DE SOFTWARE CON AGENTES IA
**Fecha de Analisis:** 2025-12-18
**Version:** 1.0.0
**Autor:** Sistema NEXUS - Claude Opus 4.5
**Tipo:** Documento de Analisis Integral
---
## TABLA DE CONTENIDOS
1. [Vision General del Workspace](#1-vision-general-del-workspace)
2. [Estructura de Carpetas y Organizacion](#2-estructura-de-carpetas-y-organizacion)
3. [Sistema de Orquestacion de Agentes (NEXUS)](#3-sistema-de-orquestacion-de-agentes-nexus)
4. [Perfiles de Agentes](#4-perfiles-de-agentes)
5. [Sistema de Directivas SIMCO](#5-sistema-de-directivas-simco)
6. [Principios Fundamentales](#6-principios-fundamentales)
7. [Catalogo de Funcionalidades Reutilizables](#7-catalogo-de-funcionalidades-reutilizables)
8. [Proyectos y Verticales](#8-proyectos-y-verticales)
9. [Referencias Base (Odoo y Legacy)](#9-referencias-base-odoo-y-legacy)
10. [Estandares de Documentacion](#10-estandares-de-documentacion)
11. [Arquitectura SaaS Multi-Portal](#11-arquitectura-saas-multi-portal)
12. [Flujos de Trabajo y Segmentacion](#12-flujos-de-trabajo-y-segmentacion)
---
## 1. VISION GENERAL DEL WORKSPACE
### 1.1 Proposito
Este workspace implementa una **Fabrica de Software gestionada por Agentes de IA**, con las siguientes caracteristicas:
- **Multi-proyecto:** Soporte para proyectos standalone y suites multi-verticales
- **Reutilizacion de codigo:** Catalogo centralizado de funcionalidades probadas
- **Base de conocimiento compartida:** Referencias de Odoo, patrones ERP, legacy code
- **Orquestacion inteligente:** Sistema NEXUS para coordinacion de agentes especializados
### 1.2 Estadisticas del Workspace
| Metrica | Valor |
|---------|-------|
| Proyectos Standalone | 4 (Gamilit, Trading, Betting, Inmobiliaria) |
| Suite Multi-vertical | 1 (ERP Suite con 5 verticales) |
| Verticales ERP | 5 (Construccion, Mecanicas, Vidrio, Retail, Clinicas) |
| Funcionalidades en Catalogo | 8 |
| Perfiles de Agentes | 12+ |
| Directivas SIMCO | 22+ |
| Story Points Totales | 1,663+ |
---
## 2. ESTRUCTURA DE CARPETAS Y ORGANIZACION
### 2.1 Estructura Principal
```
~/workspace/
|
+-- core/ # NUCLEO DE LA FABRICA
| +-- orchestration/ # Sistema de agentes NEXUS + SIMCO
| | +-- agents/ # Perfiles de agentes
| | | +-- perfiles/ # Definiciones de roles
| | | +-- legacy/ # Prompts anteriores
| | +-- directivas/ # Directivas y principios
| | | +-- simco/ # Sistema SIMCO completo
| | | +-- principios/ # 5 principios fundamentales
| | | +-- legacy/ # Directivas historicas
| | +-- templates/ # Plantillas CAPVED
| | +-- checklists/ # Listas de verificacion
| | +-- patrones/ # Patrones de codigo
| | +-- referencias/ # ALIASES.yml y referencias
| | +-- impactos/ # Matrices de impacto
| +-- catalog/ # Funcionalidades reutilizables
| +-- modules/ # Codigo compartido
| +-- constants/ # Constantes globales
| +-- types/ # Tipos TypeScript compartidos
| +-- standards/ # Estandares tecnicos
|
+-- projects/ # PROYECTOS/PRODUCTOS
| +-- erp-suite/ # Suite ERP multi-vertical
| | +-- apps/
| | | +-- erp-core/ # Core compartido
| | | +-- verticales/ # 5 verticales especializadas
| | | +-- products/ # Productos derivados
| | +-- orchestration/ # Orquestacion a nivel suite
| +-- gamilit/ # Plataforma EdTech
| +-- trading-platform/ # Bots de trading
| +-- betting-analytics/ # Prediccion apuestas
| +-- inmobiliaria-analytics/ # Analisis inmobiliario
|
+-- customers/ # IMPLEMENTACIONES PERSONALIZADAS
| +-- template/ # Template para nuevos clientes
|
+-- knowledge-base/ # BASE DE CONOCIMIENTO (RAG)
| +-- reference/
| | +-- odoo/ # Referencia de Odoo
| | +-- erp-inmobiliaria-legacy/
|
+-- workspaces/ # Workspaces efimeros por tarea
|
+-- devtools/ # HERRAMIENTAS DE DESARROLLO
| +-- scripts/ # Scripts de automatizacion
| +-- templates/ # Templates de proyectos
| +-- docker/ # Configuracion Docker
|
+-- orchestration/ # Orquestacion nivel workspace
+-- referencias/
+-- PROYECTOS-ACTIVOS.yml # Registro de proyectos
```
### 2.2 Sistema de Niveles Jerarquicos
El workspace utiliza un sistema de **niveles jerarquicos** para organizacion:
| Nivel | Descripcion | Ejemplo |
|-------|-------------|---------|
| **0** | Workspace Root | `~/workspace/` |
| **1** | Core de la Fabrica | `core/` |
| **2A** | Proyectos Standalone | `projects/gamilit/` |
| **2B** | Suite Multi-vertical | `projects/erp-suite/` |
| **2B.1** | Core de Suite | `erp-suite/apps/erp-core/` |
| **2B.2** | Verticales | `erp-suite/apps/verticales/construccion/` |
| **3** | Modulos/Features | `vertical/backend/src/modules/x/` |
---
## 3. SISTEMA DE ORQUESTACION DE AGENTES (NEXUS)
### 3.1 Arquitectura del Sistema NEXUS
```
+-----------------------------------------------------------------------+
| SISTEMA NEXUS |
+-----------------------------------------------------------------------+
| |
| +------------------+ +------------------+ +------------------+ |
| | TECH-LEADER | | REQUIREMENTS | | ARCHITECTURE | |
| | (Orquestador) | | ANALYST | | ANALYST | |
| +--------+---------+ +--------+---------+ +--------+---------+ |
| | | | |
| +----------+------------+------------+----------+ |
| | | |
| +------------------+|+------------------+ +------------------+ |
| | DATABASE-AGENT ||| BACKEND-AGENT | | FRONTEND-AGENT | |
| | (PostgreSQL) ||| (NestJS/Express)| | (React) | |
| +------------------+|+------------------+ +------------------+ |
| | |
| +------------------+|+------------------+ +------------------+ |
| | WORKSPACE-MGR ||| CODE-REVIEWER | | BUG-FIXER | |
| | (Gobernanza) ||| (Calidad) | | (Correccion) | |
| +------------------+|+------------------+ +------------------+ |
| |
+-----------------------------------------------------------------------+
```
### 3.2 Principios de Orquestacion
1. **Cualquier agente puede orquestar a cualquier otro**
2. **Contexto completo en cada invocacion** (Protocolo CCA)
3. **Fases anidadas:** Analisis -> Planeacion -> Validacion -> Ejecucion
4. **Pool compartido de 15 subagentes**
### 3.3 Protocolo CCA (Carga de Contexto Automatica)
Todo agente ejecuta CCA antes de actuar:
```yaml
PASO_0_IDENTIFICAR_NIVEL:
- Leer SIMCO-NIVELES.md
- Determinar working_directory, nivel, orchestration_path
PASO_1_CARGAR_CORE:
- 5 Principios fundamentales
- Perfil del agente
- Indice SIMCO
- ALIASES.yml
PASO_2_CARGAR_PROYECTO:
- CONTEXTO-PROYECTO.md
- PROXIMA-ACCION.md
- Inventarios relevantes
PASO_3_CARGAR_OPERACION:
- Verificar @CATALOG_INDEX primero
- SIMCO segun operacion (CREAR, MODIFICAR, VALIDAR)
PASO_4_CARGAR_TAREA:
- Documentacion especifica
- Codigo existente relacionado
- Dependencias
```
---
## 4. PERFILES DE AGENTES
### 4.1 Agentes Tecnicos
| Agente | Alias | Dominio | Responsabilidades |
|--------|-------|---------|-------------------|
| **Database-Agent** | NEXUS-DATABASE | PostgreSQL | DDL, RLS, triggers, seeds |
| **Backend-Agent** | NEXUS-BACKEND | NestJS/Express | Entities, services, controllers, APIs |
| **Backend-Express** | BE-EXPRESS | Express.js | APIs con Express puro |
| **Frontend-Agent** | NEXUS-FRONTEND | React | Componentes, hooks, stores, pages |
| **Mobile-Agent** | NEXUS-MOBILE | React Native | Apps moviles |
| **ML-Specialist** | NEXUS-ML | Python/ML | Modelos, predicciones |
### 4.2 Agentes de Coordinacion
| Agente | Responsabilidades |
|--------|-------------------|
| **Tech-Leader** | Orquestacion general, delegacion, validacion |
| **Architecture-Analyst** | Diseno arquitectonico, ADRs |
| **Requirements-Analyst** | Especificaciones, historias de usuario |
| **Workspace-Manager** | Gobernanza, limpieza, organizacion |
### 4.3 Agentes de Calidad
| Agente | Responsabilidades |
|--------|-------------------|
| **Code-Reviewer** | Revision de codigo, mejores practicas |
| **Bug-Fixer** | Diagnostico y correccion de errores |
| **Documentation-Validator** | Validacion de documentacion |
### 4.4 Estructura de un Perfil de Agente
```yaml
# Estructura de PERFIL-{AGENTE}.md
PROTOCOLO_DE_INICIALIZACION_CCA:
- 6 pasos obligatorios antes de actuar
IDENTIDAD:
- Nombre, Alias, Dominio
RESPONSABILIDADES:
- Lo que SI hago
- Lo que NO hago (delegar a otros)
STACK_TECNOLOGICO:
- Framework, lenguaje, herramientas
DIRECTIVAS_SIMCO_A_SEGUIR:
- Principios (5 obligatorios)
- SIMCO por operacion
FLUJO_DE_TRABAJO:
- 10 pasos estandar
VALIDACION_OBLIGATORIA:
- Comandos que DEBEN pasar
COORDINACION_CON_OTROS_AGENTES:
- Cuando delegar y a quien
```
---
## 5. SISTEMA DE DIRECTIVAS SIMCO
### 5.1 Que es SIMCO?
**SIMCO** (Sistema Integrado de Metodologia de Codigo y Orquestacion) es el framework de directivas que gobierna como trabajan los agentes.
### 5.2 Estructura de Directivas SIMCO
```
core/orchestration/directivas/simco/
|
+-- SIMCO-INICIALIZACION.md # Bootstrap de agentes
+-- SIMCO-TAREA.md # Punto de entrada para HUs
+-- SIMCO-NIVELES.md # Jerarquia del workspace
+-- SIMCO-QUICK-REFERENCE.md # Referencia rapida
|
+-- # OPERACIONES UNIVERSALES
+-- SIMCO-CREAR.md # Crear objetos nuevos
+-- SIMCO-MODIFICAR.md # Modificar existentes
+-- SIMCO-VALIDAR.md # Validacion
+-- SIMCO-BUSCAR.md # Investigacion
+-- SIMCO-DOCUMENTAR.md # Documentacion
+-- SIMCO-DELEGACION.md # Delegar a otros agentes
+-- SIMCO-REUTILIZAR.md # Reutilizar del catalogo
+-- SIMCO-CONTRIBUIR-CATALOGO.md # Agregar al catalogo
|
+-- # OPERACIONES POR DOMINIO
+-- SIMCO-DDL.md # Base de datos
+-- SIMCO-BACKEND.md # Backend
+-- SIMCO-FRONTEND.md # Frontend
+-- SIMCO-MOBILE.md # Mobile
+-- SIMCO-ML.md # Machine Learning
|
+-- # COORDINACION
+-- SIMCO-PROPAGACION.md # Propagacion entre niveles
+-- SIMCO-ALINEACION.md # Alineacion de capas
+-- SIMCO-DECISION-MATRIZ.md # Toma de decisiones
+-- SIMCO-ESCALAMIENTO.md # Escalamiento a humanos
+-- SIMCO-GIT.md # Operaciones Git
```
### 5.3 Flujo de una Tarea con SIMCO
```
+---> SIMCO-TAREA.md (Punto de entrada)
|
+---> CAPVED: Contexto -> Analisis -> Planeacion -> Validacion -> Ejecucion -> Doc
|
+---> Por cada subtarea:
|
+---> Verificar @CATALOG_INDEX
| |
| +-- Si existe --> SIMCO-REUTILIZAR.md
| +-- Si no existe --> SIMCO-CREAR.md + SIMCO-{DOMINIO}.md
|
+---> Ejecutar con validacion (build, lint)
|
+---> Actualizar inventarios
|
+---> SIMCO-PROPAGACION.md (a niveles superiores)
```
---
## 6. PRINCIPIOS FUNDAMENTALES
### 6.1 Los 5 Principios Obligatorios
Todos los agentes DEBEN seguir estos 5 principios:
#### 1. PRINCIPIO-CAPVED (Ciclo de Vida de Tareas)
```
C - CONTEXTO: Vincular HU, clasificar tipo, cargar SIMCO
A - ANALISIS: Comportamiento, restricciones, impacto, dependencias
P - PLANEACION: Desglose en subtareas, criterios de aceptacion
V - VALIDACION: Plan vs Analisis, scope creep -> HU derivada
E - EJECUCION: docs/ primero, subtareas en orden, build/lint
D - DOCUMENTACION: Actualizar diagramas, specs, inventarios, trazas
```
**Regla clave:** Si aparece trabajo fuera del alcance, se genera HU derivada.
#### 2. PRINCIPIO-DOC-PRIMERO
```
"Documentacion antes de codigo"
1. Leer docs/ del proyecto ANTES de modificar
2. Actualizar docs/ PRIMERO durante ejecucion
3. HU no esta Done si documentacion no esta actualizada
```
#### 3. PRINCIPIO-ANTI-DUPLICACION
```
"Antes de crear, verificar que no existe"
Orden de verificacion:
1. @CATALOG_INDEX (funcionalidades reutilizables)
2. @INVENTORY del proyecto
3. Busqueda en codigo existente
Si existe en catalogo -> REUTILIZAR
Si existe en proyecto -> USAR EXISTENTE
Si existe similar -> PREGUNTAR
```
#### 4. PRINCIPIO-VALIDACION-OBLIGATORIA
```
"Build y lint DEBEN pasar antes de completar"
Backend: npm run build && npm run lint
Frontend: npm run build && npm run lint && npm run typecheck
Database: Carga limpia exitosa
```
#### 5. PRINCIPIO-ECONOMIA-TOKENS
```
"Desglosar tareas grandes en subtareas manejables"
- Identificar limites de contexto
- Dividir por dominio (DB, BE, FE)
- Completar y documentar por partes
- No acumular cambios sin commit
```
### 6.2 Principios SOLID para Documentacion
Adaptacion de SOLID al manejo de documentacion:
| Principio | Aplicacion a Docs |
|-----------|-------------------|
| **SRP** | Un archivo = un proposito |
| **OCP** | Archivos abiertos para extension, modificar existente vs crear duplicado |
| **LSP** | Archivos del mismo tipo siguen misma estructura |
| **ISP** | Archivos especificos mejor que gigantes |
| **DIP** | Referencias a abstracciones, no lineas especificas |
### 6.3 Normalizacion de Documentacion (como BD)
| Forma Normal | Aplicacion |
|--------------|------------|
| **1FN** | Eliminar grupos repetitivos (1 archivo por feature) |
| **2FN** | Eliminar dependencias parciales (separar por dominio) |
| **3FN** | Eliminar dependencias transitivas (usar referencias, no duplicar) |
---
## 7. CATALOGO DE FUNCIONALIDADES REUTILIZABLES
### 7.1 Proposito del Catalogo
```
+====================================================================+
| |
| ANTES DE IMPLEMENTAR, VERIFICAR SI YA EXISTE EN @CATALOG |
| |
| "Codigo probado > codigo nuevo" |
| "Reutilizar es mas rapido que reinventar" |
| |
+====================================================================+
```
### 7.2 Funcionalidades Disponibles
| Funcionalidad | Estado | Origen | Stack |
|---------------|--------|--------|-------|
| **auth** | Production-Ready | Gamilit | NestJS + JWT + Passport |
| **session-management** | Production-Ready | Gamilit | NestJS + TypeORM |
| **rate-limiting** | Production-Ready | Gamilit | NestJS + @nestjs/throttler |
| **notifications** | Production-Ready | Gamilit | NestJS + Nodemailer + FCM |
| **multi-tenancy** | Production-Ready | Gamilit | PostgreSQL RLS + NestJS |
| **feature-flags** | Production-Ready | Gamilit | NestJS + TypeORM |
| **websocket** | Production-Ready | Trading | NestJS + Socket.io |
| **payments** | Production-Ready | Trading | NestJS + Stripe |
### 7.3 Estructura de cada Funcionalidad
```
core/catalog/{funcionalidad}/
|
+-- README.md # Descripcion, cuando usar, trade-offs
+-- IMPLEMENTATION.md # Guia paso a paso
+-- _reference/ # Codigo de referencia
+-- {archivo}.ts
+-- {archivo}.spec.ts
```
### 7.4 Flujo de Reutilizacion
```
1. grep -i "{funcionalidad}" @CATALOG_INDEX
2. Si encuentra:
a. Leer README.md (descripcion, trade-offs)
b. Verificar compatibilidad de stack
c. Seguir IMPLEMENTATION.md
d. Copiar/adaptar codigo de _reference/
3. Si NO encuentra:
a. Implementar siguiendo SIMCO
b. Considerar agregar al catalogo despues
```
---
## 8. PROYECTOS Y VERTICALES
### 8.1 Proyectos Standalone (Nivel 2A)
| Proyecto | Descripcion | Estado | Stack |
|----------|-------------|--------|-------|
| **Gamilit** | Plataforma de gamificacion educativa | 60% MVP | NestJS + React |
| **Trading Platform** | Trading algoritmico con ML | 50% | Express + FastAPI + React |
| **Betting Analytics** | Prediccion de apuestas deportivas | Planificacion | NestJS + React |
| **Inmobiliaria Analytics** | Analisis de mercado inmobiliario | En desarrollo | NestJS + React |
### 8.2 ERP Suite (Nivel 2B) - Arquitectura Multi-Vertical
```
+------------------+
| @core/ |
| (workspace) |
+--------+---------+
|
+--------v---------+
| erp-core |
| (60-70%) |
+--------+---------+
|
+----------+---------+---------+----------+
| | | | |
+-------v---+ +----v----+ +--v---+ +---v---+ +----v----+
|Construccion| |Mecanicas| |Vidrio| |Retail | |Clinicas |
| (+30%) | | (+25%) | |(+35%)| |(+40%) | | (+50%) |
+-----------+ +---------+ +------+ +-------+ +---------+
```
### 8.3 Verticales del ERP Suite
| Vertical | Estado | DDL | Backend | Modulos | Story Points |
|----------|--------|-----|---------|---------|--------------|
| **Construccion** | En desarrollo | Completo | 15% | 18 (MAI-001 a MAI-018) | 450+ |
| **Mecanicas Diesel** | DDL Implementado | Completo | 0% | 5 (MMD-001 a MMD-005) | 150+ |
| **Vidrio Templado** | Epicas completas | Planificado | 0% | 8 (VT-001 a VT-008) | 259 |
| **Retail** | Epicas completas | Planificado | 0% | 10 (RT-001 a RT-010) | 353 |
| **Clinicas** | Epicas completas | Planificado | 0% | 12 (CL-001 a CL-012) | 451 |
### 8.4 Herencia de Especificaciones
El erp-core proporciona **30 especificaciones transversales** que las verticales heredan:
- SPEC-VALORACION-INVENTARIO.md
- SPEC-TRAZABILIDAD-LOTES-SERIES.md
- SPEC-INVENTARIOS-CICLICOS.md
- SPEC-MAIL-THREAD-TRACKING.md
- SPEC-TAREAS-RECURRENTES.md
- SPEC-PROYECTOS-DEPENDENCIAS-BURNDOWN.md
- SPEC-INTEGRACION-CALENDAR.md
- SPEC-PRICING-RULES.md
- SPEC-RRHH-EVALUACIONES-SKILLS.md
- SPEC-WIZARD-TRANSIENT-MODEL.md
- Y mas...
### 8.5 Metricas Consolidadas ERP Suite
```yaml
Modulos por vertical:
construccion: 18
mecanicas_diesel: 5
vidrio_templado: 8
retail: 10
clinicas: 12
total: 53
Story points totales: 1,663+
Database:
tablas_core: 144
schemas_core: 12
tablas_especificas: 63+
tablas_planificadas: 105
Documentacion:
total_archivos: 1,400+
specs_transversales: 30
```
---
## 9. REFERENCIAS BASE (ODOO Y LEGACY)
### 9.1 Knowledge Base
El workspace incluye una base de conocimiento en `knowledge-base/reference/`:
```
knowledge-base/
+-- reference/
+-- odoo/ # Referencia de Odoo
| +-- README.md # Documentacion del ERP
+-- erp-inmobiliaria-legacy/ # Sistema legacy de referencia
+-- gamilit/ # Codigo Gamilit legacy
+-- database/ # DDL, seeds, scripts
+-- orchestration/ # Trazas y handoffs historicos
```
### 9.2 Inspiracion de Odoo
El ERP Suite toma inspiracion de Odoo para:
- **Modulos genericos reutilizables:** auth, partners, inventory, sales, purchases, financial, HR, projects
- **Sistema de herencia:** Core -> Verticales
- **Patron wizard/transient model:** Para operaciones complejas
- **Mail thread tracking:** Seguimiento de comunicaciones
- **Multi-tenancy con RLS:** Aislamiento de datos
### 9.3 Patron de Extension
```typescript
// erp-core: Modulo base
@Module({
exports: [BaseInventoryService]
})
export class InventoryModule {}
// vertical/construccion: Extension
@Module({
imports: [InventoryModule],
providers: [ConstructionInventoryService] // Extiende BaseInventoryService
})
export class ConstructionInventoryModule {}
```
---
## 10. ESTANDARES DE DOCUMENTACION
### 10.1 Estructura de Documentacion por Proyecto
```
proyecto/docs/
|
+-- 00-vision-general/ # Vision y alcance
+-- 01-fase-alcance-inicial/ # MVP, features iniciales
+-- 02-fase-robustecimiento/ # Mejoras, estabilizacion
+-- 03-fase-extensiones/ # Features adicionales
+-- 04-modelado/ # Diagramas, especificaciones
+-- 90-transversal/ # Cross-cutting concerns
+-- 95-guias-desarrollo/ # Guias para desarrolladores
| +-- backend/
| +-- frontend/
+-- 97-adr/ # Architecture Decision Records
+-- 98-standards/ # Estandares del proyecto
```
### 10.2 Inventarios SIMCO
Cada proyecto debe tener estos 6 inventarios:
| Inventario | Proposito |
|------------|-----------|
| `MASTER_INVENTORY.yml` | Vision consolidada del proyecto |
| `DATABASE_INVENTORY.yml` | Tablas, schemas, funciones |
| `BACKEND_INVENTORY.yml` | Modules, services, controllers |
| `FRONTEND_INVENTORY.yml` | Components, pages, hooks |
| `TRACEABILITY_MATRIX.yml` | HU -> Implementacion |
| `DEPENDENCY_GRAPH.yml` | Dependencias entre modulos |
### 10.3 Sistema de Trazas
```
orchestration/trazas/
|
+-- TRAZA-TAREAS-DATABASE.md # Log de tareas DB
+-- TRAZA-TAREAS-BACKEND.md # Log de tareas BE
+-- TRAZA-TAREAS-FRONTEND.md # Log de tareas FE
+-- TRAZA-PROPAGACION.md # Propagacion entre niveles
```
### 10.4 Formato de Traza de Tarea
```markdown
## [HU-XXX] Titulo de la HU - YYYY-MM-DD
**Tipo:** feature | fix | refactor
**Estado:** Done | En Progreso | Bloqueado
**Agente:** {perfil-agente}
**Fase CAPVED:** C | A | P | V | E | D
### Subtareas
- [x] Subtarea 1
- [x] Subtarea 2
- [ ] Subtarea 3
### Archivos Modificados
- `path/to/file1.ts`
- `path/to/file2.ts`
### Validaciones
- [x] npm run build pasa
- [x] npm run lint pasa
- [x] Tests pasan
### HUs Derivadas
- DERIVED-HU-XXX-001: {descripcion}
### Notas
{Observaciones relevantes}
```
---
## 11. ARQUITECTURA SAAS MULTI-PORTAL
### 11.1 Vision de Plataforma SaaS
El workspace contempla una arquitectura SaaS con **3 portales diferenciados**:
```
+===================================================================+
| PLATAFORMA SAAS |
+===================================================================+
| |
| +------------------+ +------------------+ +------------------+ |
| | PORTAL USUARIO | | PORTAL CLIENTE | | PORTAL ADMIN | |
| | (End User) | | (Tenant Admin) | | (Platform) | |
| +------------------+ +------------------+ +------------------+ |
| | | | |
| | | | |
| +-------v--------------------v----------------------v---------+ |
| | API GATEWAY | |
| | - Autenticacion JWT | |
| | - Rate Limiting | |
| | - Multi-tenancy (tenant_id en context) | |
| +-------------------------------------------------------------+ |
| | |
| +---------------------------v---------------------------------+ |
| | BACKEND SERVICES | |
| | - Auth Service (catalog/auth) | |
| | - Billing Service (catalog/payments) | |
| | - Notification Service (catalog/notifications) | |
| | - Core Business Services | |
| +-------------------------------------------------------------+ |
| | |
| +---------------------------v---------------------------------+ |
| | PostgreSQL + RLS | |
| | - Row Level Security por tenant | |
| | - Schemas por modulo | |
| | - Aislamiento de datos garantizado | |
| +-------------------------------------------------------------+ |
| |
+===================================================================+
```
### 11.2 Roles y Portales
| Portal | Rol | Funcionalidades |
|--------|-----|-----------------|
| **Portal Usuario** | End User | Uso de la aplicacion, perfil, configuracion personal |
| **Portal Cliente** | Tenant Admin | Gestion de usuarios del tenant, configuracion, reportes |
| **Portal Admin** | Platform Admin | Gestion de tenants, billing, feature flags, soporte |
### 11.3 Funcionalidades SaaS del Catalogo
| Funcionalidad | Portal Usuario | Portal Cliente | Portal Admin |
|---------------|:--------------:|:--------------:|:------------:|
| auth | x | x | x |
| session-management | x | x | x |
| multi-tenancy | - | x | x |
| feature-flags | - | - | x |
| payments | - | x | x |
| notifications | x | x | x |
### 11.4 Modelos de Suscripcion (Planeado)
```yaml
planes:
free:
usuarios: 3
storage: 1GB
features: basicas
soporte: comunidad
professional:
usuarios: 25
storage: 50GB
features: avanzadas
soporte: email
enterprise:
usuarios: ilimitados
storage: ilimitado
features: todas
soporte: dedicado
sla: 99.9%
```
---
## 12. FLUJOS DE TRABAJO Y SEGMENTACION
### 12.1 Segmentacion del Trabajo por Agentes
```
+-------------------------------------------------------------------+
| FLUJO DE TAREA COMPLETA |
+-------------------------------------------------------------------+
| |
| [1] TECH-LEADER recibe HU |
| | |
| v |
| [2] CAPVED: C-A-P-V (Contexto, Analisis, Plan, Validacion) |
| | |
| v |
| [3] Delegacion segun dominio: |
| | |
| +---> DATABASE-AGENT (si DDL necesario) |
| | | |
| | v |
| | Crear tablas, indices, RLS |
| | | |
| +---> BACKEND-AGENT (si API necesario) |
| | | |
| | v |
| | Crear entities, services, controllers |
| | | |
| +---> FRONTEND-AGENT (si UI necesario) |
| | |
| v |
| Crear components, pages, hooks |
| |
| [4] Cada agente: |
| - Ejecuta CCA (Carga Contexto Automatica) |
| - Verifica @CATALOG antes de crear |
| - Sigue SIMCO correspondiente |
| - Valida (build, lint) |
| - Actualiza inventario |
| - Propaga a nivel superior |
| |
| [5] TECH-LEADER valida integracion |
| | |
| v |
| [6] CAPVED: E-D (Ejecucion final, Documentacion) |
| | |
| v |
| [7] HU marcada como Done |
| |
+-------------------------------------------------------------------+
```
### 12.2 Flujo de Delegacion (SIMCO-DELEGACION)
```markdown
## Template de Delegacion
Seras {PERFIL_AGENTE} trabajando en el proyecto {PROYECTO}
para realizar: {DESCRIPCION_TAREA}
Contexto heredado:
- HU origen: {HU_ID}
- Fase CAPVED: {fase_actual}
- Dependencias: {dependencias}
- Restricciones: {restricciones}
Antes de actuar, ejecuta el protocolo CCA.
```
### 12.3 Flujo de Propagacion (SIMCO-PROPAGACION)
```
Nivel 2B.2 (Vertical)
|
| Actualiza inventarios locales
| Actualiza trazas locales
|
v
Nivel 2B.1 (Suite Core) [si aplica]
|
| Propaga metricas consolidadas
|
v
Nivel 2B (Suite Master)
|
| Actualiza SUITE_MASTER_INVENTORY.yml
| Actualiza STATUS.yml
|
v
Nivel 0 (Workspace)
|
| Actualiza PROYECTOS-ACTIVOS.yml
```
### 12.4 Sistema de Aliases para Navegacion
El archivo `ALIASES.yml` define atajos para navegacion consistente:
```yaml
# Aliases Globales
@CATALOG: "core/catalog/"
@SIMCO: "core/orchestration/directivas/simco/"
@PRINCIPIOS: "core/orchestration/directivas/principios/"
@PERFILES: "core/orchestration/agents/perfiles/"
# Aliases de Operacion
@CREAR: "SIMCO-CREAR.md"
@MODIFICAR: "SIMCO-MODIFICAR.md"
@VALIDAR: "SIMCO-VALIDAR.md"
@REUTILIZAR: "SIMCO-REUTILIZAR.md"
# Aliases de Proyecto (variables)
@INVENTORY: "orchestration/inventarios/MASTER_INVENTORY.yml"
@INV_DB: "orchestration/inventarios/DATABASE_INVENTORY.yml"
@INV_BE: "orchestration/inventarios/BACKEND_INVENTORY.yml"
@INV_FE: "orchestration/inventarios/FRONTEND_INVENTORY.yml"
@CONTEXTO: "orchestration/00-guidelines/CONTEXTO-PROYECTO.md"
```
---
## ANEXO A: RESUMEN DE COMANDOS UTILES
### Desarrollo
```bash
# Iniciar servicios Docker
./devtools/scripts/dev.sh docker-up
# Iniciar proyecto especifico
./devtools/scripts/dev.sh start gamilit
./devtools/scripts/dev.sh start mecanicas
# Ver estado del workspace
./devtools/scripts/dev.sh status
# Ver asignacion de puertos
./devtools/scripts/dev.sh ports
```
### Verificacion Anti-Duplicacion
```bash
# Buscar en catalogo
grep -i "{funcionalidad}" @CATALOG_INDEX
# Buscar en inventario
grep -i "{objeto}" orchestration/inventarios/MASTER_INVENTORY.yml
# Buscar archivos
find apps/ -name "*{nombre}*"
# Buscar en codigo
grep -rn "{patron}" apps/
```
### Validacion
```bash
# Backend
cd apps/backend && npm run build && npm run lint
# Frontend
cd apps/frontend && npm run build && npm run lint && npm run typecheck
# Database (carga limpia)
cd database && ./recreate-database.sh
```
---
## ANEXO B: GLOSARIO
| Termino | Definicion |
|---------|------------|
| **CCA** | Carga de Contexto Automatica - Protocolo de bootstrap de agentes |
| **CAPVED** | Ciclo de vida: Contexto, Analisis, Planeacion, Validacion, Ejecucion, Documentacion |
| **SIMCO** | Sistema Integrado de Metodologia de Codigo y Orquestacion |
| **NEXUS** | Nombre del sistema de orquestacion de agentes |
| **RLS** | Row Level Security - Aislamiento de datos en PostgreSQL |
| **Vertical** | Especializacion de negocio del ERP (construccion, retail, etc.) |
| **HU** | Historia de Usuario |
| **DDL** | Data Definition Language - Scripts de definicion de BD |
| **SSOT** | Single Source of Truth - Fuente unica de verdad |
---
## ANEXO C: CHECKLIST DE NUEVA SESION
### Para un Agente que Inicia Sesion:
```markdown
[ ] 1. Identificar nivel jerarquico (SIMCO-NIVELES.md)
[ ] 2. Leer 5 principios fundamentales
[ ] 3. Leer mi perfil (PERFIL-{TIPO}.md)
[ ] 4. Leer ALIASES.yml
[ ] 5. Leer CONTEXTO-PROYECTO.md del proyecto
[ ] 6. Leer PROXIMA-ACCION.md
[ ] 7. Leer inventario relevante
[ ] 8. Verificar @CATALOG_INDEX antes de crear
[ ] 9. Seguir SIMCO de operacion correspondiente
[ ] 10. Validar build/lint antes de completar
[ ] 11. Actualizar inventarios
[ ] 12. Propagar a niveles superiores
```
---
**Documento generado por:** Claude Opus 4.5 - Sistema NEXUS
**Fecha:** 2025-12-18
**Version:** 1.0.0
---
*Este documento representa el estado actual del workspace y sus sistemas de orquestacion. Debe ser actualizado cuando haya cambios significativos en la arquitectura o procesos.*