Update to Skynet v7 - Complete documentation restructure

- Nueva estructura de carpetas según Skynet v7
- Añadidos schemas SQL completos
- Documentación de entidades, componentes e integraciones
- Modelo de seguridad actualizado
- Infraestructura y operaciones reorganizadas
This commit is contained in:
ARCHITECT
2025-12-29 18:23:41 +00:00
parent ac481fe266
commit 6ea70bd34f
76 changed files with 13029 additions and 4340 deletions

View File

@@ -0,0 +1,205 @@
# Factory Protocol
**Versión:** 1.0
**Estado:** Especificación
---
## Descripción
THE FACTORY es el sistema de generación iterativa. Implementa un ciclo de mejora continua con Director, Executor, Evaluator y Auditor.
```
┌─────────────────────────────────────────────────────────────────┐
│ THE FACTORY │
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ DIRECTOR │───▶│ EXECUTOR │───▶│ EVALUATOR│ │
│ │ (decide) │◀───│ (genera) │◀───│ (evalúa) │ │
│ └────┬─────┘ └──────────┘ └──────────┘ │
│ │ │
│ ▼ │
│ ┌──────────┐ │
│ │ AUDITOR │ ──▶ SENTINEL │
│ │(registra)│ │
│ └──────────┘ │
└─────────────────────────────────────────────────────────────────┘
```
---
## Componentes
### DIRECTOR
Cerebro de THE FACTORY:
- Recibe jobs de Alfred (DECK) o Clara (CORP)
- Selecciona modelos apropiados
- Decide convergencia
- Gestiona presupuesto e iteraciones
```javascript
// Convergencia si:
// - confidence >= 0.85
// - mejora < 0.02 con confidence > 0.7 (rendimientos decrecientes)
const decision = director.decideConvergence(job, evaluation);
```
### EXECUTOR
Genera artefactos según tipo:
| Función | Modelos |
|---------|---------|
| TEXT_GENERATION | claude-sonnet, claude-opus, gpt-4, llama-3 |
| IMAGE_GENERATION | flux-pro, flux-dev, sdxl, dalle-3 |
| CODE_GENERATION | claude-sonnet, claude-opus, gpt-4 |
| DOCUMENT_GENERATION | claude-opus, gpt-4 |
| AUDIO_GENERATION | elevenlabs, bark, xtts |
| VIDEO_GENERATION | runway, pika, stable-video |
### EVALUATOR
Analiza cada artefacto:
```json
{
"confidence": 0.82,
"strengths": ["Cumple estructura básica", "Lenguaje apropiado"],
"weaknesses": ["Falta detalle en sección X"],
"feedback": "Mejorar especificidad y añadir ejemplos."
}
```
### AUDITOR
Registra eventos para trazabilidad:
- `JOB_CREATED` - Inicio del job
- `JOB_STARTED` - Ejecución iniciada
- `ITERATION_COMPLETED` - Cada iteración
- `JOB_COMPLETED` - Finalización
---
## Ciclo de Iteración
```
1. DIRECTOR recibe job
2. DIRECTOR selecciona modelo para EXECUTOR
3. EXECUTOR genera artefacto
4. EVALUATOR evalúa resultado
5. DIRECTOR decide:
- Converge → Finalizar
- No converge → Volver a paso 3 con feedback
6. AUDITOR registra cada paso
```
---
## Request
```json
{
"contract_version": "2.1",
"profile": "FULL",
"routing": {
"module": "FACTORY",
"version": "1.0"
},
"factory": {
"function": "TEXT_GENERATION",
"objective": "Generar artículo sobre IA",
"constraints": {
"max_iterations": 5,
"min_confidence": 0.85,
"max_cost_units": 1.0
},
"context": {
"style": "profesional",
"length": "1500 palabras",
"audience": "técnico"
}
},
"payload": {
"type": "text",
"content": "Brief del artículo..."
}
}
```
---
## Response
```json
{
"result": {
"status": "SUCCESS",
"content": "Artículo generado...",
"content_hash": "sha256"
},
"factory": {
"iterations": 3,
"final_confidence": 0.89,
"model_used": "claude-opus",
"convergence_reason": "confidence_threshold"
},
"audit": {
"job_id": "uuid",
"events": [
{"type": "JOB_CREATED", "ts": "..."},
{"type": "ITERATION_COMPLETED", "iteration": 1, "confidence": 0.72},
{"type": "ITERATION_COMPLETED", "iteration": 2, "confidence": 0.81},
{"type": "ITERATION_COMPLETED", "iteration": 3, "confidence": 0.89},
{"type": "JOB_COMPLETED", "ts": "..."}
]
},
"performance": {
"total_ms": 45000,
"cost_units": 0.45
}
}
```
---
## Convergencia
| Condición | Acción |
|-----------|--------|
| confidence >= threshold | Converge |
| mejora < 0.02 && confidence > 0.7 | Converge (rendimientos decrecientes) |
| iteraciones >= max | Converge forzado |
| costo >= max | Converge forzado |
---
## Configuración
```yaml
factory:
default_max_iterations: 5
default_min_confidence: 0.85
default_max_cost: 1.0
convergence:
confidence_threshold: 0.85
diminishing_returns_threshold: 0.02
diminishing_returns_min_confidence: 0.7
models:
text:
primary: claude-opus
fallback: [claude-sonnet, gpt-4]
image:
primary: flux-pro
fallback: [flux-dev, sdxl]
```

