Compare commits

..

No commits in common. "develop" and "main" have entirely different histories.

4517 changed files with 1375763 additions and 85118 deletions

48
.gitignore vendored
View File

@ -180,51 +180,3 @@ backups/
# Backup de gamilit (submodule migration)
projects/gamilit.bak.*/
# -----------------------------------------------------------------------------
# MCP SERVERS - Repositorios independientes
# -----------------------------------------------------------------------------
# Los MCP servers internos son repositorios independientes que se clonan
# manualmente despues de clonar workspace-v1.
# Ver core/mcp-servers/_registry.yml para lista completa e instrucciones.
# -----------------------------------------------------------------------------
core/mcp-servers/internal/rag-knowledge/
core/mcp-servers/internal/scrum-taiga/
# Mantener estructura base (README, registry, templates)
!core/mcp-servers/README.md
!core/mcp-servers/_registry.yml
!core/mcp-servers/internal/.gitkeep
!core/mcp-servers/external/
!core/mcp-servers/templates/
# -----------------------------------------------------------------------------
# SUBREPOSITORIOS - Proyectos con repositorios independientes en Gitea
# -----------------------------------------------------------------------------
# Estos proyectos tienen sus propios repositorios en http://72.60.226.4:3000/rckrdmrd
# Ver archivo SUBREPOSITORIOS.md para referencias completas
#
# NOTA: gamilit NO se ignora porque es un submodulo Git (ver .gitmodules)
# -----------------------------------------------------------------------------
# ERP Family
projects/erp-suite/
projects/erp-core/
projects/erp-construccion/
projects/erp-clinicas/
projects/erp-retail/
projects/erp-mecanicas-diesel/
projects/erp-vidrio-templado/
# Trading & Analytics
projects/trading-platform/
projects/betting-analytics/
projects/inmobiliaria-analytics/
projects/platform_marketing_content/
# Nuevos proyectos (2026-01-07)
projects/michangarrito/
projects/template-saas/
projects/clinica-dental/
projects/clinica-veterinaria/
# Gitea token (no commitear)
.gitea-token

View File

@ -1,308 +0,0 @@
# Subrepositorios del Workspace
**Fecha:** 2026-01-07
**Version:** 1.3
---
## Arquitectura de Repositorios
Este workspace utiliza una arquitectura de repositorios donde cada proyecto puede tener su propio repositorio independiente.
### Repositorio Principal
| Campo | Valor |
|-------|-------|
| **Nombre** | workspace-v1 |
| **Path Local** | `/home/isem/workspace-v1` |
| **Remote SSH** | `git@gitea-server:rckrdmrd/workspace-v1.git` |
| **Remote HTTP** | `http://72.60.226.4:3000/rckrdmrd/workspace-v1` |
---
## GAMILIT - Workspace Independiente
### Configuracion
| Campo | Valor |
|-------|-------|
| **Path Local** | `projects/gamilit` |
| **Tipo** | Submodulo Git |
| **Remote HTTPS** | `https://github.com/rckrdmrd/gamilit-workspace.git` |
| **Remote SSH** | `git@github.com:rckrdmrd/gamilit-workspace.git` |
| **Referencia** | `/home/isem/workspace-old/wsl-ubuntu/workspace/workspace-gamilit/gamilit/projects/gamilit` |
### Estructura
Gamilit es un **workspace completo** SIN subrepositorios. Contiene:
```
projects/gamilit/
├── apps/
│ ├── backend/ # NestJS API (NO es subrepositorio)
│ ├── frontend/ # React App (NO es subrepositorio)
│ ├── database/ # DDL y Scripts (NO es subrepositorio)
│ └── devops/ # Scripts DevOps (NO es subrepositorio)
├── docs/ # Documentacion (incluye contenido de niveles superiores)
├── orchestration/ # Sistema NEXUS (incluye contenido de niveles superiores)
├── scripts/ # Scripts de produccion
├── k8s/ # Configuracion Kubernetes
└── ...
```
### Reglas Especiales
1. **Sin subrepositorios**: Todo el contenido de `apps/` es parte del mismo repositorio
2. **Solo ignora node_modules**: Los archivos de codigo van al repo
3. **Workspace autocontenido**: Contiene su propia documentacion y orchestration
4. **Deployment directo**: Se clona directamente en produccion
### Servidor de Produccion
| Campo | Valor |
|-------|-------|
| **IP** | 74.208.126.102 |
| **Path** | `/home/isem/workspace/workspace-gamilit/gamilit/projects/gamilit` |
| **Backend** | Puerto 3006 (PM2 cluster x2) |
| **Frontend** | Puerto 3005 (PM2 fork) |
| **Database** | PostgreSQL :5432, `gamilit_platform` |
---
## Proyectos con Repositorios en Gitea
Los siguientes proyectos tienen repositorios independientes en `http://72.60.226.4:3000/rckrdmrd/`.
Estan ignorados en el `.gitignore` del workspace principal.
Estos proyectos SI pueden tener subrepositorios para sus apps (backend, frontend, database).
### Familia ERP
| Proyecto | Path Local | Repositorio |
|----------|------------|-------------|
| **erp-suite** | `projects/erp-suite` | `http://72.60.226.4:3000/rckrdmrd/erp-suite.git` |
| **erp-core** | `projects/erp-core` | `http://72.60.226.4:3000/rckrdmrd/erp-core.git` |
| **erp-construccion** | `projects/erp-construccion` | `http://72.60.226.4:3000/rckrdmrd/erp-construccion.git` |
| **erp-clinicas** | `projects/erp-clinicas` | `http://72.60.226.4:3000/rckrdmrd/erp-clinicas.git` |
| **erp-retail** | `projects/erp-retail` | `http://72.60.226.4:3000/rckrdmrd/erp-retail.git` |
| **erp-mecanicas-diesel** | `projects/erp-mecanicas-diesel` | `http://72.60.226.4:3000/rckrdmrd/erp-mecanicas-diesel.git` |
| **erp-vidrio-templado** | `projects/erp-vidrio-templado` | `http://72.60.226.4:3000/rckrdmrd/erp-vidrio-templado.git` |
### Otros Proyectos
| Proyecto | Path Local | Repositorio |
|----------|------------|-------------|
| **trading-platform** | `projects/trading-platform` | `http://72.60.226.4:3000/rckrdmrd/trading-platform.git` |
| **betting-analytics** | `projects/betting-analytics` | `http://72.60.226.4:3000/rckrdmrd/betting-analytics.git` |
| **inmobiliaria-analytics** | `projects/inmobiliaria-analytics` | `http://72.60.226.4:3000/rckrdmrd/inmobiliaria-analytics.git` |
| **platform_marketing_content** | `projects/platform_marketing_content` | `http://72.60.226.4:3000/rckrdmrd/platform_marketing_content.git` |
### Proyectos Nuevos (2026-01-07)
| Proyecto | Path Local | Repositorio | Subrepositorios |
|----------|------------|-------------|-----------------|
| **michangarrito** | `projects/michangarrito` | `http://72.60.226.4:3000/rckrdmrd/michangarrito.git` | backend, frontend, mobile, database, mcp-server, whatsapp |
| **template-saas** | `projects/template-saas` | `http://72.60.226.4:3000/rckrdmrd/template-saas.git` | backend, frontend, database |
| **clinica-dental** | `projects/clinica-dental` | `http://72.60.226.4:3000/rckrdmrd/clinica-dental.git` | database |
| **clinica-veterinaria** | `projects/clinica-veterinaria` | `http://72.60.226.4:3000/rckrdmrd/clinica-veterinaria.git` | database |
### Estructura con Subrepositorios (para proyectos Gitea)
Los proyectos en Gitea pueden usar esta estructura de subrepositorios:
```
projects/[proyecto]/
├── .gitmodules # Define subrepositorios
├── apps/
│ ├── backend/ # Subrepositorio -> [proyecto]-backend.git
│ ├── frontend/ # Subrepositorio -> [proyecto]-frontend.git
│ └── database/ # Subrepositorio -> [proyecto]-database.git
├── docs/
└── orchestration/
```
---
## Configuracion SSH
### Para Gitea (72.60.226.4)
```
# ~/.ssh/config
Host gitea-server
HostName 72.60.226.4
Port 22
User git
IdentityFile ~/.ssh/id_ed25519
IdentitiesOnly yes
```
### Para GitHub
```
# ~/.ssh/config
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519
IdentitiesOnly yes
```
---
## Comandos Utiles
### Gamilit (GitHub)
```bash
# Actualizar submodulo
cd /home/isem/workspace-v1
git submodule update --remote projects/gamilit
# Trabajar dentro de gamilit
cd /home/isem/workspace-v1/projects/gamilit
git pull origin master
git add -A
git commit -m "mensaje"
git push origin master
# Actualizar referencia en workspace-v1
cd /home/isem/workspace-v1
git add projects/gamilit
git commit -m "chore: actualizar submodulo gamilit"
```
### Proyectos Gitea
```bash
# Clonar un proyecto
cd /home/isem/workspace-v1/projects
git clone http://72.60.226.4:3000/rckrdmrd/[PROYECTO].git
# Inicializar subrepositorios (si aplica)
cd [PROYECTO]
git submodule update --init --recursive
```
### Ver estado de todos los repositorios
```bash
# Workspace principal
git -C /home/isem/workspace-v1 status
# Gamilit
git -C /home/isem/workspace-v1/projects/gamilit status
```
---
## Notas Importantes
1. **gamilit** es especial:
- Es un workspace independiente sin subrepositorios
- Se despliega directamente en produccion
- Contiene docs y orchestration propios (redundantes con workspace)
- Usa GitHub (no Gitea)
2. **Otros proyectos** (ERP, trading, etc.):
- Usan Gitea como servidor Git
- Pueden tener subrepositorios para sus apps
- No se incluyen en el repositorio workspace-v1
3. **Sincronizacion**:
- Desarrollo activo de gamilit: `/home/isem/workspace/projects/gamilit`
- Referencia de produccion: `/home/isem/workspace-old/.../gamilit`
- Submodulo en workspace-v1: `/home/isem/workspace-v1/projects/gamilit`
---
## Estado Actual de Repositorios en Gitea
### Repositorios Existentes (2026-01-04)
| Repositorio | Tipo | Estado |
|-------------|------|--------|
| workspace | Principal | Activo |
| workspace-v1 | Principal | Activo |
| erp-construccion-backend | Subrepositorio | Activo |
| erp-construccion-frontend-web | Subrepositorio | Activo |
| erp-construccion-frontend-mobile | Subrepositorio | Activo |
| erp-construccion-database | Subrepositorio | Activo |
| erp-mecanicas-diesel-backend | Subrepositorio | Activo |
| erp-mecanicas-diesel-frontend-web | Subrepositorio | Activo |
| erp-mecanicas-diesel-database | Subrepositorio | Activo |
| erp-core-backend | Subrepositorio | Activo |
| erp-core-frontend-web | Subrepositorio | Activo |
| erp-core-database | Subrepositorio | Activo |
### Repositorios Creados (2026-01-07)
Los siguientes repositorios fueron creados via API:
| Repositorio | Tipo | Estado |
|-------------|------|--------|
| michangarrito | Principal | ✅ Creado |
| michangarrito-backend | Subrepositorio | ✅ Creado |
| michangarrito-frontend | Subrepositorio | ✅ Creado |
| michangarrito-mobile | Subrepositorio | ✅ Creado |
| michangarrito-database | Subrepositorio | ✅ Creado |
| michangarrito-mcp-server | Subrepositorio | ✅ Creado |
| michangarrito-whatsapp | Subrepositorio | ✅ Creado |
| template-saas | Principal | ✅ Creado |
| template-saas-backend | Subrepositorio | ✅ Creado |
| template-saas-frontend | Subrepositorio | ✅ Creado |
| template-saas-database | Subrepositorio | ✅ Creado |
| clinica-dental | Principal | ✅ Creado |
| clinica-dental-database | Subrepositorio | ✅ Creado |
| clinica-veterinaria | Principal | ✅ Creado |
| clinica-veterinaria-database | Subrepositorio | ✅ Creado |
### Repositorios Pendientes de Crear
Los siguientes repositorios principales necesitan crearse via API o web de Gitea:
- erp-suite (principal)
- erp-core (principal)
- erp-construccion (principal)
- erp-clinicas (principal)
- erp-retail (principal)
- erp-mecanicas-diesel (principal)
- erp-vidrio-templado (principal)
- trading-platform (principal)
- betting-analytics (principal)
- inmobiliaria-analytics (principal)
- platform-marketing-content (principal)
---
## Scripts de Gestion
### Crear repositorios en Gitea
```bash
# Requiere token de API de Gitea
./scripts/create-gitea-repos-api.sh <GITEA_TOKEN>
# Para obtener el token:
# 1. Ir a http://72.60.226.4:3000/rckrdmrd
# 2. Settings -> Applications -> Generate New Token
# 3. Dar permisos de 'repo' y 'write:repository'
```
### Push de todos los proyectos
```bash
# Despues de crear los repositorios
./scripts/push-all-projects.sh
```
### Configurar repositorios locales
```bash
# Configura remotes en cada proyecto
./scripts/create-gitea-repos.sh
```
---
*Generado por NEXUS v3.4 - Sistema de Orquestacion*

View File

@ -155,7 +155,7 @@ repositories:
shared-libs:
type: "shared"
description: "Librerias compartidas"
path: "shared/catalog/"
path: "shared/libs/"
status: "planned"
packages:
- "@workspace/auth"

View File

