"""Autonomous Developer Service — The Self-Healing Loop. This service monitors the server logs for errors and orchestrates the Error Handler and Code Fixer agents to diagnose and propose fixes. """ import os import asyncio from typing import Any, Dict, List, Optional from loguru import logger from app.services.agent_service import call_agent_json, call_agent class AutonomousDevService: """Monitors logs and triggers self-healing cycles. Respects runtime workflow toggles stored in `workflow_configs` table. Caches workflow status in-memory for TTL 15s to avoid DB bursts. """ LOG_FILE = "server.log" _workflow_config_cache: dict = {} # { workflow_name: { 'is_active': bool, 'fetched_at': datetime } } _cache_ttl_seconds = 15 @classmethod async def _fetch_workflow_status_from_db(cls, workflow_name: str) -> bool: """Query DB for workflow status.""" from sqlalchemy import select from app.database import AsyncSessionLocal from app.models.system import WorkflowConfig try: async with AsyncSessionLocal() as session: stmt = select(WorkflowConfig).where(WorkflowConfig.workflow_name == workflow_name) res = await session.execute(stmt) row = res.scalar_one_or_none() if row is None: return False return bool(row.is_active) except Exception as e: logger.error(f"[AutonomousDev] Failed to read workflow config for {workflow_name}: {e}") return False @classmethod async def _is_workflow_active(cls, workflow_name: str) -> bool: """Return cached status if fresh; otherwise refresh from DB.""" from datetime import datetime, timedelta, timezone entry = cls._workflow_config_cache.get(workflow_name) now = datetime.now(timezone.utc) if entry: fetched = entry.get("fetched_at") if fetched and (now - fetched).total_seconds() < cls._cache_ttl_seconds: return entry.get("is_active", False) # Cache miss or stale -> fetch is_active = await cls._fetch_workflow_status_from_db(workflow_name) cls._workflow_config_cache[workflow_name] = {"is_active": is_active, "fetched_at": now} return is_active @classmethod async def monitor_logs(cls): """Background task to watch the log file and trigger workflows if enabled.""" from datetime import datetime, timezone logger.info("[AutonomousDev] Starting log monitor loop...") # Keep track of the last read position last_pos = 0 if os.path.exists(cls.LOG_FILE): last_pos = os.path.getsize(cls.LOG_FILE) while True: try: if os.path.exists(cls.LOG_FILE): current_size = os.path.getsize(cls.LOG_FILE) if current_size > last_pos: with open(cls.LOG_FILE, "r", encoding="utf-8", errors="ignore") as f: f.seek(last_pos) new_content = f.read() last_pos = current_size if "ERROR" in new_content or "Exception" in new_content: # Check workflow toggle before running active = await cls._is_workflow_active("autonomous-dev") if not active: logger.info("[AutonomousDev] autonomous-dev workflow is disabled; skipping healing cycle.") else: await cls.trigger_healing_cycle(new_content) await asyncio.sleep(60) # Check every minute except Exception as e: logger.error(f"[AutonomousDev] Monitor loop error: {e}") await asyncio.sleep(60) @classmethod async def trigger_healing_cycle(cls, error_context: str): """Orchestrate the Error Handler -> Code Fixer flow. Also record last_run on the workflow_configs row. """ from datetime import datetime, timezone from sqlalchemy import update from app.database import AsyncSessionLocal from app.models.system import WorkflowConfig logger.warning("[AutonomousDev] Error detected! Triggering self-healing cycle...") # 1. Error Handler Analysis analysis_prompt = ( f"Analisalah log error berikut dan tentukan akar masalahnya:\n\n{error_context[:2000]}\n\n" "Berikan respon dalam format JSON:\n" "{\n" " \"root_cause\": \"Penjelasan singkat penyebab error\",\n" " \"file_affected\": \"Path file yang bermasalah\",\n" " \"line_number\": \"Baris yang bermasalah (jika ada)\",\n" " \"fix_instructions\": \"Instruksi langkah-demi-langkah untuk Code Fixer\"\n" "}" ) handler_resp = await call_agent_json("cto-agent", analysis_prompt) if not handler_resp["success"]: logger.error("[AutonomousDev] Error Handler failed to analyze.") return analysis = handler_resp["data"] logger.info(f"[AutonomousDev] Root Cause identified: {analysis.get('root_cause')}") # Update last_run in workflow_configs try: async with AsyncSessionLocal() as session: stmt = update(WorkflowConfig).where(WorkflowConfig.workflow_name == "autonomous-dev").values({"last_run": datetime.now(timezone.utc), "updated_at": datetime.now(timezone.utc)}) await session.execute(stmt) await session.commit() except Exception as e: logger.warning(f"[AutonomousDev] Could not update workflow last_run: {e}") # 2. Code Fixer Proposal fix_prompt = ( f"Berdasarkan analisis berikut, buatlah rencana perbaikan kode:\n" f"Akar Masalah: {analysis.get('root_cause')}\n" f"File: {analysis.get('file_affected')}\n" f"Instruksi: {analysis.get('fix_instructions')}\n\n" "Berikan respon berupa potongan kode (diff) atau penjelasan perbaikan yang harus diterapkan." ) fixer_resp = await call_agent("code-fixer", fix_prompt) if fixer_resp["success"]: logger.success(f"[AutonomousDev] Fix proposed by Code Fixer:\n{fixer_resp['reply'][:500]}...") else: logger.error("[AutonomousDev] Code Fixer failed to propose a fix.")