@@ -193,7 +193,6 @@ pub trait KnowledgeGraphAgentMatcher: Send + Sync {
193193}
194194
195195/// Knowledge graph-based agent matcher implementation
196- #[ allow( dead_code) ]
197196pub struct TerraphimKnowledgeGraphMatcher {
198197 /// Knowledge graph automata
199198 automata : Arc < Automata > ,
@@ -300,6 +299,23 @@ impl TerraphimKnowledgeGraphMatcher {
300299 return Ok ( 0.0 ) ;
301300 }
302301
302+ // Consult the performance cache when caching is enabled. The key is
303+ // built from the (order-independent) concept sets so identical analyses
304+ // are served from memory.
305+ let cache_key = if self . config . enable_caching {
306+ let mut task_sorted = task_concepts. to_vec ( ) ;
307+ task_sorted. sort ( ) ;
308+ let mut agent_sorted = agent_concepts. to_vec ( ) ;
309+ agent_sorted. sort ( ) ;
310+ let key = format ! ( "{}|{}" , task_sorted. join( "," ) , agent_sorted. join( "," ) ) ;
311+ if let Some ( cached) = self . cache . read ( ) . await . get ( & key) {
312+ return Ok ( * cached) ;
313+ }
314+ Some ( key)
315+ } else {
316+ None
317+ } ;
318+
303319 let mut total_connectivity = 0.0 ;
304320 let mut connection_count = 0 ;
305321
@@ -334,6 +350,11 @@ impl TerraphimKnowledgeGraphMatcher {
334350 connectivity_score, total_connectivity as u32 , connection_count
335351 ) ;
336352
353+ // Store the result for subsequent identical analyses.
354+ if let Some ( key) = cache_key {
355+ self . cache . write ( ) . await . insert ( key, connectivity_score) ;
356+ }
357+
337358 Ok ( connectivity_score)
338359 }
339360
@@ -606,10 +627,25 @@ impl KnowledgeGraphAgentMatcher for TerraphimKnowledgeGraphMatcher {
606627 ]
607628 . concat ( ) ;
608629
609- let connectivity_score = self
630+ let mut connectivity_score = self
610631 . analyze_connectivity ( & task_concepts, & agent_concepts)
611632 . await ?;
612633
634+ // If a dedicated role graph exists for the agent's primary role,
635+ // use it to corroborate connectivity. This can only strengthen a
636+ // match (the score is never reduced below the automata result).
637+ if let Some ( role_graph) = self . role_graphs . get ( & agent. primary_role . role_id ) {
638+ let terms = task_concepts
639+ . iter ( )
640+ . chain ( agent_concepts. iter ( ) )
641+ . cloned ( )
642+ . collect :: < Vec < _ > > ( )
643+ . join ( " " ) ;
644+ if !terms. trim ( ) . is_empty ( ) && role_graph. is_all_terms_connected_by_path ( & terms) {
645+ connectivity_score = connectivity_score. max ( 1.0 ) ;
646+ }
647+ }
648+
613649 // Calculate overall match score
614650 let match_score = capability_score * self . config . capability_weight
615651 + domain_score * self . config . domain_weight
0 commit comments