# TRACEABILITY.yml - OQI-007 LLM Strategy Agent
# Mapeo de requerimientos a implementación

version: "1.1.0"
epic: OQI-007
name: "LLM Strategy Agent (Copilot)"
updated: "2026-01-28"
status: in_progress

# Resumen de trazabilidad
summary:
  total_requirements: 6
  total_specs: 7
  total_user_stories: 11
  total_files_to_implement: 48
  test_coverage: "15%"
  story_points: 60
  implementation_progress: "45%"
  documentation_progress: "100%"
  phase: 2

# Mapeo de Requerimientos Funcionales
requirements:
  RF-LLM-001:
    name: "Chat Interface"
    status: planned
    specs:
      - ET-LLM-001
      - ET-LLM-005
    user_stories:
      - US-LLM-001
      - US-LLM-002
    implementation:
      backend:
        - path: apps/backend/src/modules/copilot/services/chat.service.ts
          description: "Servicio de chat con LLM"
          methods:
            - sendMessage
            - getConversation
            - getConversations
            - clearConversation
            - regenerateResponse
        - path: apps/backend/src/modules/copilot/controllers/copilot.controller.ts
          methods:
            - chat
            - getConversations
            - getConversation
            - deleteConversation
        - path: apps/backend/src/modules/copilot/copilot.routes.ts
          routes:
            - "POST /copilot/chat"
            - "GET /copilot/conversations"
            - "GET /copilot/conversations/:id"
            - "DELETE /copilot/conversations/:id"
      frontend:
        - path: apps/frontend/src/modules/copilot/pages/Copilot.tsx
          description: "Página principal del Copilot"
        - path: apps/frontend/src/modules/copilot/components/ChatInterface.tsx
          description: "Interfaz de chat"
        - path: apps/frontend/src/modules/copilot/components/MessageBubble.tsx
          description: "Burbuja de mensaje"
        - path: apps/frontend/src/modules/copilot/components/ChatInput.tsx
          description: "Input de chat"
        - path: apps/frontend/src/modules/copilot/components/ConversationList.tsx
          description: "Lista de conversaciones"
      database:
        - path: apps/database/schemas/07_llm_schema.sql
          tables:
            - conversations
            - messages
            - message_feedback
          enums:
            - message_role_enum
            - feedback_type_enum
    tests:
      - path: apps/backend/tests/copilot/chat.service.test.ts
        status: planned

  RF-LLM-002:
    name: "Market Analysis"
    status: planned
    specs:
      - ET-LLM-002
      - ET-LLM-003
    user_stories:
      - US-LLM-003
      - US-LLM-004
    implementation:
      backend:
        - path: apps/backend/src/modules/copilot/services/analysis.service.ts
          description: "Servicio de análisis de mercado"
          methods:
            - analyzeSymbol
            - analyzeTrend
            - analyzeNews
            - generateInsights
            - compareSymbols
        - path: apps/backend/src/modules/copilot/agents/market-analyst.agent.ts
          description: "Agente especializado en análisis"
        - path: apps/backend/src/modules/copilot/copilot.routes.ts
          routes:
            - "POST /copilot/analyze/:symbol"
            - "GET /copilot/insights/:symbol"
            - "POST /copilot/compare"
      frontend:
        - path: apps/frontend/src/modules/copilot/components/AnalysisPanel.tsx
          description: "Panel de análisis"
        - path: apps/frontend/src/modules/copilot/components/InsightCard.tsx
          description: "Tarjeta de insight"
        - path: apps/frontend/src/modules/copilot/components/SymbolAnalysis.tsx
          description: "Análisis de símbolo"
      database:
        - path: apps/database/schemas/07_llm_schema.sql
          tables:
            - analysis_cache
            - insights
    tests:
      - path: apps/backend/tests/copilot/analysis.service.test.ts
        status: planned

  RF-LLM-003:
    name: "Strategy Suggestions"
    status: planned
    specs:
      - ET-LLM-002
      - ET-LLM-004
    user_stories:
      - US-LLM-005
      - US-LLM-006
    implementation:
      backend:
        - path: apps/backend/src/modules/copilot/services/strategy.service.ts
          description: "Servicio de sugerencias de estrategia"
          methods:
            - suggestStrategy
            - evaluateStrategy
            - optimizeStrategy
            - backtestStrategy
            - getStrategies
        - path: apps/backend/src/modules/copilot/agents/strategy-advisor.agent.ts
          description: "Agente de estrategias"
        - path: apps/backend/src/modules/copilot/copilot.routes.ts
          routes:
            - "POST /copilot/strategy/suggest"
            - "POST /copilot/strategy/evaluate"
            - "POST /copilot/strategy/backtest"
      frontend:
        - path: apps/frontend/src/modules/copilot/components/StrategySuggestion.tsx
          description: "Sugerencia de estrategia"
        - path: apps/frontend/src/modules/copilot/components/StrategyBuilder.tsx
          description: "Constructor de estrategia"
        - path: apps/frontend/src/modules/copilot/components/BacktestResults.tsx
          description: "Resultados de backtest"
      database:
        - path: apps/database/schemas/07_llm_schema.sql
          tables:
            - strategy_suggestions
            - backtest_results
    tests:
      - path: apps/backend/tests/copilot/strategy.service.test.ts
        status: planned

  RF-LLM-004:
    name: "Educational Assistance"
    status: planned
    specs:
      - ET-LLM-005
    user_stories:
      - US-LLM-007
    implementation:
      backend:
        - path: apps/backend/src/modules/copilot/services/tutor.service.ts
          description: "Servicio de tutoría"
          methods:
            - explainConcept
            - answerQuestion
            - generateQuiz
            - recommendCourse
            - explainIndicator
        - path: apps/backend/src/modules/copilot/agents/tutor.agent.ts
          description: "Agente tutor"
        - path: apps/backend/src/modules/copilot/copilot.routes.ts
          routes:
            - "POST /copilot/tutor/explain"
            - "POST /copilot/tutor/quiz"
            - "GET /copilot/tutor/recommendations"
      frontend:
        - path: apps/frontend/src/modules/copilot/components/TutorChat.tsx
          description: "Chat de tutoría"
        - path: apps/frontend/src/modules/copilot/components/ConceptExplainer.tsx
          description: "Explicador de conceptos"
      database:
        - path: apps/database/schemas/07_llm_schema.sql
          tables:
            - learning_interactions
    tests:
      - path: apps/backend/tests/copilot/tutor.service.test.ts
        status: planned

  RF-LLM-005:
    name: "Tool Integration"
    status: planned
    specs:
      - ET-LLM-003
      - ET-LLM-006
    user_stories:
      - US-LLM-008
      - US-LLM-009
    implementation:
      backend:
        - path: apps/backend/src/modules/copilot/tools/chart-tool.ts
          description: "Herramienta de charts"
          functions:
            - getChartData
            - addIndicator
            - drawTrendline
            - setTimeframe
        - path: apps/backend/src/modules/copilot/tools/order-tool.ts
          description: "Herramienta de órdenes"
          functions:
            - previewOrder
            - createOrder
            - modifyOrder
            - cancelOrder
        - path: apps/backend/src/modules/copilot/tools/research-tool.ts
          description: "Herramienta de investigación"
          functions:
            - searchNews
            - getEarnings
            - getFundamentals
            - getSentiment
        - path: apps/backend/src/modules/copilot/tools/portfolio-tool.ts
          description: "Herramienta de portfolio"
          functions:
            - getPositions
            - getPerformance
            - analyzeRisk
        - path: apps/backend/src/modules/copilot/services/tool-executor.service.ts
          description: "Ejecutor de herramientas"
      frontend:
        - path: apps/frontend/src/modules/copilot/components/ToolOutput.tsx
          description: "Output de herramientas"
        - path: apps/frontend/src/modules/copilot/components/ActionPreview.tsx
          description: "Preview de acción"
        - path: apps/frontend/src/modules/copilot/components/ConfirmAction.tsx
          description: "Confirmación de acción"
      database:
        - path: apps/database/schemas/07_llm_schema.sql
          tables:
            - tool_executions
            - tool_audit_log
    tests:
      - path: apps/backend/tests/copilot/tools.test.ts
        status: planned

  RF-LLM-006:
    name: "Context Management"
    status: planned
    specs:
      - ET-LLM-001
      - ET-LLM-004
    user_stories:
      - US-LLM-010

  # Nueva: Trading Execution via Chat
  RF-LLM-007:
    name: "Trading Execution via Chat"
    status: planned
    specs:
      - ET-LLM-005
      - ET-LLM-007
    user_stories:
      - US-LLM-011
    implementation:
      backend:
        - path: apps/backend/src/modules/copilot/services/context.service.ts
          description: "Servicio de gestión de contexto"
          methods:
            - buildContext
            - getMarketContext
            - getUserContext
            - getHistoricalContext
            - summarizeConversation
        - path: apps/backend/src/modules/copilot/services/memory.service.ts
          description: "Servicio de memoria"
          methods:
            - storeMemory
            - retrieveMemories
            - forgetMemory
            - updateMemory
        - path: apps/backend/src/modules/copilot/prompts/system-prompts.ts
          description: "System prompts por contexto"
      database:
        - path: apps/database/schemas/07_llm_schema.sql
          tables:
            - user_memories
            - context_snapshots
    tests:
      - path: apps/backend/tests/copilot/context.service.test.ts
        status: planned