@ -1,127 +1,119 @@
# Core - Arquitectura del Workspace
# Core - Núcleo de la Fábrica de Software
**Version:** 2.0.0
**Actualizado:** 2026-01-04
## Descripción
## Descripcion
El directorio `core/` contiene todo lo que se comparte a nivel de **fábrica**, no de proyecto individual:
El directorio `core/` contiene la **arquitectura central del workspace**: sistema de orquestacion, MCP servers, y herramientas de ambiente. NO contiene codigo de aplicacion ni recursos compartidos (esos estan en `shared/`).
- Sistema de orquestación de agentes
- Módulos de código reutilizables
- Estándares técnicos y de negocio
- Directivas globales para agentes/subagentes
- Constantes y tipos universales
## Estructura
```
core/
├── README.md # Este archivo
├── modules/ # Código compartido ejecutable
│ ├── utils/ # Utilidades universales ✅
│ │ ├── date.util.ts # Manipulación de fechas
│ │ ├── string.util.ts # Manipulación de strings
│ │ ├── validation.util.ts # Validaciones
│ │ └── index.ts
│ ├── auth/ # Autenticación (por implementar)
│ ├── billing/ # Facturación
│ ├── notifications/ # Notificaciones
│ ├── payments/ # Pagos
│ └── multitenant/ # Multi-tenancy
├── mcp-servers/ # MCP Servers para el workspace
│ ├── internal/ # Servidores MCP internos
│ ├── external/ # Referencias a servidores externos
│ ├── templates/ # Templates para crear nuevos MCP servers
│ └── _registry.yml # Registro de servidores disponibles
├── constants/ # Constantes globales ✅
│ ├── enums.constants.ts # Enums universales
│ ├── regex.constants.ts # Patrones regex
│ └── index.ts
├── orchestration/ # Sistema NEXUS/SIMCO de orquestacion
│ ├── agents/ # Perfiles de agentes
│ │ ├── perfiles/ # Perfiles ligeros SIMCO
│ │ └── legacy/ # Prompts legacy (referencia)
│ ├── directivas/ # Directivas por operacion
│ │ ├── simco/ # Sistema SIMCO
│ │ ├── legacy/ # Directivas legacy
│ │ └── _MAP.md
│ ├── referencias/ # ALIASES.yml y referencias
│ ├── templates/ # Templates de documentacion
│ ├── auditorias/ # Auditorias arquitectonicas
│ ├── impactos/ # Matrices de impacto
│ ├── inventarios/ # Inventarios de deployment
│ ├── procesos/ # Guias de procesos
│ ├── deployment/ # Arquitectura de deployment
│ ├── claude/ # Configuraciones Claude
│ └── _historico/ # Documentos archivados
├── types/ # Tipos TypeScript compartidos ✅
│ ├── api.types.ts # Tipos de API
│ ├── common.types.ts # Tipos comunes
│ └── index.ts
└── devtools/ # Herramientas de ambiente
└── environment/ # Configuracion de ambientes
├── scripts/ # Scripts de setup
├── templates/ # Templates .env
└── DEV-ENVIRONMENT-REGISTRY.yml
├── catalog/ # Documentación de funcionalidades
│ ├── auth/
│ ├── notifications/
│ └── ...
├── orchestration/ # Sistema de agentes NEXUS
│ ├── agents/
│ ├── directivas/
│ ├── templates/
│ └── referencias/
└── standards/ # Estándares técnicos globales
├── CODING-STANDARDS.md
├── TESTING-STANDARDS.md
└── ...
```
## Que NO esta en core/
Los siguientes elementos fueron movidos a `shared/`:
| Elemento | Nueva ubicacion |
|----------|-----------------|
| catalog/ | `shared/catalog/` |
| modules/ | `shared/modules/` |
| constants/ | `shared/constants/` |
| types/ | `shared/types/` |
| standards/ | `shared/knowledge-base/standards/` |
## Uso
### MCP Servers
### Importar Utilidades
```bash
# Ver servidores disponibles
cat core/mcp-servers/_registry.yml
```typescript
// En cualquier proyecto del workspace
import { formatDate, slugify, isEmail } from '@core/modules/utils';
# Crear nuevo servidor MCP interno
cp -r core/mcp-servers/templates/TEMPLATE-MCP-INTERNO core/mcp-servers/internal/mi-servidor
// O importar específico
import { formatToISO, addDays } from '@core/modules/utils/date.util';
```
### Sistema de Orquestacion
### Importar Constantes
Los agentes cargan automaticamente las directivas de `core/orchestration/directivas/` al inicializar.
```markdown
# Inicializacion de agente
1. Leer core/orchestration/directivas/simco/_INDEX.md
2. Leer core/orchestration/directivas/principios/*.md
3. Cargar perfil desde core/orchestration/agents/perfiles/
4. Leer ALIASES.yml para navegacion
```typescript
import { UserStatus, PaymentStatus } from '@core/constants';
import { EMAIL_REGEX, UUID_REGEX } from '@core/constants/regex.constants';
```
### Herramientas de Ambiente
### Importar Tipos
```bash
# Validar ambiente de un proyecto
./core/devtools/environment/scripts/validate-environment.sh /path/to/project
# Setup de ambiente
./core/devtools/environment/scripts/setup-project-env.sh /path/to/project
```typescript
import { ApiResponse, PaginatedResponse } from '@core/types';
import { BaseEntity, Address } from '@core/types/common.types';
```
## Relacion con otras carpetas
## Módulos Disponibles
```
workspace-v1/
├── core/ # ARQUITECTURA (este directorio)
│ └── orchestration/ # Sistema SIMCO/NEXUS
├── shared/ # RECURSOS COMPARTIDOS
│ ├── catalog/ # Funcionalidades reutilizables
│ ├── modules/ # Codigo ejecutable
│ ├── constants/ # Constantes globales
│ ├── types/ # Tipos TypeScript
│ └── knowledge-base/ # Documentacion
├── control-plane/ # GOVERNANCE
│ ├── registries/ # Puertos, dominios, BDs
│ ├── manifests/ # Configuraciones de repos
│ └── devtools/ # CI/CD, Docker
├── orchestration/ # DIRECTIVAS A NIVEL WORKSPACE (hereda de core/)
└── projects/ # PROYECTOS DE PRODUCTO
```
### Utils (`@core/modules/utils`)
## Ver Tambien
| Archivo | Funciones | Descripción |
|---------|-----------|-------------|
| `date.util.ts` | formatDate, addDays, diffInDays, etc. | Manipulación de fechas |
| `string.util.ts` | slugify, capitalize, truncate, etc. | Manipulación de strings |
| `validation.util.ts` | isEmail, isUUID, isStrongPassword, etc. | Validaciones |
- [Sistema de Orquestacion](orchestration/README.md)
- [MCP Servers](mcp-servers/README.md)
- [Recursos Compartidos](../shared/README.md)
- [Catalogo de Funcionalidades](../shared/catalog/README.md)
### Constants (`@core/constants`)
---
| Archivo | Contenido |
|---------|-----------|
| `enums.constants.ts` | UserStatus, PaymentStatus, NotificationType, etc. |
| `regex.constants.ts` | EMAIL_REGEX, UUID_REGEX, PHONE_REGEX, etc. |
**Mantenido por:** Tech-Leader
**Ultima actualizacion:** 2026-01-04
### Types (`@core/types`)
| Archivo | Tipos |
|---------|-------|
| `api.types.ts` | ApiResponse, PaginatedResponse, ErrorCodes |
| `common.types.ts` | BaseEntity, Address, Money, Result |
## Proyectos que Usan Core
- **Gamilit** - Plataforma educativa de gamificación
- **Trading Platform** - OrbiQuant IA trading
- **ERP Suite** - Sistema ERP multi-vertical
## Sistema de Orquestación
Los agentes cargan automáticamente las directivas de `core/orchestration/directivas/` al inicializar.
## Ver También
- [Sistema de Orquestación](orchestration/README.md)
- [Catálogo de Funcionalidades](catalog/README.md)
- [Plan de Organización](../PLAN-ORGANIZACION-WORKSPACE.md)

View File

@ -0,0 +1,481 @@
# ═══════════════════════════════════════════════════════════════════════════════
# ÍNDICE DEL CATÁLOGO DE FUNCIONALIDADES REUTILIZABLES
# ═══════════════════════════════════════════════════════════════════════════════
#
# Versión: 1.0.0
# Fecha: 2025-12-08
# Propósito: Índice máquina-readable para búsqueda rápida de funcionalidades
#
# USO:
# Los agentes consultan este archivo ANTES de implementar funcionalidades comunes.
# Usar: grep -i "{funcionalidad}" @CATALOG_INDEX
#
# ═══════════════════════════════════════════════════════════════════════════════
version: "1.1.0"
fecha_actualizacion: "2025-12-27"
total_funcionalidades: 11
# ─────────────────────────────────────────────────────────────────────────────────
# ÍNDICE DE FUNCIONALIDADES
# ─────────────────────────────────────────────────────────────────────────────────
funcionalidades:
# ═══════════════════════════════════════════════════════════════════
# AUTENTICACIÓN Y SEGURIDAD
# ═══════════════════════════════════════════════════════════════════
auth:
nombre: "Autenticación y Autorización"
path: "core/catalog/auth/"
alias: "@CATALOG_AUTH"
estado: "production-ready" # production-ready | documentando | pendiente
origen: "projects/gamilit"
version: "1.0.0"
stack:
- "NestJS"
- "JWT"
- "Passport"
- "bcrypt"
- "TypeORM"
keywords:
- "login"
- "registro"
- "jwt"
- "token"
- "password"
- "oauth"
- "social-login"
- "autenticacion"
- "authorization"
- "guard"
caracteristicas:
- "JWT access + refresh tokens"
- "Password hashing con bcrypt"
- "Multiple OAuth providers"
- "Auth attempts tracking"
- "Password recovery"
dependencias_npm:
- "@nestjs/jwt"
- "@nestjs/passport"
- "passport-jwt"
- "bcrypt"
tablas_requeridas:
- "auth.users"
- "auth.user_sessions"
- "auth.auth_attempts"
session-management:
nombre: "Gestión de Sesiones"
path: "core/catalog/session-management/"
alias: "@CATALOG_SESSION"
estado: "production-ready"
origen: "projects/gamilit"
version: "1.0.0"
stack:
- "NestJS"
- "TypeORM"
- "PostgreSQL"
keywords:
- "sesion"
- "session"
- "logout"
- "dispositivo"
- "device"
- "concurrent"
- "max-sessions"
caracteristicas:
- "Máximo N sesiones concurrentes"
- "Auto-cleanup de sesiones expiradas"
- "Tracking de dispositivos"
- "Logout de sesión específica"
- "Logout de todas las sesiones"
dependencias_npm:
- "typeorm"
tablas_requeridas:
- "auth.user_sessions"
rate-limiting:
nombre: "Limitación de Tasa (Rate Limiting)"
path: "core/catalog/rate-limiting/"
alias: "@CATALOG_RATELIMIT"
estado: "production-ready"
origen: "projects/gamilit"
version: "1.0.0"
stack:
- "NestJS"
- "Redis (opcional)"
keywords:
- "rate-limit"
- "throttle"
- "429"
- "too-many-requests"
- "abuse"
- "ddos"
- "limite"
caracteristicas:
- "Rate limiting por usuario/IP"
- "Configuración por endpoint"
- "Headers de límite estándar"
- "Respuestas 429 con retry-after"
dependencias_npm:
- "@nestjs/throttler"
tablas_requeridas: []
# ═══════════════════════════════════════════════════════════════════
# COMUNICACIÓN Y NOTIFICACIONES
# ═══════════════════════════════════════════════════════════════════
notifications:
nombre: "Sistema de Notificaciones"
path: "core/catalog/notifications/"
alias: "@CATALOG_NOTIFY"
estado: "production-ready"
origen: "projects/gamilit"
version: "1.0.0"
stack:
- "NestJS"
- "TypeORM"
- "Nodemailer"
- "FCM (opcional)"
keywords:
- "notificacion"
- "notification"
- "email"
- "push"
- "in-app"
- "alerta"
- "mensaje"
caracteristicas:
- "Notificaciones email"
- "Notificaciones in-app"
- "Push notifications (FCM)"
- "Preferencias de usuario"
- "Historial de notificaciones"
- "Templates de email"
dependencias_npm:
- "nodemailer"
- "@nestjs/mailer"
- "firebase-admin (opcional)"
tablas_requeridas:
- "notifications.notifications"
- "notifications.notification_preferences"
- "notifications.notification_templates"
websocket:
nombre: "Comunicación WebSocket"
path: "core/catalog/websocket/"
alias: "@CATALOG_WS"
estado: "production-ready"
origen: "projects/trading-platform"
version: "1.0.0"
stack:
- "NestJS"
- "Socket.io"
keywords:
- "websocket"
- "socket"
- "realtime"
- "tiempo-real"
- "streaming"
- "live"
- "push"
caracteristicas:
- "Conexiones WebSocket"
- "Rooms/canales"
- "Autenticación de socket"
- "Broadcasting"
- "Heartbeat/ping"
dependencias_npm:
- "@nestjs/websockets"
- "@nestjs/platform-socket.io"
- "socket.io"
tablas_requeridas: []
# ═══════════════════════════════════════════════════════════════════
# ARQUITECTURA MULTI-TENANT
# ═══════════════════════════════════════════════════════════════════
multi-tenancy:
nombre: "Soporte Multi-Tenant"
path: "core/catalog/multi-tenancy/"
alias: "@CATALOG_TENANT"
estado: "production-ready"
origen: "projects/gamilit"
version: "1.0.0"
stack:
- "PostgreSQL"
- "RLS"
- "NestJS"
keywords:
- "tenant"
- "multi-tenant"
- "organization"
- "empresa"
- "aislamiento"
- "rls"
- "row-level-security"
caracteristicas:
- "Aislamiento por tenant"
- "Row Level Security (RLS)"
- "Tenant context en requests"
- "Configuración por tenant"
dependencias_npm:
- "typeorm"
tablas_requeridas:
- "core.organizations"
- "core.organization_members"
# ═══════════════════════════════════════════════════════════════════
# FEATURE FLAGS Y CONFIGURACIÓN
# ═══════════════════════════════════════════════════════════════════
feature-flags:
nombre: "Feature Flags Dinámicos"
path: "core/catalog/feature-flags/"
alias: "@CATALOG_FLAGS"
estado: "production-ready"
origen: "projects/gamilit"
version: "1.0.0"
stack:
- "NestJS"
- "TypeORM"
- "PostgreSQL"
keywords:
- "feature-flag"
- "toggle"
- "feature"
- "bandera"
- "a/b-test"
- "rollout"
- "configuracion"
caracteristicas:
- "Flags por ambiente"
- "Flags por usuario/rol"
- "Activación gradual (rollout)"
- "Cache de flags"
- "UI de administración"
dependencias_npm:
- "typeorm"
tablas_requeridas:
- "config.feature_flags"
- "config.feature_flag_rules"
# ═══════════════════════════════════════════════════════════════════
# PAGOS E INTEGRACIONES
# ═══════════════════════════════════════════════════════════════════
payments:
nombre: "Integración de Pagos"
path: "core/catalog/payments/"
alias: "@CATALOG_PAYMENTS"
estado: "production-ready"
origen: "projects/trading-platform"
version: "1.0.0"
stack:
- "NestJS"
- "Stripe"
keywords:
- "pago"
- "payment"
- "stripe"
- "subscription"
- "suscripcion"
- "factura"
- "invoice"
- "checkout"
caracteristicas:
- "Integración Stripe"
- "Webhooks de pago"
- "Suscripciones"
- "Checkout sessions"
- "Historial de pagos"
dependencias_npm:
- "stripe"
tablas_requeridas:
- "billing.subscriptions"
- "billing.payments"
- "billing.invoices"
# ═══════════════════════════════════════════════════════════════════
# TEMPLATES Y ARQUITECTURA
# ═══════════════════════════════════════════════════════════════════
template-saas:
nombre: "Template SaaS Multi-tenant"
path: "core/catalog/template-saas/"
alias: "@CATALOG_SAAS"
estado: "production-ready"
origen: "projects/erp-core, projects/gamilit"
version: "1.0.0"
stack:
- "NestJS"
- "React"
- "PostgreSQL"
- "Stripe"
keywords:
- "saas"
- "template"
- "multi-tenant"
- "suscripcion"
- "subscription"
- "billing"
- "onboarding"
- "plans"
- "pricing"
caracteristicas:
- "Estructura de proyecto SaaS"
- "Sistema de planes y pricing"
- "Suscripciones con Stripe"
- "Flujo de onboarding"
- "Dashboard de admin"
- "Metricas de uso"
dependencias_npm:
- "stripe"
- "@nestjs/config"
- "zustand"
tablas_requeridas:
- "billing.plans"
- "billing.subscriptions"
- "billing.payments"
portales:
nombre: "Portales y Dashboards"
path: "core/catalog/portales/"
alias: "@CATALOG_PORTALES"
estado: "production-ready"
origen: "projects/gamilit, projects/trading-platform"
version: "1.0.0"
stack:
- "React"
- "NestJS"
- "Socket.io"
- "Recharts"
keywords:
- "portal"
- "dashboard"
- "widget"
- "metricas"
- "kpi"
- "charts"
- "graficos"
- "admin"
- "layout"
caracteristicas:
- "Dashboards multi-rol"
- "Widgets configurables"
- "Metricas en tiempo real"
- "Layouts personalizables"
- "Preferencias de usuario"
dependencias_npm:
- "recharts"
- "react-grid-layout"
- "socket.io-client"
tablas_requeridas:
- "config.dashboard_layouts"
- "config.user_dashboard_preferences"
- "config.widgets"
audit-logs:
nombre: "Sistema de Auditoria"
path: "core/catalog/audit-logs/"
alias: "@CATALOG_AUDIT"
estado: "production-ready"
origen: "projects/gamilit, projects/erp-core"
version: "1.0.0"
stack:
- "NestJS"
- "TypeORM"
- "PostgreSQL"
keywords:
- "audit"
- "auditoria"
- "log"
- "tracking"
- "historial"
- "cambios"
- "acceso"
- "compliance"
- "gdpr"
- "hipaa"
caracteristicas:
- "Entity tracking automatico"
- "Access logs para recursos sensibles"
- "Action logs de usuario"
- "Busqueda y filtrado"
- "Politicas de retencion"
- "Exportacion CSV/JSON"
dependencias_npm:
- "typeorm"
- "nestjs-cls"
tablas_requeridas:
- "audit.entity_logs"
- "audit.access_logs"
- "audit.action_logs"
# ─────────────────────────────────────────────────────────────────────────────────
# BÚSQUEDA RÁPIDA POR KEYWORD
# ─────────────────────────────────────────────────────────────────────────────────
#
# Para buscar funcionalidad por keyword:
# grep -i "{keyword}" core/catalog/CATALOG-INDEX.yml
#
# Ejemplos:
# grep -i "login" → auth
# grep -i "sesion" → session-management
# grep -i "429" → rate-limiting
# grep -i "email" → notifications
# grep -i "realtime" → websocket
# grep -i "tenant" → multi-tenancy
# grep -i "toggle" → feature-flags
# grep -i "stripe" → payments
# grep -i "saas" → template-saas
# grep -i "dashboard" → portales
# grep -i "audit" → audit-logs
#
# ─────────────────────────────────────────────────────────────────────────────────
# ─────────────────────────────────────────────────────────────────────────────────
# INSTRUCCIONES PARA AGENTES
# ─────────────────────────────────────────────────────────────────────────────────
instrucciones:
cuando_consultar: |
SIEMPRE consultar este índice ANTES de implementar:
- Autenticación/login
- Gestión de sesiones
- Rate limiting
- Notificaciones
- WebSockets/tiempo real
- Multi-tenancy
- Feature flags
- Pagos/suscripciones
- Template SaaS/onboarding
- Dashboards/portales
- Auditoria/logs
como_buscar: |
1. Buscar por keyword:
grep -i "{lo que necesito}" @CATALOG_INDEX
2. Si encuentra match:
- Leer path indicado
- Verificar estado (preferir production-ready)
- Verificar stack compatible
3. Si NO encuentra:
- Proceder con implementación nueva
- Considerar agregar al catálogo después
que_hacer_si_encuentra: |
1. Ir a: core/catalog/{funcionalidad}/
2. Leer: README.md (descripción y trade-offs)
3. Seguir: IMPLEMENTATION.md (pasos)
4. Copiar: _reference/ (código base)
5. Adaptar: configuración al proyecto actual
6. Validar: ejecutar tests de referencia
# ═══════════════════════════════════════════════════════════════════════════════
# FIN DEL ÍNDICE
# ═══════════════════════════════════════════════════════════════════════════════

469
core/catalog/README.md Normal file
View File

@ -0,0 +1,469 @@
# CATÁLOGO DE FUNCIONALIDADES REUTILIZABLES
**Versión:** 1.0.0
**Fecha:** 2025-12-08
**Sistema:** NEXUS SIMCO v3.0
---
## PROPÓSITO
Este catálogo centraliza **código funcional probado y documentado** que puede ser reutilizado entre proyectos. Antes de implementar una funcionalidad común, los agentes DEBEN consultar este catálogo.
---
## PRINCIPIO FUNDAMENTAL
```
╔══════════════════════════════════════════════════════════════════════╗
║ ║
║ ANTES DE IMPLEMENTAR, VERIFICAR SI YA EXISTE EN @CATALOG
║ ║
║ "Código probado > código nuevo" ║
║ "Reutilizar es más rápido que reinventar" ║
║ ║
╚══════════════════════════════════════════════════════════════════════╝
```
---
## ESTRUCTURA DEL CATÁLOGO
```
core/catalog/
├── README.md ← ESTÁS AQUÍ
├── CATALOG-INDEX.yml # Índice máquina-readable
├── auth/ # Autenticación y autorización
│ ├── README.md # Descripción, cuándo usar
│ ├── IMPLEMENTATION.md # Guía de implementación
│ └── _reference/ # Código de referencia
├── session-management/ # Gestión de sesiones
│ ├── README.md
│ ├── IMPLEMENTATION.md
│ └── _reference/
├── rate-limiting/ # Limitación de tasa
│ ├── README.md
│ ├── IMPLEMENTATION.md
│ └── _reference/
├── notifications/ # Sistema de notificaciones
│ ├── README.md
│ ├── IMPLEMENTATION.md
│ └── _reference/
├── multi-tenancy/ # Soporte multi-tenant
│ ├── README.md
│ ├── IMPLEMENTATION.md
│ └── _reference/
├── feature-flags/ # Feature flags dinámicos
│ ├── README.md
│ ├── IMPLEMENTATION.md
│ └── _reference/
├── websocket/ # Comunicación en tiempo real
│ ├── README.md
│ ├── IMPLEMENTATION.md
│ └── _reference/
└── payments/ # Integración de pagos
├── README.md
├── IMPLEMENTATION.md
└── _reference/
```
---
## CÓMO USAR EL CATÁLOGO
### Para Agentes: Flujo de Verificación
```
┌─────────────────────────────────────────────────────────────────┐
│ ANTES de implementar funcionalidad común: │
│ │
│ 1. Consultar @CATALOG_INDEX
│ → ¿Existe la funcionalidad? │
│ │
│ 2. Si existe: │
│ → Leer {funcionalidad}/README.md │
│ → Verificar compatibilidad de stack │
│ → Seguir {funcionalidad}/IMPLEMENTATION.md │
│ → Copiar código de _reference/ │
│ │
│ 3. Si NO existe: │
│ → Implementar siguiendo @SIMCO
│ → Considerar agregar al catálogo después │
└─────────────────────────────────────────────────────────────────┘
```
### Alias Disponibles
```yaml
@CATALOG: core/catalog/
@CATALOG_INDEX: core/catalog/CATALOG-INDEX.yml
@CATALOG_AUTH: core/catalog/auth/
@CATALOG_SESSION: core/catalog/session-management/
@CATALOG_RATELIMIT: core/catalog/rate-limiting/
@CATALOG_NOTIFY: core/catalog/notifications/
@CATALOG_TENANT: core/catalog/multi-tenancy/
@CATALOG_FLAGS: core/catalog/feature-flags/
@CATALOG_WS: core/catalog/websocket/
@CATALOG_PAYMENTS: core/catalog/payments/
```
---
## FUNCIONALIDADES DISPONIBLES
### Estado Actual
| 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 + Email/Push/WebPush |
| multi-tenancy | 🟢 Production-Ready | Gamilit | NestJS + PostgreSQL RLS |
| feature-flags | 🟢 Production-Ready | Gamilit | NestJS + TypeORM |
| websocket | 🟢 Production-Ready | Trading | NestJS + Socket.io |
| payments | 🟢 Production-Ready | Trading | NestJS + Stripe |
**Leyenda:**
- 🟢 Production-Ready: README.md + IMPLEMENTATION.md completos
- 🟡 Documentando: En proceso de documentación
- 🔴 Pendiente: Identificado pero no documentado
**Última actualización:** 2025-12-08
---
## ESTRUCTURA DE CADA FUNCIONALIDAD
Cada funcionalidad en el catálogo incluye:
### README.md
```markdown
# {Nombre} - Catálogo de Funcionalidad
## Metadata
- Versión, origen, estado, stack
## Descripción
- Qué hace
- Cuándo usar
- Cuándo NO usar
## Características
- Lista de features incluidas
## Dependencias
- npm packages
- Tablas de BD
- Servicios externos
## Trade-offs
- Limitaciones conocidas
- Alternativas
```
### IMPLEMENTATION.md
```markdown
# Implementación: {Nombre}
## Prerequisitos
- Lo que debe existir antes
## Pasos de Implementación
1. Paso detallado 1
2. Paso detallado 2
...
## Configuración
- Variables de entorno
- Opciones de configuración
## Verificación
- Cómo validar que funciona
## Troubleshooting
- Problemas comunes y soluciones
```
### _reference/
```
_reference/
├── {archivo1}.ts # Código de referencia
├── {archivo2}.ts
├── {archivo}.spec.ts # Tests
└── README.md # Descripción de cada archivo
```
---
## CONTRIBUIR AL CATÁLOGO
### IMPORTANTE: Directiva de Mantenimiento
```
╔══════════════════════════════════════════════════════════════════════════════╗
║ CUANDO IMPLEMENTES UNA FUNCIONALIDAD REUTILIZABLE EN UN PROYECTO: ║
║ ║
║ 1. EVALÚA si es candidata para el catálogo (ver criterios abajo) ║
║ 2. DOCUMENTA mientras desarrollas (más fácil que después) ║
║ 3. EXTRAE al catálogo cuando esté estable ║
║ ║
║ El catálogo crece con cada proyecto exitoso. ║
╚══════════════════════════════════════════════════════════════════════════════╝
```
### Criterios de Inclusión
Una funcionalidad DEBE agregarse al catálogo si cumple **TODOS** estos criterios:
| Criterio | Descripción |
|----------|-------------|
| ✅ Probada | Funciona en producción (al menos 1 proyecto) |
| ✅ Reutilizable | No es específica de un dominio de negocio |
| ✅ Común | Se necesita en múltiples proyectos típicamente |
| ✅ Compleja | Tiene suficiente complejidad que justifica documentar |
| ✅ Estable | API/estructura no cambia frecuentemente |
**Ejemplos de funcionalidades candidatas:**
- Autenticación, sesiones, rate limiting
- Notificaciones, emails, push
- Pagos, suscripciones
- WebSockets, real-time
- Multi-tenancy, feature flags
- File upload, image processing
- Audit logs, activity tracking
- Caching strategies
**Ejemplos que NO van al catálogo:**
- Lógica de negocio específica (cálculo de comisiones de trading)
- UI components específicos (aunque pueden ir a un catálogo de UI)
- Configuraciones específicas de un proyecto
### Proceso de Adición (Checklist)
```markdown
PASO 1: PREPARAR ESTRUCTURA
[ ] Crear directorio: core/catalog/{nombre-en-kebab-case}/
[ ] Crear README.md vacío
[ ] Crear IMPLEMENTATION.md vacío
PASO 2: DOCUMENTAR README.md
[ ] Agregar metadata (versión, origen, estado, fecha)
[ ] Escribir descripción clara
[ ] Listar características
[ ] Definir stack tecnológico
[ ] Listar dependencias NPM
[ ] Listar tablas de BD requeridas
[ ] Documentar endpoints principales
[ ] Agregar diagrama de flujo si aplica
PASO 3: DOCUMENTAR IMPLEMENTATION.md
[ ] Listar pre-requisitos
[ ] Escribir pasos numerados de implementación
[ ] Incluir código de ejemplo en cada paso
[ ] Documentar variables de entorno
[ ] Crear checklist de verificación
[ ] Agregar sección de troubleshooting
PASO 4: ACTUALIZAR ÍNDICES (OBLIGATORIO)
[ ] Actualizar CATALOG-INDEX.yml:
- Agregar entrada bajo funcionalidades:
- Incluir: nombre, path, alias, estado, origen, version
- Incluir: stack, keywords, caracteristicas
- Incluir: dependencias_npm, tablas_requeridas
[ ] Actualizar este README.md:
- Agregar fila en tabla de "Estado Actual"
- Agregar en estructura de directorios
PASO 5: ACTUALIZAR ALIASES (OBLIGATORIO)
[ ] Editar core/orchestration/referencias/ALIASES.yml:
- Agregar alias @CATALOG_{NOMBRE}
- Ejemplo: @CATALOG_AUDIT: "core/catalog/audit-logs/"
PASO 6: VALIDAR
[ ] Verificar que grep encuentra la funcionalidad en CATALOG-INDEX.yml
[ ] Verificar que el alias funciona
[ ] Revisar que README e IMPLEMENTATION son claros
```
### Plantilla para Nueva Funcionalidad
**README.md:**
```markdown
# {Nombre de la Funcionalidad}
**Versión:** 1.0.0
**Origen:** projects/{proyecto}
**Estado:** Production-Ready | Documentando
**Última actualización:** YYYY-MM-DD
---
## Descripción
{Descripción clara de qué hace y para qué sirve}
---
## Características
| Característica | Descripción |
|----------------|-------------|
| ... | ... |
---
## Stack Tecnológico
\`\`\`yaml
backend:
framework: NestJS
# ...
\`\`\`
---
## Dependencias NPM
\`\`\`json
{
"paquete": "^version"
}
\`\`\`
---
## Tablas Requeridas
| Tabla | Propósito |
|-------|-----------|
| ... | ... |
---
## Endpoints Principales
| Método | Ruta | Descripción |
|--------|------|-------------|
| ... | ... | ... |
---
**Mantenido por:** Sistema NEXUS
**Proyecto origen:** {Proyecto}
```
**IMPLEMENTATION.md:**
```markdown
# Guía de Implementación: {Nombre}
**Versión:** 1.0.0
**Tiempo estimado:** X-Y horas
**Complejidad:** Baja | Media | Alta
---
## Pre-requisitos
- [ ] Requisito 1
- [ ] Requisito 2
---
## Paso 1: {Nombre del Paso}
{Descripción}
\`\`\`typescript
// Código de ejemplo
\`\`\`
---
## Variables de Entorno
\`\`\`env
VARIABLE=valor
\`\`\`
---
## Checklist de Implementación
- [ ] Paso completado 1
- [ ] Paso completado 2
- [ ] Build pasa sin errores
- [ ] Tests pasan
---
## Troubleshooting
### Error: "{mensaje}"
{Solución}
---
**Versión:** 1.0.0
**Sistema:** SIMCO Catálogo
```
---
## INTEGRACIÓN CON SIMCO
Este catálogo se integra con el sistema SIMCO:
| Directiva | Integración |
|-----------|-------------|
| @SIMCO-REUTILIZAR | Directiva específica para reutilización |
| PRINCIPIO-ANTI-DUPLICACION | Verificar @CATALOG antes de crear |
| SIMCO-CREAR | Paso 0: Verificar catálogo |
| SIMCO-BUSCAR | Incluir @CATALOG como fuente |
| SIMCO-DELEGACION | Incluir @CATALOG en contexto |
---
## MANTENIMIENTO
### Actualizar Funcionalidad Existente
```markdown
Cuando el código de referencia mejore en un proyecto:
1. Evaluar si el cambio es generalizable
2. Si sí: actualizar _reference/ y IMPLEMENTATION.md
3. Incrementar versión en README.md
4. Documentar cambio en historial
```
### Deprecar Funcionalidad
```markdown
Si una funcionalidad ya no es recomendada:
1. Marcar como "⚠️ Deprecated" en README.md
2. Documentar razón y alternativa
3. NO eliminar inmediatamente
4. Eliminar después de 2 versiones mayores
```
---
## REFERENCIAS
- **Sistema SIMCO:** `/core/orchestration/directivas/simco/`
- **Principios:** `/core/orchestration/directivas/principios/`
- **Aliases:** `/core/orchestration/referencias/ALIASES.yml`
---
**Versión:** 1.0.0 | **Sistema:** NEXUS SIMCO | **Mantenido por:** Tech Lead

View File

@ -0,0 +1,356 @@
/**
* Universal Enums - Core Constants
*
* Enums compartidos entre todos los proyectos del workspace.
* Estos son los enums "universales" que aplican a múltiples proyectos.
* Los enums específicos de cada proyecto deben estar en su propio repositorio.
*
* @module @core/constants/enums
* @version 1.0.0
*/
// ============================================================================
// USER STATUS & ROLES (Universal)
// ============================================================================
/**
* User status across all applications
*/
export enum UserStatus {
ACTIVE = 'active',
INACTIVE = 'inactive',
PENDING = 'pending',
SUSPENDED = 'suspended',
BANNED = 'banned',
DELETED = 'deleted',
}
/**
* Base user roles (can be extended per project)
*/
export enum BaseRole {
SUPER_ADMIN = 'super_admin',
ADMIN = 'admin',
USER = 'user',
GUEST = 'guest',
}
// ============================================================================
// AUTHENTICATION (Universal)
// ============================================================================
/**
* Authentication providers
*/
export enum AuthProvider {
LOCAL = 'local',
GOOGLE = 'google',
FACEBOOK = 'facebook',
APPLE = 'apple',
GITHUB = 'github',
MICROSOFT = 'microsoft',
}
/**
* Token types
*/
export enum TokenType {
ACCESS = 'access',
REFRESH = 'refresh',
RESET_PASSWORD = 'reset_password',
EMAIL_VERIFICATION = 'email_verification',
API_KEY = 'api_key',
}
/**
* Session status
*/
export enum SessionStatus {
ACTIVE = 'active',
EXPIRED = 'expired',
REVOKED = 'revoked',
}
// ============================================================================
// SUBSCRIPTION & BILLING (Universal)
// ============================================================================
/**
* Subscription tiers
*/
export enum SubscriptionTier {
FREE = 'free',
BASIC = 'basic',
PROFESSIONAL = 'professional',
ENTERPRISE = 'enterprise',
}
/**
* Subscription status
*/
export enum SubscriptionStatus {
ACTIVE = 'active',
INACTIVE = 'inactive',
CANCELLED = 'cancelled',
PAST_DUE = 'past_due',
TRIALING = 'trialing',
PAUSED = 'paused',
}
/**
* Payment status
*/
export enum PaymentStatus {
PENDING = 'pending',
PROCESSING = 'processing',
COMPLETED = 'completed',
FAILED = 'failed',
REFUNDED = 'refunded',
CANCELLED = 'cancelled',
}
/**
* Payment methods
*/
export enum PaymentMethod {
CREDIT_CARD = 'credit_card',
DEBIT_CARD = 'debit_card',
BANK_TRANSFER = 'bank_transfer',
PAYPAL = 'paypal',
STRIPE = 'stripe',
CASH = 'cash',
}
// ============================================================================
// NOTIFICATIONS (Universal)
// ============================================================================
/**
* Notification types
*/
export enum NotificationType {
INFO = 'info',
SUCCESS = 'success',
WARNING = 'warning',
ERROR = 'error',
ALERT = 'alert',
}
/**
* Notification channels
*/
export enum NotificationChannel {
EMAIL = 'email',
PUSH = 'push',
SMS = 'sms',
IN_APP = 'in_app',
WEBHOOK = 'webhook',
}
/**
* Notification priority
*/
export enum NotificationPriority {
LOW = 'low',
MEDIUM = 'medium',
HIGH = 'high',
CRITICAL = 'critical',
}
/**
* Notification status
*/
export enum NotificationStatus {
PENDING = 'pending',
SENT = 'sent',
DELIVERED = 'delivered',
READ = 'read',
FAILED = 'failed',
}
// ============================================================================
// CONTENT STATUS (Universal)
// ============================================================================
/**
* Content/Entity status
*/
export enum ContentStatus {
DRAFT = 'draft',
PENDING_REVIEW = 'pending_review',
PUBLISHED = 'published',
ARCHIVED = 'archived',
DELETED = 'deleted',
}
/**
* Media types
*/
export enum MediaType {
IMAGE = 'image',
VIDEO = 'video',
AUDIO = 'audio',
DOCUMENT = 'document',
PDF = 'pdf',
SPREADSHEET = 'spreadsheet',
}
/**
* File processing status
*/
export enum ProcessingStatus {
PENDING = 'pending',
PROCESSING = 'processing',
COMPLETED = 'completed',
FAILED = 'failed',
}
// ============================================================================
// AUDIT & LOGGING (Universal)
// ============================================================================
/**
* Audit action types
*/
export enum AuditAction {
CREATE = 'create',
READ = 'read',
UPDATE = 'update',
DELETE = 'delete',
LOGIN = 'login',
LOGOUT = 'logout',
EXPORT = 'export',
IMPORT = 'import',
}
/**
* Log levels
*/
export enum LogLevel {
DEBUG = 'debug',
INFO = 'info',
WARN = 'warn',
ERROR = 'error',
FATAL = 'fatal',
}
// ============================================================================
// UI/PREFERENCES (Universal)
// ============================================================================
/**
* Theme options
*/
export enum Theme {
LIGHT = 'light',
DARK = 'dark',
AUTO = 'auto',
}
/**
* Supported languages
*/
export enum Language {
ES = 'es',
EN = 'en',
FR = 'fr',
PT = 'pt',
}
/**
* Device types
*/
export enum DeviceType {
DESKTOP = 'desktop',
MOBILE = 'mobile',
TABLET = 'tablet',
UNKNOWN = 'unknown',
}
// ============================================================================
// TIME PERIODS (Universal)
// ============================================================================
/**
* Time periods for reports/aggregations
*/
export enum TimePeriod {
HOURLY = 'hourly',
DAILY = 'daily',
WEEKLY = 'weekly',
MONTHLY = 'monthly',
QUARTERLY = 'quarterly',
YEARLY = 'yearly',
}
/**
* Days of week
*/
export enum DayOfWeek {
MONDAY = 'monday',
TUESDAY = 'tuesday',
WEDNESDAY = 'wednesday',
THURSDAY = 'thursday',
FRIDAY = 'friday',
SATURDAY = 'saturday',
SUNDAY = 'sunday',
}
// ============================================================================
// SORT & FILTER (Universal)
// ============================================================================
/**
* Sort direction
*/
export enum SortDirection {
ASC = 'asc',
DESC = 'desc',
}
/**
* Comparison operators
*/
export enum ComparisonOperator {
EQUALS = 'eq',
NOT_EQUALS = 'ne',
GREATER_THAN = 'gt',
GREATER_THAN_OR_EQUALS = 'gte',
LESS_THAN = 'lt',
LESS_THAN_OR_EQUALS = 'lte',
CONTAINS = 'contains',
STARTS_WITH = 'starts_with',
ENDS_WITH = 'ends_with',
IN = 'in',
NOT_IN = 'not_in',
IS_NULL = 'is_null',
IS_NOT_NULL = 'is_not_null',
}
// ============================================================================
// HELPERS
// ============================================================================
/**
* Check if value is valid enum value
*/
export const isValidEnumValue = <T extends object>(
enumObj: T,
value: unknown,
): boolean => {
return Object.values(enumObj).includes(value);
};
/**
* Get all values from enum
*/
export const getEnumValues = <T extends object>(enumObj: T): string[] => {
return Object.values(enumObj);
};
/**
* Get all keys from enum
*/
export const getEnumKeys = <T extends object>(enumObj: T): string[] => {
return Object.keys(enumObj).filter((key) => isNaN(Number(key)));
};

11
core/constants/index.ts Normal file
View File

@ -0,0 +1,11 @@
/**
* Core Constants Module
*
* Universal constants shared across all projects in the workspace.
*
* @module @core/constants
* @version 1.0.0
*/
export * from './enums.constants';
export * from './regex.constants';

View File

@ -3,7 +3,7 @@
*
* Regex patterns compartidos entre todos los proyectos del workspace.
*
* @module @shared/constants/regex
* @module @core/constants/regex
* @version 1.0.0
*/

View File

