selfware 0.6.1

Your personal AI workshop — software you own, software that lasts
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
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, VecDeque};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tracing::{debug, info, warn};

use super::{RecoveryAction, RecoveryStrategy, SelfHealingConfig, StateManager};

/// Recovery execution result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RecoveryExecution {
    /// Strategy used
    pub strategy: String,
    /// Started at
    pub started_at: u64,
    /// Completed at
    pub completed_at: Option<u64>,
    /// Success
    pub success: bool,
    /// Actions executed
    pub actions_executed: Vec<String>,
    /// Error if failed
    pub error: Option<String>,
}

/// Tracks retry state for a given error pattern to support exponential backoff.
#[derive(Debug, Clone)]
struct RetryState {
    /// Number of retry attempts so far
    attempt_count: u32,
    /// Delay used on the last retry (ms)
    last_delay_ms: u64,
    /// Timestamp of first attempt
    first_attempt_at: u64,
}

/// Recovery executor — runs recovery actions with real retry delays,
/// exponential backoff, checkpoint restore, cache clearing, and more.
pub struct RecoveryExecutor {
    config: SelfHealingConfig,
    /// Execution history
    history: RwLock<VecDeque<RecoveryExecution>>,
    /// Per-pattern retry state for exponential backoff
    retry_states: RwLock<HashMap<String, RetryState>>,
    /// Statistics
    stats: ExecutorStats,
}

/// Executor statistics
#[derive(Debug, Default)]
pub struct ExecutorStats {
    pub executions: AtomicU64,
    pub successes: AtomicU64,
    pub failures: AtomicU64,
    pub retries_performed: AtomicU64,
    pub total_backoff_ms: AtomicU64,
}

impl RecoveryExecutor {
    pub fn new(config: SelfHealingConfig) -> Self {
        Self {
            history: RwLock::new(VecDeque::with_capacity(100)),
            retry_states: RwLock::new(HashMap::new()),
            config,
            stats: ExecutorStats::default(),
        }
    }

    /// Execute a recovery strategy without external state access.
    pub async fn execute(&self, strategy: &RecoveryStrategy) -> RecoveryExecution {
        self.execute_internal(strategy, None, None).await
    }

    /// Execute a recovery strategy with state-manager integration for
    /// restore/clear/reset actions.
    pub async fn execute_with_state(
        &self,
        strategy: &RecoveryStrategy,
        state_manager: &StateManager,
    ) -> RecoveryExecution {
        self.execute_internal(strategy, Some(state_manager), None)
            .await
    }

    /// Execute a recovery strategy with state manager and an error pattern key
    /// used to track per-pattern retry state for exponential backoff.
    pub async fn execute_for_pattern(
        &self,
        strategy: &RecoveryStrategy,
        state_manager: &StateManager,
        pattern_key: &str,
    ) -> RecoveryExecution {
        self.execute_internal(strategy, Some(state_manager), Some(pattern_key))
            .await
    }

    async fn execute_internal(
        &self,
        strategy: &RecoveryStrategy,
        state_manager: Option<&StateManager>,
        pattern_key: Option<&str>,
    ) -> RecoveryExecution {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        if !self.config.enabled {
            return RecoveryExecution {
                strategy: strategy.name.clone(),
                started_at: now,
                completed_at: Some(now),
                success: false,
                actions_executed: vec![],
                error: Some("Self-healing is disabled".to_string()),
            };
        }

        self.stats.executions.fetch_add(1, Ordering::Relaxed);

        let mut actions_executed = Vec::new();
        let mut success = true;
        let mut error = None;

        let max_actions = self.config.max_healing_attempts.max(1) as usize;

        for (index, action) in strategy.actions.iter().enumerate() {
            if index >= max_actions {
                success = false;
                error = Some(format!(
                    "Recovery aborted: exceeded max healing attempts ({})",
                    self.config.max_healing_attempts
                ));
                break;
            }

            let name = action_name(action);
            actions_executed.push(name.to_string());

            info!("Executing recovery action: {}", name);

            if let Err(e) = self
                .execute_action(action, state_manager, pattern_key)
                .await
            {
                success = false;
                error = Some(format!("Action '{}' failed: {}", name, e));
                warn!("Recovery action '{}' failed: {}", name, e);
                break;
            }

            debug!("Recovery action '{}' completed successfully", name);
        }

        if success {
            self.stats.successes.fetch_add(1, Ordering::Relaxed);
            info!(
                "Recovery strategy '{}' completed successfully ({} actions)",
                strategy.name,
                actions_executed.len()
            );
        } else {
            self.stats.failures.fetch_add(1, Ordering::Relaxed);
        }

        let completed_at = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        let execution = RecoveryExecution {
            strategy: strategy.name.clone(),
            started_at: now,
            completed_at: Some(completed_at),
            success,
            actions_executed,
            error,
        };

        {
            let mut history = self.history.write();
            history.push_back(execution.clone());
            while history.len() > 100 {
                history.pop_front();
            }
        }

        execution
    }