# Agentes especializados
agents:
  - name: Market Analyst
    role: "Análisis técnico y fundamental"
    tools: [chart-tool, research-tool]
    prompt_template: market_analyst_prompt.md
  - name: Strategy Advisor
    role: "Sugerencias de estrategia"
    tools: [chart-tool, portfolio-tool]
    prompt_template: strategy_advisor_prompt.md
  - name: Trading Tutor
    role: "Educación y explicaciones"
    tools: [chart-tool]
    prompt_template: tutor_prompt.md
  - name: Order Assistant
    role: "Ayuda con órdenes"
    tools: [order-tool, chart-tool]
    prompt_template: order_assistant_prompt.md

# Mapeo de archivos de configuración
config_files:
  backend:
    - path: apps/backend/src/modules/copilot/copilot.module.ts
      description: "Módulo de Copilot"
    - path: apps/backend/src/modules/copilot/types/copilot.types.ts
      description: "Tipos TypeScript"
    - path: apps/backend/src/config/llm.config.ts
      description: "Configuración de LLM"
    - path: apps/backend/src/modules/copilot/prompts/
      description: "Directorio de prompts"
  frontend:
    - path: apps/frontend/src/modules/copilot/stores/copilot.store.ts
      description: "Store de Copilot Zustand"
    - path: apps/frontend/src/modules/copilot/hooks/useCopilot.ts
      description: "Hook principal de Copilot"
    - path: apps/frontend/src/modules/copilot/services/copilot.api.ts
      description: "Cliente API de Copilot"