@ -1,228 +0,0 @@
# MCP Servers
**Version:** 1.0.0
**Fecha:** 2026-01-04
**Sistema:** NEXUS v3.4 + SIMCO
---
## Proposito
Esta carpeta contiene la infraestructura para MCP (Model Context Protocol) servers del workspace. Los MCP servers proporcionan herramientas especializadas para agentes de IA.
---
## Estructura
```
mcp-servers/
├── README.md # Este archivo
├── _registry.yml # Registro central de MCP servers
├── internal/ # MCP servers desarrollados internamente
│ ├── .gitkeep
│ ├── rag-knowledge/ # [REPO INDEPENDIENTE] Sistema RAG
│ └── scrum-taiga/ # [REPO INDEPENDIENTE] Integracion Taiga
├── external/ # MCP servers de terceros
│ ├── .gitkeep
│ └── _sources.yml # Fuentes confiables
└── templates/ # Templates para nuevos MCP
└── TEMPLATE-MCP-INTERNO/
```
---
## Arquitectura: Repositorios Independientes
Los MCP servers internos son **repositorios independientes** (NO submodules):
| Caracteristica | Valor |
|----------------|-------|
| Versionado | Independiente del workspace |
| Dependencias | Propias (node_modules excluidos) |
| Desarrollo | Ciclo de vida propio |
| Clonacion | Manual despues de workspace |
### Por que NO son submodules?
1. **Flexibilidad:** Pueden actualizarse sin afectar workspace
2. **Desarrollo independiente:** Equipos pueden trabajar en paralelo
3. **Reutilizacion:** Pueden usarse en otros contextos
4. **Simplicidad:** Sin complejidad de submodules anidados
---
## MCP Servers Disponibles
### Internos (Desarrollo Propio)
| MCP Server | Descripcion | Prioridad | Estado |
|------------|-------------|-----------|--------|
| **rag-knowledge** | Sistema RAG como fuente de verdad | MAXIMA | Planificado |
| **scrum-taiga** | Integracion con Taiga SCRUM | ALTA | Planificado |
### Externos (Terceros)
Ver `external/_sources.yml` para fuentes confiables de MCP servers externos.
---
## Instalacion
### 1. Requisitos Previos
- workspace-v1 clonado
- SSH configurado para Gitea (ver `orchestration/referencias/REPOSITORY-STRUCTURE.md`)
- Node.js >= 18
### 2. Clonar MCP Servers
```bash
# Navegar a carpeta de MCP internos
cd /home/isem/workspace-v1/core/mcp-servers/internal
# Clonar RAG Knowledge Base (recomendado para desarrollo)
git clone git@gitea-server:rckrdmrd/mcp-rag-knowledge.git rag-knowledge
# Clonar SCRUM Taiga (opcional)
git clone git@gitea-server:rckrdmrd/mcp-scrum-taiga.git scrum-taiga
```
### 3. Instalar Dependencias
```bash
# RAG Knowledge
cd rag-knowledge
npm install
cp .env.example .env
# Configurar .env con credenciales
# SCRUM Taiga
cd ../scrum-taiga
npm install
cp .env.example .env
# Configurar .env con credenciales Taiga
```
### 4. Verificar Instalacion
```bash
# Desde workspace-v1
cd /home/isem/workspace-v1
# Verificar estructura
ls -la core/mcp-servers/internal/
# Verificar que MCP servers responden
cd core/mcp-servers/internal/rag-knowledge
npm run health-check
```
---
## Desarrollo de Nuevos MCP
### Usar Template
```bash
# Copiar template
cp -r templates/TEMPLATE-MCP-INTERNO nuevo-mcp-server
# Personalizar
cd nuevo-mcp-server
# Editar package.json, README.md, etc.
```
### Directivas a Seguir
| Directiva | Proposito |
|-----------|-----------|
| @SIMCO_MCP | Desarrollo de MCP servers |
| @SIMCO_MCP_IMPORT | Importacion de MCP externos |
| @SIMCO_RAG | Interaccion con sistema RAG |
### Registrar en _registry.yml
Despues de crear un nuevo MCP server, agregarlo a `_registry.yml`:
```yaml
mcp_servers:
internal:
nuevo-mcp:
name: "Nombre del MCP"
description: "Descripcion"
status: "development"
repository:
url: "git@gitea-server:rckrdmrd/mcp-nuevo.git"
# ...
```
---
## Perfiles de Agentes Relacionados
| Perfil | Responsabilidad |
|--------|-----------------|
| @PERFIL_MCP_ARCHITECT | Diseno e integracion de MCP |
| @PERFIL_MCP_DEVELOPER | Desarrollo de MCP internos |
| @PERFIL_MCP_INTEGRATOR | Importacion de MCP externos |
| @PERFIL_RAG_ENGINEER | Mantenimiento del RAG |
---
## Aliases Utiles
```yaml
@MCP_SERVERS: "core/mcp-servers/"
@MCP_REGISTRY: "core/mcp-servers/_registry.yml"
@MCP_RAG: "core/mcp-servers/internal/rag-knowledge/"
@MCP_TAIGA: "core/mcp-servers/internal/scrum-taiga/"
```
---
## Troubleshooting
### MCP server no clonado
```bash
# Verificar SSH
ssh -T gitea-server
# Si falla, verificar ~/.ssh/config
cat ~/.ssh/config | grep gitea
```
### Dependencias faltantes
```bash
# Reinstalar
cd core/mcp-servers/internal/rag-knowledge
rm -rf node_modules
npm install
```
### Variables de entorno
```bash
# Verificar .env existe
ls -la .env
# Verificar variables requeridas
cat .env.example
```
---
## Referencias
- `_registry.yml` - Registro completo de MCP servers
- `orchestration/directivas/simco/SIMCO-MCP.md` - Directiva de desarrollo
- `orchestration/referencias/REPOSITORY-STRUCTURE.md` - Estructura de repos
---
**Mantenido por:** @PERFIL_MCP_ARCHITECT
**Sistema:** NEXUS v3.4 + SIMCO

View File

@ -1,172 +0,0 @@
# MCP Servers Registry
# ====================
# Registro central de todos los MCP servers del workspace
#
# Version: 1.0.0
# Fecha: 2026-01-04
# Sistema: NEXUS v3.4 + SIMCO
version: "1.0.0"
last_updated: "2026-01-04"
maintainer: "@PERFIL_MCP_ARCHITECT"
# ============================================================================
# MCP SERVERS INTERNOS
# ============================================================================
# Desarrollados internamente para necesidades especificas del workspace
# Cada uno es un repositorio independiente que se clona manualmente
mcp_servers:
internal:
# -------------------------------------------------------------------------
# RAG Knowledge Base - PRIORIDAD MAXIMA
# -------------------------------------------------------------------------
rag-knowledge:
name: "RAG Knowledge Base"
description: |
Sistema RAG (Retrieval-Augmented Generation) como fuente de verdad
del workspace. Proporciona busqueda semantica sobre documentacion,
directivas, perfiles y codigo.
status: "planned"
priority: "maxima"
repository:
type: "gitea"
url: "git@gitea-server:rckrdmrd/mcp-rag-knowledge.git"
https: "http://72.60.226.4:3000/rckrdmrd/mcp-rag-knowledge"
clone_path: "core/mcp-servers/internal/rag-knowledge"
dependencies:
runtime:
- "Node.js >= 18"
- "TypeScript >= 5.0"
database:
- "PostgreSQL >= 15"
- "pgvector extension"
external_apis:
- "OpenAI API (embeddings)"
tools_provided:
- rag_query_context
- rag_get_directive
- rag_get_agent_profile
- rag_trace_reference
- rag_get_relations
- rag_find_code
- rag_explain_impact
- rag_index_document
- rag_sync_category
- rag_get_sync_status
- rag_validate_coverage
- rag_report_feedback
documentation:
architecture: "docs/ARCHITECTURE.md"
deployment: "docs/DEPLOYMENT.md"
usage: "docs/USAGE.md"
tools_spec: "docs/MCP-TOOLS-SPEC.md"
# -------------------------------------------------------------------------
# SCRUM Taiga Integration - PRIORIDAD ALTA
# -------------------------------------------------------------------------
scrum-taiga:
name: "SCRUM Taiga Integration"
description: |
Integracion con Taiga para gestion de proyectos SCRUM.
Permite sincronizar EPICs, User Stories y Tasks entre
el workspace y Taiga.
status: "planned"
priority: "alta"
repository:
type: "gitea"
url: "git@gitea-server:rckrdmrd/mcp-scrum-taiga.git"
https: "http://72.60.226.4:3000/rckrdmrd/mcp-scrum-taiga"
clone_path: "core/mcp-servers/internal/scrum-taiga"
dependencies:
runtime:
- "Node.js >= 18"
- "TypeScript >= 5.0"
external_apis:
- "Taiga API"
tools_provided:
- taiga_get_project
- taiga_list_epics
- taiga_create_epic
- taiga_list_user_stories
- taiga_create_user_story
- taiga_list_tasks
- taiga_create_task
- taiga_update_status
- taiga_sync_sprint
documentation:
architecture: "docs/ARCHITECTURE.md"
deployment: "docs/DEPLOYMENT.md"
usage: "docs/USAGE.md"
# ============================================================================
# MCP SERVERS EXTERNOS
# ============================================================================
# MCP servers de terceros evaluados y aprobados para uso
external:
# Lista de MCP servers externos pendientes de evaluacion
pending_evaluation: []
# MCP servers externos aprobados
approved: []
# Fuentes confiables para buscar MCP servers
trusted_sources:
- name: "Anthropic Official"
url: "https://github.com/anthropics"
priority: 1
- name: "MCP Community"
url: "https://github.com/modelcontextprotocol"
priority: 2
# ============================================================================
# INSTRUCCIONES DE CLONACION
# ============================================================================
clone_instructions: |
# Despues de clonar workspace-v1, clonar los MCP servers necesarios:
# 1. Navegar a la carpeta de MCP internos
cd /home/isem/workspace-v1/core/mcp-servers/internal
# 2. Clonar RAG Knowledge Base (recomendado)
git clone git@gitea-server:rckrdmrd/mcp-rag-knowledge.git rag-knowledge
cd rag-knowledge && npm install && cd ..
# 3. Clonar SCRUM Taiga (opcional)
git clone git@gitea-server:rckrdmrd/mcp-scrum-taiga.git scrum-taiga
cd scrum-taiga && npm install && cd ..
# 4. Verificar instalacion
ls -la
# ============================================================================
# VALIDACION
# ============================================================================
validation:
required_for_development:
- rag-knowledge
optional:
- scrum-taiga
check_command: |
# Verificar que MCP servers estan clonados
for mcp in rag-knowledge scrum-taiga; do
if [ -d "core/mcp-servers/internal/$mcp" ]; then
echo "OK: $mcp"
else
echo "MISSING: $mcp (clone con: git clone git@gitea-server:rckrdmrd/mcp-$mcp.git)"
fi
done

View File

@ -1,2 +0,0 @@
# Esta carpeta contiene MCP servers externos evaluados e instalados
# Ver _sources.yml para fuentes confiables

View File

@ -1,125 +0,0 @@
# MCP External Sources
# ====================
# Fuentes confiables para MCP servers externos
#
# Version: 1.0.0
# Fecha: 2026-01-04
version: "1.0.0"
last_updated: "2026-01-04"
# ============================================================================
# FUENTES CONFIABLES
# ============================================================================
# Lista de repositorios/organizaciones confiables para MCP servers
trusted_sources:
# Nivel 1: Oficial (maxima confianza)
official:
- name: "Anthropic Official"
url: "https://github.com/anthropics"
description: "MCP servers oficiales de Anthropic"
trust_level: "official"
auto_approve: true
- name: "Model Context Protocol"
url: "https://github.com/modelcontextprotocol"
description: "Repositorio oficial del protocolo MCP"
trust_level: "official"
auto_approve: true
# Nivel 2: Comunidad Verificada (alta confianza)
community_verified:
- name: "MCP Community Servers"
url: "https://github.com/mcp-community"
description: "Servidores MCP de la comunidad verificados"
trust_level: "verified"
auto_approve: false
requires_review: true
# Nivel 3: Terceros (requiere evaluacion completa)
third_party: []
# ============================================================================
# PROCESO DE EVALUACION
# ============================================================================
evaluation_process:
steps:
1_identify:
description: "Identificar MCP server de interes"
actions:
- Verificar fuente en trusted_sources
- Revisar repositorio y documentacion
- Verificar actividad y mantenimiento
2_security_review:
description: "Revision de seguridad"
actions:
- Revisar dependencias (npm audit)
- Buscar vulnerabilidades conocidas
- Verificar permisos requeridos
- Revisar codigo fuente si es necesario
3_functionality_test:
description: "Prueba de funcionalidad"
actions:
- Instalar en ambiente de prueba
- Ejecutar tests incluidos
- Verificar herramientas funcionan
- Documentar comportamiento
4_approval:
description: "Aprobacion final"
actions:
- Documentar en _registry.yml
- Agregar a external/installed/
- Actualizar documentacion
criteria:
mandatory:
- "Codigo fuente disponible"
- "Sin vulnerabilidades criticas"
- "Documentacion adecuada"
- "Tests incluidos"
recommended:
- "Mantenimiento activo (< 6 meses)"
- "Mas de 10 estrellas en GitHub"
- "Issues respondidos"
# ============================================================================
# MCP SERVERS EXTERNOS INSTALADOS
# ============================================================================
installed: []
# Formato cuando se instale uno:
# - name: "nombre-del-mcp"
# source: "url del repo"
# version: "1.0.0"
# installed_date: "2026-01-04"
# installed_by: "@PERFIL_MCP_INTEGRATOR"
# location: "external/installed/nombre-del-mcp"
# review_notes: "Notas de la evaluacion"
# ============================================================================
# MCP SERVERS PENDIENTES DE EVALUACION
# ============================================================================
pending_evaluation: []
# Formato:
# - name: "nombre"
# source: "url"
# requested_by: "quien lo solicito"
# requested_date: "fecha"
# reason: "por que se necesita"
# ============================================================================
# MCP SERVERS RECHAZADOS
# ============================================================================
rejected: []
# Formato:
# - name: "nombre"
# source: "url"
# rejected_date: "fecha"
# reason: "razon del rechazo"

View File

@ -1,3 +0,0 @@
# Esta carpeta contiene MCP servers internos como repositorios independientes
# Cada MCP server se clona manualmente despues de clonar workspace-v1
# Ver _registry.yml para lista de MCP servers disponibles

View File

@ -1 +0,0 @@
# Esta carpeta contiene templates para crear nuevos MCP servers

View File

@ -1,16 +0,0 @@
# ============================================================================
# MCP Server Configuration
# ============================================================================
# Server
PORT=3100
NODE_ENV=development
# Database (PostgreSQL with pgvector)
DATABASE_URL=postgresql://user:password@localhost:5432/mcp_db
# OpenAI (for embeddings)
OPENAI_API_KEY=sk-your-api-key-here
# Logging
LOG_LEVEL=info

View File

@ -1,35 +0,0 @@
# Dependencies
node_modules/
# Build
dist/
*.tsbuildinfo
# Environment
.env
.env.local
.env.*.local
# Logs
logs/
*.log
npm-debug.log*
# Testing
coverage/
.nyc_output/
# IDE
.idea/
.vscode/
*.swp
*.swo
# OS
.DS_Store
Thumbs.db
# Temp
tmp/
temp/
.cache/

View File

@ -1,121 +0,0 @@
# {NOMBRE_MCP}
**Version:** 0.1.0
**Fecha:** {FECHA}
**Sistema:** NEXUS v3.4 + SIMCO
---
## Descripcion
{DESCRIPCION_DEL_MCP}
---
## Instalacion
```bash
# Clonar (desde workspace-v1/core/mcp-servers/internal/)
git clone git@gitea-server:rckrdmrd/mcp-{nombre}.git {nombre}
cd {nombre}
# Instalar dependencias
npm install
# Configurar
cp .env.example .env
# Editar .env con credenciales
```
---
## Configuracion
### Variables de Entorno
| Variable | Descripcion | Requerido |
|----------|-------------|-----------|
| `DATABASE_URL` | URL de PostgreSQL | Si |
| `OPENAI_API_KEY` | API key de OpenAI | Si |
### Archivo .env.example
```env
# Database
DATABASE_URL=postgresql://user:pass@localhost:5432/db
# OpenAI (para embeddings)
OPENAI_API_KEY=sk-...
# Server
PORT=3100
```
---
## Uso
### Iniciar Servidor
```bash
npm run start
```
### Desarrollo
```bash
npm run dev
```
### Tests
```bash
npm run test
```
---
## Herramientas MCP Disponibles
| Herramienta | Descripcion |
|-------------|-------------|
| `{tool_1}` | {descripcion} |
| `{tool_2}` | {descripcion} |
---
## Estructura
```
{nombre}/
├── README.md
├── package.json
├── tsconfig.json
├── .env.example
├── .gitignore
├── docs/
│ ├── ARCHITECTURE.md
│ ├── DEPLOYMENT.md
│ └── USAGE.md
├── orchestration/
│ └── 00-guidelines/
│ └── CONTEXTO-PROYECTO.md
├── src/
│ ├── index.ts
│ ├── tools/
│ └── services/
├── config/
└── tests/
```
---
## Referencias
- Directiva: @SIMCO_MCP
- Perfil: @PERFIL_MCP_DEVELOPER
- Registry: core/mcp-servers/_registry.yml
---
**Mantenido por:** @PERFIL_MCP_DEVELOPER

View File

@ -1 +0,0 @@
# Configuration files directory

View File

@ -1,318 +0,0 @@
# ============================================================================
# CHUNKING-STRATEGIES.yml
# Estrategias de Chunking para Sistema RAG
# ============================================================================
# Version: 1.0.0
# Fecha: 2026-01-04
# EPIC: EPIC-013
# ============================================================================
# ----------------------------------------------------------------------------
# CONFIGURACION GLOBAL
# ----------------------------------------------------------------------------
global:
# Modelo de embeddings a usar
embedding_model: "text-embedding-ada-002"
embedding_dimensions: 1536
# Limites generales
max_chunk_size: 1500 # Caracteres maximos por chunk
min_chunk_size: 100 # Caracteres minimos (evitar chunks muy pequeños)
chunk_overlap: 200 # Overlap entre chunks consecutivos
# Separadores de chunk (en orden de prioridad)
separators:
- "\n## " # Heading nivel 2
- "\n### " # Heading nivel 3
- "\n#### " # Heading nivel 4
- "\n\n" # Parrafo
- "\n" # Linea
- ". " # Oracion
- " " # Palabra (ultimo recurso)
# ----------------------------------------------------------------------------
# ESTRATEGIAS POR TIPO DE DOCUMENTO
# ----------------------------------------------------------------------------
strategies:
# --------------------------------------------------------------------------
# DIRECTIVAS SIMCO
# --------------------------------------------------------------------------
directiva:
description: "Documentos de directivas del sistema SIMCO"
file_patterns:
- "orchestration/directivas/**/*.md"
- "**/SIMCO-*.md"
chunking:
method: "semantic" # semantic | fixed | paragraph
preserve_headings: true # Mantener jerarquia de headings en cada chunk
max_chunk_size: 1200 # Directivas son densos, chunks mas pequenos
include_frontmatter: true # Incluir frontmatter en primer chunk
metadata_extraction:
- field: "version"
pattern: "Version:\\s*([\\d.]+)"
- field: "priority"
pattern: "Prioridad:\\s*(\\w+)"
- field: "applies_to"
pattern: "Aplica a:\\s*(.+)"
heading_weights:
"RESUMEN EJECUTIVO": 1.5 # Boost para secciones importantes
"PRINCIPIO FUNDAMENTAL": 1.5
"CHECKLIST": 1.3
# --------------------------------------------------------------------------
# PERFILES DE AGENTES
# --------------------------------------------------------------------------
perfil:
description: "Perfiles de agentes del sistema NEXUS"
file_patterns:
- "orchestration/perfiles/**/*.md"
- "**/PERFIL-*.md"
chunking:
method: "semantic"
preserve_headings: true
max_chunk_size: 1000 # Perfiles necesitan precision alta
include_frontmatter: true
metadata_extraction:
- field: "agent_id"
pattern: "@(PERFIL_[A-Z_]+)"
- field: "system"
pattern: "Sistema:\\s*(\\w+)"
- field: "context_level"
pattern: "Contexto:\\s*(\\w+)"
special_sections:
- name: "DIRECTIVAS APLICABLES"
extract_as: "applicable_directives"
is_list: true
- name: "HERRAMIENTAS MCP"
extract_as: "mcp_tools"
is_list: true
# --------------------------------------------------------------------------
# TEMPLATES
# --------------------------------------------------------------------------
template:
description: "Templates y plantillas del workspace"
file_patterns:
- "**/templates/**/*"
- "**/TEMPLATE-*.md"
chunking:
method: "fixed" # Templates se dividen por tamano fijo
preserve_code_blocks: true # No cortar bloques de codigo
max_chunk_size: 2000 # Templates pueden ser mas largos
metadata_extraction:
- field: "template_type"
pattern: "Tipo:\\s*(\\w+)"
- field: "usage"
pattern: "Uso:\\s*(.+)"
special_handling:
- pattern: "```"
action: "preserve_block" # Mantener bloques de codigo intactos
# --------------------------------------------------------------------------
# CODIGO FUENTE
# --------------------------------------------------------------------------
code:
description: "Archivos de codigo fuente"
file_patterns:
- "**/*.ts"
- "**/*.tsx"
- "**/*.js"
- "**/*.jsx"
- "**/*.sql"
- "**/*.py"
chunking:
method: "ast" # Usar Abstract Syntax Tree
preserve_functions: true # No cortar funciones a la mitad
include_context: true # Incluir imports y contexto
max_chunk_size: 2500 # Codigo puede necesitar mas contexto
metadata_extraction:
- field: "language"
from: "file_extension"
- field: "exports"
pattern: "export\\s+(function|class|const|type)\\s+(\\w+)"
- field: "imports"
pattern: "import\\s+.*from\\s+['\"](.+)['\"]"
special_sections:
- type: "function"
extract_signature: true
extract_jsdoc: true
- type: "class"
extract_signature: true
include_methods: true
# --------------------------------------------------------------------------
# ESPECIFICACIONES
# --------------------------------------------------------------------------
spec:
description: "Documentos de especificacion tecnica"
file_patterns:
- "**/specs/**/*.md"
- "**/SPEC-*.md"
- "**/DDL-*.sql"
chunking:
method: "semantic"
preserve_headings: true
preserve_code_blocks: true
max_chunk_size: 1800
metadata_extraction:
- field: "spec_type"
pattern: "Tipo:\\s*(\\w+)"
- field: "version"
pattern: "Version:\\s*([\\d.]+)"
special_handling:
- pattern: "CREATE TABLE"
action: "preserve_statement"
- pattern: "CREATE FUNCTION"
action: "preserve_statement"
# --------------------------------------------------------------------------
# GUIAS Y DOCUMENTACION
# --------------------------------------------------------------------------
guide:
description: "Guias de uso y documentacion general"
file_patterns:
- "**/docs/**/*.md"
- "**/README.md"
- "**/USAGE.md"
- "**/GUIDE-*.md"
chunking:
method: "paragraph" # Por parrafos naturales
preserve_headings: true
preserve_code_blocks: true
max_chunk_size: 1500
metadata_extraction:
- field: "doc_type"
from: "filename"
- field: "project"
from: "path_segment"
segment_index: 1
# --------------------------------------------------------------------------
# EPICS Y TAREAS
# --------------------------------------------------------------------------
epic:
description: "Documentos de EPICs y planificacion"
file_patterns:
- "**/EPIC-*.md"
- "**/epics/**/*.md"
chunking:
method: "semantic"
preserve_headings: true
max_chunk_size: 1200
metadata_extraction:
- field: "epic_id"
pattern: "EPIC-(\\d+)"
- field: "status"
pattern: "Estado:\\s*(\\w+)"
- field: "priority"
pattern: "Prioridad:\\s*(\\w+)"
special_sections:
- name: "TAREAS"
extract_as: "tasks"
is_list: true
- name: "DEPENDENCIAS"
extract_as: "dependencies"
is_list: true
# --------------------------------------------------------------------------
# TRAZAS DE SESION
# --------------------------------------------------------------------------
traza:
description: "Trazas de sesiones de agentes"
file_patterns:
- "**/trazas/TRAZA-*.md"
chunking:
method: "fixed"
max_chunk_size: 2000 # Trazas son largas
preserve_code_blocks: true
metadata_extraction:
- field: "session_id"
pattern: "TRAZA-(\\d+)"
- field: "agent"
pattern: "Agente:\\s*@(\\w+)"
- field: "date"
pattern: "Fecha:\\s*([\\d-]+)"
indexing:
priority: "low" # Trazas tienen menor prioridad
retention_days: 90 # Mantener por 90 dias
# ----------------------------------------------------------------------------
# PROCESAMIENTO ESPECIAL
# ----------------------------------------------------------------------------
preprocessing:
# Limpiar antes de chunking
cleanup:
- remove_html_comments: true
- normalize_whitespace: true
- convert_tabs_to_spaces: true
# Frontmatter YAML
frontmatter:
extract: true
include_in_first_chunk: true
fields_to_index:
- "title"
- "version"
- "applicable_agents"
- "priority"
postprocessing:
# Agregar contexto a cada chunk
add_context:
- document_title: true
- heading_path: true
- document_category: true
# Validacion
validation:
- min_length: 50
- max_length: 3000
- require_content: true
# ----------------------------------------------------------------------------
# CONFIGURACION DE EMBEDDINGS
# ----------------------------------------------------------------------------
embeddings:
# Proveedor
provider: "openai"
model: "text-embedding-ada-002"
dimensions: 1536
# Batching
batch_size: 100
max_retries: 3
retry_delay_ms: 1000
# Cache
cache:
enabled: true
ttl_hours: 168 # 7 dias
storage: "postgres"
# ----------------------------------------------------------------------------
# FIN DE CONFIGURACION
# ----------------------------------------------------------------------------

View File

@ -1,359 +0,0 @@
# ============================================================================
# PATH-MAPPINGS.yml
# Mapeo de Rutas del Workspace a Categorias RAG
# ============================================================================
# Version: 1.0.0
# Fecha: 2026-01-04
# EPIC: EPIC-013
# ============================================================================
# ----------------------------------------------------------------------------
# CONFIGURACION BASE
# ----------------------------------------------------------------------------
base:
workspace_root: "/home/isem/workspace-v1"
# Categorias principales del sistema RAG
categories:
- orchestration # Sistema de orquestacion (directivas, perfiles, trazas)
- core # Componentes core (MCP servers, utilidades)
- knowledge-base # Base de conocimiento (documentacion, snippets)
- projects # Proyectos activos (gamilit, erp-core, etc)
# ----------------------------------------------------------------------------
# MAPEOS DE RUTAS
# ----------------------------------------------------------------------------
mappings:
# ==========================================================================
# ORCHESTRATION - Sistema de Orquestacion
# ==========================================================================
orchestration:
base_path: "orchestration/"
description: "Sistema NEXUS de orquestacion de agentes"
priority: "maxima"
subcategories:
# Directivas SIMCO
directivas:
paths:
- "orchestration/directivas/**/*.md"
document_type: "directiva"
applicable_agents: ["*"]
index_priority: 1
# Perfiles de agentes
perfiles:
paths:
- "orchestration/perfiles/**/*.md"
document_type: "perfil"
applicable_agents: ["*"]
index_priority: 1
# Templates de orquestacion
templates:
paths:
- "orchestration/templates/**/*"
document_type: "template"
applicable_agents: ["PERFIL_ARCHITECT", "PERFIL_DEVELOPER"]
index_priority: 2
# Trazas de sesiones
trazas:
paths:
- "orchestration/trazas/**/*.md"
document_type: "traza"
applicable_agents: ["PERFIL_ANALYST"]
index_priority: 3
retention_days: 90
# Referencias
referencias:
paths:
- "orchestration/referencias/**/*.md"
document_type: "reference"
applicable_agents: ["*"]
index_priority: 2
# EPICs
epics:
paths:
- "orchestration/epics/**/*.md"
document_type: "epic"
applicable_agents: ["PERFIL_SCRUM_MANAGER", "PERFIL_ARCHITECT"]
index_priority: 2
# ==========================================================================
# CORE - Componentes Core del Workspace
# ==========================================================================
core:
base_path: "core/"
description: "Componentes core compartidos"
priority: "alta"
subcategories:
# MCP Servers
mcp-servers:
paths:
- "core/mcp-servers/**/*.md"
- "core/mcp-servers/**/*.yml"
- "core/mcp-servers/**/*.yaml"
- "core/mcp-servers/templates/**/*"
document_type: "spec"
applicable_agents: ["PERFIL_MCP_ARCHITECT", "PERFIL_MCP_DEVELOPER"]
index_priority: 1
exclude:
- "core/mcp-servers/internal/*/node_modules/**"
- "core/mcp-servers/internal/*/.git/**"
- "core/mcp-servers/external/installed/**"
# Utilidades compartidas
utils:
paths:
- "core/utils/**/*"
document_type: "code"
applicable_agents: ["PERFIL_DEVELOPER"]
index_priority: 2
# Scripts
scripts:
paths:
- "core/scripts/**/*"
document_type: "code"
applicable_agents: ["PERFIL_DEVOPS"]
index_priority: 3
# ==========================================================================
# KNOWLEDGE-BASE - Base de Conocimiento
# ==========================================================================
knowledge-base:
base_path: "knowledge-base/"
description: "Documentacion y recursos de referencia"
priority: "alta"
subcategories:
# Documentacion tecnica
technical:
paths:
- "knowledge-base/technical/**/*.md"
document_type: "guide"
applicable_agents: ["*"]
index_priority: 2
# Snippets de codigo
snippets:
paths:
- "knowledge-base/snippets/**/*"
document_type: "code"
applicable_agents: ["PERFIL_DEVELOPER"]
index_priority: 2
# Mejores practicas
best-practices:
paths:
- "knowledge-base/best-practices/**/*.md"
document_type: "guide"
applicable_agents: ["*"]
index_priority: 2
# Patrones de diseno
patterns:
paths:
- "knowledge-base/patterns/**/*.md"
document_type: "guide"
applicable_agents: ["PERFIL_ARCHITECT", "PERFIL_DEVELOPER"]
index_priority: 2
# ==========================================================================
# PROJECTS - Proyectos Activos
# ==========================================================================
projects:
base_path: "projects/"
description: "Proyectos en desarrollo activo"
priority: "alta"
# Proyectos especificos
project_mappings:
# Gamilit - Sistema educativo
gamilit:
paths:
- "projects/gamilit/orchestration/**/*.md"
- "projects/gamilit/docs/**/*.md"
- "projects/gamilit/apps/*/README.md"
document_type: "spec"
project: "gamilit"
applicable_agents:
- "PERFIL_ARCHITECT"
- "PERFIL_BACKEND_DEVELOPER"
- "PERFIL_FRONTEND_DEVELOPER"
index_priority: 1
exclude:
- "projects/gamilit/**/node_modules/**"
- "projects/gamilit/**/dist/**"
- "projects/gamilit/**/.git/**"
# ERP Core - Sistema ERP
erp-core:
paths:
- "projects/erp-core/orchestration/**/*.md"
- "projects/erp-core/docs/**/*.md"
document_type: "spec"
project: "erp-core"
applicable_agents:
- "PERFIL_ARCHITECT"
- "PERFIL_DEVELOPER"
index_priority: 2
# Template de proyecto (para nuevos proyectos)
_template:
paths:
- "projects/*/orchestration/**/*.md"
- "projects/*/docs/**/*.md"
document_type: "spec"
index_priority: 3
# ----------------------------------------------------------------------------
# EXCLUSIONES GLOBALES
# ----------------------------------------------------------------------------
global_exclusions:
# Carpetas de dependencias
- "**/node_modules/**"
- "**/.npm/**"
- "**/vendor/**"
# Carpetas de build
- "**/dist/**"
- "**/build/**"
- "**/.next/**"
- "**/coverage/**"
# Control de versiones
- "**/.git/**"
- "**/.svn/**"
# Cache y temporales
- "**/.cache/**"
- "**/tmp/**"
- "**/.tmp/**"
- "**/temp/**"
# Logs
- "**/logs/**"
- "**/*.log"
# IDE y editores
- "**/.idea/**"
- "**/.vscode/**"
- "**/*.swp"
- "**/*.swo"
# Archivos binarios
- "**/*.png"
- "**/*.jpg"
- "**/*.jpeg"
- "**/*.gif"
- "**/*.ico"
- "**/*.pdf"
- "**/*.zip"
- "**/*.tar.gz"
# ----------------------------------------------------------------------------
# REGLAS DE DETECCION DE TIPO
# ----------------------------------------------------------------------------
type_detection:
# Por nombre de archivo
by_filename:
- pattern: "SIMCO-*.md"
type: "directiva"
- pattern: "PERFIL-*.md"
type: "perfil"
- pattern: "TEMPLATE-*.md"
type: "template"
- pattern: "EPIC-*.md"
type: "epic"
- pattern: "TRAZA-*.md"
type: "traza"
- pattern: "DDL-*.sql"
type: "spec"
- pattern: "README.md"
type: "guide"
- pattern: "*.test.ts"
type: "test"
# Por extension
by_extension:
- extension: ".md"
default_type: "guide"
- extension: ".ts"
type: "code"
- extension: ".tsx"
type: "code"
- extension: ".sql"
type: "spec"
- extension: ".yml"
type: "config"
- extension: ".yaml"
type: "config"
# ----------------------------------------------------------------------------
# RELACIONES AUTOMATICAS
# ----------------------------------------------------------------------------
auto_relations:
# Detectar referencias entre documentos
reference_patterns:
- pattern: "@(SIMCO[/_][A-Z-]+)"
relation_type: "references"
target_category: "orchestration"
- pattern: "@(PERFIL_[A-Z_]+)"
relation_type: "references"
target_category: "orchestration"
- pattern: "EPIC-(\\d+)"
relation_type: "references"
target_category: "orchestration"
- pattern: "MEJ-(\\d+)-(\\d+)"
relation_type: "implements"
target_category: "orchestration"
# Detectar imports en codigo
code_imports:
- pattern: "from ['\"](.+)['\"]"
relation_type: "imports"
resolve_path: true
# ----------------------------------------------------------------------------
# SINCRONIZACION
# ----------------------------------------------------------------------------
sync:
# Frecuencia de sincronizacion por categoria
schedules:
orchestration:
frequency: "realtime" # Sincronizar inmediatamente al cambiar
core:
frequency: "hourly" # Cada hora
knowledge-base:
frequency: "daily" # Diariamente
projects:
frequency: "on_demand" # Solo cuando se solicite
# Hooks de sincronizacion
hooks:
pre_sync:
- validate_frontmatter: true
- check_file_size: true
- max_file_size_mb: 5
post_sync:
- update_relations: true
- validate_coverage: true
- notify_if_errors: true
# ----------------------------------------------------------------------------
# FIN DE CONFIGURACION
# ----------------------------------------------------------------------------

