
    iB                    v   d Z ddlmZ ddlZddlZddlZddlmZmZm	Z	 ddl
mZ ddlmZ ddlmZ dd	lmZ dd
lmZ  ej        e          Zddddg ddddddddddddddiddddddg ddddddddddddd dd!d"gd#d$Zd%d&ddd'd(gddd)dd*d"d+gd#d$Zd3d.Z G d/ d0e          Zd4d2ZdS )5uU  hermes-memory-store — holographic memory plugin using MemoryProvider interface.

Registers as a MemoryProvider plugin, giving the agent structured fact storage
with entity resolution, trust scoring, and HRR-based compositional retrieval.

Original plugin by dusterbloom (PR #2351), adapted to the MemoryProvider ABC.

Config in $HERMES_HOME/config.yaml (profile-scoped):
  plugins:
    hermes-memory-store:
      db_path: $HERMES_HOME/memory_store.db   # omit to use the default
      auto_extract: false
      default_trust: 0.5
      min_trust_threshold: 0.3
      temporal_decay_half_life: 0
    )annotationsN)AnyDictList)MemoryProvider)
tool_error   )MemoryStore)FactRetriever)cfg_get
fact_storeu  Deep structured memory with algebraic reasoning. Use alongside the memory tool — memory for always-on context, fact_store for deep recall and compositional queries.

ACTIONS (simple → powerful):
• add — Store a fact the user would expect you to remember.
• search — Keyword lookup ('editor config', 'deploy process').
• probe — Entity recall: ALL facts about a person/thing.
• related — What connects to an entity? Structural adjacency.
• reason — Compositional: facts connected to MULTIPLE entities simultaneously.
• contradict — Memory hygiene: find facts making conflicting claims.
• update/remove/list — CRUD operations.

IMPORTANT: Before answering questions about the user, ALWAYS probe or reason first.objectstring)	addsearchproberelatedreason
contradictupdateremovelist)typeenumz"Fact content (required for 'add').)r   descriptionz%Search query (required for 'search').z"Entity name for 'probe'/'related'.arrayr   zEntity names for 'reason'.)r   itemsr   integerzFact ID for 'update'/'remove'.)	user_prefprojecttoolgeneralzComma-separated tags.numberzTrust adjustment for 'update'.z$Minimum trust filter (default: 0.3).zMax results (default: 10).)actioncontentqueryentityentitiesfact_idcategorytagstrust_delta	min_trustlimitr$   )r   
propertiesrequired)namer   
parametersfact_feedbacku   Rate a fact after using it. Mark 'helpful' if accurate, 'unhelpful' if outdated. This trains the memory — good facts rise, bad facts sink.helpful	unhelpfulzThe fact ID to rate.)r$   r)   r)   returndictc                 (   ddl m}   |             dz  }|                                si S 	 dd l}t	          |          5 }|                    |          pi }d d d            n# 1 swxY w Y   t          |ddi           pi S # t          $ r i cY S w xY w)Nr   get_hermes_homeconfig.yamlpluginshermes-memory-store)default)hermes_constantsr:   existsyamlopen	safe_loadr   	Exception)r:   config_pathrA   f
all_configs        H/home/piyush/.hermes/hermes-agent/plugins/memory/holographic/__init__.py_load_plugin_configrI   a   s   000000!/##m3K 	+ 	1!**0bJ	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1z9.CRPPPVTVV   			s4   B A"B "A&&B )A&*B BBc                      e Zd ZdZd*d+dZed,d            Zd-d
Zd Zd Z	d.dZ
d,dZddd/dZddd0dZd1dZd2dZd3dZd4d#Zd5d$Zd6d&Zd6d'Zd7d)ZdS )8HolographicMemoryProviderzOHolographic memory with structured facts, entity resolution, and HRR retrieval.Nconfigdict | Nonec                    |pt                      | _        d | _        d | _        t	          | j                            dd                    | _        d S )Nmin_trust_threshold333333?)rI   _config_store
_retrieverfloatget
_min_trust)selfrL   s     rH   __init__z"HolographicMemoryProvider.__init__v   sI    6!4!6!6 0 01F L LMM    r6   strc                    dS )Nholographic rW   s    rH   r1   zHolographicMemoryProvider.name|   s    }rY   boolc                    dS )NTr]   r^   s    rH   is_availablez&HolographicMemoryProvider.is_available   s    trY   c                   ddl m}  ||          dz  }	 ddl}i }|                                r>t	          |          5 }|                    |          pi }ddd           n# 1 swxY w Y   |                    di            ||d         d<   t	          |d          5 }|                    ||d	           ddd           dS # 1 swxY w Y   dS # t          $ r Y dS w xY w)
z>Write config to config.yaml under plugins.hermes-memory-store.r   )Pathr;   Nr<   r=   wF)default_flow_style)	pathlibrc   rA   r@   rB   rC   
setdefaultdumprD   )rW   valueshermes_homerc   rE   rA   existingrF   s           rH   save_configz%HolographicMemoryProvider.save_config   s         d;''-7	KKKH!!## 7+&& 7!#~~a006BH7 7 7 7 7 7 7 7 7 7 7 7 7 7 7	2...9?HY 56k3'' A1		(A%	@@@A A A A A A A A A A A A A A A A A A 	 	 	DD	sX   )C A#C #A''C *A'+4C C8C C		C C	C 
C C c                Z    ddl m}  |             d}dd|dddd	d
d	gdddddddddgS )Nr   )display_hermes_home/memory_store.dbdb_pathzSQLite database path)keyr   r>   auto_extractz!Auto-extract facts at session endfalsetrue)rq   r   r>   choicesdefault_trustz!Default trust score for new factsz0.5hrr_dimzHRR vector dimensions1024)r?   rn   )rW   rn   _default_dbs      rH   get_config_schemaz+HolographicMemoryProvider.get_config_schema   s    888888,,..@@@.DQ\]]"3Vcjx~  AH  xI  J  J#4Wdijj.ERXYY	
 	
