llm-memory-graph 0.1.0

Graph-based context-tracking and prompt-lineage database for LLM systems
Documentation
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! Hook execution framework
//!
//! This module provides infrastructure for managing and executing plugin hooks
//! at specific points in the system's execution flow.

use super::{Plugin, PluginContext, PluginError};
use std::collections::HashMap;
use std::sync::Arc;
use tracing::{debug, warn};

/// Hook point identifier
///
/// Represents specific points in the execution flow where plugins can be invoked.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum HookPoint {
    /// Before creating a node
    BeforeCreateNode,
    /// After creating a node
    AfterCreateNode,
    /// Before creating a session
    BeforeCreateSession,
    /// After creating a session
    AfterCreateSession,
    /// Before executing a query
    BeforeQuery,
    /// After executing a query
    AfterQuery,
    /// Before creating an edge
    BeforeCreateEdge,
    /// After creating an edge
    AfterCreateEdge,
    /// Before updating a node
    BeforeUpdateNode,
    /// After updating a node
    AfterUpdateNode,
    /// Before deleting a node
    BeforeDeleteNode,
    /// After deleting a node
    AfterDeleteNode,
    /// Before deleting a session
    BeforeDeleteSession,
    /// After deleting a session
    AfterDeleteSession,
}

impl HookPoint {
    /// Get the hook name as a string
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::BeforeCreateNode => "before_create_node",
            Self::AfterCreateNode => "after_create_node",
            Self::BeforeCreateSession => "before_create_session",
            Self::AfterCreateSession => "after_create_session",
            Self::BeforeQuery => "before_query",
            Self::AfterQuery => "after_query",
            Self::BeforeCreateEdge => "before_create_edge",
            Self::AfterCreateEdge => "after_create_edge",
            Self::BeforeUpdateNode => "before_update_node",
            Self::AfterUpdateNode => "after_update_node",
            Self::BeforeDeleteNode => "before_delete_node",
            Self::AfterDeleteNode => "after_delete_node",
            Self::BeforeDeleteSession => "before_delete_session",
            Self::AfterDeleteSession => "after_delete_session",
        }
    }

    /// Check if this is a "before" hook
    pub fn is_before(&self) -> bool {
        matches!(
            self,
            Self::BeforeCreateNode
                | Self::BeforeCreateSession
                | Self::BeforeQuery
                | Self::BeforeCreateEdge
                | Self::BeforeUpdateNode
                | Self::BeforeDeleteNode
                | Self::BeforeDeleteSession
        )
    }

    /// Check if this is an "after" hook
    pub fn is_after(&self) -> bool {
        !self.is_before()
    }

    /// Get all hook points
    pub fn all() -> Vec<Self> {
        vec![
            Self::BeforeCreateNode,
            Self::AfterCreateNode,
            Self::BeforeCreateSession,
            Self::AfterCreateSession,
            Self::BeforeQuery,
            Self::AfterQuery,
            Self::BeforeCreateEdge,
            Self::AfterCreateEdge,
            Self::BeforeUpdateNode,
            Self::AfterUpdateNode,
            Self::BeforeDeleteNode,
            Self::AfterDeleteNode,
            Self::BeforeDeleteSession,
            Self::AfterDeleteSession,
        ]
    }
}

impl std::fmt::Display for HookPoint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Hook registry
///
/// Maintains mappings between hook points and the plugins that should be
/// invoked at those points. This allows for efficient hook execution.
pub struct HookRegistry {
    hooks: HashMap<HookPoint, Vec<Arc<dyn Plugin>>>,
}

impl HookRegistry {
    /// Create a new hook registry
    pub fn new() -> Self {
        Self {
            hooks: HashMap::new(),
        }
    }

    /// Register a plugin for a specific hook point
    pub fn register_hook(&mut self, hook: HookPoint, plugin: Arc<dyn Plugin>) {
        self.hooks.entry(hook).or_default().push(plugin);
    }

    /// Unregister a plugin from a specific hook point
    pub fn unregister_hook(&mut self, hook: HookPoint, plugin_name: &str) {
        if let Some(plugins) = self.hooks.get_mut(&hook) {
            plugins.retain(|p| p.metadata().name != plugin_name);
        }
    }

    /// Unregister a plugin from all hook points
    pub fn unregister_plugin(&mut self, plugin_name: &str) {
        for plugins in self.hooks.values_mut() {
            plugins.retain(|p| p.metadata().name != plugin_name);
        }
    }

    /// Get all plugins registered for a hook point
    pub fn get_plugins(&self, hook: HookPoint) -> Vec<Arc<dyn Plugin>> {
        self.hooks.get(&hook).cloned().unwrap_or_default()
    }