View File

@ -1,103 +0,0 @@
# Arquitectura: MCP {NOMBRE}
**Version:** 0.1.0
**Fecha:** {FECHA}
---
## 1. Vision General
```
┌─────────────────────────────────────────────────────────┐
│ Claude / Agente │
└───────────────────────────┬─────────────────────────────┘
│ MCP Protocol
v
┌─────────────────────────────────────────────────────────┐
│ MCP Server {NOMBRE} │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Tools │ │ Services │ │ Config │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
└───────────────────────────┬─────────────────────────────┘
v
┌─────────────────────────────────────────────────────────┐
│ PostgreSQL + pgvector │
└─────────────────────────────────────────────────────────┘
```
---
## 2. Componentes
### 2.1 Tools Layer
Herramientas expuestas via MCP Protocol:
| Tool | Descripcion |
|------|-------------|
| `{tool_1}` | {desc} |
| `{tool_2}` | {desc} |
### 2.2 Services Layer
Logica de negocio:
| Service | Responsabilidad |
|---------|-----------------|
| `{Service1}` | {resp} |
| `{Service2}` | {resp} |
### 2.3 Data Layer
Acceso a datos:
- PostgreSQL para almacenamiento persistente
- pgvector para busqueda semantica
---
## 3. Flujo de Datos
```
Request (Tool Call)
v
Validate Input
v
Service Logic
v
Database Query
v
Format Response
v
Response (Tool Result)
```
---
## 4. Tecnologias
| Componente | Tecnologia |
|------------|------------|
| Runtime | Node.js 18+ |
| Lenguaje | TypeScript 5+ |
| Database | PostgreSQL 15+ |
| Vector Search | pgvector |
| HTTP | Express |
---
## 5. Seguridad
- Variables sensibles en .env (no versionado)
- Validacion de entrada en cada tool
- Conexion a DB via SSL en produccion
---
**Documento generado:** {FECHA}

View File

