do-memory-core 0.1.31

Core episodic learning system for AI agents with pattern extraction, reward scoring, and dual storage backend
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
//! Input validation for memory API boundaries
//!
//! Provides validation functions to enforce size limits and prevent
//! resource exhaustion attacks. All public API entry points should
//! validate inputs using these functions.

use crate::episode::{Episode, ExecutionStep};
use crate::error::{Error, Result};
use crate::types::{
    MAX_ARTIFACT_SIZE, MAX_DESCRIPTION_LEN, MAX_EPISODE_SIZE, MAX_OBSERVATION_LEN, MAX_STEP_COUNT,
};

/// Validate task description length.
///
/// Ensures the task description does not exceed [`MAX_DESCRIPTION_LEN`] (10KB).
/// Prevents `DoS` attacks via unbounded input strings.
///
/// # Arguments
///
/// * `description` - Task description to validate
///
/// # Errors
///
/// Returns [`Error::InvalidInput`] if description exceeds maximum length.
///
/// # Examples
///
/// ```
/// use do_memory_core::memory::validation::validate_task_description;
///
/// // Valid description
/// let valid = "Implement authentication".to_string();
/// assert!(validate_task_description(&valid).is_ok());
///
/// // Invalid - too long
/// let too_long = "a".repeat(10_001);
/// assert!(validate_task_description(&too_long).is_err());
/// ```
pub fn validate_task_description(description: &str) -> Result<()> {
    if description.len() > MAX_DESCRIPTION_LEN {
        return Err(Error::InvalidInput(format!(
            "Task description length {} exceeds maximum {} bytes ({}KB)",
            description.len(),
            MAX_DESCRIPTION_LEN,
            MAX_DESCRIPTION_LEN / 1024
        )));
    }
    Ok(())
}

/// Validate execution step before adding to episode.
///
/// Enforces multiple constraints:
/// - Step count must not exceed [`MAX_STEP_COUNT`] (1000)
/// - Observation length must not exceed [`MAX_OBSERVATION_LEN`] (10KB)
/// - Artifact sizes in parameters must not exceed [`MAX_ARTIFACT_SIZE`] (1MB)
///
/// # Arguments
///
/// * `episode` - Episode to validate step count against
/// * `step` - Execution step to validate
///
/// # Errors
///
/// Returns [`Error::InvalidInput`] if any validation constraint is violated.
///
/// # Examples
///
/// ```
/// use do_memory_core::{Episode, ExecutionStep, TaskContext, TaskType, ExecutionResult};
/// use do_memory_core::memory::validation::validate_execution_step;
///
/// let episode = Episode::new(
///     "Test task".to_string(),
///     TaskContext::default(),
///     TaskType::Testing,
/// );
///
/// // Valid step
/// let mut valid_step = ExecutionStep::new(1, "tool".to_string(), "action".to_string());
/// valid_step.result = Some(ExecutionResult::Success {
///     output: "OK".to_string(),
/// });
/// assert!(validate_execution_step(&episode, &valid_step).is_ok());
///
/// // Invalid - observation too long
/// let mut invalid_step = ExecutionStep::new(1, "tool".to_string(), "action".to_string());
/// invalid_step.result = Some(ExecutionResult::Success {
///     output: "x".repeat(10_001),
/// });
/// assert!(validate_execution_step(&episode, &invalid_step).is_err());
/// ```
pub fn validate_execution_step(episode: &Episode, step: &ExecutionStep) -> Result<()> {
    // Check step count limit
    if episode.steps.len() >= MAX_STEP_COUNT {
        return Err(Error::InvalidInput(format!(
            "Episode step count {} exceeds maximum {}",
            episode.steps.len(),
            MAX_STEP_COUNT
        )));
    }

    // Validate observation length (result output/error messages)
    if let Some(result) = &step.result {
        let observation_len = match result {
            crate::types::ExecutionResult::Success { output } => output.len(),
            crate::types::ExecutionResult::Error { message } => message.len(),
            crate::types::ExecutionResult::Timeout => 0,
        };

        if observation_len > MAX_OBSERVATION_LEN {
            return Err(Error::InvalidInput(format!(
                "Step observation length {} exceeds maximum {} bytes ({}KB)",
                observation_len,
                MAX_OBSERVATION_LEN,
                MAX_OBSERVATION_LEN / 1024
            )));
        }
    }

    // Validate artifact sizes in parameters
    // Check if parameters contain large data that could be artifacts
    if let Some(params_obj) = step.parameters.as_object() {
        for (key, value) in params_obj {
            // Check for common artifact-like field names
            if key.contains("artifact")
                || key.contains("data")
                || key.contains("content")
                || key.contains("file")
            {
                if let Some(string_value) = value.as_str() {
                    #[allow(clippy::excessive_nesting)]
                    if string_value.len() > MAX_ARTIFACT_SIZE {
                        return Err(Error::InvalidInput(format!(
                            "Artifact '{}' size {} exceeds maximum {} bytes ({}MB)",
                            key,
                            string_value.len(),
                            MAX_ARTIFACT_SIZE,
                            MAX_ARTIFACT_SIZE / 1_000_000
                        )));
                    }
                }
            }
        }
    }

    // Validate serialized parameters size
    let params_json = serde_json::to_string(&step.parameters)
        .map_err(|e| Error::InvalidInput(format!("Failed to serialize step parameters: {e}")))?;
    if params_json.len() > MAX_ARTIFACT_SIZE {
        return Err(Error::InvalidInput(format!(
            "Step parameters size {} exceeds maximum {} bytes ({}MB)",
            params_json.len(),
            MAX_ARTIFACT_SIZE,
            MAX_ARTIFACT_SIZE / 1_000_000
        )));
    }

    Ok(())
}