View File

@@ -0,0 +1,125 @@
# GPU Services
**Plataforma:** RunPod
**Estado:** Operativo
---
## Servicios
| Servicio | Endpoint ID | GPU | Workers | Función |
|----------|-------------|-----|---------|---------|
| **Grace** | {grace_id} | NVIDIA L4 | 2 | Procesamiento IA |
| **Penny** | 0mxhaokgsmgee3 | NVIDIA L4 | 2 | Asistente voz |
| **The Factory** | {factory_id} | NVIDIA L4 | 2 | Generación iterativa |
---
## Arquitectura
```
┌─────────────────────────────────────────────────────────────────┐
│ RunPod │
├─────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ GRACE │ │ PENNY │ │ FACTORY │ │
│ │ │ │ │ │ │ │
│ │ 18 módulos │ │ ASR + TTS │ │ Iterativo │ │
│ │ NVIDIA L4 │ │ + Claude │ │ NVIDIA L4 │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────┘
▲ ▲ ▲
│ │ │
└──────────────────┼──────────────────┘
┌───────┴───────┐
│ S-CONTRACT │
│ v2.1 │
└───────────────┘
┌──────────────┴──────────────┐
│ │
┌────┴────┐ ┌────┴────┐
│ DECK │ │ CORP │
│ Alfred │ │ Jared │
└─────────┘ └─────────┘
```
---
## Llamada a Servicio
### URL Base
```
https://api.runpod.ai/v2/{endpoint_id}/runsync
```
### Headers
```
Authorization: Bearer {RUNPOD_API_KEY}
Content-Type: application/json
```
### Request
```json
{
"input": {
"contract": {
"contract_version": "2.1",
"source": { "system": "DECK" },
"target": { "service": "GRACE", "module": "SUMMARIZER" },
"input": { "type": "text", "data": "..." }
}
}
}
```
### Response
```json
{
"id": "job_id",
"status": "COMPLETED",
"output": {
"status": "completed",
"output": { "data": "..." },
"usage": { "cost_usd": 0.002 }
}
}
```
---
## Modos de Ejecución
| Modo | Endpoint | Uso |
|------|----------|-----|
| **runsync** | /runsync | Espera respuesta |
| **run** | /run | Asíncrono, devuelve job_id |
| **status** | /status/{job_id} | Consultar estado |
---
## Costes
| Recurso | Coste |
|---------|-------|
| NVIDIA L4 | ~$0.20/hora |
| Worker idle | $0 (serverless) |
| Por request | Variable según tokens |
---
## Monitoreo
```bash
# Estado de endpoints
curl -H "Authorization: Bearer $RUNPOD_API_KEY" \
https://api.runpod.ai/v2/{endpoint_id}/health
```

162
05_INTEGRACIONES/hst-api.md Normal file
View File