@ -1,432 +0,0 @@
-- ============================================================================
-- DDL-RAG-SCHEMA.sql
-- Schema de Base de Datos para Sistema RAG
-- ============================================================================
-- Version: 1.0.0
-- Fecha: 2026-01-04
-- Database: PostgreSQL 15+ con extension pgvector
-- EPIC: EPIC-013
-- ============================================================================
-- ============================================================================
-- EXTENSIONES REQUERIDAS
-- ============================================================================
CREATE EXTENSION IF NOT EXISTS vector; -- Para embeddings y busqueda semantica
CREATE EXTENSION IF NOT EXISTS pg_trgm; -- Para busqueda fuzzy de texto
-- ============================================================================
-- TABLA: documents
-- ============================================================================
-- Almacena documentos indexados del workspace
CREATE TABLE IF NOT EXISTS documents (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
-- Identificacion
path TEXT NOT NULL UNIQUE, -- Ruta relativa al workspace
title TEXT NOT NULL, -- Titulo del documento
-- Clasificacion
category TEXT NOT NULL, -- orchestration, core, knowledge-base, projects
subcategory TEXT, -- directivas, perfiles, templates, etc.
document_type TEXT NOT NULL, -- directiva, perfil, template, spec, code, guide
project TEXT, -- Proyecto especifico (gamilit, erp-core, etc.)
-- Contenido
content TEXT NOT NULL, -- Contenido completo del documento
content_hash TEXT NOT NULL, -- Hash para detectar cambios
-- Metadata
applicable_agents TEXT[] DEFAULT '{}', -- Agentes que deben conocer este doc
metadata JSONB DEFAULT '{}', -- Metadata adicional flexible
frontmatter JSONB, -- Frontmatter parseado (si existe)
-- Timestamps
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
-- Soft delete
is_deleted BOOLEAN DEFAULT FALSE,
deleted_at TIMESTAMPTZ
);
-- Indices para documents
CREATE INDEX idx_documents_path ON documents(path);
CREATE INDEX idx_documents_category ON documents(category);
CREATE INDEX idx_documents_type ON documents(document_type);
CREATE INDEX idx_documents_project ON documents(project);
CREATE INDEX idx_documents_agents ON documents USING GIN(applicable_agents);
CREATE INDEX idx_documents_deleted ON documents(is_deleted) WHERE is_deleted = FALSE;
-- ============================================================================
-- TABLA: document_chunks
-- ============================================================================
-- Chunks de documentos con embeddings para busqueda semantica
CREATE TABLE IF NOT EXISTS document_chunks (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
document_id UUID REFERENCES documents(id) ON DELETE CASCADE,
-- Posicion
chunk_index INTEGER NOT NULL, -- Orden del chunk en el documento
-- Contenido
content TEXT NOT NULL, -- Contenido del chunk
heading_path TEXT[] DEFAULT '{}', -- Jerarquia de headings (## Seccion > ### Subseccion)
-- Ubicacion en archivo original
line_start INTEGER, -- Linea de inicio
line_end INTEGER, -- Linea de fin
-- Embedding
embedding vector(1536), -- Vector de embedding (OpenAI ada-002)
-- Timestamps
created_at TIMESTAMPTZ DEFAULT NOW(),
-- Constraint de unicidad
UNIQUE(document_id, chunk_index)
);
-- Indice IVFFlat para busqueda por similitud coseno
-- lists = 100 es un buen balance para ~10k-100k chunks
CREATE INDEX idx_chunks_embedding ON document_chunks
USING ivfflat (embedding vector_cosine_ops)
WITH (lists = 100);
CREATE INDEX idx_chunks_document ON document_chunks(document_id);
CREATE INDEX idx_chunks_heading ON document_chunks USING GIN(heading_path);
-- ============================================================================
-- TABLA: document_relations
-- ============================================================================
-- Relaciones entre documentos (grafo de dependencias)
CREATE TABLE IF NOT EXISTS document_relations (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
-- Documentos relacionados
source_document_id UUID REFERENCES documents(id) ON DELETE CASCADE,
target_document_id UUID REFERENCES documents(id) ON DELETE CASCADE,
-- Tipo de relacion
relation_type TEXT NOT NULL, -- references, extends, implements, uses, etc.
context TEXT, -- Contexto adicional de la relacion
-- Metadata
auto_detected BOOLEAN DEFAULT FALSE, -- True si fue detectado automaticamente
-- Timestamps
created_at TIMESTAMPTZ DEFAULT NOW(),
-- Constraint para evitar duplicados
UNIQUE(source_document_id, target_document_id, relation_type)
);
-- Indices para relaciones
CREATE INDEX idx_relations_source ON document_relations(source_document_id);
CREATE INDEX idx_relations_target ON document_relations(target_document_id);
CREATE INDEX idx_relations_type ON document_relations(relation_type);
-- ============================================================================
-- TABLA: code_references
-- ============================================================================
-- Referencias a codigo encontradas en documentos
CREATE TABLE IF NOT EXISTS code_references (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
document_id UUID REFERENCES documents(id) ON DELETE CASCADE,
-- Identificacion del codigo
code_path TEXT NOT NULL, -- Ruta al archivo de codigo
code_name TEXT NOT NULL, -- Nombre (funcion, clase, etc.)
code_type TEXT NOT NULL, -- function, class, interface, const, type
-- Metadata
language TEXT, -- typescript, javascript, sql, etc.
line_start INTEGER, -- Linea de inicio en codigo
line_end INTEGER, -- Linea de fin
context TEXT, -- Contexto de la referencia
-- Timestamps
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- Indices para referencias de codigo
CREATE INDEX idx_code_refs_document ON code_references(document_id);
CREATE INDEX idx_code_refs_path ON code_references(code_path);
CREATE INDEX idx_code_refs_name ON code_references(code_name);
CREATE INDEX idx_code_refs_type ON code_references(code_type);
-- ============================================================================
-- TABLA: sync_log
-- ============================================================================
-- Log de sincronizacion para tracking
CREATE TABLE IF NOT EXISTS sync_log (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
-- Operacion
operation TEXT NOT NULL, -- index, update, delete, sync_category
document_path TEXT, -- Ruta del documento (si aplica)
category TEXT, -- Categoria (si aplica)
-- Resultado
status TEXT NOT NULL, -- success, error, skipped
message TEXT, -- Mensaje de resultado
chunks_processed INTEGER DEFAULT 0, -- Chunks procesados
duration_ms INTEGER, -- Duracion en milisegundos
-- Timestamps
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX idx_sync_log_created ON sync_log(created_at DESC);
CREATE INDEX idx_sync_log_status ON sync_log(status);
-- ============================================================================
-- FUNCIONES DE BUSQUEDA
-- ============================================================================
-- Busqueda semantica principal
CREATE OR REPLACE FUNCTION search_knowledge(
query_embedding vector(1536),
p_category TEXT DEFAULT NULL,
p_document_type TEXT DEFAULT NULL,
p_project TEXT DEFAULT NULL,
p_agent TEXT DEFAULT NULL,
p_threshold FLOAT DEFAULT 0.7,
p_limit INTEGER DEFAULT 10
)
RETURNS TABLE (
document_id UUID,
chunk_id UUID,
path TEXT,
title TEXT,
category TEXT,
document_type TEXT,
chunk_content TEXT,
heading_path TEXT[],
line_start INTEGER,
line_end INTEGER,
similarity FLOAT,
applicable_agents TEXT[]
)
LANGUAGE plpgsql
AS $$
BEGIN
RETURN QUERY
SELECT
d.id as document_id,
c.id as chunk_id,
d.path,
d.title,
d.category,
d.document_type,
c.content as chunk_content,
c.heading_path,
c.line_start,
c.line_end,
1 - (c.embedding <=> query_embedding) as similarity,
d.applicable_agents
FROM document_chunks c
JOIN documents d ON d.id = c.document_id
WHERE
d.is_deleted = FALSE
AND (p_category IS NULL OR d.category = p_category)
AND (p_document_type IS NULL OR d.document_type = p_document_type)
AND (p_project IS NULL OR d.project = p_project)
AND (p_agent IS NULL OR p_agent = ANY(d.applicable_agents))
AND 1 - (c.embedding <=> query_embedding) > p_threshold
ORDER BY c.embedding <=> query_embedding
LIMIT p_limit;
END;
$$;
-- Obtener documentos relacionados (recursivo)
CREATE OR REPLACE FUNCTION get_related_documents(
p_document_id UUID,
p_relation_types TEXT[] DEFAULT NULL,
p_depth INTEGER DEFAULT 1
)
RETURNS TABLE (
document_id UUID,
path TEXT,
title TEXT,
relation_type TEXT,
relation_depth INTEGER,
relation_context TEXT
)
LANGUAGE plpgsql
AS $$
BEGIN
RETURN QUERY
WITH RECURSIVE related AS (
-- Nivel 0: documento inicial
SELECT
d.id,
d.path,
d.title,
NULL::TEXT as rel_type,
0 as depth,
NULL::TEXT as context
FROM documents d
WHERE d.id = p_document_id
UNION ALL
-- Niveles siguientes
SELECT
d.id,
d.path,
d.title,
r.relation_type,
related.depth + 1,
r.context
FROM related
JOIN document_relations r ON r.source_document_id = related.id
JOIN documents d ON d.id = r.target_document_id
WHERE
related.depth < p_depth
AND d.is_deleted = FALSE
AND (p_relation_types IS NULL OR r.relation_type = ANY(p_relation_types))
)
SELECT
related.id as document_id,
related.path,
related.title,
related.rel_type as relation_type,
related.depth as relation_depth,
related.context as relation_context
FROM related
WHERE related.depth > 0
ORDER BY related.depth, related.title;
END;
$$;
-- Trazar referencia (para evitar alucinaciones)
CREATE OR REPLACE FUNCTION trace_reference(
p_query TEXT,
p_embedding vector(1536)
)
RETURNS TABLE (
source_type TEXT,
source_path TEXT,
source_title TEXT,
line_reference TEXT,
content_snippet TEXT,
confidence FLOAT,
related_documents JSONB
)
LANGUAGE plpgsql
AS $$
BEGIN
RETURN QUERY
WITH best_matches AS (
SELECT
d.id,
d.path,
d.title,
d.category as src_type,
c.line_start,
c.line_end,
c.content,
1 - (c.embedding <=> p_embedding) as sim
FROM document_chunks c
JOIN documents d ON d.id = c.document_id
WHERE
d.is_deleted = FALSE
AND 1 - (c.embedding <=> p_embedding) > 0.75
ORDER BY c.embedding <=> p_embedding
LIMIT 5
)
SELECT
bm.src_type as source_type,
bm.path as source_path,
bm.title as source_title,
bm.path || ':' || bm.line_start || '-' || bm.line_end as line_reference,
LEFT(bm.content, 500) as content_snippet,
bm.sim as confidence,
(
SELECT jsonb_agg(jsonb_build_object(
'path', d.path,
'title', d.title,
'relation', r.relation_type
))
FROM document_relations r
JOIN documents d ON d.id = r.target_document_id
WHERE r.source_document_id = bm.id
LIMIT 5
) as related_documents
FROM best_matches bm;
END;
$$;
-- ============================================================================
-- TRIGGERS
-- ============================================================================
-- Actualizar updated_at automaticamente
CREATE OR REPLACE FUNCTION update_updated_at()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trigger_documents_updated_at
BEFORE UPDATE ON documents
FOR EACH ROW
EXECUTE FUNCTION update_updated_at();
-- ============================================================================
-- VISTAS UTILES
-- ============================================================================
-- Vista de documentos con estadisticas
CREATE OR REPLACE VIEW v_document_stats AS
SELECT
d.id,
d.path,
d.title,
d.category,
d.document_type,
d.project,
COUNT(c.id) as chunk_count,
d.created_at,
d.updated_at
FROM documents d
LEFT JOIN document_chunks c ON c.document_id = d.id
WHERE d.is_deleted = FALSE
GROUP BY d.id;
-- Vista de estado de sincronizacion por categoria
CREATE OR REPLACE VIEW v_sync_status AS
SELECT
category,
COUNT(*) as total_documents,
MAX(updated_at) as last_updated,
COUNT(CASE WHEN updated_at < NOW() - INTERVAL '1 hour' THEN 1 END) as stale_count
FROM documents
WHERE is_deleted = FALSE
GROUP BY category;
-- ============================================================================
-- COMENTARIOS
-- ============================================================================
COMMENT ON TABLE documents IS 'Documentos indexados del workspace para busqueda RAG';
COMMENT ON TABLE document_chunks IS 'Chunks de documentos con embeddings para busqueda semantica';
COMMENT ON TABLE document_relations IS 'Grafo de relaciones entre documentos';
COMMENT ON TABLE code_references IS 'Referencias a codigo encontradas en documentos';
COMMENT ON TABLE sync_log IS 'Log de operaciones de sincronizacion';
COMMENT ON FUNCTION search_knowledge IS 'Busqueda semantica principal con filtros';
COMMENT ON FUNCTION get_related_documents IS 'Obtiene grafo de documentos relacionados recursivamente';
COMMENT ON FUNCTION trace_reference IS 'Verifica origen de informacion para evitar alucinaciones';
-- ============================================================================
-- FIN DEL SCHEMA
-- ============================================================================

View File

@ -1,687 +0,0 @@
# MCP-TOOLS-SPEC: Especificación de Herramientas RAG
**Version:** 1.0.0
**Fecha:** 2026-01-04
**MCP Server:** mcp-rag-knowledge
**EPIC:** EPIC-013
---
## RESUMEN
Este documento especifica las 12 herramientas MCP del sistema RAG para consulta y gestión del conocimiento del workspace.
---
## HERRAMIENTAS DE CONSULTA SEMÁNTICA
### 1. rag_query_context
**Descripción:** Busqueda semántica principal sobre el conocimiento del workspace.
**Parámetros:**
| Nombre | Tipo | Requerido | Descripción |
|--------|------|-----------|-------------|
| query | string | Sí | Pregunta o consulta en lenguaje natural |
| category | string | No | Filtrar por categoría (orchestration, core, knowledge-base, projects) |
| document_type | string | No | Filtrar por tipo (directiva, perfil, template, code, spec, guide) |
| project | string | No | Filtrar por proyecto específico |
| agent | string | No | Filtrar documentos aplicables a un agente específico |
| threshold | float | No | Umbral mínimo de similitud (default: 0.7) |
| limit | integer | No | Máximo de resultados (default: 10) |
**Retorno:**
```typescript
interface QueryResult {
results: Array<{
document_id: string;
chunk_id: string;
path: string;
title: string;
category: string;
document_type: string;
content: string;
heading_path: string[];
line_start: number;
line_end: number;
similarity: number;
applicable_agents: string[];
}>;
query_time_ms: number;
total_matches: number;
}
```
**Ejemplo:**
```typescript
const result = await rag_query_context({
query: "¿Cómo se debe documentar un cambio según SIMCO?",
category: "orchestration",
threshold: 0.75,
limit: 5
});
// Resultado esperado:
// {
// results: [{
// path: "orchestration/directivas/simco/SIMCO-DOCUMENTAR.md",
// title: "SIMCO-DOCUMENTAR",
// similarity: 0.89,
// content: "## Proceso de Documentación...",
// line_start: 45,
// line_end: 78
// }],
// query_time_ms: 120,
// total_matches: 3
// }
```
**Errores Comunes:**
| Código | Mensaje | Solución |
|--------|---------|----------|
| 400 | "Query too short" | Proporcionar query de al menos 3 palabras |
| 404 | "No results found" | Reducir threshold o generalizar query |
| 503 | "Embedding service unavailable" | Reintentar después de unos segundos |
---
### 2. rag_get_directive
**Descripción:** Obtiene una directiva SIMCO específica por su identificador.
**Parámetros:**
| Nombre | Tipo | Requerido | Descripción |
|--------|------|-----------|-------------|
| directive_id | string | Sí | Identificador de la directiva (ej: "SIMCO-TAREA") |
| include_relations | boolean | No | Incluir documentos relacionados (default: false) |
**Retorno:**
```typescript
interface DirectiveResult {
found: boolean;
directive: {
id: string;
path: string;
title: string;
version: string;
priority: string;
applies_to: string;
content: string;
sections: Array<{
heading: string;
content: string;
line_start: number;
line_end: number;
}>;
checklist: string[];
};
relations?: Array<{
path: string;
title: string;
relation_type: string;
}>;
}
```
**Ejemplo:**
```typescript
const directive = await rag_get_directive({
directive_id: "SIMCO-RAG",
include_relations: true
});
```
---
### 3. rag_get_agent_profile
**Descripción:** Carga el perfil completo de un agente para inicialización.
**Parámetros:**
| Nombre | Tipo | Requerido | Descripción |
|--------|------|-----------|-------------|
| agent_id | string | Sí | Identificador del agente (ej: "PERFIL_BACKEND_DEVELOPER") |
| include_directives | boolean | No | Incluir directivas aplicables (default: true) |
| include_tools | boolean | No | Incluir herramientas MCP disponibles (default: true) |
**Retorno:**
```typescript
interface AgentProfileResult {
found: boolean;
profile: {
id: string;
name: string;
system: string;
context_level: string;
responsibilities: string[];
applicable_directives: string[];
mcp_tools: string[];
constraints: string[];
full_content: string;
};
directives?: DirectiveResult[];
tools?: ToolSpec[];
}
```
**Ejemplo:**
```typescript
const profile = await rag_get_agent_profile({
agent_id: "PERFIL_MCP_DEVELOPER",
include_directives: true,
include_tools: true
});
```
---
## HERRAMIENTAS DE TRAZABILIDAD
### 4. rag_trace_reference
**Descripción:** Verifica el origen de una afirmación para prevenir alucinaciones.
**Parámetros:**
| Nombre | Tipo | Requerido | Descripción |
|--------|------|-----------|-------------|
| claim | string | Sí | Afirmación a verificar |
| context | string | No | Contexto adicional para la búsqueda |
| min_confidence | float | No | Confianza mínima requerida (default: 0.75) |
**Retorno:**
```typescript
interface TraceResult {
verified: boolean;
sources: Array<{
source_type: string;
source_path: string;
source_title: string;
line_reference: string; // formato: "path:line_start-line_end"
content_snippet: string;
confidence: number;
related_documents: Array<{
path: string;
title: string;
relation: string;
}>;
}>;
recommendation: "cite" | "verify" | "cannot_confirm";
}
```
**Ejemplo:**
```typescript
const trace = await rag_trace_reference({
claim: "Las directivas SIMCO son obligatorias para todos los agentes",
min_confidence: 0.8
});
// Si verified = true, usar las fuentes para citar
// Si verified = false, indicar que no se puede confirmar
```
---
### 5. rag_get_relations
**Descripción:** Obtiene el grafo de relaciones de un documento.
**Parámetros:**
| Nombre | Tipo | Requerido | Descripción |
|--------|------|-----------|-------------|
| document_path | string | Sí | Ruta del documento |
| relation_types | string[] | No | Filtrar por tipos de relación |
| depth | integer | No | Profundidad de recursión (default: 1, max: 3) |
| direction | string | No | "outgoing" \| "incoming" \| "both" (default: "both") |
**Retorno:**
```typescript
interface RelationsResult {
document: {
id: string;
path: string;
title: string;
};
relations: Array<{
document_id: string;
path: string;
title: string;
relation_type: string;
relation_depth: number;
direction: "outgoing" | "incoming";
context: string;
}>;
graph_summary: {
total_relations: number;
by_type: Record<string, number>;
max_depth_reached: number;
};
}
```
**Tipos de Relación:**
| Tipo | Descripción |
|------|-------------|
| references | Documento A menciona/cita a documento B |
| extends | Documento A extiende/amplía documento B |
| implements | Documento A implementa especificación B |
| uses | Documento A usa/depende de documento B |
| supersedes | Documento A reemplaza documento B |
---
### 6. rag_find_code
**Descripción:** Busca referencias de código en el workspace.
**Parámetros:**
| Nombre | Tipo | Requerido | Descripción |
|--------|------|-----------|-------------|
| name | string | No | Nombre de función/clase/tipo a buscar |
| code_type | string | No | Tipo: function, class, interface, const, type |
| language | string | No | Lenguaje: typescript, javascript, sql, python |
| path_pattern | string | No | Patrón glob para filtrar rutas |
| include_context | boolean | No | Incluir código circundante (default: true) |
**Retorno:**
```typescript
interface CodeSearchResult {
matches: Array<{
path: string;
name: string;
code_type: string;
language: string;
line_start: number;
line_end: number;
signature: string;
documentation: string;
code_snippet: string;
related_documents: string[]; // Documentos que referencian este código
}>;
total_matches: number;
}
```
**Ejemplo:**
```typescript
const code = await rag_find_code({
name: "validateParams",
code_type: "function",
language: "typescript"
});
```
---
### 7. rag_explain_impact
**Descripción:** Analiza el impacto de modificar un documento.
**Parámetros:**
| Nombre | Tipo | Requerido | Descripción |
|--------|------|-----------|-------------|
| document_path | string | Sí | Ruta del documento a analizar |
| change_type | string | Sí | "create" \| "modify" \| "delete" |
| affected_sections | string[] | No | Secciones específicas afectadas |
**Retorno:**
```typescript
interface ImpactAnalysis {
document: {
path: string;
title: string;
category: string;
document_type: string;
};
impact: {
direct_dependents: Array<{
path: string;
title: string;
relation_type: string;
impact_level: "high" | "medium" | "low";
}>;
indirect_dependents: Array<{
path: string;
title: string;
distance: number;
impact_level: "high" | "medium" | "low";
}>;
agents_affected: string[];
risk_level: "critical" | "high" | "medium" | "low";
propagation_order: string[]; // Orden sugerido para actualizar
};
recommendations: string[];
}
```
**Ejemplo:**
```typescript
const impact = await rag_explain_impact({
document_path: "orchestration/directivas/simco/SIMCO-TAREA.md",
change_type: "modify",
affected_sections: ["PRINCIPIO FUNDAMENTAL"]
});
// Antes de hacer cambios significativos, revisar:
// - impact.risk_level
// - impact.agents_affected
// - impact.propagation_order
```
---
## HERRAMIENTAS DE INDEXACIÓN
### 8. rag_index_document
**Descripción:** Indexa o re-indexa un documento en el sistema RAG.
**Parámetros:**
| Nombre | Tipo | Requerido | Descripción |
|--------|------|-----------|-------------|
| path | string | Sí | Ruta del documento a indexar |
| force | boolean | No | Forzar re-indexación aunque no haya cambios (default: false) |
| extract_relations | boolean | No | Detectar y crear relaciones automáticamente (default: true) |
**Retorno:**
```typescript
interface IndexResult {
success: boolean;
document: {
id: string;
path: string;
title: string;
category: string;
document_type: string;
};
indexing: {
chunks_created: number;
relations_detected: number;
code_references_found: number;
processing_time_ms: number;
};
status: "created" | "updated" | "unchanged" | "error";
error?: string;
}
```
**Ejemplo:**
```typescript
// Después de crear o modificar un documento
const result = await rag_index_document({
path: "orchestration/directivas/simco/SIMCO-NUEVA.md",
extract_relations: true
});
if (result.success) {
console.log(`Indexado: ${result.indexing.chunks_created} chunks`);
} else {
console.error(`Error: ${result.error}`);
}
```
---
### 9. rag_sync_category
**Descripción:** Sincroniza todos los documentos de una categoría.
**Parámetros:**
| Nombre | Tipo | Requerido | Descripción |
|--------|------|-----------|-------------|
| category | string | Sí | Categoría a sincronizar |
| subcategory | string | No | Subcategoría específica |
| force | boolean | No | Forzar re-indexación completa (default: false) |
| dry_run | boolean | No | Solo simular, no hacer cambios (default: false) |
**Retorno:**
```typescript
interface SyncResult {
category: string;
subcategory?: string;
summary: {
total_files: number;
indexed: number;
updated: number;
unchanged: number;
deleted: number;
errors: number;
};
details: Array<{
path: string;
status: "indexed" | "updated" | "unchanged" | "deleted" | "error";
chunks: number;
error?: string;
}>;
duration_ms: number;
}
```
**Ejemplo:**
```typescript
// Sincronizar todas las directivas
const sync = await rag_sync_category({
category: "orchestration",
subcategory: "directivas",
dry_run: false
});
console.log(`Sincronizado: ${sync.summary.indexed} nuevos, ${sync.summary.updated} actualizados`);
```
---
### 10. rag_get_sync_status
**Descripción:** Obtiene el estado de sincronización del sistema.
**Parámetros:**
| Nombre | Tipo | Requerido | Descripción |
|--------|------|-----------|-------------|
| category | string | No | Filtrar por categoría |
| include_stale | boolean | No | Incluir documentos desactualizados (default: true) |
**Retorno:**
```typescript
interface SyncStatus {
overall: {
total_documents: number;
total_chunks: number;
last_sync: string; // ISO timestamp
health: "healthy" | "degraded" | "unhealthy";
};
by_category: Array<{
category: string;
total_documents: number;
last_updated: string;
stale_count: number;
stale_documents?: string[];
}>;
pending_sync: Array<{
path: string;
reason: "new" | "modified" | "deleted";
detected_at: string;
}>;
}
```
---
## HERRAMIENTAS DE VALIDACIÓN
### 11. rag_validate_coverage
**Descripción:** Verifica la cobertura de indexación del workspace.
**Parámetros:**
| Nombre | Tipo | Requerido | Descripción |
|--------|------|-----------|-------------|
| category | string | No | Categoría a validar (todas si no se especifica) |
| report_missing | boolean | No | Incluir lista de archivos no indexados (default: true) |
**Retorno:**
```typescript
interface CoverageReport {
summary: {
total_files_expected: number;
total_files_indexed: number;
coverage_percentage: number;
health: "complete" | "partial" | "incomplete";
};
by_category: Array<{
category: string;
expected: number;
indexed: number;
coverage: number;
}>;
missing: Array<{
path: string;
category: string;
reason: "not_indexed" | "outdated" | "excluded";
}>;
recommendations: string[];
}
```
**Ejemplo:**
```typescript
const coverage = await rag_validate_coverage({
category: "orchestration",
report_missing: true
});
if (coverage.summary.coverage_percentage < 100) {
console.log("Documentos faltantes:", coverage.missing);
}
```
---
### 12. rag_report_feedback
**Descripción:** Reporta problemas de calidad en el sistema RAG.
**Parámetros:**
| Nombre | Tipo | Requerido | Descripción |
|--------|------|-----------|-------------|
| feedback_type | string | Sí | "missing_info" \| "incorrect_info" \| "outdated" \| "low_relevance" |
| query | string | Sí | Query que generó el problema |
| context | string | No | Contexto adicional del problema |
| document_path | string | No | Documento específico afectado |
| expected_result | string | No | Qué se esperaba encontrar |
**Retorno:**
```typescript
interface FeedbackResult {
feedback_id: string;
received: boolean;
suggested_actions: Array<{
action: string;
priority: "high" | "medium" | "low";
automated: boolean;
}>;
}
```
**Ejemplo:**
```typescript
// Cuando una búsqueda no encuentra lo esperado
const feedback = await rag_report_feedback({
feedback_type: "missing_info",
query: "¿Cómo configurar hooks en NEXUS?",
expected_result: "Debería encontrar SIMCO-HOOKS pero no está indexado",
document_path: "orchestration/directivas/simco/SIMCO-HOOKS.md"
});
```
---
## SCHEMAS JSON PARA REGISTRO MCP
```typescript
// schemas/tools.ts
export const toolSchemas = {
rag_query_context: {
name: "rag_query_context",
description: "Búsqueda semántica en el conocimiento del workspace",
parameters: {
type: "object",
properties: {
query: { type: "string", description: "Consulta en lenguaje natural" },
category: { type: "string", enum: ["orchestration", "core", "knowledge-base", "projects"] },
document_type: { type: "string", enum: ["directiva", "perfil", "template", "code", "spec", "guide"] },
project: { type: "string" },
agent: { type: "string" },
threshold: { type: "number", default: 0.7 },
limit: { type: "integer", default: 10 }
},
required: ["query"]
}
},
// ... resto de schemas
};
```
---
## NOTAS DE IMPLEMENTACIÓN
### Manejo de Errores
Todas las herramientas deben manejar:
1. **Errores de conexión:** Reintentar con backoff exponencial
2. **Errores de embedding:** Cachear embeddings para evitar recálculos
3. **Documentos no encontrados:** Retornar resultado vacío, no error
### Rate Limiting
- Embeddings: Máximo 100 requests/minuto a OpenAI
- Queries: Sin límite interno (depende de PostgreSQL)
- Sync: Máximo 1 sync completo por minuto
### Caché
- Embeddings: Cache de 7 días en PostgreSQL
- Queries: Cache de 5 minutos para queries idénticos
- Perfiles: Cache en memoria durante sesión
---
**Version:** 1.0.0 | **EPIC:** EPIC-013 | **Sistema:** SIMCO

View File

@ -1,83 +0,0 @@
# CONTEXTO-PROYECTO: MCP {NOMBRE}
**Version:** 0.1.0
**Fecha:** {FECHA}
**Sistema:** NEXUS v3.4 + SIMCO
---
## IDENTIFICACION
```yaml
proyecto: "mcp-{nombre}"
tipo: "mcp-server-interno"
estado: "development"
prioridad: "{alta|maxima}"
ubicacion:
workspace: "/home/isem/workspace-v1"
proyecto: "core/mcp-servers/internal/{nombre}"
repositorio: "git@gitea-server:rckrdmrd/mcp-{nombre}.git"
stack:
runtime: "Node.js >= 18"
lenguaje: "TypeScript"
database: "PostgreSQL + pgvector"
```
---
## PROPOSITO
{DESCRIPCION_DETALLADA_DEL_PROPOSITO}
---
## HERRAMIENTAS MCP
| Herramienta | Descripcion | Estado |
|-------------|-------------|--------|
| `{tool_1}` | {descripcion} | planned |
| `{tool_2}` | {descripcion} | planned |
---
## DEPENDENCIAS
### Externas
- PostgreSQL >= 15 con extension pgvector
- OpenAI API (para embeddings)
### Del Workspace
- Acceso a documentacion en orchestration/
- Acceso a knowledge-base/
---
## DIRECTIVAS APLICABLES
```yaml
siempre:
- @SIMCO_MCP
- @PRINCIPIO_CAPVED
- @PRINCIPIO_DOC_PRIMERO
operaciones:
crear_herramienta: [@SIMCO_CREAR]
modificar: [@SIMCO_MODIFICAR]
validar: [@SIMCO_VALIDAR]
```
---
## PERFILES RELACIONADOS
| Perfil | Responsabilidad |
|--------|-----------------|
| @PERFIL_MCP_DEVELOPER | Desarrollo de este MCP |
| @PERFIL_RAG_ENGINEER | Integracion con RAG |
| @PERFIL_MCP_ARCHITECT | Diseno y arquitectura |
---
**Contexto generado:** {FECHA}

View File

@ -1,50 +0,0 @@
{
"name": "mcp-{nombre}",
"version": "0.1.0",
"description": "{DESCRIPCION}",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc",
"start": "node dist/index.js",
"dev": "ts-node-dev --respawn src/index.ts",
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"lint": "eslint src/**/*.ts",
"lint:fix": "eslint src/**/*.ts --fix",
"typecheck": "tsc --noEmit",
"health-check": "curl -s http://localhost:${PORT:-3100}/health || echo 'Server not running'"
},
"keywords": [
"mcp",
"model-context-protocol",
"anthropic",
"claude"
],
"author": "workspace-v1",
"license": "MIT",
"dependencies": {
"@anthropic-ai/sdk": "^0.25.0",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"pg": "^8.11.3",
"pgvector": "^0.1.8"
},
"devDependencies": {
"@types/express": "^4.17.21",
"@types/jest": "^29.5.11",
"@types/node": "^20.10.0",
"@types/pg": "^8.10.9",
"@typescript-eslint/eslint-plugin": "^6.13.0",
"@typescript-eslint/parser": "^6.13.0",
"eslint": "^8.54.0",
"jest": "^29.7.0",
"ts-jest": "^29.1.1",
"ts-node-dev": "^2.0.0",
"typescript": "^5.3.0"
},
"engines": {
"node": ">=18.0.0"
}
}

View File

@ -1,61 +0,0 @@
/**
* MCP Server: {NOMBRE}
*
* {DESCRIPCION}
*
* @version 0.1.0
*/
import express from 'express';
import dotenv from 'dotenv';
// Load environment variables
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3100;
// Middleware
app.use(express.json());
// Health check endpoint
app.get('/health', (req, res) => {
res.json({
status: 'ok',
service: 'mcp-{nombre}',
version: '0.1.0',
timestamp: new Date().toISOString(),
});
});
// MCP Tools endpoint
app.post('/tools/:toolName', async (req, res) => {
const { toolName } = req.params;
const { parameters } = req.body;
try {
// TODO: Implement tool routing
const result = await handleTool(toolName, parameters);
res.json({ success: true, result });
} catch (error) {
res.status(500).json({
success: false,
error: error instanceof Error ? error.message : 'Unknown error',
});
}
});
// Tool handler
async function handleTool(toolName: string, parameters: unknown): Promise<unknown> {
switch (toolName) {
// TODO: Add tool cases
default:
throw new Error(`Unknown tool: ${toolName}`);
}
}
// Start server
app.listen(PORT, () => {
console.log(`MCP Server {nombre} running on port ${PORT}`);
console.log(`Health check: http://localhost:${PORT}/health`);
});

View File

@ -1 +0,0 @@
# Tests directory

171
core/modules/auth/README.md Normal file
View File

@ -0,0 +1,171 @@
# Auth - Core Module
**Modulo:** core/modules/auth/
**Version:** 0.1.0
**Fecha:** 2026-01-03
**Owner:** Backend-Agent
**Estado:** desarrollo
---
## Descripcion
Modulo de autenticacion compartido que provee guards, decorators y utilidades JWT para proyectos NestJS. Complementa el catalogo `core/catalog/auth/` con codigo listo para importar.
---
## Instalacion
### Prerequisitos
```bash
npm install @nestjs/jwt @nestjs/passport passport-jwt bcrypt
npm install -D @types/passport-jwt @types/bcrypt
```
### Configuracion de Paths
```json
{
"compilerOptions": {
"paths": {
"@core/modules/*": ["../../core/modules/*"]
}
}
}
```
---
## API Publica (Planificada)
### Guards
| Guard | Descripcion | Uso |
|-------|-------------|-----|
| `JwtAuthGuard` | Protege rutas con JWT | `@UseGuards(JwtAuthGuard)` |
| `RolesGuard` | Verifica roles de usuario | `@UseGuards(RolesGuard)` |
| `PermissionsGuard` | Verifica permisos | `@UseGuards(PermissionsGuard)` |
### Decorators
| Decorator | Descripcion | Ejemplo |
|-----------|-------------|---------|
| `@CurrentUser()` | Extrae usuario actual | `@CurrentUser() user: User` |
| `@Roles()` | Define roles requeridos | `@Roles('admin', 'editor')` |
| `@Public()` | Marca ruta como publica | `@Public()` |
### Servicios
| Servicio | Descripcion |
|----------|-------------|
| `TokenService` | Generacion/validacion JWT |
| `PasswordService` | Hashing con bcrypt |
| `SessionService` | Gestion de sesiones |
---
## Ejemplos de Uso
### Ejemplo 1: Proteger Controller
```typescript
import { JwtAuthGuard, CurrentUser, Roles } from '@core/modules/auth';
@Controller('users')
@UseGuards(JwtAuthGuard)
export class UsersController {
@Get('profile')
getProfile(@CurrentUser() user: User) {
return user;
}
@Get('admin')
@Roles('admin')
@UseGuards(RolesGuard)
adminOnly() {
return { message: 'Admin access' };
}
}
```
### Ejemplo 2: Hash de Password
```typescript
import { PasswordService } from '@core/modules/auth';
const passwordService = new PasswordService();
// Hash
const hash = await passwordService.hash('myPassword123');
// Verify
const isValid = await passwordService.verify('myPassword123', hash);
```
---
## Dependencias
### Internas
| Modulo | Uso |
|--------|-----|
| `@core/modules/utils` | Validaciones |
### Externas (npm)
| Paquete | Version | Uso |
|---------|---------|-----|
| `@nestjs/jwt` | `^10.0` | Tokens JWT |
| `@nestjs/passport` | `^10.0` | Estrategias auth |
| `passport-jwt` | `^4.0` | Estrategia JWT |
| `bcrypt` | `^5.0` | Hashing passwords |
---
## Relacion con Catalogo
Este modulo (`core/modules/auth/`) provee **codigo importable**.
El catalogo (`core/catalog/auth/`) provee **documentacion y referencia** para implementaciones completas.
```yaml
Usar modules/auth cuando:
- Necesitas guards/decorators listos
- Proyecto ya tiene auth y solo extiende
Usar catalog/auth cuando:
- Implementas auth desde cero
- Necesitas documentacion completa
- Requieres DDL y estructura de tablas
```
---
## Estado Actual
```markdown
- [ ] JwtAuthGuard implementado
- [ ] RolesGuard implementado
- [ ] CurrentUser decorator
- [ ] Roles decorator
- [ ] Public decorator
- [ ] TokenService
- [ ] PasswordService
- [ ] SessionService
- [ ] Tests unitarios
- [ ] Documentacion completa
```
---
## Changelog
### v0.1.0 (2026-01-03)
- Estructura inicial
- README con planificacion
---
**Modulo:** core/modules/auth/ | **Owner:** Backend-Agent | **Estado:** desarrollo

View File

@ -0,0 +1,194 @@
# Billing - Core Module
**Modulo:** core/modules/billing/
**Version:** 0.1.0
**Fecha:** 2026-01-03
**Owner:** Backend-Agent
**Estado:** desarrollo
---
## Descripcion
Modulo de facturacion compartido que provee logica de negocio para planes, pricing, invoices y metricas de uso. Trabaja en conjunto con el modulo de payments para la parte transaccional.
---
## Instalacion
### Prerequisitos
```bash
# El modulo de billing depende de payments
npm install stripe
```
### Configuracion de Paths
```json
{
"compilerOptions": {
"paths": {
"@core/modules/*": ["../../core/modules/*"]
}
}
}
```
---
## API Publica (Planificada)
### Servicios
| Servicio | Descripcion |
|----------|-------------|
| `PlanService` | Gestion de planes y pricing |
| `InvoiceService` | Generacion y gestion de facturas |
| `UsageService` | Tracking de metricas de uso |
| `QuotaService` | Verificacion de limites y cuotas |
### Tipos
```typescript
interface Plan {
id: string;
name: string;
description: string;
price: number;
currency: string;
interval: 'monthly' | 'yearly';
features: PlanFeature[];
limits: PlanLimits;
isActive: boolean;
}
interface PlanLimits {
users: number;
storage: number; // GB
apiCalls: number; // per month
projects: number;
}
interface Invoice {
id: string;
customerId: string;
subscriptionId: string;
amount: number;
currency: string;
status: 'draft' | 'open' | 'paid' | 'void';
dueDate: Date;
paidAt?: Date;
lineItems: InvoiceLineItem[];
}
interface UsageRecord {
subscriptionId: string;
metric: string;
quantity: number;
timestamp: Date;
}
```
---
## Ejemplos de Uso
### Ejemplo 1: Verificar Cuota
```typescript
import { QuotaService } from '@core/modules/billing';
@Injectable()
export class ProjectService {
constructor(private quota: QuotaService) {}
async createProject(orgId: string, data: CreateProjectDto) {
// Verificar si la organizacion puede crear mas proyectos
const canCreate = await this.quota.check(orgId, 'projects', 1);
if (!canCreate) {
throw new QuotaExceededException('Project limit reached');
}
// Crear proyecto...
const project = await this.projectRepo.save(data);
// Incrementar uso
await this.quota.increment(orgId, 'projects', 1);
return project;
}
}
```
### Ejemplo 2: Obtener Plan Actual
```typescript
import { PlanService, UsageService } from '@core/modules/billing';
@Controller('billing')
export class BillingController {
constructor(
private plans: PlanService,
private usage: UsageService,
) {}
@Get('current-plan')
async getCurrentPlan(@CurrentOrg() orgId: string) {
const subscription = await this.plans.getActiveSubscription(orgId);
const plan = await this.plans.getPlan(subscription.planId);
const usage = await this.usage.getCurrentPeriodUsage(subscription.id);
return {
plan,
subscription,
usage,
limits: plan.limits,
};
}
}
```
---
## Dependencias
### Internas
| Modulo | Uso |
|--------|-----|
| `@core/modules/payments` | Transacciones |
| `@core/modules/utils` | Formateo |
### Externas (npm)
| Paquete | Version | Uso |
|---------|---------|-----|
| `stripe` | `^14.0` | Billing API |
---
## Estado Actual
```markdown
- [ ] PlanService
- [ ] InvoiceService
- [ ] UsageService
- [ ] QuotaService
- [ ] Integracion con payments
- [ ] Metricas de uso
- [ ] Tests unitarios
```
---
## Changelog
### v0.1.0 (2026-01-03)
- Estructura inicial
- README con planificacion
---
**Modulo:** core/modules/billing/ | **Owner:** Backend-Agent

View File

@ -0,0 +1,216 @@
# Multitenant - Core Module
**Modulo:** core/modules/multitenant/
**Version:** 0.1.0
**Fecha:** 2026-01-03
**Owner:** Backend-Agent
**Estado:** desarrollo
---
## Descripcion
Modulo de multi-tenancy compartido que provee aislamiento de datos por organizacion usando Row Level Security (RLS) de PostgreSQL. Incluye middleware, decorators y utilidades para gestion de tenant context.
---
## Instalacion
### Prerequisitos
```bash
# Requiere TypeORM y PostgreSQL con RLS habilitado
npm install typeorm pg
```
### Configuracion de Paths
```json
{
"compilerOptions": {
"paths": {
"@core/modules/*": ["../../core/modules/*"]
}
}
}
```
---
## API Publica (Planificada)
### Middleware
| Middleware | Descripcion |
|------------|-------------|
| `TenantMiddleware` | Extrae tenant_id de JWT/header y lo setea en contexto |
### Guards
| Guard | Descripcion |
|-------|-------------|
| `TenantGuard` | Verifica que usuario pertenece al tenant |
### Decorators
| Decorator | Descripcion | Ejemplo |
|-----------|-------------|---------|
| `@CurrentTenant()` | Extrae tenant actual | `@CurrentTenant() tenantId: string` |
| `@TenantAware()` | Marca entity como tenant-aware | En entity class |
### Servicios
| Servicio | Descripcion |
|----------|-------------|
| `TenantService` | Gestion de tenants |
| `TenantContextService` | Almacena contexto del request |
### Tipos
```typescript
interface Tenant {
id: string;
name: string;
slug: string;
settings: TenantSettings;
plan: string;
status: 'active' | 'suspended' | 'trial';
createdAt: Date;
}
interface TenantSettings {
timezone: string;
locale: string;
currency: string;
features: Record<string, boolean>;
}
interface TenantContext {
tenantId: string;
userId: string;
roles: string[];
}
```
---
## Ejemplos de Uso
### Ejemplo 1: Entity con RLS
```typescript
import { TenantAware } from '@core/modules/multitenant';
@Entity('projects')
@TenantAware()
export class Project {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
name: string;
@Column({ name: 'tenant_id' })
tenantId: string; // RLS filtra automaticamente por este campo
}
```
### Ejemplo 2: Acceder al Tenant Actual
```typescript
import { CurrentTenant, TenantGuard } from '@core/modules/multitenant';
@Controller('projects')
@UseGuards(TenantGuard)
export class ProjectsController {
@Get()
findAll(@CurrentTenant() tenantId: string) {
// Solo retorna proyectos del tenant actual
// RLS en PostgreSQL filtra automaticamente
return this.projectService.findAll();
}
}
```
### Ejemplo 3: Configurar RLS en PostgreSQL
```sql
-- Habilitar RLS en tabla
ALTER TABLE projects ENABLE ROW LEVEL SECURITY;
-- Politica de lectura
CREATE POLICY tenant_isolation ON projects
FOR ALL
USING (tenant_id = current_setting('app.current_tenant_id')::uuid);
-- Setear tenant en sesion (lo hace el middleware)
SET app.current_tenant_id = 'uuid-del-tenant';
```
---
## Dependencias
### Internas
| Modulo | Uso |
|--------|-----|
| `@core/modules/auth` | JWT, user context |
### Externas (npm)
| Paquete | Version | Uso |
|---------|---------|-----|
| `typeorm` | `^0.3` | ORM |
| `pg` | `^8.0` | PostgreSQL driver |
| `nestjs-cls` | `^4.0` | Context storage |
---
## Configuracion RLS
### Tablas Requeridas
```sql
-- Tabla de tenants
CREATE TABLE core.tenants (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(255) NOT NULL,
slug VARCHAR(100) UNIQUE NOT NULL,
settings JSONB DEFAULT '{}',
status VARCHAR(20) DEFAULT 'active',
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- Para cada tabla tenant-aware:
ALTER TABLE {schema}.{table} ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON {schema}.{table}
FOR ALL USING (tenant_id = current_setting('app.current_tenant_id')::uuid);
```
---
## Estado Actual
```markdown
- [ ] TenantMiddleware
- [ ] TenantGuard
- [ ] @CurrentTenant decorator
- [ ] @TenantAware decorator
- [ ] TenantService
- [ ] TenantContextService con CLS
- [ ] Integracion TypeORM
- [ ] Tests con RLS
```
---
## Changelog
### v0.1.0 (2026-01-03)
- Estructura inicial
- README con planificacion
---
**Modulo:** core/modules/multitenant/ | **Owner:** Backend-Agent

View File

@ -0,0 +1,171 @@
# Notifications - Core Module
**Modulo:** core/modules/notifications/
**Version:** 0.1.0
**Fecha:** 2026-01-03
**Owner:** Backend-Agent
**Estado:** desarrollo
---
## Descripcion
Modulo de notificaciones compartido que provee servicios para envio de emails, push notifications e in-app notifications. Abstrae los proveedores de notificacion para uso unificado en todos los proyectos.
---
## Instalacion
### Prerequisitos
```bash
npm install nodemailer @nestjs/mailer
npm install -D @types/nodemailer
# Opcional para push:
npm install firebase-admin
```
### Configuracion de Paths
```json
{
"compilerOptions": {
"paths": {
"@core/modules/*": ["../../core/modules/*"]
}
}
}
```
---
## API Publica (Planificada)
### Servicios
| Servicio | Descripcion | Canales |
|----------|-------------|---------|
| `NotificationService` | Servicio principal unificado | email, push, in-app |
| `EmailService` | Envio de emails | SMTP, SES |
| `PushService` | Push notifications | FCM, APNs |
| `InAppService` | Notificaciones in-app | WebSocket, polling |
### Tipos
```typescript
interface Notification {
id: string;
userId: string;
type: 'email' | 'push' | 'in-app';
title: string;
body: string;
data?: Record<string, any>;
status: 'pending' | 'sent' | 'failed' | 'read';
createdAt: Date;
sentAt?: Date;
readAt?: Date;
}
interface NotificationPreferences {
userId: string;
email: boolean;
push: boolean;
inApp: boolean;
categories: Record<string, boolean>;
}
```
---
## Ejemplos de Uso
### Ejemplo 1: Enviar Notificacion
```typescript
import { NotificationService } from '@core/modules/notifications';
@Injectable()
export class OrderService {
constructor(private notifications: NotificationService) {}
async createOrder(order: Order) {
// ... crear orden
await this.notifications.send({
userId: order.userId,
type: 'email',
title: 'Orden Confirmada',
body: `Tu orden #${order.id} ha sido confirmada`,
template: 'order-confirmation',
data: { order },
});
}
}
```
### Ejemplo 2: Notificacion Multi-canal
```typescript
await this.notifications.sendMulti({
userId: user.id,
channels: ['email', 'push', 'in-app'],
title: 'Nuevo Mensaje',
body: 'Tienes un nuevo mensaje',
respectPreferences: true, // Respetar preferencias del usuario
});
```
---
## Dependencias
### Internas
| Modulo | Uso |
|--------|-----|
| `@core/modules/utils` | Formateo, validaciones |
### Externas (npm)
| Paquete | Version | Uso |
|---------|---------|-----|
| `nodemailer` | `^6.9` | Envio SMTP |
| `@nestjs/mailer` | `^1.9` | Integracion NestJS |
| `firebase-admin` | `^11.0` | Push FCM (opcional) |
---
## Relacion con Catalogo
| Aspecto | modules/notifications | catalog/notifications |
|---------|----------------------|----------------------|
| Contenido | Servicios listos | Documentacion + DDL |
| Uso | Importar directamente | Copiar y adaptar |
| DDL | No incluye | Incluye tablas |
---
## Estado Actual
```markdown
- [ ] NotificationService base
- [ ] EmailService con nodemailer
- [ ] PushService con FCM
- [ ] InAppService con eventos
- [ ] Template engine
- [ ] Preferencias de usuario
- [ ] Tests unitarios
- [ ] Documentacion completa
```
---
## Changelog
### v0.1.0 (2026-01-03)
- Estructura inicial
- README con planificacion
---
**Modulo:** core/modules/notifications/ | **Owner:** Backend-Agent

29
core/modules/package.json Normal file
View File

@ -0,0 +1,29 @@
{
"name": "@core/modules",
"version": "1.0.0",
"description": "Core modules compartidos para todos los proyectos del workspace",
"main": "index.ts",
"types": "index.ts",
"scripts": {
"build": "tsc",
"lint": "eslint . --ext .ts",
"test": "jest"
},
"dependencies": {},
"devDependencies": {
"@types/node": "^20.10.0",
"typescript": "^5.3.0"
},
"exports": {
"./utils": "./utils/index.ts",
"./utils/*": "./utils/*.ts"
},
"keywords": [
"core",
"utils",
"shared",
"workspace"
],
"author": "ISEM Team",
"license": "PROPRIETARY"
}

View File

@ -0,0 +1,198 @@
# Payments - Core Module
**Modulo:** core/modules/payments/
**Version:** 0.1.0
**Fecha:** 2026-01-03
**Owner:** Backend-Agent
**Estado:** desarrollo
---
## Descripcion
Modulo de pagos compartido que abstrae integraciones con proveedores de pago (Stripe, PayPal, MercadoPago). Provee interfaces unificadas para procesamiento de pagos, suscripciones y webhooks.
---
## Instalacion
### Prerequisitos
```bash
npm install stripe
# Opcional:
npm install @paypal/checkout-server-sdk
npm install mercadopago
```
### Configuracion de Paths
```json
{
"compilerOptions": {
"paths": {
"@core/modules/*": ["../../core/modules/*"]
}
}
}
```
---
## API Publica (Planificada)
### Servicios
| Servicio | Descripcion | Proveedor |
|----------|-------------|-----------|
| `PaymentService` | Servicio unificado | Multi-provider |
| `StripeService` | Integracion Stripe | Stripe |
| `SubscriptionService` | Gestion suscripciones | Stripe |
| `WebhookService` | Procesamiento webhooks | Multi-provider |
### Tipos
```typescript
interface PaymentIntent {
id: string;
amount: number;
currency: string;
status: 'pending' | 'processing' | 'succeeded' | 'failed';
provider: 'stripe' | 'paypal' | 'mercadopago';
customerId?: string;
metadata?: Record<string, any>;
}
interface Subscription {
id: string;
customerId: string;
planId: string;
status: 'active' | 'canceled' | 'past_due' | 'trialing';
currentPeriodStart: Date;
currentPeriodEnd: Date;
cancelAtPeriodEnd: boolean;
}
interface CheckoutSession {
id: string;
url: string;
expiresAt: Date;
lineItems: LineItem[];
successUrl: string;
cancelUrl: string;
}
```
---
## Ejemplos de Uso
### Ejemplo 1: Crear Checkout Session
```typescript
import { PaymentService } from '@core/modules/payments';
@Injectable()
export class CheckoutService {
constructor(private payments: PaymentService) {}
async createCheckout(items: CartItem[], userId: string) {
const session = await this.payments.createCheckoutSession({
customerId: userId,
lineItems: items.map(item => ({
name: item.name,
amount: item.price,
quantity: item.quantity,
})),
successUrl: '/checkout/success',
cancelUrl: '/checkout/cancel',
});
return { checkoutUrl: session.url };
}
}
```
### Ejemplo 2: Procesar Webhook
```typescript
import { WebhookService } from '@core/modules/payments';
@Controller('webhooks')
export class WebhookController {
constructor(private webhooks: WebhookService) {}
@Post('stripe')
async handleStripeWebhook(
@Headers('stripe-signature') signature: string,
@Body() rawBody: Buffer,
) {
const event = await this.webhooks.verifyStripeEvent(rawBody, signature);
switch (event.type) {
case 'payment_intent.succeeded':
await this.handlePaymentSuccess(event.data);
break;
case 'customer.subscription.updated':
await this.handleSubscriptionUpdate(event.data);
break;
}
return { received: true };
}
}
```
---
## Dependencias
### Internas
| Modulo | Uso |
|--------|-----|
| `@core/modules/utils` | Formateo moneda |
### Externas (npm)
| Paquete | Version | Uso |
|---------|---------|-----|
| `stripe` | `^14.0` | API Stripe |
---
## Relacion con Catalogo
| Aspecto | modules/payments | catalog/payments |
|---------|-----------------|------------------|
| Contenido | Servicios listos | Documentacion + DDL |
| Uso | Importar | Copiar y adaptar |
| DDL tablas | No | Si |
| Webhooks docs | Basico | Completo |
---
## Estado Actual
```markdown
- [ ] PaymentService base
- [ ] StripeService integracion
- [ ] SubscriptionService
- [ ] WebhookService
- [ ] Checkout sessions
- [ ] Customer management
- [ ] Refunds
- [ ] Tests unitarios
```
---
## Changelog
### v0.1.0 (2026-01-03)
- Estructura inicial
- README con planificacion
---
**Modulo:** core/modules/payments/ | **Owner:** Backend-Agent

View File

@ -0,0 +1,285 @@
# Utils - Core Module
**Modulo:** core/modules/utils/
**Version:** 1.0.0
**Fecha:** 2026-01-03
**Owner:** Tech-Leader
**Estado:** production-ready
---
## Descripcion
Modulo de utilidades genericas framework-agnostic que provee funciones para manipulacion de fechas, strings y validaciones. Puede ser usado en cualquier proyecto del workspace (NestJS, Express, React, etc.) sin dependencias externas.
---
## Instalacion
### Prerequisitos
No requiere dependencias npm adicionales. Usa solo APIs nativas de JavaScript/TypeScript.
### Configuracion de Paths
Agregar en `tsconfig.json` del proyecto consumidor:
```json
{
"compilerOptions": {
"paths": {
"@core/modules/*": ["../../core/modules/*"]
}
}
}
```
---
## API Publica
### Funciones de Fecha (date.util.ts)
| Funcion | Descripcion | Parametros | Retorno |
|---------|-------------|------------|---------|
| `formatToISO` | Formatea a ISO string | `(date: Date)` | `string` |
| `formatToDate` | Formatea a YYYY-MM-DD | `(date: Date)` | `string` |
| `formatToDateTime` | Formatea a YYYY-MM-DD HH:mm:ss | `(date: Date)` | `string` |
| `formatDate` | Formatea con patron custom | `(date: Date, pattern: string)` | `string` |
| `addDays` | Agrega dias a fecha | `(date: Date, days: number)` | `Date` |
| `addHours` | Agrega horas a fecha | `(date: Date, hours: number)` | `Date` |
| `addMinutes` | Agrega minutos a fecha | `(date: Date, minutes: number)` | `Date` |
| `addMonths` | Agrega meses a fecha | `(date: Date, months: number)` | `Date` |
| `isPast` | Verifica si fecha ya paso | `(date: Date)` | `boolean` |
| `isFuture` | Verifica si fecha es futura | `(date: Date)` | `boolean` |
| `startOfDay` | Obtiene inicio del dia | `(date: Date)` | `Date` |
| `endOfDay` | Obtiene fin del dia | `(date: Date)` | `Date` |
| `startOfMonth` | Obtiene inicio del mes | `(date: Date)` | `Date` |
| `endOfMonth` | Obtiene fin del mes | `(date: Date)` | `Date` |
| `diffInDays` | Diferencia en dias | `(date1: Date, date2: Date)` | `number` |
| `diffInHours` | Diferencia en horas | `(date1: Date, date2: Date)` | `number` |
| `diffInMinutes` | Diferencia en minutos | `(date1: Date, date2: Date)` | `number` |
| `isSameDay` | Verifica si es mismo dia | `(date1: Date, date2: Date)` | `boolean` |
| `parseISO` | Parsea ISO string a Date | `(isoString: string)` | `Date` |
| `isValidDate` | Verifica si string es fecha valida | `(dateString: string)` | `boolean` |
| `getRelativeTime` | Obtiene tiempo relativo | `(date: Date)` | `string` |
| `toUnixTimestamp` | Convierte a Unix timestamp | `(date: Date)` | `number` |
| `fromUnixTimestamp` | Crea Date desde Unix | `(timestamp: number)` | `Date` |
| `isToday` | Verifica si es hoy | `(date: Date)` | `boolean` |
| `isYesterday` | Verifica si es ayer | `(date: Date)` | `boolean` |
| `getAge` | Calcula edad desde fecha nacimiento | `(birthDate: Date)` | `number` |
### Funciones de String (string.util.ts)
| Funcion | Descripcion | Parametros | Retorno |
|---------|-------------|------------|---------|
| `slugify` | Genera slug URL-friendly | `(text: string)` | `string` |
| `capitalize` | Capitaliza primera letra | `(text: string)` | `string` |
| `capitalizeWords` | Capitaliza cada palabra | `(text: string)` | `string` |
| `truncate` | Trunca con ellipsis | `(text: string, maxLength: number)` | `string` |
| `stripHtml` | Remueve tags HTML | `(html: string)` | `string` |
| `sanitize` | Sanitiza caracteres especiales | `(text: string)` | `string` |
| `isEmpty` | Verifica si string es vacio | `(text: string \| null \| undefined)` | `boolean` |
| `isNotEmpty` | Verifica si string NO es vacio | `(text: string \| null \| undefined)` | `boolean` |
| `randomString` | Genera string aleatorio | `(length?: number, charset?: string)` | `string` |
| `randomNumeric` | Genera string numerico aleatorio | `(length?: number)` | `string` |
| `maskString` | Enmascara string | `(text: string, visibleChars?: number)` | `string` |
| `maskEmail` | Enmascara email | `(email: string)` | `string` |
| `toCamelCase` | Convierte a camelCase | `(text: string)` | `string` |
| `toSnakeCase` | Convierte a snake_case | `(text: string)` | `string` |
| `toKebabCase` | Convierte a kebab-case | `(text: string)` | `string` |
| `toConstantCase` | Convierte a CONSTANT_CASE | `(text: string)` | `string` |
| `toPascalCase` | Convierte a PascalCase | `(text: string)` | `string` |
| `escapeRegex` | Escapa caracteres regex | `(text: string)` | `string` |
| `wordCount` | Cuenta palabras | `(text: string)` | `number` |
| `reverse` | Invierte string | `(text: string)` | `string` |
| `padLeft` | Padding izquierdo | `(text: string, length: number, char?: string)` | `string` |
| `padRight` | Padding derecho | `(text: string, length: number, char?: string)` | `string` |
| `removeAccents` | Remueve acentos | `(text: string)` | `string` |
| `getInitials` | Extrae iniciales | `(name: string, maxChars?: number)` | `string` |
| `formatCurrency` | Formatea como moneda | `(amount: number, currency?: string, locale?: string)` | `string` |
| `formatNumber` | Formatea con separadores | `(num: number, locale?: string)` | `string` |
| `parseQueryString` | Parsea query string a objeto | `(queryString: string)` | `Record<string, string>` |
| `buildQueryString` | Construye query string | `(params: Record<string, ...>)` | `string` |
### Funciones de Validacion (validation.util.ts)
| Funcion | Descripcion | Parametros | Retorno |
|---------|-------------|------------|---------|
| `isEmail` | Valida email | `(email: string)` | `boolean` |
| `isUUID` | Valida UUID v4 | `(uuid: string)` | `boolean` |
| `isURL` | Valida URL | `(url: string)` | `boolean` |
| `isStrongPassword` | Valida password fuerte | `(password: string)` | `boolean` |
| `getPasswordStrength` | Obtiene fuerza de password (0-4) | `(password: string)` | `number` |
| `isPhoneNumber` | Valida telefono internacional | `(phone: string)` | `boolean` |
| `isNumeric` | Valida si es numerico | `(value: string)` | `boolean` |
| `isInteger` | Valida si es entero | `(value: string \| number)` | `boolean` |
| `isAlphanumeric` | Valida alfanumerico | `(value: string)` | `boolean` |
| `isAlphabetic` | Valida solo letras | `(value: string)` | `boolean` |
| `isInRange` | Valida rango numerico | `(value: number, min: number, max: number)` | `boolean` |
| `hasRequiredFields` | Valida campos requeridos | `(obj: T, fields: (keyof T)[])` | `boolean` |
| `isValidJSON` | Valida JSON string | `(value: string)` | `boolean` |
| `isPositive` | Valida numero positivo | `(value: number)` | `boolean` |
| `isNonNegative` | Valida numero >= 0 | `(value: number)` | `boolean` |
| `isCreditCard` | Valida tarjeta (Luhn) | `(cardNumber: string)` | `boolean` |
| `isIPv4` | Valida IP v4 | `(ip: string)` | `boolean` |
| `isHexColor` | Valida color hex | `(color: string)` | `boolean` |
| `isSlug` | Valida slug | `(slug: string)` | `boolean` |
| `isValidUsername` | Valida username | `(username: string)` | `boolean` |
| `isEmptyObject` | Valida objeto vacio | `(obj: object)` | `boolean` |
| `isEmptyArray` | Valida array vacio | `(arr: T[])` | `boolean` |
| `isNullOrUndefined` | Valida null/undefined | `(value: unknown)` | `boolean` |
| `isDefined` | Valida definido | `(value: T \| null \| undefined)` | `boolean` |
| `isMexicanRFC` | Valida RFC mexicano | `(rfc: string)` | `boolean` |
| `isMexicanCURP` | Valida CURP mexicano | `(curp: string)` | `boolean` |
| `createValidator` | Crea cadena de validacion | `(value: T)` | `Validator<T>` |
---
## Ejemplos de Uso
### Ejemplo 1: Formateo de Fechas
```typescript
import { formatDate, addDays, isPast, getRelativeTime } from '@core/modules/utils';
// Formatear fecha
const fecha = new Date();
console.log(formatDate(fecha, 'YYYY-MM-DD')); // "2026-01-03"
console.log(formatDate(fecha, 'DD/MM/YYYY')); // "03/01/2026"
// Manipular fechas
const enUnaSemana = addDays(fecha, 7);
console.log(isPast(enUnaSemana)); // false
// Tiempo relativo
const ayer = addDays(new Date(), -1);
console.log(getRelativeTime(ayer)); // "1 day ago"
```
### Ejemplo 2: Manipulacion de Strings
```typescript
import { slugify, capitalize, maskEmail, formatCurrency } from '@core/modules/utils';
// Generar slug
const slug = slugify('Hello World 2026!'); // "hello-world-2026"
// Capitalizar
const nombre = capitalize('john'); // "John"
// Enmascarar email
const emailMasked = maskEmail('john.doe@example.com'); // "jo***@example.com"
// Formatear moneda
const precio = formatCurrency(1234.50, 'USD'); // "$1,234.50"
const precioMXN = formatCurrency(1234.50, 'MXN', 'es-MX'); // "$1,234.50"
```
### Ejemplo 3: Validaciones
```typescript
import { isEmail, isStrongPassword, hasRequiredFields, createValidator } from '@core/modules/utils';
// Validaciones simples
console.log(isEmail('test@example.com')); // true
console.log(isStrongPassword('Abc123!@')); // true
// Validar campos requeridos
const user = { name: 'John', email: 'john@example.com' };
console.log(hasRequiredFields(user, ['name', 'email'])); // true
// Cadena de validacion
const result = createValidator('john@example.com')
.validate(isEmail('john@example.com'), 'Email invalido')
.validate(true, 'Otro check')
.result();
console.log(result); // { isValid: true, errors: [] }
```
---
## Dependencias
### Internas (otros modulos de core/)
Ninguna. Este modulo es standalone.
### Externas (npm)
Ninguna. Solo usa APIs nativas de JavaScript.
---
## Proyectos Consumidores
| Proyecto | Desde Version | Funciones Usadas |
|----------|---------------|------------------|
| gamilit | 1.0.0 | `formatDate`, `slugify`, `isEmail` |
| trading-platform | 1.0.0 | `formatCurrency`, `toUnixTimestamp` |
| erp-suite | 1.0.0 | `isMexicanRFC`, `formatNumber`, validaciones |
---
## Estructura de Archivos
```
core/modules/utils/
+-- index.ts # Punto de entrada, re-exporta todo
+-- date.util.ts # 25 funciones de fecha
+-- string.util.ts # 30 funciones de string
+-- validation.util.ts # 35 funciones de validacion
+-- README.md # Esta documentacion
```
---
## Changelog
### v1.0.0 (2026-01-03)
- Release inicial
- 25 funciones de fecha
- 30 funciones de string
- 35 funciones de validacion
- Validaciones mexicanas (RFC, CURP)
- Cadena de validacion con createValidator
---
## Contribuir
### Proceso
1. Crear branch desde `main`
2. Implementar cambios con ejemplos en JSDoc
3. Verificar que no rompe consumidores existentes
4. Crear PR hacia `main`
5. Solicitar review del owner (Tech-Leader)
### Reglas
- Funciones deben ser puras (sin side effects)
- No agregar dependencias externas
- Mantener retrocompatibilidad
- Documentar con JSDoc
- Agregar ejemplos en comentarios
---
## Checklist de Completitud
```markdown
- [x] Descripcion clara del modulo
- [x] Instalacion documentada
- [x] API publica completa con tipos (90 funciones)
- [x] Ejemplos de uso funcionales
- [x] Dependencias listadas (ninguna)
- [x] Proyectos consumidores documentados
- [ ] Tests existentes y pasando
- [x] Changelog actualizado
```
---
**Modulo:** core/modules/utils/ | **Owner:** Tech-Leader | **90 funciones**

View File

@ -4,7 +4,7 @@
* Framework-agnostic date manipulation and formatting functions.
* Can be used in any project (NestJS, Express, Frontend, etc.)
*
* @module @shared/utils/date
* @module @core/utils/date
* @version 1.0.0
*/

View File

@ -0,0 +1,77 @@
/**
* Core Utilities Module
*
* Framework-agnostic utility functions that can be used across
* all projects in the workspace (Gamilit, Trading Platform, ERP Suite, etc.)
*
* @module @core/utils
* @version 1.0.0
*
* @example
* ```typescript
* import { formatDate, slugify, isEmail } from '@core/utils';
*
* const date = formatDate(new Date(), 'YYYY-MM-DD');
* const slug = slugify('Hello World');
* const valid = isEmail('test@example.com');
* ```
*/
// Date utilities
export * from './date.util';
// String utilities
export * from './string.util';
// Validation utilities
export * from './validation.util';
// Re-export commonly used functions for convenience
export {
// Date
formatToISO,
formatToDate,
formatToDateTime,
formatDate,
addDays,
addHours,
isPast,
isFuture,
diffInDays,
parseISO,
isValidDate,
toUnixTimestamp,
fromUnixTimestamp,
} from './date.util';
export {
// String
slugify,
capitalize,
capitalizeWords,
truncate,
isEmpty,
isNotEmpty,
randomString,
maskString,
maskEmail,
toCamelCase,
toSnakeCase,
toKebabCase,
formatCurrency,
formatNumber,
} from './string.util';
export {
// Validation
isEmail,
isUUID,
isURL,
isStrongPassword,
isPhoneNumber,
isNumeric,
isInRange,
hasRequiredFields,
isDefined,
isNullOrUndefined,
} from './validation.util';

View File

@ -4,7 +4,7 @@
* Framework-agnostic string manipulation and formatting functions.
* Can be used in any project (NestJS, Express, Frontend, etc.)
*
* @module @shared/utils/string
* @module @core/utils/string
* @version 1.0.0
*/

View File

@ -4,7 +4,7 @@
* Framework-agnostic validation helper functions.
* Can be used in any project (NestJS, Express, Frontend, etc.)
*
* @module @shared/utils/validation
* @module @core/utils/validation
* @version 1.0.0
*/

View File

@ -27,7 +27,7 @@ Este directorio contiene el **Sistema NEXUS** de orquestación de agentes IA par
### Acceso Rápido
```
shared/catalog/ # 🆕 CATÁLOGO DE FUNCIONALIDADES (CONSULTAR PRIMERO)
core/catalog/ # 🆕 CATÁLOGO DE FUNCIONALIDADES (CONSULTAR PRIMERO)
├── CATALOG-INDEX.yml # Índice máquina-readable
├── auth/ # Autenticación y autorización
├── session-management/ # Gestión de sesiones
@ -102,8 +102,8 @@ referencias/
@TPL_CAPVED: templates/TEMPLATE-TAREA-CAPVED.md
# CATÁLOGO DE FUNCIONALIDADES (CONSULTAR PRIMERO)
@CATALOG: shared/catalog/
@CATALOG_INDEX: shared/catalog/CATALOG-INDEX.yml
@CATALOG: core/catalog/
@CATALOG_INDEX: core/catalog/CATALOG-INDEX.yml
# Operaciones
@REUTILIZAR: directivas/simco/SIMCO-REUTILIZAR.md

