
    `gjE                    r   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d0d,Z G d- d.e      Zd1d/Zy)2uU  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)   c                    ddl m}   |        dz  }|j                         si S 	 dd l}t	        |d      5 }|j                  |      xs i }d d d        t        ddi       xs i S # 1 sw Y   xY w# t        $ r i cY S w xY w)	Nr   get_hermes_homeconfig.yaml	utf-8-sigencodingpluginshermes-memory-store)default)hermes_constantsr8   existsyamlopen	safe_loadr   	Exception)r8   config_pathrB   f
all_configs        V/root/.hermes/venv/lib/python3.12/site-packages/plugins/memory/holographic/__init__.py_load_plugin_configrJ   a   s    0!#m3K	+4 	1*0bJ	1z9.CRPVTVV	1 	1  	s(   A2 A&A2 &A/+A2 2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ddZddZddZddZd dZd!dZd"dZd"dZd#dZy)$HolographicMemoryProviderzOHolographic memory with structured facts, entity resolution, and HRR retrieval.Nc                    |xs
 t               | _        d | _        d | _        t	        | j                  j                  dd            | _        y )Nmin_trust_threshold333333?)rJ   _config_store
_retrieverfloatget
_min_trust)selfconfigs     rI   __init__z"HolographicMemoryProvider.__init__v   s>    6!4!6 0 01F LM    c                     y)Nholographic rV   s    rI   r1   zHolographicMemoryProvider.name|   s    rY   c                     y)NTr\   r]   s    rI   is_availablez&HolographicMemoryProvider.is_available   s    rY   c                   ddl m}  ||      dz  }	 ddl}i }|j                         r+t	        |d      5 }|j                  |      xs i }ddd       |j                  di        ||d   d<   t	        |d	d
      5 }|j                  ||d       ddd       y# 1 sw Y   OxY w# 1 sw Y   yxY w# t        $ r Y yw xY w)z>Write config to config.yaml under plugins.hermes-memory-store.r   )Pathr9   Nr:   r;   r=   r>   wzutf-8F)default_flow_style)	pathlibra   rB   rA   rC   rD   
setdefaultdumprE   )rV   valueshermes_homera   rF   rB   existingrG   s           rI   save_configz%HolographicMemoryProvider.save_config   s     ;'-7	H!!#+< 7#~~a06BH7	2.9?HY 56k39 AQ		(A%	@A A	7 7A A 		sF   #B2 B0B2 <B&B2 B#B2 &B/+B2 /B2 2	B>=B>c                T    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)ro   r   r?   choicesdefault_trustz!Default trust score for new factsz0.5hrr_dimzHRR vector dimensions1024)r@   rl   )rV   rl   _default_dbs      rI   get_config_schemaz+HolographicMemoryProvider.get_config_schema   sd    8,.//?@.DQ\]"3Vcjx~  AH  xI  J#4Wdij.ERXY	
 	
rY   c                r   ddl m} t         |             }|dz   }| j                  j	                  d|      }t        |t              r$|j                  d|      }|j                  d|      }t        | j                  j	                  dd            }t        | j                  j	                  d	d
            }t        | j                  j	                  dd            }	t        | j                  j	                  dd            }
t        |||      | _
        t        | j                  |
|	|      | _        || _        y )Nr   r7   rm   rn   z$HERMES_HOMEz${HERMES_HOME}rt   g      ?ru   i   
hrr_weightrO   temporal_decay_half_life)rn   rt   ru   )storer{   rz   ru   )r@   r8   strrP   rT   
isinstancereplacerS   intr
   rQ   r   rR   _session_id)rV   
session_idkwargsr8   _hermes_homerw   rn   rt   ru   rz   temporal_decays              rI   
initializez$HolographicMemoryProvider.initialize   s   4?,-"%77,,""9k: gs#oonlCGoo&6EGdll..DEdll&&y$784<<++L#>?
T\\--.H!LM!'X_`'++%3!	
 &rY   c                    | j                   sy	 | j                   j                  j                  d      j                         d   }|dk(  r	 yd| dS # t        $ r d}Y w xY w)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).)rQ   _connexecutefetchonerE   )rV   totals     rI   system_prompt_blockz-HolographicMemoryProvider.system_prompt_block   s    {{	KK%%--,hjE
 A:Zg VW	
  	E	s   6A A A r   )r   c          
        | j                   r|sy	 | j                   j                  || j                  d      }|syg }|D ]L  }|j                  d|j                  dd            }|j	                  d|dd	|j                  d