@@ -0,0 +1,162 @@
# HST API
**Base URL:** https://tzrtech.org/api
**Estado:** Implementado
---
## Endpoints
### Listar Tags
```
GET /tags
```
**Query params:**
| Param | Tipo | Descripción |
|-------|------|-------------|
| grupo | string | Filtrar por grupo (hst, spe, vsn, flg, vue) |
| activo | boolean | Solo activos |
| limit | integer | Límite de resultados |
**Response:**
```json
{
"tags": [
{
"ref": "person",
"h_maestro": "a1b2c3...",
"grupo": "hst",
"nombre_es": "Persona",
"nombre_en": "Person",
"imagen_url": "https://tzrtech.org/a1b2c3...png"
}
],
"total": 639
}
```
---
### Obtener Tag
```
GET /tags/{ref}
```
**Response:**
```json
{
"ref": "person",
"h_maestro": "a1b2c3...",
"grupo": "hst",
"nombre_es": "Persona",
"nombre_en": "Person",
"descripcion": "...",
"imagen_url": "https://tzrtech.org/a1b2c3...png",
"activo": true,
"version": 1
}
```
---
### Buscar Tags
```
GET /tags/search?q={query}
```
**Response:**
```json
{
"query": "person",
"results": [
{ "ref": "person", "score": 1.0 },
{ "ref": "people", "score": 0.8 }
]
}
```
---
### Biblioteca de Usuario
```
GET /biblioteca
```
**Headers:**
```
Authorization: Bearer {token}
```
**Response:**
```json
{
"user_id": 123,
"tags": [
{
"ref": "mi_tag",
"h_usuario": "def456...",
"nombre": "Mi Tag Personal"
}
]
}
```
---
### Crear Tag de Usuario
```
POST /biblioteca
```
**Body:**
```json
{
"ref": "mi_tag",
"nombre": "Mi Tag Personal",
"metadata": {}
}
```
**Response:**
```json
{
"ref": "mi_tag",
"h_usuario": "def456...",
"created": true
}
```
---
## Autenticación
| Endpoint | Auth |
|----------|------|
| GET /tags | Pública |
| GET /tags/{ref} | Pública |
| GET /tags/search | Pública |
| GET /biblioteca | Token requerido |
| POST /biblioteca | Token requerido |
---
## Rate Limits
| Tipo | Límite |
|------|--------|
| Público | 100 req/min |
| Autenticado | 1000 req/min |

250
05_INTEGRACIONES/notario.md Normal file
View File

