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
// Justified clippy suppressions for this crate (WG-113 audit)
//
// CAST-RELATED (necessary for embedding/similarity calculations):
// - cast_precision_loss: f32/f64 conversions in similarity math
// - cast_possible_truncation: usize to u32 for storage IDs
// - cast_sign_loss: positive integers cast to unsigned
// - cast_possible_wrap: negative to unsigned with validation
//
// DOCUMENTATION (would require extensive rework across all functions):
// - missing_errors_doc: Documenting every Result error variant
// - missing_panics_doc: Documenting every potential panic
// - doc_markdown: Backticks around field names in docs is pedantic
//
// API DESIGN CHOICES (intentional decisions):
// - unused_self: Methods that may use self in future extensions
// - implicit_hasher: Accepting HashMap/HashSet without generic bound
// - needless_pass_by_value: Ownership semantics for builder pattern
//
// PEDANTIC LINTS (widespread, provide minimal value):
// - must_use_candidate: Constructors commonly return Self; not worth marking all
// - redundant_closure_for_method_calls: Style preference; closures are clear
// - ref_option: API design choice for consistency with existing patterns
// - match_same_arms: Merging arms reduces readability for maintenance
// - map_unwrap_or: map_or is less readable than the explicit pattern
// - float_cmp: Intentional exact comparisons for known values (e.g., 1.0, 0.5)
// - assigning_clones: clone_from is not always more efficient
//! # Memory Core
//!
//! Core data structures and types for the self-learning memory system with episodic learning.
//!
//! This crate provides the fundamental building blocks for AI agents to learn from execution:
//!
//! ## Core Concepts
//!
//! - **Episodes**: Complete task execution records with steps, outcomes, and metadata
//! - **Patterns**: Reusable patterns extracted from episodes using statistical analysis
//! - **Heuristics**: Learned condition-action rules for future decision-making
//! - **Reflections**: Generated insights after episode completion
//! - **Rewards**: Quantitative scoring of episode success
//!
//! ## Module Organization
//!
//! ### Primary APIs
//! - [`memory`]: Main orchestrator for the learning cycle
//! - [`episode`]: Episode creation, logging, and management
//! - [`patterns`]: Pattern extraction, clustering, and validation
//! - [`embeddings`]: Semantic embedding generation and similarity search
//!
//! ### Support Modules
//! - [`types`]: Common types used across the system
//! - [`storage`]: Storage backend abstractions
//! - [`retrieval`]: Memory retrieval and caching
//! - [`search`]: Search and ranking functionality
//! - [`security`]: Audit logging and security
//! - [`monitoring`]: Agent performance monitoring
//!
//! ## Quick Start
//!
//! ### Basic Episode Recording
//!
//! ```no_run
//! use do_memory_core::memory::SelfLearningMemory;
//! use do_memory_core::{TaskContext, TaskType, TaskOutcome, ExecutionStep, ExecutionResult};
//!
//! #[tokio::main]
//! async fn main() {
//! let memory = SelfLearningMemory::new();
//!
//! // 1. Start an episode for a task
//! let context = TaskContext::default();
//! let episode_id = memory.start_episode(
//! "Implement authentication".to_string(),
//! context,
//! TaskType::CodeGeneration,
//! ).await;
//!
//! // 2. Log execution steps
//! let mut step = ExecutionStep::new(
//! 1,
//! "analyzer".to_string(),
//! "Analyze requirements".to_string()
//! );
//! step.result = Some(ExecutionResult::Success {
//! output: "Requirements clear".to_string()
//! });
//! memory.log_step(episode_id, step).await;
//!
//! // 3. Complete episode with learning
//! memory.complete_episode(episode_id, TaskOutcome::Success {
//! verdict: "Auth implemented successfully".to_string(),
//! artifacts: vec!["auth.rs".to_string()],
//! }).await.unwrap();
//!
//! // 4. Retrieve relevant context for future tasks
//! let relevant = memory.retrieve_relevant_context(
//! "Add authorization".to_string(),
//! TaskContext::default(),
//! 5,
//! ).await;
//!
//! println!("Found {} relevant episodes", relevant.len());
//! }
//! ```
//!
//! ### Pattern-Based Learning
//!
//! The system automatically extracts reusable patterns from completed episodes:
//!
//! ```no_run
//! use do_memory_core::memory::SelfLearningMemory;
//! use do_memory_core::patterns::HybridPatternExtractor;
//! use do_memory_core::episode::Episode;
//!
//! # #[tokio::main]
//! # async fn main() {
//! # let memory = SelfLearningMemory::new();
//! // Configure hybrid pattern extraction
//! let extractor = HybridPatternExtractor::new();
//!
//! // Patterns are automatically extracted during episode completion
//! // The system tracks pattern effectiveness over time
//! # }
//! ```
//!
//! ### Semantic Search with Embeddings
//!
//! ```no_run
//! use do_memory_core::embeddings::{SemanticService, EmbeddingConfig, InMemoryEmbeddingStorage};
//! use do_memory_core::episode::Episode;
//! use do_memory_core::TaskContext;
//!
//! # #[tokio::main]
//! # async fn main() {
//! # let config = EmbeddingConfig::default();
//! // Use semantic similarity to find related episodes
//! # let storage = Box::new(InMemoryEmbeddingStorage::new());
//! let semantic = SemanticService::default(storage).await.unwrap();
//!
//! let related_episodes = semantic
//! .find_similar_episodes(
//! "fix authentication bug",
//! &TaskContext::default(),
//! 10
//! )
//! .await
//! .unwrap();
//! # }
//! ```
//!
//! ## Learning Cycle
//!
//! 1. **Start Episode**: Create a new episode with task context
//! 2. **Log Steps**: Record each execution step with outcomes
//! 3. **Complete Episode**: Mark episode as success/failure
//! 4. **Extract Patterns**: Identify reusable patterns
//! 5. **Generate Reflection**: Create insights and lessons learned
//! 6. **Calculate Reward**: Score episode success
//! 7. **Retrieve**: Use learned patterns for future tasks
//!
//! ## Error Handling
//!
//! Most functions return [`Result<T>`] for proper error handling:
//!
//! ```no_run
//! use do_memory_core::{Error, Result};
//!
//! async fn example() -> Result<()> {
//! // Operations that can fail
//! // .await?
//! Ok(())
//! }
//! ```
//!
//! ## Feature Flags
//!
//! - `openai`: Enable OpenAI embeddings
//! - `local-embeddings`: Enable local ONNX-based embeddings
//! - `turso`: Enable Turso/libSQL storage backend
//! - `redb`: Enable redb cache storage
//! - `full`: Enable all features
//!
pub use StorageSynchronizer;
// Semantic embeddings module (simplified version)
// Re-export commonly used types
pub use ;
pub use ;
pub use ;
pub use PatternExtractor;
pub use ;
pub use ;
pub use SelfLearningMemory;
pub use ;
pub use ;
pub use BatchConfig;
pub use ;
pub use ;
pub use ;
pub use ReflectionGenerator;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
// Re-export attribution types (ADR-044 Feature 2)
pub use ;
// Re-export context bundle types (WG-117)
pub use ;