    async fn execute_action(
        &self,
        action: &RecoveryAction,
        state_manager: Option<&StateManager>,
        pattern_key: Option<&str>,
    ) -> Result<(), String> {
        match action {
            RecoveryAction::Retry {
                delay_ms,
                max_attempts,
            } => {
                self.execute_retry(*delay_ms, *max_attempts, pattern_key)
                    .await
            }

            RecoveryAction::Restart { component } => {
                if component.trim().is_empty() {
                    return Err("component cannot be empty".to_string());
                }

                info!(
                    "Recovery: restarting component '{}' (restoring last checkpoint)",
                    component
                );

                // A "restart" in the agent context means restore from the last
                // known-good checkpoint so the agent loop re-executes from a
                // clean state.
                if let Some(mgr) = state_manager {
                    if mgr.restore(None).is_some() {
                        info!("Component '{}' state restored from checkpoint", component);
                    } else {
                        debug!(
                            "No checkpoint available for '{}', proceeding with restart signal",
                            component
                        );
                    }
                }
                Ok(())
            }

            RecoveryAction::Fallback { target } => {
                if target.trim().is_empty() {
                    return Err("fallback target cannot be empty".to_string());
                }

                info!("Recovery: activating fallback '{}'", target);

                // Fallback signals the caller to switch strategy. The executor
                // returns success so the agent loop can interpret the action and
                // adjust (e.g. inject error guidance, switch parsing mode).
                Ok(())
            }

            RecoveryAction::RestoreCheckpoint { checkpoint_id } => {
                let manager = state_manager
                    .ok_or_else(|| "state manager unavailable for restore action".to_string())?;

                if let Some(checkpoint) = manager.restore(checkpoint_id.as_deref()) {
                    info!(
                        "Restored checkpoint '{}' ({})",
                        checkpoint.id, checkpoint.description
                    );
                    Ok(())
                } else {
                    Err("no checkpoint available to restore".to_string())
                }
            }

            RecoveryAction::ClearCache { scope } => {
                let manager = state_manager.ok_or_else(|| {
                    "state manager unavailable for clear-cache action".to_string()
                })?;

                info!("Recovery: clearing cache (scope: {})", scope);
                manager.clear();

                // Also clear retry states so the next recovery starts fresh
                {
                    self.retry_states.write().clear();
                    debug!("Retry states cleared");
                }

                Ok(())
            }

            RecoveryAction::ResetState { scope } => {
                let manager = state_manager.ok_or_else(|| {
                    "state manager unavailable for reset-state action".to_string()
                })?;

                info!("Recovery: resetting state (scope: {})", scope);
                manager.clear();

                // Reset retry tracking
                self.retry_states.write().clear();

                Ok(())
            }

            RecoveryAction::Custom { name, params } => {
                if name.trim().is_empty() {
                    return Err("custom action name cannot be empty".to_string());
                }

                info!("Recovery: executing custom action '{}'", name);

                // Handle well-known custom actions
                match name.as_str() {
                    "compress_context" => {
                        // Signal caller to compress the agent's context window
                        info!("Custom action: context compression requested");
                        Ok(())
                    }
                    "reduce_tool_set" => {
                        // Signal caller to reduce available tools
                        info!("Custom action: tool set reduction requested");
                        Ok(())
                    }
                    "switch_parsing_mode" => {
                        // Signal caller to switch between native/XML tool parsing
                        let mode = params.get("mode").map(|s| s.as_str()).unwrap_or("xml");
                        info!("Custom action: switch parsing mode to '{}'", mode);
                        Ok(())
                    }
                    _ => {
                        debug!(
                            "Unknown custom action '{}' with {} params — treating as no-op signal",
                            name,
                            params.len()
                        );
                        Ok(())
                    }
                }
            }
        }
    }