    /// Get the number of plugins registered for a hook point
    pub fn count_plugins(&self, hook: HookPoint) -> usize {
        self.hooks.get(&hook).map(Vec::len).unwrap_or(0)
    }

    /// Clear all hook registrations
    pub fn clear(&mut self) {
        self.hooks.clear();
    }

    /// Get statistics about hook registrations
    pub fn stats(&self) -> HashMap<HookPoint, usize> {
        self.hooks
            .iter()
            .map(|(hook, plugins)| (*hook, plugins.len()))
            .collect()
    }
}

impl Default for HookRegistry {
    fn default() -> Self {
        Self::new()
    }
}

/// Hook executor
///
/// Responsible for executing plugin hooks at specific points in the system.
/// Handles error propagation, logging, and execution order.
pub struct HookExecutor {
    /// Whether to stop execution on first error (before hooks only)
    fail_fast: bool,
    /// Whether to collect timing metrics
    collect_metrics: bool,
}

impl HookExecutor {
    /// Create a new hook executor
    pub fn new() -> Self {
        Self {
            fail_fast: true,
            collect_metrics: false,
        }
    }

    /// Create a hook executor with fail-fast disabled
    ///
    /// When fail-fast is disabled, all plugins will be executed even if
    /// some fail. Useful for after-hooks where you want to ensure all
    /// plugins get a chance to run.
    pub fn without_fail_fast() -> Self {
        Self {
            fail_fast: false,
            collect_metrics: false,
        }
    }

    /// Enable metrics collection
    pub fn with_metrics(mut self) -> Self {
        self.collect_metrics = true;
        self
    }

    /// Execute before hooks
    ///
    /// Executes all plugins at the specified hook point. If fail_fast is enabled,
    /// stops at the first error. Otherwise, collects all errors and returns them.
    pub async fn execute_before(
        &self,
        hook: HookPoint,
        plugins: &[Arc<dyn Plugin>],
        context: &PluginContext,
    ) -> Result<(), PluginError> {
        debug!("Executing {} with {} plugins", hook, plugins.len());

        let mut errors = Vec::new();

        for plugin in plugins {
            let plugin_name = &plugin.metadata().name;
            debug!("Executing hook {} for plugin {}", hook, plugin_name);

            let start = std::time::Instant::now();

            match plugin.before_hook(hook.as_str(), context).await {
                Ok(()) => {
                    if self.collect_metrics {
                        let duration = start.elapsed();
                        debug!(
                            "Plugin {} completed {} in {:?}",
                            plugin_name, hook, duration
                        );
                    }
                }
                Err(e) => {
                    warn!("Plugin {} failed on {}: {}", plugin_name, hook, e);

                    if self.fail_fast {
                        return Err(e);
                    }
                    errors.push((plugin_name.clone(), e));
                }
            }
        }

        if !errors.is_empty() {
            let error_msg = errors
                .iter()
                .map(|(name, e)| format!("{}: {}", name, e))
                .collect::<Vec<_>>()
                .join("; ");

            return Err(PluginError::HookFailed(format!(
                "Multiple plugins failed: {}",
                error_msg
            )));
        }

        Ok(())
    }

    /// Execute after hooks
    ///
    /// Executes all plugins at the specified hook point. After hooks never
    /// fail the operation - errors are logged but execution continues.
    pub async fn execute_after(
        &self,
        hook: HookPoint,
        plugins: &[Arc<dyn Plugin>],
        context: &PluginContext,
    ) -> Result<(), PluginError> {
        debug!("Executing {} with {} plugins", hook, plugins.len());

        for plugin in plugins {
            let plugin_name = &plugin.metadata().name;
            debug!("Executing hook {} for plugin {}", hook, plugin_name);

            let start = std::time::Instant::now();

            match plugin.after_hook(hook.as_str(), context).await {
                Ok(()) => {
                    if self.collect_metrics {
                        let duration = start.elapsed();
                        debug!(
                            "Plugin {} completed {} in {:?}",
                            plugin_name, hook, duration
                        );
                    }
                }
                Err(e) => {
                    // After hooks should not fail the operation
                    warn!(
                        "Plugin {} failed on after hook {}: {}",
                        plugin_name, hook, e
                    );
                }
            }
        }

        Ok(())
    }

    /// Execute a hook point
    ///
    /// Automatically determines whether to use before or after hook semantics
    /// based on the hook point.
    pub async fn execute(
        &self,
        hook: HookPoint,
        plugins: &[Arc<dyn Plugin>],
        context: &PluginContext,
    ) -> Result<(), PluginError> {
        if hook.is_before() {
            self.execute_before(hook, plugins, context).await
        } else {
            self.execute_after(hook, plugins, context).await
        }
    }
}