rY   
session_idNonec                   ddl m} t           |                      }|dz   }| j                            d|          }t          |t                    r,|                    d|          }|                    d|          }t          | j                            dd                    }t          | j                            d	d
                    }t          | j                            dd                    }	t          | j                            dd                    }
t          |||          | _
        t          | j
        |
|	|          | _        || _        d S )Nr   r9   ro   rp   z$HERMES_HOMEz${HERMES_HOME}rv   g      ?rw   i   
hrr_weightrP   temporal_decay_half_life)rp   rv   rw   )storer   r~   rw   )r?   r:   rZ   rQ   rU   
isinstancereplacerT   intr
   rR   r   rS   _session_id)rW   r{   kwargsr:   _hermes_homery   rp   rv   rw   r~   temporal_decays              rH   
initializez$HolographicMemoryProvider.initialize   sO   444444??,,--"%77,""9k:: gs## 	FoonlCCGoo&6EEGdl..DDEEdl&&y$77884<++L#>>??
T\--.H!LLMM!'X_```'+%3!	
 
 
 &rY   c                    | j         sdS 	 | j         j                            d                                          d         }n# t          $ r d}Y nw xY w|dk    r	 dS d| dS )N zSELECT COUNT(*) FROM factsr   u%  # Holographic Memory
Active. Empty fact store — proactively add facts the user would expect you to remember.
Use fact_store(action='add') to store durable structured facts about people, projects, preferences, decisions.
Use fact_feedback to rate facts after using them (trains trust scores).z# Holographic Memory
Active. z facts stored with entity resolution and trust scoring.
Use fact_store to search, probe entities, reason across entities, or add facts.
Use fact_feedback to rate facts after using them (trains trust scores).)rR   _connexecutefetchonerD   )rW   totals     rH   system_prompt_blockz-HolographicMemoryProvider.system_prompt_block   s    { 	2	K%--, hjjEE  	 	 	EEE	A::Z WW W W	
s   7A AAr   )r{   r&   c          
        | j         r|sdS 	 | j                             || j        d          }|sdS g }|D ]\}|                    d|                    dd                    }|                    d|dd	|                    d
d                      ]dd                    |          z   S # t          $ r&}t                              d|           Y d }~dS d }~ww xY w)Nr      )r-   r.   trust_scoretrustr   z- [z.1fz] r%   z## Holographic Memory