    /// Execute a retry with exponential backoff.
    async fn execute_retry(
        &self,
        base_delay_ms: u64,
        max_attempts: u32,
        pattern_key: Option<&str>,
    ) -> Result<(), String> {
        if max_attempts == 0 {
            return Err("max_attempts must be greater than 0".to_string());
        }

        let key = pattern_key.unwrap_or("default").to_string();
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        // Get or create retry state for this pattern
        let (attempt, actual_delay_ms) = {
            let mut states = self.retry_states.write();

            let state = states.entry(key.clone()).or_insert_with(|| RetryState {
                attempt_count: 0,
                last_delay_ms: 0,
                first_attempt_at: now,
            });

            if state.attempt_count >= max_attempts {
                let elapsed = now.saturating_sub(state.first_attempt_at);
                // Clean up exhausted entry to prevent unbounded map growth
                states.remove(&key);
                return Err(format!(
                    "Max retry attempts ({}) exhausted for pattern '{}' over {}s",
                    max_attempts, key, elapsed
                ));
            }

            // Exponential backoff with jitter: base_delay * 2^attempt ± 25%, capped at 30s
            let exponent = state.attempt_count.min(5);
            let base = base_delay_ms.saturating_mul(1u64 << exponent).min(30_000);
            // Simple jitter: ±25% using timestamp nanos as entropy source
            let jitter_seed = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .subsec_nanos() as u64;
            let jitter_range = base / 4; // 25%
            let jitter_offset = if jitter_range > 0 {
                jitter_seed % (jitter_range * 2)
            } else {
                0
            };
            let actual_delay = base
                .saturating_sub(jitter_range)
                .saturating_add(jitter_offset)
                .min(30_000);

            state.attempt_count += 1;
            state.last_delay_ms = actual_delay;

            (state.attempt_count, actual_delay)
        };

        info!(
            "Retry attempt {}/{} for '{}' — backing off {}ms",
            attempt, max_attempts, key, actual_delay_ms
        );

        self.stats.retries_performed.fetch_add(1, Ordering::Relaxed);
        self.stats
            .total_backoff_ms
            .fetch_add(actual_delay_ms, Ordering::Relaxed);

        // Actual async sleep — this is the real recovery delay. Using `tokio::time::sleep`
        // keeps the Tokio worker free instead of blocking the thread.
        if actual_delay_ms > 0 {
            let capped_delay = actual_delay_ms.min(30_000);
            tokio::time::sleep(Duration::from_millis(capped_delay)).await;
        }

        debug!(
            "Retry backoff complete for '{}' ({}ms elapsed)",
            key, actual_delay_ms
        );

        Ok(())
    }

    /// Reset retry state for a specific pattern (e.g. after a successful operation).
    pub fn reset_retry_state(&self, pattern_key: &str) {
        self.retry_states.write().remove(pattern_key);
    }

    /// Get the current retry attempt count for a pattern.
    pub fn retry_attempt_count(&self, pattern_key: &str) -> u32 {
        self.retry_states
            .read()
            .get(pattern_key)
            .map(|s| s.attempt_count)
            .unwrap_or(0)
    }

    /// Get success rate
    pub fn success_rate(&self) -> f32 {
        let total = self.stats.executions.load(Ordering::Relaxed) as f32;
        let successes = self.stats.successes.load(Ordering::Relaxed) as f32;
        if total > 0.0 {
            successes / total
        } else {
            0.0
        }
    }

    /// Get history
    pub fn history(&self) -> Vec<RecoveryExecution> {
        self.history.read().iter().cloned().collect()
    }

    /// Get summary
    pub fn summary(&self) -> ExecutorSummary {
        ExecutorSummary {
            executions: self.stats.executions.load(Ordering::Relaxed),
            successes: self.stats.successes.load(Ordering::Relaxed),
            failures: self.stats.failures.load(Ordering::Relaxed),
            success_rate: self.success_rate(),
        }
    }
}

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

/// Executor summary
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutorSummary {
    pub executions: u64,
    pub successes: u64,
    pub failures: u64,
    pub success_rate: f32,
}

fn action_name(action: &RecoveryAction) -> &str {
    match action {
        RecoveryAction::Retry { .. } => "retry",
        RecoveryAction::Restart { .. } => "restart",
        RecoveryAction::Fallback { .. } => "fallback",
        RecoveryAction::RestoreCheckpoint { .. } => "restore",
        RecoveryAction::ClearCache { .. } => "clear_cache",
        RecoveryAction::ResetState { .. } => "reset_state",
        RecoveryAction::Custom { name, .. } => name.as_str(),
    }
}

#[cfg(test)]
#[path = "../../tests/unit/self_healing/executor/executor_test.rs"]
mod tests;