View File

@ -46,7 +46,7 @@ core/orchestration/
│ ├── SIMCO-BACKEND.md
│ └── ...
└── shared/catalog/ # 🆕 CATÁLOGO DE FUNCIONALIDADES
└── core/catalog/ # 🆕 CATÁLOGO DE FUNCIONALIDADES
├── CATALOG-INDEX.yml # Índice para búsqueda
├── auth/
├── session-management/
@ -138,7 +138,7 @@ Los archivos `INIT-NEXUS-*.md` siguen siendo útiles como:
- **Índice SIMCO:** core/orchestration/directivas/simco/_INDEX.md
- **Perfiles de Agentes:** core/orchestration/agents/perfiles/
- **Catálogo:** shared/catalog/
- **Catálogo:** core/catalog/
- **Aliases:** core/orchestration/referencias/ALIASES.yml
---

View File

@ -33,7 +33,7 @@ core/orchestration/
│ ├── SIMCO-MODIFICAR.md
│ └── SIMCO-{DOMINIO}.md
└── shared/catalog/ # Funcionalidades reutilizables
└── core/catalog/ # Funcionalidades reutilizables
├── auth/
├── notifications/
└── ...

View File

@ -2,10 +2,9 @@
**ID:** @PERFIL_KB_MANAGER
**Nombre:** Knowledge-Base Manager
**Version:** 1.1.0
**Version:** 1.0.0
**Sistema:** NEXUS v3.4 + SIMCO + CAPVED
**Creado:** 2026-01-04
**Actualizado:** 2026-01-04
**EPIC:** EPIC-012
---
@ -13,7 +12,7 @@
## ROL
Gestor de la base de conocimiento compartida del workspace, responsable de:
- Coordinar mejoras en `shared/catalog/` y `shared/knowledge-base/`
- Coordinar mejoras en `core/catalog/` y `shared/knowledge-base/`
- Analizar mejoras propagables siguiendo proceso CAPVED
- Detectar dependencias internas entre modulos
- Generar tareas SCRUM formales para propagacion
@ -31,7 +30,7 @@ Gestor de la base de conocimiento compartida del workspace, responsable de:
- C: Contexto del modulo afectado
- A: Analisis de impacto en KB y proyectos consumidores
- P: Plan de propagacion por niveles
3. **Actualizar shared/catalog** si la mejora aplica a modulos base
3. **Actualizar core/catalog** si la mejora aplica a modulos base
4. **Actualizar shared/knowledge-base** con cambios sincronizados
5. **Generar tareas SCRUM** para proyectos afectados usando `generate-scrum-tasks.sh`
6. **Coordinar con @PERFIL_PROJECT_AGENT** para ejecucion en proyectos
@ -102,7 +101,7 @@ Scripts disponibles en `devtools/scripts/propagation/`:
|
v
4. ACTUALIZAR NIVEL 0 (si aplica)
Actualizar modulo en shared/catalog/
Actualizar modulo en core/catalog/
Validar: Documentacion actualizada
|
v
@ -170,9 +169,6 @@ Scripts disponibles en `devtools/scripts/propagation/`:
| @PERFIL_DOCUMENTATION | Colabora en documentacion de cambios | Seccion en TASK |
| @PERFIL_INTEGRATION_VALIDATOR | Valida integracion final | Checklist de validacion |
| @PERFIL_TECH_LEADER | Escala decisiones arquitecturales | Issue/Reunion |
| @PERFIL_PROPAGATION_TRACKER | Tracking de estado de propagaciones | TRAZABILIDAD-PROPAGACION.yml |
| @PERFIL_PRODUCTION_MANAGER | Sincroniza cambios con produccion | Registro/Alerta |
| @PERFIL_SECRETS_MANAGER | Coordina cambios de secretos | Protocolo seguro |
---
@ -237,13 +233,6 @@ formato: "Comentario en tarea o seccion EJECUCION"
- USAGE.md: `shared/knowledge-base/propagacion/USAGE.md`
- USAGE-ORQUESTACION.md: `shared/knowledge-base/propagacion/USAGE-ORQUESTACION.md`
### Perfiles Relacionados
- @PERFIL_PROPAGATION_TRACKER: `orchestration/agents/perfiles/PERFIL-PROPAGATION-TRACKER.md`
- @PERFIL_PRODUCTION_MANAGER: `orchestration/agents/perfiles/PERFIL-PRODUCTION-MANAGER.md`
- @PERFIL_SECRETS_MANAGER: `orchestration/agents/perfiles/PERFIL-SECRETS-MANAGER.md`
- @PERFIL_MONITORING_AGENT: `orchestration/agents/perfiles/PERFIL-MONITORING-AGENT.md`
---
**Perfil creado por:** EPIC-012

View File

@ -45,7 +45,7 @@ grep "Versión:" /home/isem/workspace/core/orchestration/README.md | head -1
**Cambios realizados:**
- 131 archivos en `core/orchestration/` corregidos
- 11 archivos en `shared/catalog/_reference/` corregidos
- 11 archivos en `core/catalog/_reference/` corregidos
- Archivos de catalog raíz (*.yml, *.md) corregidos
**Verificación:**
@ -162,7 +162,7 @@ grep -n "Versión:" ~/workspace/core/orchestration/README.md | head -1
find ~/workspace/core/orchestration -perm 600 -type f | wc -l # Debe ser 0
# Verificar _reference/ poblados
find ~/workspace/shared/catalog -name "*.reference.ts" | wc -l # Debe ser 11
find ~/workspace/core/catalog -name "*.reference.ts" | wc -l # Debe ser 11
# Verificar UserIdConversionService exportado
grep "UserIdConversionService" ~/workspace/projects/gamilit/apps/backend/src/shared/services/index.ts

View File

@ -236,7 +236,7 @@ Sprint 0 P0 - Completado
# ERP-Suite shared-libs
ls -la ~/workspace/projects/erp-suite/apps/shared-libs/core/entities/
ls -la ~/workspace/projects/erp-suite/apps/shared-libs/core/middleware/
ls -la ~/workspace/projects/erp-suite/apps/shared-libs/shared/constants/
ls -la ~/workspace/projects/erp-suite/apps/shared-libs/core/constants/
# Betting Analytics
ls -la ~/workspace/projects/betting-analytics/apps/backend/src/

View File

@ -78,7 +78,7 @@ core:
contenido: Directivas, principios, agentes, templates
prioridad: P0
- nombre: shared/catalog
- nombre: core/catalog
nivel: 0 (Global)
contenido: Funcionalidades reutilizables
prioridad: P0
@ -334,7 +334,7 @@ herramientas:
secuencia:
1_core:
- core/orchestration/directivas/ (principios base)
- shared/catalog/ (funcionalidades compartidas)
- core/catalog/ (funcionalidades compartidas)
prioridad: PRIMERO (establecer baseline)
2_proyectos_maduros:
@ -698,7 +698,7 @@ protocolo:
orden_ejecucion:
fase_6a_core:
- Correcciones en core/orchestration
- Correcciones en shared/catalog
- Correcciones en core/catalog
razon: Base para proyectos
fase_6b_proyectos_referencia:

View File

@ -849,7 +849,7 @@ P0 Completado
[ ] core/orchestration versión unificada 3.3
[ ] core/orchestration permisos 644
[ ] core/orchestration 6 principios documentados
[ ] shared/catalog _reference/ poblados (8 funcionalidades)
[ ] core/catalog _reference/ poblados (8 funcionalidades)
[ ] gamilit UserIdConversionService creado
[ ] gamilit Repository Factory implementado
[ ] gamilit God classes divididas (al menos 2)

View File

@ -13,7 +13,7 @@ Se completó el análisis exhaustivo de **6 áreas** del workspace:
| Área | Estado | Score | Hallazgos P0 | P1 | P2 |
|------|--------|-------|--------------|----|----|
| **core/orchestration** | 🟡 Necesita mejoras | 7/10 | 3 | 5 | 3 |
| **shared/catalog** | 🟡 Necesita mejoras | 8/10 | 1 | 4 | 6 |
| **core/catalog** | 🟡 Necesita mejoras | 8/10 | 1 | 4 | 6 |
| **gamilit** | 🟡 Deuda técnica | 6.5/10 | 4 | 6 | 10 |
| **trading-platform** | 🟡 MVP en progreso | 6/10 | 5 | 5 | 4 |
| **erp-suite** | 🟡 Duplicación crítica | 5/10 | 3 | 4 | 3 |
@ -123,7 +123,7 @@ Se completó el análisis exhaustivo de **6 áreas** del workspace:
| Proyecto | Docs | ADRs | Inventarios | Propagación |
|----------|------|------|-------------|-------------|
| core/orchestration | ✅ 177 MD | ✅ Sistema | ✅ YAML | 🟡 Parcial |
| shared/catalog | ✅ 8 funciones | N/A | ✅ Tracking | ✅ OK |
| core/catalog | ✅ 8 funciones | N/A | ✅ Tracking | ✅ OK |
| gamilit | ✅ 17 carpetas | ✅ 20 ADRs | ✅ Completos | ✅ OK |
| trading-platform | ✅ 264 docs | ✅ 14 ADRs | ✅ Completos | ✅ OK |
| erp-suite | ✅ 449+ docs | ⚠️ Parcial | 🟡 Parcial | 🟡 Parcial |
@ -134,7 +134,7 @@ Se completó el análisis exhaustivo de **6 áreas** del workspace:
## CÓDIGO DUPLICADO ENTRE PROYECTOS
### Candidatos para shared/catalog
### Candidatos para core/catalog
| Funcionalidad | Proyectos | Estado | Acción |
|---------------|-----------|--------|--------|
@ -183,7 +183,7 @@ Se completó el análisis exhaustivo de **6 áreas** del workspace:
| # | Acción | Proyectos | Esfuerzo |
|---|--------|-----------|----------|
| 1 | Poblar `_reference/` en shared/catalog | catalog | 8h |
| 1 | Poblar `_reference/` en core/catalog | catalog | 8h |
| 2 | Sincronizar versionado orchestration a 3.3 | core | 2h |
| 3 | Cambiar permisos 600→644 en orchestration | core | 1h |
| 4 | Crear UserIdConversionService en gamilit | gamilit | 4h |

View File