# Dependencias externas
external_dependencies:
  npm_backend:
    - name: openai
      version: "^4.20.0"
      usage: "OpenAI API client"
    - name: "@anthropic-ai/sdk"
      version: "^0.9.0"
      usage: "Claude API client"
    - name: langchain
      version: "^0.0.200"
      usage: "LLM framework"
    - name: "@pinecone-database/pinecone"
      version: "^2.0.0"
      usage: "Vector database"
  npm_frontend:
    - name: react-markdown
      version: "^9.0.0"
      usage: "Renderizar respuestas markdown"
    - name: prismjs
      version: "^1.29.0"
      usage: "Syntax highlighting"

# APIs de terceros
third_party_apis:
  - name: OpenAI API
    docs: https://platform.openai.com/docs
    models:
      - gpt-4-turbo
      - gpt-4-vision
    usage:
      - Chat completions
      - Function calling
      - Embeddings
  - name: Anthropic Claude
    docs: https://docs.anthropic.com
    models:
      - claude-3-opus
      - claude-3-sonnet
    usage:
      - Análisis complejo
      - Respuestas largas
  - name: Pinecone
    docs: https://docs.pinecone.io
    usage:
      - Vector storage
      - Similarity search
      - Memory retrieval

# Endpoints API
api_endpoints:
  base_path: /api/v1/copilot
  endpoints:
    # Chat
    - method: POST
      path: /chat
      requirement: RF-LLM-001
      auth: true
      description: "Enviar mensaje"
    - method: GET
      path: /conversations
      requirement: RF-LLM-001
      auth: true
    - method: GET
      path: /conversations/:id
      requirement: RF-LLM-001
      auth: true
    - method: DELETE
      path: /conversations/:id
      requirement: RF-LLM-001
      auth: true
    # Análisis
    - method: POST
      path: /analyze/:symbol
      requirement: RF-LLM-002
      auth: true
    - method: GET
      path: /insights/:symbol
      requirement: RF-LLM-002
      auth: true
    # Estrategias
    - method: POST
      path: /strategy/suggest
      requirement: RF-LLM-003
      auth: true
    - method: POST
      path: /strategy/backtest
      requirement: RF-LLM-003
      auth: true
    # Tutor
    - method: POST
      path: /tutor/explain
      requirement: RF-LLM-004
      auth: true
    # Acciones
    - method: POST
      path: /action/preview
      requirement: RF-LLM-005
      auth: true
    - method: POST
      path: /action/execute
      requirement: RF-LLM-005
      auth: true

# WebSocket para streaming
websocket_endpoints:
  - channel: "copilot"
    events:
      - "message_start"
      - "message_delta"
      - "message_end"
      - "tool_call"
      - "tool_result"
      - "error"

# Dependencias de épicas
dependencies:
  blocks: []
  blocked_by:
    - epic: OQI-001
      reason: "Requiere autenticación"
    - epic: OQI-003
      reason: "Necesita datos de trading para análisis"
    - epic: OQI-006
      reason: "Integra señales ML en respuestas"

# Rate limiting
rate_limits:
  free_tier:
    messages_per_day: 10
    tokens_per_message: 2000
  pro_tier:
    messages_per_day: 100
    tokens_per_message: 4000
  premium_tier:
    messages_per_day: unlimited
    tokens_per_message: 8000

# Notas y decisiones
notes:
  - "Streaming de respuestas vía WebSocket"
  - "Function calling para ejecutar herramientas"
  - "Contexto de mercado actualizado en tiempo real"
  - "Memoria de conversación con vector embeddings"
  - "Fallback a modelos más económicos si cuota excedida"
  - "Audit log de todas las acciones ejecutadas"
  - "Confirmación obligatoria para órdenes reales"