@@ -0,0 +1,250 @@
# Notario
**Versión:** 2.0
**Estado:** Especificación
---
## Descripción
Sistema de sellado inmutable en blockchain. Última capa de confianza del ecosistema.
```
┌─────────────────────────────────────────────────────────────────┐
│ PRINCIPIO NOTARIO │
│ │
│ "Lo que NOTARIO sella, nadie lo altera" │
└─────────────────────────────────────────────────────────────────┘
```
---
## Arquitectura
```
┌─────────────────────────────────────────────────────────────────┐
│ NOTARIO │
├─────────────────────────────────────────────────────────────────┤
│ │
│ Feldman (bloques consolidados) │
│ │ │
│ │ (auditados por SENTINEL) │
│ ▼ │
│ ┌─────────────────┐ │
│ │ BATCH COLLECTOR │ Agrupa por ventana temporal │
│ └─────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ MERKLE BUILDER │ Construye árbol Merkle │
│ └─────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ BLOCKCHAIN TX │ Publica hash raíz │
│ └─────────────────┘ │
│ │ │
│ ▼ │
│ Registro actualizado con blockchain_tx_ref │
│ │
└─────────────────────────────────────────────────────────────────┘
```
---
## Dos Franjas Temporales
### Franja Interna
Tiempo del sistema para:
- Procesar operaciones
- Ejecutar auditoría SENTINEL
- Consolidar en Feldman
**Duración:** Minutos a horas
### Franja Blockchain
Tiempo de NOTARIO para:
- Agrupar registros en batches
- Construir pruebas criptográficas
- Publicar en blockchain
- Confirmar transacciones
**Duración:** Horas a días
---
## Ciclo de Sellado
```
1. RECOLECTAR
SELECT FROM feldman_bloques
WHERE audit_status = 'DEEP_PASS'
AND blockchain_tx_ref IS NULL
2. AGRUPAR
Crear batch con ventana temporal (ej: 24h)
Asignar notario_batch_id
3. CONSTRUIR MERKLE
- Ordenar registros por h_bloque
- Calcular hash de cada registro
- Construir árbol binario
- Obtener merkle_root
4. FIRMAR
- Firmar merkle_root con llave NOTARIO
- Generar timestamp certificado
5. PUBLICAR
- Enviar transacción a blockchain
- Esperar confirmaciones
6. ACTUALIZAR
UPDATE feldman_bloques SET blockchain_tx_ref = tx_hash
```
---
## Schema SQL
```sql
CREATE TABLE notario_batches (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
batch_id UUID UNIQUE NOT NULL,
-- Ventana temporal
window_start TIMESTAMPTZ NOT NULL,
window_end TIMESTAMPTZ NOT NULL,
-- Contenido
records_count INTEGER NOT NULL,
bloque_hashes TEXT[] NOT NULL,
-- Merkle
merkle_root CHAR(64) NOT NULL,
merkle_tree JSONB,
-- Firma
signature TEXT NOT NULL,
signing_key_id VARCHAR(100),
signed_at TIMESTAMPTZ NOT NULL,
-- Blockchain
blockchain_network VARCHAR(50) DEFAULT 'ethereum',
blockchain_tx_ref VARCHAR(100),
blockchain_block BIGINT,
blockchain_timestamp TIMESTAMPTZ,
confirmations INTEGER DEFAULT 0,
-- Estado
status VARCHAR(20) DEFAULT 'PENDING',
created_at TIMESTAMPTZ DEFAULT NOW(),
CONSTRAINT valid_status CHECK (
status IN ('PENDING', 'SUBMITTED', 'CONFIRMED', 'FAILED')
)
);
CREATE INDEX idx_notario_status ON notario_batches(status);
CREATE INDEX idx_notario_window ON notario_batches(window_start, window_end);
```
---
## Verificación de Integridad
```python
def verify_record_integrity(h_bloque, notario_batch_id):
# 1. Obtener batch
batch = get_batch(notario_batch_id)
# 2. Verificar que h_bloque está en el batch
assert h_bloque in batch.bloque_hashes
# 3. Obtener registro de Feldman
record = get_feldman_record(h_bloque)
# 4. Calcular hash del registro
record_hash = sha256(serialize(record))
# 5. Verificar inclusión en merkle tree
proof = get_merkle_proof(batch.merkle_tree, h_bloque)
assert verify_merkle_proof(record_hash, proof, batch.merkle_root)
# 6. Verificar firma del batch
assert verify_signature(
batch.merkle_root,
batch.signature,
batch.signing_key_id
)
# 7. Verificar que merkle_root está en blockchain
tx = get_blockchain_tx(batch.blockchain_tx_ref)
assert tx.data == batch.merkle_root
return True
```
---
## Integración con S-CONTRACT
### Campos en Response (pre-sellado)
```json
"audit": {
"blockchain_pending": true,
"blockchain_tx_ref": null,
"notario_batch_id": "uuid-batch"
}
```
### Campos post-sellado
```json
"audit": {
"blockchain_pending": false,
"blockchain_tx_ref": "0x1234...abcd",
"notario_batch_id": "uuid-batch"
}
```
---
## Configuración
```yaml
notario:
enabled: true
# Ventana de agregación
batch_window_hours: 24
min_records_per_batch: 10
max_records_per_batch: 10000
# Blockchain
network: ethereum
contract_address: "0x..."
gas_limit: 100000
# Firma
signing_key: kv://production/signing/notario
# Reintentos
max_retries: 3
retry_delay_minutes: 60
```
---
## Pendiente
- [ ] Crear tabla notario_batches
- [ ] Implementar recolector de registros
- [ ] Implementar constructor Merkle tree
- [ ] Configurar llave de firma
- [ ] Integrar con proveedor blockchain
- [ ] Implementar verificador de integridad
- [ ] Crear workflow de sellado periódico