d              N ddj                  |      z   S # t        $ r }t        j                  d|       Y d }~yd }~ww xY w)Nr      )r-   r.   trust_scoretrustr   z- [z.1fz] r%   z## Holographic Memory

zHolographic prefetch failed: %s)	rR   r   rU   rT   appendjoinrE   loggerdebug)rV   r&   r   resultslinesrr   es           rI   prefetchz"HolographicMemoryProvider.prefetch   s    e	oo,,UdooUV,WGE HmQUU7A->?s5+Ri0D/EFGH -tyy/??? 	LL:A>	s   *B# A&B# #	C,CCc                    y Nr\   )rV   user_contentassistant_contentr   s       rI   	sync_turnz#HolographicMemoryProvider.sync_turn   s     	rY   c                    t         t        gS r   )FACT_STORE_SCHEMAFACT_FEEDBACK_SCHEMAr]   s    rI   get_tool_schemasz*HolographicMemoryProvider.get_tool_schemas   s    !#788rY   c                v    |dk(  r| j                  |      S |dk(  r| j                  |      S t        d|       S )Nr   r3   zUnknown tool: )_handle_fact_store_handle_fact_feedbackr   )rV   	tool_nameargsr   s       rI   handle_tool_callz*HolographicMemoryProvider.handle_tool_call   sF    $**400/)--d33N9+677rY   c                ~    | j                   j                  dd      sy | j                  r|sy | j                  |       y )Nrp   F)rP   rT   rQ   _auto_extract_facts)rV   messagess     rI   on_session_endz(HolographicMemoryProvider.on_session_end   s3    ||6{{(  *rY   c                    |dk(  r8| j                   r+|r(	 |dk(  rdnd}| j                   j                  ||       yyyy# t        $ r }t        j	                  d|       Y d}~yd}~ww xY w)z'Mirror built-in memory writes as facts.r   userr   r"   r*   z*Holographic memory_write mirror failed: %sN)rQ   add_factrE   r   r   )rV   r$   targetr%   r*   r   s         rI   on_memory_writez)HolographicMemoryProvider.on_memory_write   sk    U?t{{wN*0F*:;	$$Wx$@ 07{?  NI1MMNs   &? 	A(A##A(c                    | j                   	 | j                   j                          d | _         d | _        y # t        $ r }t        j	                  d|       Y d }~3d }~ww xY w)Nz'Holographic shutdown close() failed: %s)rQ   closerE   r   r   rR   )rV   r   s     rI   shutdownz"HolographicMemoryProvider.shutdown   sZ     ;;"K!!#   KFJJKs   7 	A  AA c                `   	 |d   }| j                   }| j                  }|dk(  rO|j                  |d   |j                  dd      |j                  dd            }t	        j
                  |d	d
      S |dk(  r|j                  |d   |j                  d      t        |j                  d| j                              t        |j                  dd                  }t	        j
                  |t        |      d      S |dk(  r`|j                  |d   |j                  d      t        |j                  dd                  }t	        j
                  |t        |      d      S |dk(  r`|j                  |d   |j                  d      t        |j                  dd                  }t	        j
                  |t        |      d      S |dk(  r||j                  dg       }|st        d      S |j                  ||j                  d      t        |j                  dd                  }t	        j
                  |t        |      d      S |dk(  r\|j                  |j                  d      t        |j                  dd                  }t	        j
                  |t        |      d      S |dk(  rx|j!                  t        |d         |j                  d      d|v rt        |d         nd |j                  d      |j                  d            }t	        j
                  d|i      S |dk(  r4|j#                  t        |d               }	t	        j
                  d |	i      S |d!k(  rv|j%                  |j                  d      t        |j                  dd"            t        |j                  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: )rQ   rR   r   rT   jsondumpsr   rS   rU   r   lenr   r   r   r   r   update_factremove_fact
list_factsKeyErrorrE   r}   )rV   r   r$   r|   	retrieverr)   r   r(   r   r   r   excs               rI   r   z,HolographicMemoryProvider._handle_fact_store  s   T	((^FKKEI..O!XXj)<&"- ) 
 zzg"IJJ8##**M!XXj1#DHH[$//$JKdhhw34	 +  zzgG"MNN7"#//N!XXj1dhhw34 * 
 zzgG"MNN9$#++N!XXj1dhhw34 , 
 zzgG"MNN8#88J3%&GHH#**!XXj1dhhw34 + 
 zzgG"MNN<'#..!XXj1dhhw34 /  zzgG"MNN8#++Y( HHY/>Kt>Sd=&9 :Y]&)!XXj1 ,  zz9g"6778#++CY,@Azz9g"6776!((!XXj1#DHH[#$>?dhhw34 ) 
 zzECJ"GHH "$4VH"=>> 	C ;C5ABB 	(c#h''	(ss   A0O' 3BO' <A$O' !A$O' #O' *AO' A O' (A<O' %8O' A:O' O' '	P-0P=P-P-P("P-(P-c                &   	 t        |d         }|d   dk(  }| j                  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   rQ   record_feedbackr   r   r   r   rE   r}   )rV   r   r)   r4   resultr   s         rI   r   z/HolographicMemoryProvider._handle_fact_feedbacke  s    	($y/*G8n	1G[[00'0JF::f%% 	C ;C5ABB 	(c#h''	(s0   AA
 
	BA& B&B2BBBc                v   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 ]  }|j                  d      dk7  r|j                  d	d
      }t	        |t
              rt        |      dk  rI|D ];  }|j                  |      s	 | j                  j                  |d d d       |dz  } n |D ];  }|j                  |      s	 | j                  j                  |d d d       |dz  }   |rt        j                  d|       y y # t        $ r Y jw xY w# t        $ r Y 9w xY w)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
IGNORECASErT   r~   r}   r   r   rQ   r   rE   r   info)rV   r   _PREF_PATTERNS_DECISION_PATTERNS	extractedmsgr%   patterns           rI   r   z-HolographicMemoryProvider._auto_extract_factsr  s   JJI2==YJJQSUS`S`aJJ?O
 JJJBMMZJJJBMMZ

 	 	Cwwv&(ggi,Ggs+s7|b/@) >>'*,,WTc][,Q!Q	  . >>'*,,WTc]Y,O!Q	 !	2 KKCYO  %  % s$   %F%F,	F)(F),	F87F8r   )rW   zdict | None)returnr}   )r   bool)r   r}   r   None)r&   r}   r   r}   r   r}   )r   r}   r   r}   r   r}   r   r   )r   List[Dict[str, Any]])r   r}   r   zDict[str, Any]r   r}   )r   r   r   r   )r$   r}   r   r}   r%   r}   r   r   r   r   )r   dictr   r}   )r   r   r   r   )__name__
__module____qualname____doc__rX   propertyr1   r_   rj   rx   r   r   r   r   r   r   r   r   r   r   r   r   r\   rY   rI   rL   rL   s   sz    YN  "
&2
. 9;   Y[ 
98+N"U(n	(&PrY   rL   c                R    t               }t        |      }| j                  |       y)z@Register the holographic memory provider with the plugin system.)rW   N)rJ   rL   register_memory_provider)ctxrW   providers      rI   registerr     s"     "F(7H  *rY   )r   r   r   )r   
__future__r   r   loggingr   typingr   r   r   agent.memory_providerr   tools.registryr   r|   r
   	retrievalr   hermes_cli.configr   	getLoggerr   r   r   r   rJ   rL   r   r\   rY   rI   <module>r      s6  " #   	 " " 0 %  $ %			8	$ 	^  !q !)9]^&7^_'8\]!(FH3EVrs ):Z[!)3^_%6MN$,=]^"*;ab'8TU
  J%!$ N 	F ')[1IJ ):PQ
 y) *$eP ePX	+rY   