/// Validate total episode size before completion.
///
/// Serializes the episode and checks that the total size does not exceed
/// [`MAX_EPISODE_SIZE`] (10MB). This prevents memory exhaustion during
/// storage operations.
///
/// # Arguments
///
/// * `episode` - Episode to validate
///
/// # Errors
///
/// Returns [`Error::InvalidInput`] if serialized size exceeds maximum.
///
/// # Examples
///
/// ```
/// use do_memory_core::{Episode, TaskContext, TaskType, TaskOutcome};
/// use do_memory_core::memory::validation::validate_episode_size;
///
/// let mut episode = Episode::new(
///     "Test task".to_string(),
///     TaskContext::default(),
///     TaskType::Testing,
/// );
///
/// episode.complete(TaskOutcome::Success {
///     verdict: "Done".to_string(),
///     artifacts: vec![],
/// });
///
/// assert!(validate_episode_size(&episode).is_ok());
/// ```
pub fn validate_episode_size(episode: &Episode) -> Result<()> {
    // Serialize to JSON to get accurate size
    let serialized = serde_json::to_vec(episode).map_err(|e| {
        Error::InvalidInput(format!("Failed to serialize episode for validation: {e}"))
    })?;

    if serialized.len() > MAX_EPISODE_SIZE {
        return Err(Error::InvalidInput(format!(
            "Episode serialized size {} exceeds maximum {} bytes ({}MB)",
            serialized.len(),
            MAX_EPISODE_SIZE,
            MAX_EPISODE_SIZE / 1_000_000
        )));
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{ExecutionResult, TaskContext, TaskOutcome, TaskType};

    #[test]
    fn test_validate_task_description_valid() {
        let description = "Implement user authentication".to_string();
        assert!(validate_task_description(&description).is_ok());
    }

    #[test]
    fn test_validate_task_description_at_limit() {
        let description = "a".repeat(MAX_DESCRIPTION_LEN);
        assert!(validate_task_description(&description).is_ok());
    }

    #[test]
    fn test_validate_task_description_exceeds_limit() {
        let description = "a".repeat(MAX_DESCRIPTION_LEN + 1);
        let result = validate_task_description(&description);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), Error::InvalidInput(_)));
    }

    #[test]
    fn test_validate_execution_step_valid() {
        let episode = Episode::new(
            "Test task".to_string(),
            TaskContext::default(),
            TaskType::Testing,
        );

        let mut step = ExecutionStep::new(1, "tool".to_string(), "action".to_string());
        step.result = Some(ExecutionResult::Success {
            output: "OK".to_string(),
        });

        assert!(validate_execution_step(&episode, &step).is_ok());
    }

    #[test]
    fn test_validate_execution_step_observation_at_limit() {
        let episode = Episode::new(
            "Test task".to_string(),
            TaskContext::default(),
            TaskType::Testing,
        );

        let mut step = ExecutionStep::new(1, "tool".to_string(), "action".to_string());
        step.result = Some(ExecutionResult::Success {
            output: "x".repeat(MAX_OBSERVATION_LEN),
        });

        assert!(validate_execution_step(&episode, &step).is_ok());
    }

    #[test]
    fn test_validate_execution_step_observation_exceeds_limit() {
        let episode = Episode::new(
            "Test task".to_string(),
            TaskContext::default(),
            TaskType::Testing,
        );

        let mut step = ExecutionStep::new(1, "tool".to_string(), "action".to_string());
        step.result = Some(ExecutionResult::Success {
            output: "x".repeat(MAX_OBSERVATION_LEN + 1),
        });

        let result = validate_execution_step(&episode, &step);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), Error::InvalidInput(_)));
    }

    #[test]
    fn test_validate_execution_step_error_message_exceeds_limit() {
        let episode = Episode::new(
            "Test task".to_string(),
            TaskContext::default(),
            TaskType::Testing,
        );

        let mut step = ExecutionStep::new(1, "tool".to_string(), "action".to_string());
        step.result = Some(ExecutionResult::Error {
            message: "x".repeat(MAX_OBSERVATION_LEN + 1),
        });

        let result = validate_execution_step(&episode, &step);
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_execution_step_too_many_steps() {
        let mut episode = Episode::new(
            "Test task".to_string(),
            TaskContext::default(),
            TaskType::Testing,
        );

        // Add MAX_STEP_COUNT steps
        for i in 0..MAX_STEP_COUNT {
            let mut step = ExecutionStep::new(i + 1, "tool".to_string(), "action".to_string());
            step.result = Some(ExecutionResult::Success {
                output: "OK".to_string(),
            });
            episode.add_step(step);
        }

        // Try to add one more
        let step = ExecutionStep::new(MAX_STEP_COUNT + 1, "tool".to_string(), "action".to_string());
        let result = validate_execution_step(&episode, &step);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), Error::InvalidInput(_)));
    }

    #[test]
    fn test_validate_execution_step_artifact_in_params() {
        let episode = Episode::new(
            "Test task".to_string(),
            TaskContext::default(),
            TaskType::Testing,
        );

        let mut step = ExecutionStep::new(1, "tool".to_string(), "action".to_string());
        step.parameters = serde_json::json!({
            "artifact_data": "x".repeat(MAX_ARTIFACT_SIZE + 1),
        });

        let result = validate_execution_step(&episode, &step);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), Error::InvalidInput(_)));
    }

    #[test]
    fn test_validate_execution_step_large_params() {
        let episode = Episode::new(
            "Test task".to_string(),
            TaskContext::default(),
            TaskType::Testing,
        );

        let mut step = ExecutionStep::new(1, "tool".to_string(), "action".to_string());
        // Create params that serialize to > MAX_ARTIFACT_SIZE
        let large_array: Vec<String> = (0..10_000)
            .map(|i| format!("item_{i}_with_some_padding_text"))
            .collect();
        step.parameters = serde_json::json!({
            "large_data": large_array,
        });

        let result = validate_execution_step(&episode, &step);
        // This might pass or fail depending on exact serialization size
        // We're just checking the validation logic runs
        let _ = result;
    }

    #[test]
    fn test_validate_episode_size_valid() {
        let mut episode = Episode::new(
            "Test task".to_string(),
            TaskContext::default(),
            TaskType::Testing,
        );

        // Add a few normal steps
        for i in 0..5 {
            let mut step = ExecutionStep::new(i + 1, "tool".to_string(), "action".to_string());
            step.result = Some(ExecutionResult::Success {
                output: "OK".to_string(),
            });
            episode.add_step(step);
        }

        episode.complete(TaskOutcome::Success {
            verdict: "Done".to_string(),
            artifacts: vec!["file.txt".to_string()],
        });

        assert!(validate_episode_size(&episode).is_ok());
    }

    #[test]
    fn test_validate_episode_size_large_but_valid() {
        let mut episode = Episode::new(
            "Test task".to_string(),
            TaskContext::default(),
            TaskType::Testing,
        );

        // Add many steps with reasonable data
        // Each step is roughly 500 bytes, so 1000 steps = ~500KB, well under 10MB
        for i in 0..1000 {
            let mut step = ExecutionStep::new(i + 1, "tool".to_string(), "action".to_string());
            step.result = Some(ExecutionResult::Success {
                output: "x".repeat(200),
            });
            episode.add_step(step);
        }

        episode.complete(TaskOutcome::Success {
            verdict: "Done".to_string(),
            artifacts: vec![],
        });

        // Should be valid (under 10MB)
        assert!(validate_episode_size(&episode).is_ok());
    }

    #[test]
    fn test_validate_episode_size_exceeds_limit() {
        let mut episode = Episode::new(
            "Test task".to_string(),
            TaskContext::default(),
            TaskType::Testing,
        );

        // Add steps with large observations to exceed 10MB
        // Each observation is 500KB, so 25 steps = 12.5MB
        for i in 0..25 {
            let mut step = ExecutionStep::new(i + 1, "tool".to_string(), "action".to_string());
            step.result = Some(ExecutionResult::Success {
                output: "x".repeat(500_000), // 500KB per step
            });
            episode.add_step(step);
        }

        episode.complete(TaskOutcome::Success {
            verdict: "Done".to_string(),
            artifacts: vec![],
        });

        let result = validate_episode_size(&episode);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), Error::InvalidInput(_)));
    }
}