Skip to main content

do_memory_core/
lib.rs

1#![allow(clippy::cast_precision_loss)]
2#![allow(clippy::missing_errors_doc)]
3#![allow(clippy::missing_panics_doc)]
4#![allow(clippy::missing_docs_in_private_items)]
5#![allow(clippy::cast_possible_wrap)]
6#![allow(clippy::cast_possible_truncation)]
7#![allow(clippy::needless_pass_by_value)]
8#![allow(clippy::redundant_closure_for_method_calls)]
9#![allow(clippy::unused_self)]
10#![allow(clippy::items_after_statements)]
11#![allow(clippy::match_same_arms)]
12#![allow(clippy::cast_sign_loss)]
13#![allow(clippy::assigning_clones)]
14#![allow(clippy::borrowed_box)]
15#![allow(clippy::float_cmp)]
16#![allow(clippy::ref_option)]
17// New clippy lints from Rust 1.93+
18#![allow(unknown_lints)]
19#![allow(renamed_and_removed_lints)]
20#![allow(clippy::duplicated_attributes)]
21#![allow(clippy::unnecessary_fallible_conversions)]
22#![allow(clippy::uninlined_format_args)]
23#![allow(clippy::unwrap_or)]
24#![allow(clippy::implicit_hasher)]
25#![allow(clippy::unnecessary_map_on_constructors)]
26#![allow(clippy::empty_line_after_doc_comments)]
27#![allow(clippy::fallible_impl_from)]
28#![allow(clippy::trait_duplication_in_bounds)]
29#![allow(clippy::type_repetition_in_bounds)]
30#![allow(clippy::self_named_constructors)]
31#![allow(clippy::map_unwrap_or)]
32#![allow(clippy::unwrap_or_result)]
33#![allow(clippy::manual_try_from)]
34#![allow(clippy::default_constructed_unit_structs)]
35#![allow(clippy::redundant_field_names)]
36#![allow(clippy::manual_string_new)]
37#![allow(clippy::match_like_matches_macro)]
38#![allow(clippy::if_same_then_else)]
39#![allow(clippy::enum_glob_use)]
40#![allow(clippy::use_self)]
41#![allow(clippy::use_debug)]
42#![allow(clippy::struct_field_names)]
43#![allow(clippy::min_ident_chars)]
44#![allow(clippy::mixed_read_write_in_expression)]
45#![allow(clippy::doc_line_length)]
46#![allow(clippy::wildcard_imports)]
47#![allow(clippy::restriction)]
48#![allow(clippy::pattern_type_mismatch)]
49#![allow(clippy::shadow_reuse)]
50#![allow(clippy::shadow_same)]
51#![allow(clippy::decimal_literal_representation)]
52#![allow(clippy::absolute_paths)]
53#![allow(clippy::single_call_fn)]
54#![allow(clippy::std_instead_of_core)]
55#![allow(clippy::std_instead_of_alloc)]
56#![allow(clippy::arithmetic_side_effects)]
57#![allow(clippy::float_arithmetic)]
58#![allow(clippy::as_conversions)]
59#![allow(clippy::implicit_return)]
60#![allow(clippy::inefficient_to_string)]
61#![allow(clippy::unreadable_literal)]
62#![allow(clippy::bare_trait_objects)]
63#![allow(clippy::must_use_candidate)]
64#![allow(clippy::doc_markdown)]
65
66//! # Memory Core
67//!
68//! Core data structures and types for the self-learning memory system with episodic learning.
69//!
70//! This crate provides the fundamental building blocks for AI agents to learn from execution:
71//!
72//! ## Core Concepts
73//!
74//! - **Episodes**: Complete task execution records with steps, outcomes, and metadata
75//! - **Patterns**: Reusable patterns extracted from episodes using statistical analysis
76//! - **Heuristics**: Learned condition-action rules for future decision-making
77//! - **Reflections**: Generated insights after episode completion
78//! - **Rewards**: Quantitative scoring of episode success
79//!
80//! ## Module Organization
81//!
82//! ### Primary APIs
83//! - [`memory`]: Main orchestrator for the learning cycle
84//! - [`episode`]: Episode creation, logging, and management
85//! - [`patterns`]: Pattern extraction, clustering, and validation
86//! - [`embeddings`]: Semantic embedding generation and similarity search
87//!
88//! ### Support Modules
89//! - [`types`]: Common types used across the system
90//! - [`storage`]: Storage backend abstractions
91//! - [`retrieval`]: Memory retrieval and caching
92//! - [`search`]: Search and ranking functionality
93//! - [`security`]: Audit logging and security
94//! - [`monitoring`]: Agent performance monitoring
95//!
96//! ## Quick Start
97//!
98//! ### Basic Episode Recording
99//!
100//! ```no_run
101//! use do_memory_core::memory::SelfLearningMemory;
102//! use do_memory_core::{TaskContext, TaskType, TaskOutcome, ExecutionStep, ExecutionResult};
103//!
104//! #[tokio::main]
105//! async fn main() {
106//!     let memory = SelfLearningMemory::new();
107//!
108//!     // 1. Start an episode for a task
109//!     let context = TaskContext::default();
110//!     let episode_id = memory.start_episode(
111//!         "Implement authentication".to_string(),
112//!         context,
113//!         TaskType::CodeGeneration,
114//!     ).await;
115//!
116//!     // 2. Log execution steps
117//!     let mut step = ExecutionStep::new(
118//!         1,
119//!         "analyzer".to_string(),
120//!         "Analyze requirements".to_string()
121//!     );
122//!     step.result = Some(ExecutionResult::Success {
123//!         output: "Requirements clear".to_string()
124//!     });
125//!     memory.log_step(episode_id, step).await;
126//!
127//!     // 3. Complete episode with learning
128//!     memory.complete_episode(episode_id, TaskOutcome::Success {
129//!         verdict: "Auth implemented successfully".to_string(),
130//!         artifacts: vec!["auth.rs".to_string()],
131//!     }).await.unwrap();
132//!
133//!     // 4. Retrieve relevant context for future tasks
134//!     let relevant = memory.retrieve_relevant_context(
135//!         "Add authorization".to_string(),
136//!         TaskContext::default(),
137//!         5,
138//!     ).await;
139//!
140//!     println!("Found {} relevant episodes", relevant.len());
141//! }
142//! ```
143//!
144//! ### Pattern-Based Learning
145//!
146//! The system automatically extracts reusable patterns from completed episodes:
147//!
148//! ```no_run
149//! use do_memory_core::memory::SelfLearningMemory;
150//! use do_memory_core::patterns::HybridPatternExtractor;
151//! use do_memory_core::episode::Episode;
152//!
153//! # #[tokio::main]
154//! # async fn main() {
155//! # let memory = SelfLearningMemory::new();
156//! // Configure hybrid pattern extraction
157//! let extractor = HybridPatternExtractor::new();
158//!
159//! // Patterns are automatically extracted during episode completion
160//! // The system tracks pattern effectiveness over time
161//! # }
162//! ```
163//!
164//! ### Semantic Search with Embeddings
165//!
166//! ```no_run
167//! use do_memory_core::embeddings::{SemanticService, EmbeddingConfig, InMemoryEmbeddingStorage};
168//! use do_memory_core::episode::Episode;
169//! use do_memory_core::TaskContext;
170//!
171//! # #[tokio::main]
172//! # async fn main() {
173//! # let config = EmbeddingConfig::default();
174//! // Use semantic similarity to find related episodes
175//! # let storage = Box::new(InMemoryEmbeddingStorage::new());
176//! let semantic = SemanticService::default(storage).await.unwrap();
177//!
178//! let related_episodes = semantic
179//!     .find_similar_episodes(
180//!         "fix authentication bug",
181//!         &TaskContext::default(),
182//!         10
183//!     )
184//!     .await
185//!     .unwrap();
186//! # }
187//! ```
188//!
189//! ## Learning Cycle
190//!
191//! 1. **Start Episode**: Create a new episode with task context
192//! 2. **Log Steps**: Record each execution step with outcomes
193//! 3. **Complete Episode**: Mark episode as success/failure
194//! 4. **Extract Patterns**: Identify reusable patterns
195//! 5. **Generate Reflection**: Create insights and lessons learned
196//! 6. **Calculate Reward**: Score episode success
197//! 7. **Retrieve**: Use learned patterns for future tasks
198//!
199//! ## Error Handling
200//!
201//! Most functions return [`Result<T>`] for proper error handling:
202//!
203//! ```no_run
204//! use do_memory_core::{Error, Result};
205//!
206//! async fn example() -> Result<()> {
207//!     // Operations that can fail
208//!     // .await?
209//!     Ok(())
210//! }
211//! ```
212//!
213//! ## Feature Flags
214//!
215//! - `openai`: Enable OpenAI embeddings
216//! - `local-embeddings`: Enable local ONNX-based embeddings
217//! - `turso`: Enable Turso/libSQL storage backend
218//! - `redb`: Enable redb cache storage
219//! - `full`: Enable all features
220//!
221
222pub mod constants;
223pub mod embeddings;
224pub mod episode;
225pub mod episodic;
226pub mod error;
227pub mod extraction;
228pub mod indexing;
229pub mod learning;
230pub mod memory;
231pub mod monitoring;
232pub mod pattern;
233pub mod patterns;
234pub mod pre_storage;
235pub mod reflection;
236pub mod retrieval;
237pub mod reward;
238pub mod search;
239pub mod security;
240pub mod semantic;
241pub mod spatiotemporal;
242pub mod storage;
243pub mod sync;
244pub use sync::StorageSynchronizer;
245pub mod types;
246
247// Semantic embeddings module (simplified version)
248pub mod embeddings_simple;
249
250// Re-export commonly used types
251pub use episode::{Episode, ExecutionStep, PatternId};
252pub use episodic::{CapacityManager, EvictionPolicy};
253pub use error::{CacheError, Error, RelationshipError, Result};
254pub use extraction::PatternExtractor;
255pub use indexing::{
256    BenchmarkResult, IndexMetrics, IndexableMemory, QueryPerformance,
257    hierarchical::{HierarchicalIndex, HierarchicalIndexStats, HierarchicalQuery},
258    spatiotemporal::{IndexStats, QueryOptions, SpatiotemporalIndex, TimeBucket},
259};
260pub use learning::queue::{PatternExtractionQueue, QueueConfig, QueueStats};
261pub use memory::SelfLearningMemory;
262pub use memory::checkpoint::{CheckpointMeta, HandoffPack};
263pub use memory::filters::{EpisodeFilter, EpisodeFilterBuilder, OutcomeType};
264pub use memory::step_buffer::BatchConfig;
265pub use monitoring::{AgentMetrics, AgentMonitor, AgentType, MonitoringConfig, TaskMetrics};
266pub use pattern::{Heuristic, Pattern, PatternEffectiveness};
267pub use patterns::{
268    Anomaly, AnomalyReason, ChangeDirection, ChangeType, Changepoint, ChangepointConfig,
269    ChangepointDetector, ClusterCentroid, ClusteringConfig, DBSCANAnomalyDetector,
270    DBSCANClusterResult, DBSCANConfig, DBSCANStats, EffectivenessTracker, EpisodeCluster,
271    FeatureWeights, PatternClusterer, PatternMetrics, PatternUsage, PatternValidator,
272    SegmentComparison, SegmentComparisonConfig, SegmentStats, UsageStats, ValidationConfig,
273};
274pub use reflection::ReflectionGenerator;
275pub use retrieval::{CacheKey, CacheMetrics, QueryCache};
276pub use reward::{
277    AdaptiveRewardCalculator, DomainStatistics, DomainStatisticsCache, RewardCalculator,
278};
279pub use security::audit::{
280    ActorType, AuditConfig, AuditContext, AuditEntry, AuditEventType, AuditLogLevel, AuditLogger,
281    AuditOutput, AuditResult,
282};
283pub use storage::{DEFAULT_QUERY_LIMIT, MAX_QUERY_LIMIT, StorageBackend, apply_query_limit};
284pub use types::{
285    ComplexityLevel, ConcurrencyConfig, DualRewardScore, Evidence, ExecutionResult, MemoryConfig,
286    OutcomeStats, Reflection, RewardScore, StorageConfig, TaskContext, TaskOutcome, TaskType,
287};
288
289// Re-export attribution types (ADR-044 Feature 2)
290pub use memory::attribution::{
291    RecommendationFeedback, RecommendationSession, RecommendationStats, RecommendationTracker,
292};