zHolographic prefetch failed: %s)	rS   r   rV   rU   appendjoinrD   loggerdebug)rW   r&   r{   resultslinesrr   es           rH   prefetchz"HolographicMemoryProvider.prefetch   s    	e 	2	o,,UdoUV,WWG rE H HmQUU7A->->??F5FFFi0D0DFFGGGG,tyy/?/??? 	 	 	LL:A>>>22222	s   $B, A8B, ,
C6CCuser_contentassistant_contentc                   d S Nr]   )rW   r   r   r{   s       rH   	sync_turnz#HolographicMemoryProvider.sync_turn   s	     	rY   List[Dict[str, Any]]c                    t           t          gS r   )FACT_STORE_SCHEMAFACT_FEEDBACK_SCHEMAr^   s    rH   get_tool_schemasz*HolographicMemoryProvider.get_tool_schemas   s    !#788rY   	tool_nameargsDict[str, Any]c                    |dk    r|                      |          S |dk    r|                     |          S t          d|           S )Nr   r3   zUnknown tool: )_handle_fact_store_handle_fact_feedbackr   )rW   r   r   r   s       rH   handle_tool_callz*HolographicMemoryProvider.handle_tool_call   sW    $$**4000/))--d3336966777rY   messagesc                    | j                             dd          sd S | j        r|sd S |                     |           d S )Nrr   F)rQ   rU   rR   _auto_extract_facts)rW   r   s     rH   on_session_endz(HolographicMemoryProvider.on_session_end   sQ    |66 	F{ 	( 	F  *****rY   r$   targetr%   c                    |dk    re| j         r`|r`	 |dk    rdnd}| j                             ||           dS # t          $ r&}t                              d|           Y d}~dS d}~ww xY wdS dS dS )z'Mirror built-in memory writes as facts.r   userr   r"   r*   z*Holographic memory_write mirror failed: %sN)rR   add_factrD   r   r   )rW   r$   r   r%   r*   r   s         rH   on_memory_writez)HolographicMemoryProvider.on_memory_write   s    U??t{?w?N*0F*:*:;;	$$Wx$@@@@@ N N NI1MMMMMMMMMN	 ?????s   &9 
A)A$$A)c                "    d | _         d | _        d S r   )rR   rS   r^   s    rH   shutdownz"HolographicMemoryProvider.shutdown   s    rY   r7   c                
   	 |d         }| j         }| j        }|dk    r]|                    |d         |                    dd          |                    dd                    }t	          j        |d	d
          S |dk    r|                    |d         |                    d          t          |                    d| j                            t          |                    dd                              }t	          j        |t          |          d          S |dk    rv|                    |d         |                    d          t          |                    dd                              }t	          j        |t          |          d          S |dk    rv|                    |d         |                    d          t          |                    dd                              }t	          j        |t          |          d          S |dk    r|                    dg           }|st          d          S |                    ||                    d          t          |                    dd                              }t	          j        |t          |          d          S |dk    ro|                    |                    d          t          |                    dd                              }t	          j        |t          |          d          S |dk    r|                    t          |d                   |                    d          d|v rt          |d                   nd |                    d          |                    d                    }t	          j        d|i          S |dk    r>|                    t          |d                             }	t	          j        d |	i          S |d!k    r|                    |                    d          t          |                    dd"                    t          |                    dd                              }
t	          j        |
t          |
          d#          S t          d$|           S # t&          $ r}t          d%|           cY d }~S d }~wt(          $ r&}t          t+          |                    cY d }~S d }~ww xY w)&Nr$   r   r%   r*   r"   r+   r   )r*   r+   added)r)   statusr   r&   r-   r.   
   )r*   r-   r.   )r   countr   r'   )r*   r.   r   r   r(   zreason requires 'entities' listr   r   r)   r,   )r%   r,   r+   r*   updatedr   removedr   g        )factsr   zUnknown action: Missing required argument: )rR   rS   r   rU   jsondumpsr   rT   rV   r   lenr   r   r   r   r   update_factremove_fact
