File size: 2,494 Bytes
03e5649
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""
intuition_engine.py — S-SIXTH-SENSE: Neural Heuristic Mapping.
Il "Sesto Senso" dell'agente: trasforma l'esperienza passata in istinto operativo.
Non è un RAG testuale, ma un estrattore di euristiche e pattern di successo/fallimento.
"""
import json
import os
import logging
from typing import List, Dict, Any

_logger = logging.getLogger("agente_ai.intuition")

class IntuitionEngine:
    def __init__(self, snapshot_path: str = ".agents/memory/cognitive_snapshot.json"):
        self.snapshot_path = snapshot_path
        self.heuristics = self._load_heuristics()

    def _load_heuristics(self) -> Dict[str, Any]:
        """Carica le euristiche scoperte e i fallimenti dai Cognitive Snapshots."""
        if os.path.exists(self.snapshot_path):
            try:
                with open(self.snapshot_path, "r") as f:
                    return json.load(f)
            except Exception as e:
                _logger.error(f"Errore caricamento snapshot: {e}")
        return {}

    def get_instinct(self, goal: str) -> str:
        """Estrae 'saggezza operativa' basata sul goal attuale e l'esperienza passata."""
        goal_lower = goal.lower()
        instincts = []

        # 1. Analisi dei fallimenti passati (Evita di ripetere errori)
        failed_goals = self.heuristics.get("failed_goals_since_last_success", [])
        for fg in failed_goals:
            if any(word in goal_lower for word in fg.lower().split()):
                instincts.append(f"ATTENZIONE: Un task simile ('{fg}') è fallito recentemente. Analizza bene il motivo del fallimento prima di procedere.")

        # 2. Applicazione di euristiche scoperte
        discovered = self.heuristics.get("discovered_heuristics", [])
        for h in discovered:
            # Se l'euristica è pertinente al goal (semplice keyword match per velocità)
            if any(word in goal_lower for word in h.lower().split() if len(word) > 4):
                instincts.append(f"EURISTICA ATTIVA: {h}")

        # 3. Sentiment e Performance Insights
        sentiment = self.heuristics.get("code_sentiment", "neutrale")
        if sentiment == "complesso":
            instincts.append("NOTA: Il codice recente è stato valutato come complesso. Cerca di semplificare l'architettura in questo ciclo.")

        if not instincts:
            return ""

        return "\n\n🧠 SESTO SENSO (Esperienza Passata):\n" + "\n".join(f"• {i}" for i in instincts)

# Singleton per uso globale
intuition = IntuitionEngine()