@ -34,7 +34,7 @@
┌─────────────────────────────────────────────────────────────────────┐
│ │
│ NUNCA referenciar un proyecto desde otro proyecto. │
│ SIEMPRE usar shared/catalog/ o core/orchestration/ como fuente. │
│ SIEMPRE usar core/catalog/ o core/orchestration/ como fuente. │
│ │
└─────────────────────────────────────────────────────────────────────┘
```
@ -47,7 +47,7 @@
| Tipo | Ejemplo | Uso Correcto |
|------|---------|--------------|
| **Core Catalog** | `shared/catalog/auth/` | Componentes reutilizables |
| **Core Catalog** | `core/catalog/auth/` | Componentes reutilizables |
| **Core Orchestration** | `core/orchestration/directivas/` | Directivas y templates |
| **Subproyecto Interno** | `erp-suite/apps/erp-core/` | Solo desde la misma suite |
| **Ejemplos Ilustrativos** | `ejemplos: "gamilit, trading"` | Solo como ilustración marcada |
@ -70,7 +70,7 @@
JERARQUÍA_VÁLIDA:
Nivel_0_Core:
- shared/catalog/ # Funcionalidades reutilizables
- core/catalog/ # Funcionalidades reutilizables
- core/orchestration/ # Directivas y templates
- core/devtools/ # Herramientas de desarrollo
@ -130,7 +130,7 @@ ANTES:
DESPUÉS:
# ELIMINAR la línea completamente
# O cambiar a:
| Catálogo global | `/home/isem/workspace/shared/catalog/` |
| Catálogo global | `/home/isem/workspace/core/catalog/` |
```
### Caso 2: Ruta a Otro Proyecto
@ -140,7 +140,7 @@ ANTES:
- Patrones auth: `projects/gamilit/apps/backend/src/auth/`
DESPUÉS:
- Patrones auth: `shared/catalog/auth/`
- Patrones auth: `core/catalog/auth/`
```
### Caso 3: Lista de Proyectos de Referencia
@ -153,11 +153,11 @@ ANTES:
DESPUÉS:
## Patrones de Referencia (desde Catálogo)
> **Nota:** Usar siempre shared/catalog/ para componentes reutilizables.
> **Nota:** Usar siempre core/catalog/ para componentes reutilizables.
| Patrón | Catálogo |
| Auth | shared/catalog/auth/ |
| RLS | shared/catalog/multi-tenancy/ |
| Auth | core/catalog/auth/ |
| RLS | core/catalog/multi-tenancy/ |
```
### Caso 4: Directiva con Header de Proyecto
@ -247,7 +247,7 @@ VALIDACIÓN_ADICIONAL:
```yaml
CONTEXTO_A_PASAR:
referencias_permitidas:
- shared/catalog/
- core/catalog/
- core/orchestration/
- {proyecto_actual}/ # Solo interno
referencias_prohibidas:
@ -295,7 +295,7 @@ echo "=== Fin de Auditoría ==="
## REFERENCIAS
- **Principio relacionado:** `PRINCIPIO-ANTI-DUPLICACION.md`
- **Catálogo global:** `shared/catalog/`
- **Catálogo global:** `core/catalog/`
- **Templates:** `core/orchestration/templates/`
- **Índice SIMCO:** `core/orchestration/directivas/simco/_INDEX.md`

View File

@ -12,7 +12,7 @@
**ANTES de implementar funcionalidades comunes**, verificar si existe código probado:
```
shared/catalog/ # FUNCIONALIDADES REUTILIZABLES
core/catalog/ # FUNCIONALIDADES REUTILIZABLES
├── CATALOG-INDEX.yml # Índice para búsqueda rápida
├── auth/ # Autenticación y autorización
├── session-management/ # Gestión de sesiones

View File

@ -1,11 +1,10 @@
# SIMCO: PROPAGACION DE MEJORAS
**Version:** 2.0.0
**Version:** 1.0.0
**Prioridad:** OBLIGATORIA para mejoras en modulos compartidos
**Sistema:** NEXUS v3.4
**Alias:** @PROPAGACION
**Fecha:** 2026-01-04
**Actualizado:** 2026-01-04 (EPIC-012)
---
@ -353,164 +352,15 @@ Este proyecto participa en el sistema de propagacion de NEXUS.
---
## 9. PROPAGACION POR NIVELES (EPIC-012)
## 9. REFERENCIAS
Ver: @NIVELES_PROP (`shared/knowledge-base/propagacion/NIVELES-PROPAGACION.yml`)
### Jerarquia
| Nivel | Nombre | Contenido |
|-------|--------|-----------|
| 0 | Core Catalog | shared/catalog/ |
| 1 | Knowledge-Base | shared/knowledge-base/ |
| 2 | Proyectos Base | erp-core, gamilit, trading-platform |
| 3 | Proyectos Hoja | Verticales ERP, otros |
### Reglas de Cascada
1. Siempre propagar de nivel N a nivel N+1 (nunca saltar)
2. Validar en cada nivel antes de continuar
3. Si nivel N falla, detener propagacion
4. Resolver dependencias internas en nivel 1 primero
### Script
```bash
./devtools/scripts/propagation/cascade-propagation.sh <modulo> <version> [--start-level N] [--stop-level N]
```
---
## 10. ROL DE @KB_MANAGER (EPIC-012)
Ver: @KB_MANAGER (`core/orchestration/agents/perfiles/PERFIL-KB-MANAGER.md`)
### Responsabilidades
1. Recibir notificaciones de mejoras propagables
2. Analizar impacto usando CAPVED
3. Coordinar actualizacion en core y KB
4. Generar tareas SCRUM para proyectos
5. Validar integracion final
### Cuando Activar @KB_MANAGER
- Mejora en modulo de knowledge-base
- Cambio que afecta multiples proyectos
- Security-fix o bug-fix critico
---
## 11. GENERACION DE TAREAS SCRUM (EPIC-012)
### Script
```bash
./devtools/scripts/propagation/generate-scrum-tasks.sh <modulo> <version> <tipo> [--epic] [--output-dir DIR]
```
### Tipos de Cambio
| Tipo | Descripcion | Prioridad |
|------|-------------|-----------|
| security-fix | Vulnerabilidad corregida | Critica |
| bug-fix | Error corregido | Alta |
| feature | Nueva funcionalidad | Media |
| refactor | Mejora interna | Baja |
### Tipos de Salida
| Tipo | Archivo | Cuando Usar |
|------|---------|-------------|
| Task | TASK-PROP-XXX-{proyecto}.md | Cambio simple |
| Epic + Tasks | EPIC-PROP-XXX.md + TASKs | Cambio complejo o multi-proyecto |
### Formato de Tarea SCRUM
Ver: `shared/knowledge-base/propagacion/templates/TAREA-PROPAGACION.md`
---
## 12. PROTOCOLO DE COORDINACION (EPIC-012)
Ver: @PROTOCOLO_PROP (`shared/knowledge-base/propagacion/PROTOCOLO-COORDINACION.yml`)
### Flujo Resumido
```
1. Desarrollador detecta mejora
|
v
2. Notifica a @KB_MANAGER
|
v
3. @KB_MANAGER analiza con CAPVED
|
v
4. Si propagar: Actualizar KB -> Generar tareas SCRUM
|
v
5. @PERFIL_PROJECT_AGENT ejecuta en cada proyecto
|
v
6. @KB_MANAGER valida integracion final
```
### Handoff
| De | A | Canal |
|----|---|-------|
| @KB_MANAGER | @PROJECT_AGENT | Tarea SCRUM formal |
| @PROJECT_AGENT | @KB_MANAGER | Reporte de ejecucion |
### Validacion Final
```bash
./devtools/scripts/propagation/validate-propagation-chain.sh <PROP-ID>
```
---
## 13. COMANDOS ACTUALIZADOS (EPIC-012)
### Propagacion Basica
```bash
./devtools/scripts/propagation/propagate-module-update.sh <modulo> <version> <origen>
```
### Propagacion con Tareas SCRUM
```bash
./devtools/scripts/propagation/propagate-module-update.sh <modulo> <version> <origen> --scrum
./devtools/scripts/propagation/propagate-module-update.sh <modulo> <version> <origen> --scrum --scrum-epic
```
### Propagacion en Cascada
```bash
./devtools/scripts/propagation/propagate-module-update.sh <modulo> <version> <origen> --cascade
```
### Combinado
```bash
./devtools/scripts/propagation/propagate-module-update.sh <modulo> <version> <origen> --scrum --cascade --tipo security-fix
```
---
## 14. REFERENCIAS ACTUALIZADAS
| Alias | Archivo |
|-------|---------|
| @PROPAGACION | Esta directiva |
| @KB_MANAGER | core/orchestration/agents/perfiles/PERFIL-KB-MANAGER.md |
| @NIVELES_PROP | shared/knowledge-base/propagacion/NIVELES-PROPAGACION.yml |
| @PROTOCOLO_PROP | shared/knowledge-base/propagacion/PROTOCOLO-COORDINACION.yml |
| @USAGE_PROP | shared/knowledge-base/propagacion/USAGE.md |
| @USAGE_ORQUESTACION | shared/knowledge-base/propagacion/USAGE-ORQUESTACION.md |
| @CATALOG | shared/knowledge-base/CATALOGO-MODULOS.yml |
- **Catalogo de modulos:** `@CATALOG``shared/knowledge-base/CATALOGO-MODULOS.yml`
- **Trazabilidad:** `shared/knowledge-base/TRAZABILIDAD-PROYECTOS.yml`
- **Guia de uso:** `shared/knowledge-base/propagacion/USAGE.md`
- **Registro:** `shared/knowledge-base/propagacion/REGISTRO-PROPAGACIONES.yml`
---
**Directiva creada:** EPIC-007
**Actualizada:** EPIC-012 (Orquestacion Avanzada)
**Sistema:** NEXUS v3.4
**Autor:** Claude Opus 4.5

View File

@ -28,16 +28,16 @@ global:
# ═══════════════════════════════════════════════════════════════════
# CATÁLOGO DE FUNCIONALIDADES REUTILIZABLES (CONSULTAR PRIMERO)
# ═══════════════════════════════════════════════════════════════════
"@CATALOG": "shared/catalog/"
"@CATALOG_INDEX": "shared/catalog/CATALOG-INDEX.yml"
"@CATALOG_AUTH": "shared/catalog/auth/"
"@CATALOG_SESSION": "shared/catalog/session-management/"
"@CATALOG_RATELIMIT": "shared/catalog/rate-limiting/"
"@CATALOG_NOTIFY": "shared/catalog/notifications/"
"@CATALOG_TENANT": "shared/catalog/multi-tenancy/"
"@CATALOG_FLAGS": "shared/catalog/feature-flags/"
"@CATALOG_WS": "shared/catalog/websocket/"
"@CATALOG_PAYMENTS": "shared/catalog/payments/"
"@CATALOG": "core/catalog/"
"@CATALOG_INDEX": "core/catalog/CATALOG-INDEX.yml"
"@CATALOG_AUTH": "core/catalog/auth/"
"@CATALOG_SESSION": "core/catalog/session-management/"
"@CATALOG_RATELIMIT": "core/catalog/rate-limiting/"
"@CATALOG_NOTIFY": "core/catalog/notifications/"
"@CATALOG_TENANT": "core/catalog/multi-tenancy/"
"@CATALOG_FLAGS": "core/catalog/feature-flags/"
"@CATALOG_WS": "core/catalog/websocket/"
"@CATALOG_PAYMENTS": "core/catalog/payments/"
# ═══════════════════════════════════════════════════════════════════
# CAPVED - CICLO DE VIDA DE TAREAS (🆕 v2.0)
@ -222,8 +222,8 @@ niveles:
# ═══════════════════════════════════════════════════════════════════
"@CORE": "core/"
"@CORE_ORCH": "core/orchestration/"
"@CORE_CATALOG": "shared/catalog/"
"@CORE_MODULES": "shared/modules/"
"@CORE_CATALOG": "core/catalog/"
"@CORE_MODULES": "core/modules/"
# ═══════════════════════════════════════════════════════════════════
# NIVEL 2: PROYECTOS (alias dinámicos)

317
core/types/api.types.ts Normal file
View File

@ -0,0 +1,317 @@
/**
* API Types - Core Module
*
* Tipos compartidos para APIs REST en todos los proyectos.
*
* @module @core/types/api
* @version 1.0.0
*/
import { SortDirection } from '../constants/enums.constants';
// ============================================================================
// API RESPONSE TYPES
// ============================================================================
/**
* Standard API response wrapper
*/
export interface ApiResponse<T = unknown> {
success: boolean;
data: T;
message?: string;
timestamp: string;
path?: string;
requestId?: string;
}
/**
* API error response
*/
export interface ApiError {
success: false;
error: {
code: string;
message: string;
details?: Record<string, unknown>;
stack?: string; // Only in development
};
timestamp: string;
path?: string;
requestId?: string;
}
/**
* Paginated response
*/
export interface PaginatedResponse<T> extends ApiResponse<T[]> {
pagination: PaginationMeta;
}
/**
* Pagination metadata
*/
export interface PaginationMeta {
page: number;
limit: number;
total: number;
totalPages: number;
hasNext: boolean;
hasPrev: boolean;
}
// ============================================================================
// REQUEST TYPES
// ============================================================================
/**
* Pagination query parameters
*/
export interface PaginationParams {
page?: number;
limit?: number;
}
/**
* Sort query parameters
*/
export interface SortParams {
sortBy?: string;
sortOrder?: SortDirection;
}
/**
* Combined query parameters
*/
export interface QueryParams extends PaginationParams, SortParams {
search?: string;
filter?: Record<string, unknown>;
}
/**
* Date range filter
*/
export interface DateRangeFilter {
startDate?: string;
endDate?: string;
}
// ============================================================================
// CRUD OPERATIONS
// ============================================================================
/**
* Create operation result
*/
export interface CreateResult<T> {
created: T;
message?: string;
}
/**
* Update operation result
*/
export interface UpdateResult<T> {
updated: T;
message?: string;
}
/**
* Delete operation result
*/
export interface DeleteResult {
deleted: boolean;
id: string;
message?: string;
}
/**
* Bulk operation result
*/
export interface BulkResult {
success: number;
failed: number;
errors?: Array<{
id: string;
error: string;
}>;
}
// ============================================================================
// HEALTH CHECK
// ============================================================================
/**
* Health check response
*/
export interface HealthCheckResponse {
status: 'healthy' | 'degraded' | 'unhealthy';
timestamp: string;
version: string;
uptime: number;
services?: Record<string, ServiceHealth>;
}
/**
* Individual service health
*/
export interface ServiceHealth {
status: 'up' | 'down' | 'degraded';
latency?: number;
message?: string;
}
// ============================================================================
// ERROR CODES
// ============================================================================
/**
* Standard error codes
*/
export const ErrorCodes = {
// Client errors (4xx)
BAD_REQUEST: 'BAD_REQUEST',
UNAUTHORIZED: 'UNAUTHORIZED',
FORBIDDEN: 'FORBIDDEN',
NOT_FOUND: 'NOT_FOUND',
METHOD_NOT_ALLOWED: 'METHOD_NOT_ALLOWED',
CONFLICT: 'CONFLICT',
UNPROCESSABLE_ENTITY: 'UNPROCESSABLE_ENTITY',
TOO_MANY_REQUESTS: 'TOO_MANY_REQUESTS',
// Server errors (5xx)
INTERNAL_ERROR: 'INTERNAL_ERROR',
SERVICE_UNAVAILABLE: 'SERVICE_UNAVAILABLE',
GATEWAY_TIMEOUT: 'GATEWAY_TIMEOUT',
// Validation errors
VALIDATION_ERROR: 'VALIDATION_ERROR',
INVALID_INPUT: 'INVALID_INPUT',
MISSING_FIELD: 'MISSING_FIELD',
// Auth errors
INVALID_CREDENTIALS: 'INVALID_CREDENTIALS',
TOKEN_EXPIRED: 'TOKEN_EXPIRED',
TOKEN_INVALID: 'TOKEN_INVALID',
SESSION_EXPIRED: 'SESSION_EXPIRED',
// Business logic errors
RESOURCE_EXISTS: 'RESOURCE_EXISTS',
RESOURCE_LOCKED: 'RESOURCE_LOCKED',
OPERATION_FAILED: 'OPERATION_FAILED',
LIMIT_EXCEEDED: 'LIMIT_EXCEEDED',
} as const;
export type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];
// ============================================================================
// HTTP STATUS
// ============================================================================
/**
* HTTP status codes mapping
*/
export const HttpStatus = {
OK: 200,
CREATED: 201,
ACCEPTED: 202,
NO_CONTENT: 204,
BAD_REQUEST: 400,
UNAUTHORIZED: 401,
FORBIDDEN: 403,
NOT_FOUND: 404,
METHOD_NOT_ALLOWED: 405,
CONFLICT: 409,
UNPROCESSABLE_ENTITY: 422,
TOO_MANY_REQUESTS: 429,
INTERNAL_SERVER_ERROR: 500,
BAD_GATEWAY: 502,
SERVICE_UNAVAILABLE: 503,
GATEWAY_TIMEOUT: 504,
} as const;
export type HttpStatusCode = (typeof HttpStatus)[keyof typeof HttpStatus];
// ============================================================================
// HELPER FUNCTIONS
// ============================================================================
/**
* Create success response
*/
export const createSuccessResponse = <T>(
data: T,
message?: string,
): ApiResponse<T> => ({
success: true,
data,
message,
timestamp: new Date().toISOString(),
});
/**
* Create error response
*/
export const createErrorResponse = (
code: ErrorCode,
message: string,
details?: Record<string, unknown>,
): ApiError => ({
success: false,
error: {
code,
message,
details,
},
timestamp: new Date().toISOString(),
});
/**
* Create paginated response
*/
export const createPaginatedResponse = <T>(
data: T[],
page: number,
limit: number,
total: number,
): PaginatedResponse<T> => {
const totalPages = Math.ceil(total / limit);
return {
success: true,
data,
timestamp: new Date().toISOString(),
pagination: {
page,
limit,
total,
totalPages,
hasNext: page < totalPages,
hasPrev: page > 1,
},
};
};
/**
* Calculate pagination offset
*/
export const calculateOffset = (page: number, limit: number): number => {
return (page - 1) * limit;
};
/**
* Normalize pagination params
*/
export const normalizePagination = (
params: PaginationParams,
defaults: { page: number; limit: number; maxLimit: number } = {
page: 1,
limit: 20,
maxLimit: 100,
},
): Required<PaginationParams> => ({
page: Math.max(1, params.page || defaults.page),
limit: Math.min(
defaults.maxLimit,
Math.max(1, params.limit || defaults.limit),
),
});

374
core/types/common.types.ts Normal file
View File