list_factsKeyErrorrD   rZ   )rW   r   r$   r   	retrieverr)   r   r(   r   r   r   excs               rH   r   z,HolographicMemoryProvider._handle_fact_store  s   T	((^FKEI..O!XXj)<<&"-- )  
 zg"I"IJJJ8###**M!XXj11#DHH[$/$J$JKKdhhw3344	 +   zgG"M"MNNN7""#//N!XXj11dhhw3344 *  
 zgG"M"MNNN9$$#++N!XXj11dhhw3344 ,  
 zgG"M"MNNN8##88J33 I%&GHHH#**!XXj11dhhw3344 +  
 zgG"M"MNNN<''#..!XXj11dhhw3344 /   zgG"M"MNNN8##++Y(( HHY//>Kt>S>Sd=&9 : : :Y]&))!XXj11 ,   z9g"67778##++CY,@,@AAz9g"67776!!((!XXj11#DHH[#$>$>??dhhw3344 )  
 zECJJ"G"GHHH ""=V"="=>>> 	C 	C 	CACAABBBBBBBB 	( 	( 	(c#hh''''''''	(st   A8R0 ;B"R0 A;R0 A;R0 ,R0 A/R0 3A4R0 (BR0 AR0 BR0 R0 0
T:STTS?9T?Tc                T   	 t          |d                   }|d         dk    }| j                            ||          }t          j        |          S # t
          $ r}t          d|           cY d }~S d }~wt          $ r&}t          t          |                    cY d }~S d }~ww xY w)Nr)   r$   r4   )r4   r   )	r   rR   record_feedbackr   r   r   r   rD   rZ   )rW   r   r)   r4   resultr   s         rH   r   z/HolographicMemoryProvider._handle_fact_feedbackZ  s    	($y/**G8n	1G[00'0JJF:f%%% 	C 	C 	CACAABBBBBBBB 	( 	( 	(c#hh''''''''	(s0   AA 
B'A4.B'4B'B"B'"B'r   c                   t          j        dt           j                  t          j        dt           j                  t          j        dt           j                  g}t          j        dt           j                  t          j        dt           j                  g}d}|D ]
}|                    d          dk    r|                    d	d
          }t	          |t
                    rt          |          dk     r\|D ]T}|                    |          r=	 | j        	                    |d d         d           |dz  }n# t          $ r Y nw xY w nU|D ]T}|                    |          r=	 | j        	                    |d d         d           |dz  }n# t          $ r Y nw xY w nU|rt                              d|           d S d S )Nz/\bI\s+(?:prefer|like|love|use|want|need)\s+(.+)z7\bmy\s+(?:favorite|preferred|default)\s+\w+\s+is\s+(.+)z%\bI\s+(?:always|never|usually)\s+(.+)z0\bwe\s+(?:decided|agreed|chose)\s+(?:to\s+)?(.+)z0\bthe\s+project\s+(?:uses|needs|requires)\s+(.+)r   roler   r%   r   r   i  r   r   r	   r    z)Auto-extracted %d facts from conversation)recompile
IGNORECASErU   r   rZ   r   r   rR   r   rD   r   info)rW   r   _PREF_PATTERNS_DECISION_PATTERNS	extractedmsgr%   patterns           rH   r   z-HolographicMemoryProvider._auto_extract_factsg  s
   JI2=YYJQSUS`aaJ?OO
 JJBMZZJJBMZZ

 	 	 	Cwwv&((ggi,,Ggs++ s7||b/@/@)  >>'** ,,WTcT][,QQQ!Q		$   E .  >>'** ,,WTcT]Y,OOO!Q		$   E  	PKKCYOOOOO	P 	Ps$   )D??
EE,)F
F#"F#r   )rL   rM   )r6   rZ   )r6   r_   )r{   rZ   r6   r|   )r&   rZ   r{   rZ   r6   rZ   )r   rZ   r   rZ   r{   rZ   r6   r|   )r6   r   )r   rZ   r   r   r6   rZ   )r   r   r6   r|   )r$   rZ   r   rZ   r%   rZ   r6   r|   r6   r|   )r   r7   r6   rZ   )r   r   r6   r|   )__name__
__module____qualname____doc__rX   propertyr1   ra   rl   rz   r   r   r   r   r   r   r   r   r   r   r   r   r]   rY   rH   rK   rK   s   s       YYN N N N N    X     "
 
 
& & & &2
 
 
 
. 9;        Y[      
9 9 9 98 8 8 8+ + + +N N N N   U( U( U( U(n	( 	( 	( 	(&P &P &P &P &P &PrY   rK   r|   c                l    t                      }t          |          }|                     |           dS )z@Register the holographic memory provider with the plugin system.)rL   N)rI   rK   register_memory_provider)ctxrL   providers      rH   registerr     s7     ""F(777H  *****rY   )r6   r7   r   )r   
__future__r   r   loggingr   typingr   r   r   agent.memory_providerr   tools.registryr   r   r
   	retrievalr   hermes_cli.configr   	getLoggerr   r   r   r   rI   rK   r   r]   rY   rH   <module>r      sd   " # " " " " "   				 " " " " " " " " " " 0 0 0 0 0 0 % % % % % %       $ $ $ $ $ $ % % % % % %		8	$	$ 	^  !qqq  !)9]^^&7^__'8\]]!(FH3EVrss ):Z[[!)3^3^3^__%6MNN$,=]^^"*;abb'8TUU
 
  J% !$ $ N 	F ')[1IJJ ):PQQ
 
 y)   *   $ZP ZP ZP ZP ZP ZP ZP ZPB	+ + + + + +rY   