impl Default for HookExecutor {
    fn default() -> Self {
        Self::new()
    }
}

/// Hook execution result with timing information
#[derive(Debug)]
pub struct HookExecutionResult {
    /// Hook point that was executed
    pub hook: HookPoint,
    /// Number of plugins executed
    pub plugins_executed: usize,
    /// Total execution time
    pub total_duration: std::time::Duration,
    /// Individual plugin execution times
    pub plugin_durations: HashMap<String, std::time::Duration>,
    /// Any errors that occurred
    pub errors: Vec<(String, String)>,
}

impl HookExecutionResult {
    /// Check if the execution was successful
    pub fn is_success(&self) -> bool {
        self.errors.is_empty()
    }

    /// Get the average execution time per plugin
    pub fn average_duration(&self) -> std::time::Duration {
        if self.plugins_executed == 0 {
            return std::time::Duration::ZERO;
        }
        self.total_duration / self.plugins_executed as u32
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::plugin::{PluginBuilder, PluginMetadata};
    use async_trait::async_trait;

    struct MockPlugin {
        metadata: PluginMetadata,
        should_fail: bool,
    }

    impl MockPlugin {
        fn new(name: &str, should_fail: bool) -> Self {
            let metadata = PluginBuilder::new(name, "1.0.0")
                .author("Test")
                .description("Test plugin")
                .build();
            Self {
                metadata,
                should_fail,
            }
        }
    }

    #[async_trait]
    impl Plugin for MockPlugin {
        fn metadata(&self) -> &PluginMetadata {
            &self.metadata
        }

        async fn before_create_node(&self, _context: &PluginContext) -> Result<(), PluginError> {
            if self.should_fail {
                Err(PluginError::HookFailed("Test failure".to_string()))
            } else {
                Ok(())
            }
        }
    }

    #[test]
    fn test_hook_point_as_str() {
        assert_eq!(HookPoint::BeforeCreateNode.as_str(), "before_create_node");
        assert_eq!(HookPoint::AfterCreateNode.as_str(), "after_create_node");
    }

    #[test]
    fn test_hook_point_is_before() {
        assert!(HookPoint::BeforeCreateNode.is_before());
        assert!(!HookPoint::AfterCreateNode.is_before());
    }

    #[test]
    fn test_hook_registry() {
        let mut registry = HookRegistry::new();
        let plugin: Arc<dyn Plugin> = Arc::new(MockPlugin::new("test", false));

        registry.register_hook(HookPoint::BeforeCreateNode, Arc::clone(&plugin));
        assert_eq!(registry.count_plugins(HookPoint::BeforeCreateNode), 1);

        let plugins = registry.get_plugins(HookPoint::BeforeCreateNode);
        assert_eq!(plugins.len(), 1);

        registry.unregister_hook(HookPoint::BeforeCreateNode, "test");
        assert_eq!(registry.count_plugins(HookPoint::BeforeCreateNode), 0);
    }

    #[tokio::test]
    async fn test_hook_executor_success() {
        let executor = HookExecutor::new();
        let plugins: Vec<Arc<dyn Plugin>> = vec![
            Arc::new(MockPlugin::new("plugin1", false)),
            Arc::new(MockPlugin::new("plugin2", false)),
        ];

        let context = PluginContext::new("test", serde_json::json!({}));

        let result = executor
            .execute_before(HookPoint::BeforeCreateNode, &plugins, &context)
            .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_hook_executor_fail_fast() {
        let executor = HookExecutor::new();
        let plugins: Vec<Arc<dyn Plugin>> = vec![
            Arc::new(MockPlugin::new("plugin1", false)),
            Arc::new(MockPlugin::new("plugin2", true)),
            Arc::new(MockPlugin::new("plugin3", false)),
        ];

        let context = PluginContext::new("test", serde_json::json!({}));

        let result = executor
            .execute_before(HookPoint::BeforeCreateNode, &plugins, &context)
            .await;

        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_hook_executor_without_fail_fast() {
        let executor = HookExecutor::without_fail_fast();
        let plugins: Vec<Arc<dyn Plugin>> = vec![
            Arc::new(MockPlugin::new("plugin1", false)),
            Arc::new(MockPlugin::new("plugin2", true)),
            Arc::new(MockPlugin::new("plugin3", false)),
        ];

        let context = PluginContext::new("test", serde_json::json!({}));

        let result = executor
            .execute_before(HookPoint::BeforeCreateNode, &plugins, &context)
            .await;

        // Should fail but only after executing all plugins
        assert!(result.is_err());
    }
}