@ -0,0 +1,374 @@
/**
* Common Types - Core Module
*
* Tipos comunes compartidos entre todos los proyectos.
*
* @module @core/types/common
* @version 1.0.0
*/
// ============================================================================
// BASE ENTITY TYPES
// ============================================================================
/**
* Base entity with standard fields
*/
export interface BaseEntity {
id: string;
createdAt: Date | string;
updatedAt: Date | string;
}
/**
* Soft-deletable entity
*/
export interface SoftDeletableEntity extends BaseEntity {
deletedAt?: Date | string | null;
isDeleted: boolean;
}
/**
* Auditable entity
*/
export interface AuditableEntity extends BaseEntity {
createdBy?: string;
updatedBy?: string;
}
/**
* Multi-tenant entity
*/
export interface TenantEntity extends BaseEntity {
tenantId: string;
}
/**
* Full featured entity (all mixins)
*/
export interface FullEntity
extends SoftDeletableEntity,
AuditableEntity,
TenantEntity {}
// ============================================================================
// USER TYPES
// ============================================================================
/**
* Base user information
*/
export interface BaseUser {
id: string;
email: string;
name: string;
avatar?: string;
}
/**
* User with authentication info
*/
export interface AuthUser extends BaseUser {
role: string;
permissions?: string[];
isEmailVerified: boolean;
lastLoginAt?: Date | string;
}
/**
* User profile
*/
export interface UserProfile extends BaseUser {
firstName?: string;
lastName?: string;
phone?: string;
timezone?: string;
locale?: string;
bio?: string;
}
// ============================================================================
// ADDRESS & LOCATION
// ============================================================================
/**
* Physical address
*/
export interface Address {
street?: string;
number?: string;
interior?: string;
neighborhood?: string;
city: string;
state: string;
country: string;
postalCode: string;
latitude?: number;
longitude?: number;
}
/**
* Geographic coordinates
*/
export interface GeoLocation {
latitude: number;
longitude: number;
accuracy?: number;
}
// ============================================================================
// CONTACT INFORMATION
// ============================================================================
/**
* Contact information
*/
export interface ContactInfo {
email?: string;
phone?: string;
mobile?: string;
fax?: string;
website?: string;
}
/**
* Social media links
*/
export interface SocialLinks {
facebook?: string;
twitter?: string;
instagram?: string;
linkedin?: string;
youtube?: string;
tiktok?: string;
}
// ============================================================================
// FILE & MEDIA
// ============================================================================
/**
* File information
*/
export interface FileInfo {
id: string;
name: string;
originalName: string;
mimeType: string;
size: number;
url: string;
path?: string;
}
/**
* Image with dimensions
*/
export interface ImageInfo extends FileInfo {
width: number;
height: number;
thumbnailUrl?: string;
}
/**
* Upload result
*/
export interface UploadResult {
success: boolean;
file?: FileInfo;
error?: string;
}
// ============================================================================
// MONEY & CURRENCY
// ============================================================================
/**
* Monetary amount
*/
export interface Money {
amount: number;
currency: string;
}
/**
* Price with optional tax
*/
export interface Price extends Money {
taxAmount?: number;
taxRate?: number;
totalAmount: number;
}
// ============================================================================
// DATE & TIME
// ============================================================================
/**
* Date range
*/
export interface DateRange {
start: Date | string;
end: Date | string;
}
/**
* Time slot
*/
export interface TimeSlot {
startTime: string; // HH:mm
endTime: string; // HH:mm
}
/**
* Schedule (day with time slots)
*/
export interface DaySchedule {
dayOfWeek: number; // 0-6, where 0 is Sunday
isOpen: boolean;
slots: TimeSlot[];
}
// ============================================================================
// METADATA
// ============================================================================
/**
* Generic metadata
*/
export type Metadata = Record<string, unknown>;
/**
* SEO metadata
*/
export interface SEOMetadata {
title?: string;
description?: string;
keywords?: string[];
ogImage?: string;
canonicalUrl?: string;
}
// ============================================================================
// KEY-VALUE PAIRS
// ============================================================================
/**
* Simple key-value pair
*/
export interface KeyValue<T = string> {
key: string;
value: T;
}
/**
* Option for select/dropdown
*/
export interface SelectOption<T = string> {
label: string;
value: T;
disabled?: boolean;
description?: string;
}
/**
* Tree node (hierarchical data)
*/
export interface TreeNode<T = unknown> {
id: string;
label: string;
data?: T;
children?: TreeNode<T>[];
parentId?: string;
}
// ============================================================================
// UTILITY TYPES
// ============================================================================
/**
* Make all properties optional except specified keys
*/
export type PartialExcept<T, K extends keyof T> = Partial<Omit<T, K>> &
Pick<T, K>;
/**
* Make specified properties required
*/
export type RequireFields<T, K extends keyof T> = T & Required<Pick<T, K>>;
/**
* Make all properties nullable
*/
export type Nullable<T> = { [K in keyof T]: T[K] | null };
/**
* Deep partial (all nested properties optional)
*/
export type DeepPartial<T> = {
[P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
};
/**
* Remove readonly from all properties
*/
export type Mutable<T> = { -readonly [P in keyof T]: T[P] };
/**
* Extract non-function properties
*/
export type DataOnly<T> = {
[K in keyof T as T[K] extends Function ? never : K]: T[K];
};
/**
* Async function type
*/
export type AsyncFunction<T = void, Args extends unknown[] = []> = (
...args: Args
) => Promise<T>;
/**
* Constructor type
*/
export type Constructor<T = object> = new (...args: unknown[]) => T;
// ============================================================================
// RESULT TYPES
// ============================================================================
/**
* Result type for operations that can fail
*/
export type Result<T, E = Error> =
| { success: true; data: T }
| { success: false; error: E };
/**
* Create success result
*/
export const success = <T>(data: T): Result<T, never> => ({
success: true,
data,
});
/**
* Create failure result
*/
export const failure = <E>(error: E): Result<never, E> => ({
success: false,
error,
});
/**
* Check if result is success
*/
export const isSuccess = <T, E>(
result: Result<T, E>,
): result is { success: true; data: T } => result.success;
/**
* Check if result is failure
*/
export const isFailure = <T, E>(
result: Result<T, E>,
): result is { success: false; error: E } => !result.success;

11
core/types/index.ts Normal file
View File

@ -0,0 +1,11 @@
/**
* Core Types Module
*
* Type definitions shared across all projects in the workspace.
*
* @module @core/types
* @version 1.0.0
*/
export * from './api.types';
export * from './common.types';

View File

@ -1,43 +0,0 @@
#!/bin/bash
# =============================================================================
# clone-workspace.sh
# =============================================================================
# Clona el workspace-v1 completo con todos los submodules
# Generado: 2026-01-04
# EPIC: EPIC-010
# =============================================================================
set -e
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'
DEFAULT_REPO="git@gitea-server:rckrdmrd/workspace-v1.git"
DEFAULT_DIR="workspace-v1"
REPO_URL="${1:-$DEFAULT_REPO}"
TARGET_DIR="${2:-$DEFAULT_DIR}"
echo "=============================================="
echo " CLONE WORKSPACE-V1"
echo "=============================================="
echo "Repositorio: $REPO_URL"
echo "Destino: $TARGET_DIR"
echo ""
if [ -d "$TARGET_DIR" ]; then
echo -e "${RED}ERROR${NC}: El directorio '$TARGET_DIR' ya existe"
exit 1
fi
echo "=== Clonando repositorio ==="
git clone --recurse-submodules "$REPO_URL" "$TARGET_DIR"
cd "$TARGET_DIR"
git submodule init
git submodule update --recursive
echo ""
echo -e "${GREEN}CLONE COMPLETADO${NC}"
echo "Workspace en: $(pwd)"

View File

@ -1,53 +0,0 @@
#!/bin/bash
# =============================================================================
# sync-submodules.sh
# =============================================================================
# Sincroniza todos los submodules a sus ultimas versiones
# Generado: 2026-01-04
# EPIC: EPIC-010
# =============================================================================
set -e
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
AUTO_COMMIT=false
[ "$1" == "--commit" ] && AUTO_COMMIT=true
if [ ! -d ".git" ]; then
echo "ERROR: No es un repositorio Git"
exit 1
fi
echo "=============================================="
echo " SYNC SUBMODULES"
echo "=============================================="
echo "=== Estado actual ==="
git submodule status
echo ""
echo "=== Sincronizando ==="
git submodule sync --recursive
git submodule update --remote --merge
echo ""
echo "=== Nuevo estado ==="
git submodule status
CHANGES=$(git status --porcelain)
if [ -n "$CHANGES" ]; then
echo ""
echo -e "${YELLOW}Cambios detectados${NC}"
if [ "$AUTO_COMMIT" = true ]; then
git add .
git commit -m "chore: update submodules"
echo -e "${GREEN}Commit creado${NC}"
else
echo "Para commit: $0 --commit"
fi
else
echo -e "${GREEN}Submodules actualizados${NC}"
fi

View File

@ -372,27 +372,15 @@ main() {
generate_tasks
update_registry
# Ejecutar generacion SCRUM si se solicito
run_scrum_generation
# Ejecutar cascada si se solicito
run_cascade_propagation
echo ""
echo "============================================"
echo " Proximos pasos:"
echo "============================================"
echo ""
if $GENERATE_SCRUM; then
echo " 1. Revisar tareas SCRUM generadas"
echo " 2. Asignar a @PERFIL_PROJECT_AGENT"
else
echo " 1. Revisar tareas generadas"
echo " 2. Priorizar segun tipo de cambio"
fi
echo " 3. Ejecutar propagacion en cada proyecto"
echo " 4. Actualizar TRAZABILIDAD-PROYECTOS.yml"
echo " 5. Validar: ./validate-propagation-chain.sh <PROP-ID>"
echo ""
echo " Ver: @PROPAGACION para proceso completo"
echo ""

View File

@ -51,9 +51,9 @@ FAIL=0
WARN=0
# Funciones de logging
check_pass() { PASS=$((PASS + 1)); echo -e " ${GREEN}[PASS]${NC} $1"; }
check_fail() { FAIL=$((FAIL + 1)); echo -e " ${RED}[FAIL]${NC} $1"; }
check_warn() { WARN=$((WARN + 1)); echo -e " ${YELLOW}[WARN]${NC} $1"; }
check_pass() { ((PASS++)); echo -e " ${GREEN}[PASS]${NC} $1"; }
check_fail() { ((FAIL++)); echo -e " ${RED}[FAIL]${NC} $1"; }
check_warn() { ((WARN++)); echo -e " ${YELLOW}[WARN]${NC} $1"; }
log_info() { echo -e " ${BLUE}[INFO]${NC} $1"; }
# Funcion de ayuda

View File

@ -1,130 +0,0 @@
#!/bin/bash
# =============================================================================
# validate-project-structure.sh
# Validar estructura de proyecto segun estandar EPIC-011
# Sistema: NEXUS v3.4 + SIMCO
# =============================================================================
set -e
PROJECT_PATH="${1:-.}"
PROJECT_NAME=$(basename "$PROJECT_PATH")
# Colores
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
ERRORS=0
WARNINGS=0
echo "=============================================="
echo "Validando: $PROJECT_NAME"
echo "Ruta: $PROJECT_PATH"
echo "=============================================="
echo ""
# -----------------------------------------------------------------------------
# Funcion para verificar existencia
# -----------------------------------------------------------------------------
check_exists() {
local path="$1"
local type="$2" # "dir" o "file"
local required="$3" # "required" o "recommended"
local name="$4"
if [ "$type" = "dir" ]; then
if [ -d "$path" ]; then
echo -e "${GREEN}[OK]${NC} $name"
return 0
fi
else
if [ -f "$path" ]; then
echo -e "${GREEN}[OK]${NC} $name"
return 0
fi
fi
if [ "$required" = "required" ]; then
echo -e "${RED}[ERROR]${NC} Falta: $name"
((ERRORS++)) || true
return 1
else
echo -e "${YELLOW}[WARN]${NC} Recomendado: $name"
((WARNINGS++)) || true
return 0
fi
}
# -----------------------------------------------------------------------------
# Validacion de orchestration/
# -----------------------------------------------------------------------------
echo "--- Verificando orchestration/ ---"
check_exists "$PROJECT_PATH/orchestration" "dir" "required" "orchestration/"
check_exists "$PROJECT_PATH/orchestration/00-guidelines" "dir" "required" "orchestration/00-guidelines/"
# Archivos obligatorios en 00-guidelines
echo ""
echo "--- Archivos obligatorios ---"
check_exists "$PROJECT_PATH/orchestration/00-guidelines/CONTEXTO-PROYECTO.md" "file" "required" "CONTEXTO-PROYECTO.md"
check_exists "$PROJECT_PATH/orchestration/00-guidelines/HERENCIA-SIMCO.md" "file" "required" "HERENCIA-SIMCO.md"
check_exists "$PROJECT_PATH/orchestration/00-guidelines/PROJECT-STATUS.md" "file" "required" "PROJECT-STATUS.md"
# Inventarios
echo ""
echo "--- Inventarios ---"
check_exists "$PROJECT_PATH/orchestration/inventarios" "dir" "required" "orchestration/inventarios/"
check_exists "$PROJECT_PATH/orchestration/inventarios/MASTER_INVENTORY.yml" "file" "recommended" "MASTER_INVENTORY.yml"
# Trazas (recomendado)
echo ""
echo "--- Trazas ---"
check_exists "$PROJECT_PATH/orchestration/trazas" "dir" "recommended" "orchestration/trazas/"
# README
echo ""
echo "--- Documentacion ---"
check_exists "$PROJECT_PATH/orchestration/README.md" "file" "recommended" "orchestration/README.md"
check_exists "$PROJECT_PATH/docs/_MAP.md" "file" "recommended" "docs/_MAP.md"
# -----------------------------------------------------------------------------
# Validar contenido de HERENCIA-SIMCO.md
# -----------------------------------------------------------------------------
echo ""
echo "--- Validando rutas en HERENCIA-SIMCO.md ---"
HERENCIA_FILE="$PROJECT_PATH/orchestration/00-guidelines/HERENCIA-SIMCO.md"
if [ -f "$HERENCIA_FILE" ]; then
# Verificar que no tenga rutas obsoletas (workspace sin -v1)
if grep -q "/home/isem/workspace/" "$HERENCIA_FILE" 2>/dev/null; then
if ! grep -q "workspace-v1" "$HERENCIA_FILE" 2>/dev/null; then
echo -e "${RED}[ERROR]${NC} Rutas obsoletas encontradas en HERENCIA-SIMCO.md"
((ERRORS++)) || true
else
echo -e "${GREEN}[OK]${NC} Rutas correctas en HERENCIA-SIMCO.md"
fi
else
echo -e "${GREEN}[OK]${NC} Sin rutas obsoletas en HERENCIA-SIMCO.md"
fi
else
echo -e "${YELLOW}[SKIP]${NC} HERENCIA-SIMCO.md no existe"
fi
# -----------------------------------------------------------------------------
# Resumen
# -----------------------------------------------------------------------------
echo ""
echo "=============================================="
echo "RESUMEN: $PROJECT_NAME"
echo "=============================================="
echo -e "Errores: ${RED}$ERRORS${NC}"
echo -e "Warnings: ${YELLOW}$WARNINGS${NC}"
echo ""
if [ $ERRORS -eq 0 ]; then
echo -e "${GREEN}Estado: PASS${NC}"
exit 0
else
echo -e "${RED}Estado: FAIL${NC}"
exit 1
fi

View File

@ -11,10 +11,10 @@
#
# ═══════════════════════════════════════════════════════════════════════════════
version: "3.8.0"
fecha_actualizacion: "2026-01-10"
version: "3.5.0"
fecha_actualizacion: "2026-01-03"
descripcion: "Indice maestro - BASE PRINCIPAL en raiz del workspace"
sistema: "SIMCO v3.8 + CAPVED + Economia de Tokens + Herencia Escalonada + Modulos + Context Engineering + Estandares Documentacion + Mantenimiento Docs"
sistema: "SIMCO v3.5 + CAPVED + Economia de Tokens + Herencia Escalonada + Modulos"
# ═══════════════════════════════════════════════════════════════════════════════
# ARQUITECTURA DE HERENCIA ESCALONADA
@ -151,215 +151,6 @@ niveles:
obligatoria: false
descripcion: "Delegar a subagentes"
# DIRECTIVAS DE SUBAGENTES Y TOKENS (v2.5.0+)
operaciones_subagentes:
- archivo: "directivas/simco/SIMCO-SUBAGENTE.md"
alias: "@SUBAGENTE"
obligatoria: false
descripcion: "Protocolo cuando recibes delegacion"
version: "1.0.0"
fecha: "2026-01-07"
- archivo: "directivas/simco/SIMCO-CCA-SUBAGENTE.md"
alias: "@CCA_SUBAGENTE"
obligatoria: false
descripcion: "CCA ligero para subagentes (~1500 tokens)"
version: "1.4.0"
fecha: "2026-01-07"
- archivo: "directivas/simco/SIMCO-CONTROL-TOKENS.md"
alias: "@CONTROL_TOKENS"
obligatoria: false
descripcion: "Gestion de limites de tokens"
version: "1.0.0"
fecha: "2026-01-07"
- archivo: "directivas/simco/SIMCO-DELEGACION-PARALELA.md"
alias: "@DELEGACION_PARALELA"
obligatoria: false
descripcion: "Delegacion paralela a multiples agentes"
version: "1.0.0"
fecha: "2026-01-07"
# DIRECTIVAS DE CONTEXT ENGINEERING (v2.4.0+)
operaciones_context:
- archivo: "directivas/simco/SIMCO-CONTEXT-ENGINEERING.md"
alias: "@CONTEXT_ENGINEERING"
obligatoria: false
descripcion: "Ingenieria de contexto para agentes"
version: "1.0.0"
fecha: "2026-01-07"
- archivo: "directivas/simco/SIMCO-CONTEXT-RESOLUTION.md"
alias: "@CONTEXT_RESOLUTION"
obligatoria: false
descripcion: "Resolucion de contextos conflictivos"
version: "1.0.0"
fecha: "2026-01-07"
# DIRECTIVAS DE GIT Y REPOSITORIOS (v2.6.0+)
operaciones_git:
- archivo: "directivas/simco/SIMCO-GIT.md"
alias: "@GIT"
obligatoria: false
descripcion: "Control de versiones y commits"
version: "1.0.0"
fecha: "2026-01-07"
- archivo: "directivas/simco/SIMCO-GIT-REMOTES.md"
alias: "@GIT_REMOTES"
obligatoria: false
descripcion: "Operaciones push/pull/clone con servidores remotos"
version: "1.0.0"
fecha: "2026-01-07"
- archivo: "directivas/simco/SIMCO-ESCALAMIENTO.md"
alias: "@ESCALAMIENTO"
obligatoria: false
descripcion: "Escalamiento a Product Owner"
version: "1.0.0"
fecha: "2026-01-07"
# DIRECTIVAS DE TOMA DE DECISIONES
operaciones_decisiones:
- archivo: "directivas/simco/SIMCO-ALINEACION.md"
alias: "@ALINEACION"
obligatoria: false
descripcion: "Validar alineacion entre capas (DDL-Entity-DTO)"
- archivo: "directivas/simco/SIMCO-DECISION-MATRIZ.md"
alias: "@DECISION_MATRIZ"
obligatoria: false
descripcion: "Matriz de decision para agentes"
version: "1.0.0"
fecha: "2026-01-07"
- archivo: "directivas/simco/SIMCO-ASIGNACION-PERFILES.md"
alias: "@ASIGNACION_PERFILES"
obligatoria: false
descripcion: "Mapeo de perfiles a tareas"
version: "1.0.0"
fecha: "2026-01-04"
# DIRECTIVAS ADICIONALES
operaciones_adicionales:
- archivo: "directivas/simco/SIMCO-CAPVED-PLUS.md"
alias: "@CAPVED_PLUS"
obligatoria: false
descripcion: "Extension del ciclo CAPVED"
version: "1.0.0"
- archivo: "directivas/simco/SIMCO-ERROR-RECURRENTE.md"
alias: "@ERROR_RECURRENTE"
obligatoria: false
descripcion: "Tratamiento de errores recurrentes"
version: "1.0.0"
- archivo: "directivas/simco/SIMCO-SCRUM-INTEGRATION.md"
alias: "@SCRUM"
obligatoria: false
descripcion: "Integracion con Scrum"
version: "1.0.0"
- archivo: "directivas/simco/SIMCO-QUICK-REFERENCE.md"
alias: "@QUICK_REF"
obligatoria: false
descripcion: "Referencia rapida optimizada"
version: "1.0.0"
- archivo: "directivas/simco/SIMCO-RAG.md"
alias: "@RAG"
obligatoria: false
descripcion: "Retrieval-Augmented Generation"
version: "1.0.0"
- archivo: "directivas/simco/SIMCO-MCP.md"
alias: "@MCP"
obligatoria: false
descripcion: "Protocolo de Contexto de Maquina"
version: "1.0.0"
- archivo: "directivas/simco/SIMCO-MCP-IMPORT.md"
alias: "@MCP_IMPORT"
obligatoria: false
descripcion: "Importacion de componentes MCP"
version: "1.0.0"
- archivo: "directivas/simco/SIMCO-REUTILIZAR.md"
alias: "@REUTILIZAR"
obligatoria: false
descripcion: "Reutilizar del catalogo"
- archivo: "directivas/simco/SIMCO-CONTRIBUIR-CATALOGO.md"
alias: "@CONTRIBUIR"
obligatoria: false
descripcion: "Contribuir al catalogo"
# DIRECTIVAS DE DOCUMENTACION Y ESTANDARES (v3.7.0+)
operaciones_documentacion:
- archivo: "directivas/simco/SIMCO-DOCUMENTACION-PROYECTO.md"
alias: "@DOC_PROYECTO"
obligatoria: true
descripcion: "Estandar base para documentacion de proyectos"
version: "1.0.0"
fecha: "2026-01-10"
- archivo: "directivas/simco/SIMCO-NOMENCLATURA.md"
alias: "@NOMENCLATURA"
obligatoria: true
descripcion: "Estandar de nomenclatura de archivos y directorios"
version: "1.0.0"
fecha: "2026-01-10"
- archivo: "directivas/simco/SIMCO-ESTRUCTURA-DOCS.md"
alias: "@ESTRUCTURA_DOCS"
obligatoria: true
descripcion: "Estructura interna de documentos MD"
version: "1.0.0"
fecha: "2026-01-10"
- archivo: "directivas/simco/SIMCO-INVENTARIOS.md"
alias: "@INVENTARIOS"
obligatoria: false
descripcion: "Estandar de inventarios YAML (SSOT)"
version: "1.0.0"
fecha: "2026-01-10"
- archivo: "directivas/simco/SIMCO-TESTING.md"
alias: "@TESTING"
obligatoria: false
descripcion: "Estandares minimos de testing"
version: "1.0.0"
fecha: "2026-01-10"
- archivo: "directivas/simco/SIMCO-MIGRACIONES-BD.md"
alias: "@MIGRACIONES"
obligatoria: false
descripcion: "Protocolo de migraciones de base de datos"
version: "1.0.0"
fecha: "2026-01-10"
- archivo: "directivas/simco/SIMCO-INTEGRACIONES-EXTERNAS.md"
alias: "@INTEGRACIONES"
obligatoria: false
descripcion: "Estandar para integraciones con APIs externas"
version: "1.0.0"
fecha: "2026-01-10"
- archivo: "directivas/simco/SIMCO-MANTENIMIENTO-DOCUMENTACION.md"
alias: "@MANTENIMIENTO_DOCS"
obligatoria: true
descripcion: "Mantenimiento, purga y deprecacion de documentacion"
version: "1.0.0"
fecha: "2026-01-10"
- archivo: "directivas/simco/SIMCO-SINCRONIZACION-BD.md"
alias: "@SYNC_BD"
obligatoria: true
descripcion: "Sincronizacion BD ↔ Codigo ↔ Documentacion"
version: "1.0.0"
fecha: "2026-01-10"
# NUEVAS DIRECTIVAS (EPIC-003)
operaciones_arquitectura:
- archivo: "directivas/simco/SIMCO-ESTRUCTURA-REPOS.md"
@ -372,7 +163,7 @@ niveles:
- archivo: "directivas/simco/SIMCO-MODULOS-COMPARTIDOS.md"
alias: "@MODULOS"
obligatoria: false
descripcion: "Uso de modulos en shared/modules/"
descripcion: "Uso de modulos en core/modules/"
version: "1.0.0"
fecha: "2026-01-03"
@ -463,7 +254,7 @@ niveles:
templates_nuevos:
- archivo: "templates/TEMPLATE-MODULO-COMPARTIDO.md"
alias: "@TPL_MODULO"
descripcion: "Template para documentar modulos en shared/modules/"
descripcion: "Template para documentar modulos en core/modules/"
version: "1.0.0"
fecha: "2026-01-03"
@ -583,32 +374,6 @@ niveles:
descripcion: "Analytics inmobiliario"
estado: "planificacion"
- nombre: "michangarrito"
descripcion: "Marketplace movil para negocios locales mexicanos"
estado: "documentado"
epicas: 28
documentacion: "docs/01-epicas/MCH-*.md"
- nombre: "template-saas"
descripcion: "Template base SaaS multi-tenant"
estado: "documentado"
modulos: 12
documentacion: "docs/01-modulos/SAAS-*.md"
- nombre: "clinica-dental"
descripcion: "ERP vertical para clinicas dentales"
estado: "documentado"
base: "erp-clinicas"
epicas: 6
documentacion: "docs/01-epicas/DENTAL-*.md"
- nombre: "clinica-veterinaria"
descripcion: "ERP vertical para clinicas veterinarias"
estado: "documentado"
base: "erp-clinicas"
epicas: 6
documentacion: "docs/01-epicas/VET-*.md"
# ------------------------------------------
# NIVEL 2B: SUITE (erp-suite)
# ------------------------------------------
@ -691,40 +456,10 @@ aliases:
"@OP_DEVOPS": "orchestration/directivas/simco/SIMCO-DEVOPS.md"
"@OP_ARQUITECTURA": "orchestration/directivas/simco/SIMCO-ARQUITECTURA.md"
# Subagentes y Tokens (v2.5.0+)
"@SUBAGENTE": "orchestration/directivas/simco/SIMCO-SUBAGENTE.md"
"@CCA_SUBAGENTE": "orchestration/directivas/simco/SIMCO-CCA-SUBAGENTE.md"
"@CONTROL_TOKENS": "orchestration/directivas/simco/SIMCO-CONTROL-TOKENS.md"
"@DELEGACION_PARALELA": "orchestration/directivas/simco/SIMCO-DELEGACION-PARALELA.md"
# Context Engineering (v2.4.0+)
"@CONTEXT_ENGINEERING": "orchestration/directivas/simco/SIMCO-CONTEXT-ENGINEERING.md"
"@CONTEXT_RESOLUTION": "orchestration/directivas/simco/SIMCO-CONTEXT-RESOLUTION.md"
# Git y Repositorios (v2.6.0+)
"@GIT": "orchestration/directivas/simco/SIMCO-GIT.md"
"@GIT_REMOTES": "orchestration/directivas/simco/SIMCO-GIT-REMOTES.md"
"@ESCALAMIENTO": "orchestration/directivas/simco/SIMCO-ESCALAMIENTO.md"
# Toma de Decisiones
"@ALINEACION": "orchestration/directivas/simco/SIMCO-ALINEACION.md"
"@DECISION_MATRIZ": "orchestration/directivas/simco/SIMCO-DECISION-MATRIZ.md"
"@ASIGNACION_PERFILES": "orchestration/directivas/simco/SIMCO-ASIGNACION-PERFILES.md"
# Adicionales
"@CAPVED_PLUS": "orchestration/directivas/simco/SIMCO-CAPVED-PLUS.md"
"@ERROR_RECURRENTE": "orchestration/directivas/simco/SIMCO-ERROR-RECURRENTE.md"
"@SCRUM": "orchestration/directivas/simco/SIMCO-SCRUM-INTEGRATION.md"
"@QUICK_REF": "orchestration/directivas/simco/SIMCO-QUICK-REFERENCE.md"
"@RAG": "orchestration/directivas/simco/SIMCO-RAG.md"
"@MCP": "orchestration/directivas/simco/SIMCO-MCP.md"
"@MCP_IMPORT": "orchestration/directivas/simco/SIMCO-MCP-IMPORT.md"
"@CONTRIBUIR": "orchestration/directivas/simco/SIMCO-CONTRIBUIR-CATALOGO.md"
# Catalogo y Modulos
"@CATALOG": "shared/catalog/CATALOG-INDEX.yml"
"@CATALOG": "core/catalog/CATALOG-INDEX.yml"
"@REUTILIZAR": "orchestration/directivas/simco/SIMCO-REUTILIZAR.md"
"@MODULES": "shared/modules/"
"@MODULES": "core/modules/"
# Templates (NUEVOS)
"@TPL_MODULO": "orchestration/templates/TEMPLATE-MODULO-COMPARTIDO.md"
@ -733,37 +468,8 @@ aliases:
"@TPL_DELEGACION": "orchestration/templates/TEMPLATE-DELEGACION-SUBAGENTE.md"
"@TPL_CAPVED": "orchestration/templates/TEMPLATE-TAREA-CAPVED.md"
# Checklists (NUEVOS)
# Checklists (NUEVO)
"@CHK_PROYECTO": "orchestration/checklists/CHECKLIST-NUEVO-PROYECTO.md"
"@CHK_DOCUMENTACION": "orchestration/checklists/CHECKLIST-DOCUMENTACION-PROYECTO.md"
"@CHK_INVENTARIOS": "orchestration/checklists/CHECKLIST-INVENTARIOS.md"
"@CHK_NOMENCLATURA": "orchestration/checklists/CHECKLIST-NOMENCLATURA.md"
# Documentacion y Estandares (v3.7.0+)
"@DOC_PROYECTO": "orchestration/directivas/simco/SIMCO-DOCUMENTACION-PROYECTO.md"
"@NOMENCLATURA": "orchestration/directivas/simco/SIMCO-NOMENCLATURA.md"
"@ESTRUCTURA_DOCS": "orchestration/directivas/simco/SIMCO-ESTRUCTURA-DOCS.md"
"@INVENTARIOS": "orchestration/directivas/simco/SIMCO-INVENTARIOS.md"
"@TESTING": "orchestration/directivas/simco/SIMCO-TESTING.md"
"@MIGRACIONES": "orchestration/directivas/simco/SIMCO-MIGRACIONES-BD.md"
"@INTEGRACIONES": "orchestration/directivas/simco/SIMCO-INTEGRACIONES-EXTERNAS.md"
"@MANTENIMIENTO_DOCS": "orchestration/directivas/simco/SIMCO-MANTENIMIENTO-DOCUMENTACION.md"
"@SYNC_BD": "orchestration/directivas/simco/SIMCO-SINCRONIZACION-BD.md"
# Checklists de Mantenimiento (v3.8.0+)
"@CHK_MANTENIMIENTO": "orchestration/checklists/CHECKLIST-MANTENIMIENTO-DOCS.md"
"@CHK_SYNC_BD": "orchestration/checklists/CHECKLIST-SINCRONIZACION-BD.md"
# Template de Deprecacion (v3.8.0+)
"@TPL_DEPRECACION": "orchestration/templates/TEMPLATE-DEPRECACION.md"
# Perfil de Mantenimiento (v3.8.0+)
"@PERFIL_DOC_MAINT": "orchestration/agents/perfiles/PERFIL-DOCUMENTATION-MAINTAINER.md"
# Templates de Documentacion (v3.7.0+)
"@TPL_INVENTARIO": "orchestration/templates/TEMPLATE-INVENTARIO-PROYECTO.md"
"@TPL_INTEGRACION": "orchestration/templates/TEMPLATE-INTEGRACION-EXTERNA.md"
"@TPL_MODULO_ESTANDAR": "orchestration/templates/TEMPLATE-MODULO-ESTANDAR.md"
# Proyectos
"@GAMILIT": "projects/gamilit"
@ -779,87 +485,32 @@ metadata:
total_niveles: 7
total_proyectos_standalone: 5
total_verticales: 5
total_directivas_simco: 51 # Actualizado: +2 directivas de mantenimiento (v3.8.0)
total_perfiles_agentes: 29 # Actualizado: +1 perfil de mantenimiento (v3.8.0)
total_directivas_simco: 29 # +2 nuevas
total_perfiles_agentes: 28
total_principios: 6
total_templates: 28 # Actualizado: +1 template deprecacion (v3.8.0)
total_checklists: 10 # Actualizado: +2 checklists mantenimiento (v3.8.0)
total_modulos_documentados: 6
sistema_simco_version: "3.7"
ultima_actualizacion: "2026-01-10"
mantenido_por: "Documentation-Architect"
epic_origen: "ESTANDARIZACION-DOC-2026-01-10"
total_templates: 24 # +2 nuevos
total_modulos_documentados: 6 # NUEVO
sistema_simco_version: "3.5"
ultima_actualizacion: "2026-01-03"
mantenido_por: "Requirements-Analyst"
epic_origen: "EPIC-003"
# ═══════════════════════════════════════════════════════════════════════════════
# CHANGELOG
# ═══════════════════════════════════════════════════════════════════════════════
changelog:
v3_8_0:
fecha: "2026-01-10"
epic: "MANTENIMIENTO-DOC"
cambios:
- "Agregadas 2 directivas de mantenimiento de documentacion"
- "SIMCO-MANTENIMIENTO-DOCUMENTACION.md - Ciclo de mantenimiento, purga y deprecacion"
- "SIMCO-SINCRONIZACION-BD.md - Sincronizacion BD ↔ Codigo ↔ Docs"
- "Agregados 2 checklists de mantenimiento"
- "CHECKLIST-MANTENIMIENTO-DOCS.md - 80 items de validacion"
- "CHECKLIST-SINCRONIZACION-BD.md - 70 items para sincronizacion BD"
- "Agregado 1 template de deprecacion"
- "TEMPLATE-DEPRECACION.md - Formato para deprecar documentos"
- "Agregado 1 perfil de agente especializado"
- "PERFIL-DOCUMENTATION-MAINTAINER.md - Agente de mantenimiento de docs"
- "Actualizado conteo: 51 directivas, 28 templates, 10 checklists, 29 perfiles"
- "6+ aliases nuevos (@MANTENIMIENTO_DOCS, @SYNC_BD, @CHK_MANTENIMIENTO, etc.)"
v3_7_0:
fecha: "2026-01-10"
epic: "ESTANDARIZACION-DOC"
cambios:
- "Agregadas 7 directivas de documentacion y estandares"
- "SIMCO-DOCUMENTACION-PROYECTO.md - Estandar base para proyectos"
- "SIMCO-NOMENCLATURA.md - Patrones de nomenclatura"
- "SIMCO-ESTRUCTURA-DOCS.md - Estructura interna de documentos"
- "SIMCO-INVENTARIOS.md - Estandar de inventarios YAML"
- "SIMCO-TESTING.md - Estandares minimos de testing"
- "SIMCO-MIGRACIONES-BD.md - Protocolo de migraciones"
- "SIMCO-INTEGRACIONES-EXTERNAS.md - APIs externas"
- "Agregados 3 templates nuevos"
- "TEMPLATE-INVENTARIO-PROYECTO.md"
- "TEMPLATE-INTEGRACION-EXTERNA.md"
- "TEMPLATE-MODULO-ESTANDAR.md"
- "Agregados 3 checklists nuevos"
- "CHECKLIST-DOCUMENTACION-PROYECTO.md"
- "CHECKLIST-INVENTARIOS.md"
- "CHECKLIST-NOMENCLATURA.md"
- "Creado _MAP.md para directorio checklists"
- "Actualizado conteo: 49 directivas, 27 templates, 8 checklists"
- "15+ aliases nuevos"
v3_6_0:
fecha: "2026-01-10"
epic: "AUDITORIA-DOC"
cambios:
- "Registradas 13 directivas faltantes (subagentes, context, git, decisiones)"
- "Agregados 25+ aliases nuevos"
- "Actualizado conteo total de directivas: 29 -> 42"
- "Nueva seccion operaciones_subagentes"
- "Nueva seccion operaciones_context"
- "Nueva seccion operaciones_git"
- "Nueva seccion operaciones_decisiones"
- "Nueva seccion operaciones_adicionales"
v3_5_0:
fecha: "2026-01-03"
epic: "EPIC-003"
cambios:
- "Agregado SIMCO-ESTRUCTURA-REPOS.md (arquitectura 4 niveles)"
- "Agregado SIMCO-MODULOS-COMPARTIDOS.md (uso de shared/modules)"
- "Agregado SIMCO-MODULOS-COMPARTIDOS.md (uso de core/modules)"
- "Agregado TEMPLATE-MODULO-COMPARTIDO.md"
- "Agregado TEMPLATE-ESTRUCTURA-VERTICAL.md"
- "Agregado CHECKLIST-NUEVO-PROYECTO.md"
- "Agregado validate-repo-structure.sh"
- "Documentados 6 modulos en shared/modules/"
- "Documentados 6 modulos en core/modules/"
- "Actualizado _INDEX.md a v2.4.0"
- "Actualizado ALIASES.yml a v2.4.0"
- "30+ aliases nuevos"

View File

@ -40,7 +40,7 @@ projects/{proyecto}/orchestration/ ← Extensiones por Proyecto
### Acceso Rápido (Rutas Relativas a Este Directorio)
```
../shared/catalog/ # CATÁLOGO DE FUNCIONALIDADES (en core/)
../core/catalog/ # CATÁLOGO DE FUNCIONALIDADES (en core/)
├── CATALOG-INDEX.yml # Índice máquina-readable
├── auth/ # Autenticación y autorización
├── session-management/ # Gestión de sesiones
@ -115,8 +115,8 @@ referencias/
@TPL_CAPVED: templates/TEMPLATE-TAREA-CAPVED.md
# CATÁLOGO DE FUNCIONALIDADES (CONSULTAR PRIMERO)
@CATALOG: shared/catalog/
@CATALOG_INDEX: shared/catalog/CATALOG-INDEX.yml
@CATALOG: core/catalog/
@CATALOG_INDEX: core/catalog/CATALOG-INDEX.yml
# Operaciones
@REUTILIZAR: directivas/simco/SIMCO-REUTILIZAR.md

Some files were not shown because too many files have changed in this diff Show More