Files
Autonomous-Bug-Explorer/.ralph/PROMPT.md

6.2 KiB

ABE — Autonomous Bug Explorer

Instrucciones Maestras para Claude Code (via Ralph)


Visión del proyecto

ABE es una plataforma enterprise self-hosted de descubrimiento autónomo de bugs en aplicaciones web. Explora apps como un usuario real, inyecta inputs inválidos (fuzzing), detecta anomalías, y genera bug reports reproducibles.

Posicionamiento: "Playwright discovers what you test. ABE discovers what you miss."

Modelo open-core enterprise self-hosted:

  • Free/OSS: exploración autónoma + reports básicos
  • Pro: dashboards avanzados, integraciones, CLI/CI
  • Enterprise: SSO, RBAC avanzado, LDAP, audit logs, licencia

Estado actual del código

Las fases 1-11 del proyecto original están implementadas con esta estructura:

src/
├── core/           ← interfaces.ts, ExplorationEngine, StateGraph, AnomalyDetector
├── plugins/        ← PlaywrightAgent, collectors, exporters, fuzzers, reproducers
├── server/         ← Express API server + socket.io
├── db/             ← SQLite repositories (better-sqlite3)
├── cli.ts          ← CLI entry point
frontend/           ← React + Vite + Tailwind (básico)

El objetivo es REFACTORIZAR este código existente hacia una arquitectura modular hexagonal, migrando pieza por pieza sin romper funcionalidad.

ESTRATEGIA DE MIGRACIÓN: No reescribir de cero. Mover código existente a la nueva estructura, adaptar interfaces, y verificar que todo sigue funcionando después de cada movimiento.


Arquitectura objetivo: Modular Monolith Hexagonal

Principio fundamental

Infrastructure → Application → Domain
(el código SIEMPRE apunta hacia adentro, nunca al revés)

Estructura de carpetas OBJETIVO

src/
├── shared/
│   ├── domain/
│   │   ├── Entity.ts
│   │   ├── AggregateRoot.ts
│   │   ├── ValueObject.ts
│   │   ├── UniqueId.ts
│   │   ├── Result.ts
│   │   └── DomainEvent.ts
│   ├── application/
│   │   ├── UseCase.ts
│   │   ├── EventBus.ts
│   │   └── EventHandler.ts
│   └── infrastructure/
│       ├── InProcessEventBus.ts
│       ├── DatabaseConnection.ts
│       ├── Logger.ts
│       ├── Config.ts
│       └── StorageProvider.ts
│
├── modules/
│   ├── crawling/
│   │   ├── domain/        (entities, value-objects, events, ports)
│   │   ├── application/   (commands, queries, event-handlers)
│   │   └── infrastructure/(adapters, repositories, http)
│   ├── fuzzing/           (misma estructura)
│   ├── findings/          (misma estructura)
│   ├── auth/              (misma estructura)
│   ├── reporting/         (misma estructura)
│   ├── integrations/      (misma estructura)
│   ├── scheduling/        (misma estructura)
│   └── licensing/         (misma estructura)
│
├── api/
│   ├── server.ts
│   ├── router.ts
│   └── middleware/
├── realtime/
│   └── SocketGateway.ts
├── jobs/
│   ├── JobQueue.ts
│   ├── SQLiteJobQueue.ts
│   └── workers/
├── cli/
│   └── abe.ts
└── main.ts               ← composition root

Reglas de arquitectura INQUEBRANTABLES

  1. Domain layer NO importa nada externo — ni Kysely, ni Express, ni Playwright.
  2. Cross-module communication SOLO via EventBus — NUNCA import directo entre módulos.
  3. Cada módulo exporta SOLO su facade via index.ts.
  4. Controllers son THIN — parsean request, llaman use case, formatean response.
  5. Use Cases retornan Result<T, E> — NUNCA throw para errores de negocio.
  6. Un archivo = una clase = una responsabilidad.
  7. Determinista — no usar Math.random() sin seed. Loguear siempre el seed.
  8. Serializable — entities y value objects JSON.stringify-able.
  9. No AI en el core loop — AIEnrichment es post-proceso opcional.
  10. Plugins nunca se importan desde core — core solo define interfaces/ports.

Stack tecnológico

Backend

  • Runtime: Node.js 20 + TypeScript 5.x (strict mode)
  • HTTP: Express.js 4.x
  • WebSocket: socket.io 4.x
  • Database: Kysely (query builder) + better-sqlite3 (default) | pg (enterprise)
  • Validation: Zod (schemas compartidos frontend/backend)
  • Auth: Better Auth + CASL
  • Browser: Playwright
  • Logger: Pino + pino-pretty (dev)
  • Jobs: SQLite-backed queue custom con worker_threads
  • Scheduler: node-cron
  • Security: Helmet, express-rate-limit, cors
  • API docs: zod-to-openapi + Scalar UI
  • Testing: Vitest + supertest (integration)

Frontend

  • React 18 + Vite + TypeScript
  • shadcn/ui (Radix UI + Tailwind CSS)
  • Tremor + Recharts (charts/dashboards)
  • TanStack Table + TanStack Query
  • Zustand (client state)
  • React Hook Form + Zod resolver
  • socket.io-client
  • Framer Motion

REGLAS OBLIGATORIAS PARA CADA TAREA

Antes de empezar

  1. Leer la tarea actual del fix_plan.md
  2. Leer la spec correspondiente en .ralph/specs/ SI existe
  3. Verificar que las dependencias (tareas previas) están completas

Después de CADA tarea individual

  1. npm run build — DEBE compilar sin errores
  2. cd frontend && npm run build — DEBE compilar sin errores
  3. npm run test — DEBE pasar (o no romper tests existentes)
  4. Si ALGUNO falla → NO marcar tarea → arreglar PRIMERO

Después de marcar tarea como completa

  1. git add -A
  2. git commit -m "fase(X.Y): descripción breve de la tarea" Ejemplo: git commit -m "fase(1.3): create ValueObject base class with equals"
  3. Verificar que el commit se hizo correctamente

Reglas de código

  • Todo nuevo código DEBE tener tipos explícitos (CERO any)
  • Imports ordenados: node_modules → shared → modules → relative
  • Nombres: PascalCase para clases, camelCase para funciones/variables
  • Cada módulo nuevo DEBE tener al menos un test unitario
  • Código existente que se MUEVE debe seguir funcionando igual

Señal de completado

Cuando TODAS las tareas en fix_plan.md estén marcadas [x]:

RALPH_STATUS: completion_indicators: done EXIT_SIGNAL: true summary: "ABE enterprise refactor complete."