ryo-executor 0.1.0

[experimental] Mutation execution engine for RYO - parallel execution, conflict detection, workspace management
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
//! Decider implementations
//!
//! Various strategies for agents to decide their next action.

use super::action::{Action, ActionKind};
use super::context::DecisionContext;
use super::state::AgentState;
use std::fmt::Debug;

// ============================================================================
// Decider Trait
// ============================================================================

/// Trait for decision-making strategies
///
/// A Decider takes the current context and state, and returns the next Action.
pub trait Decider: Send + Sync + Debug {
    /// Decide the next action based on context and state
    fn decide(&self, context: &DecisionContext, state: &AgentState) -> Action;

    /// Name of this decider (for logging)
    fn name(&self) -> &'static str;
}

// ============================================================================
// PlainDecider: Pass-through (no autonomous decisions)
// ============================================================================

/// PlainDecider: Just returns the next work item as a read action
///
/// This is for "plain mode" where agents don't make autonomous decisions
/// but simply execute the work assigned to them.
#[derive(Debug, Clone, Default)]
pub struct PlainDecider;

impl Decider for PlainDecider {
    fn decide(&self, context: &DecisionContext, _state: &AgentState) -> Action {
        // If there's remaining work, return the next item as a mutation
        if let Some(target) = context.next_work_item() {
            return Action::mutate("Execute", target.clone());
        }

        // No more work
        Action::done()
    }

    fn name(&self) -> &'static str {
        "PlainDecider"
    }
}

// ============================================================================
// ParameterizedDecider: Uses state for smarter decisions
// ============================================================================

/// ParameterizedDecider: Makes decisions based on current state
///
/// Considers errors, recent results, and other state to make better decisions.
#[derive(Debug, Clone)]
pub struct ParameterizedDecider {
    /// Weight for error-focused decisions (0.0 - 1.0)
    pub error_weight: f64,
    /// Weight for recent-file-focused decisions (0.0 - 1.0)
    pub recency_weight: f64,
}

impl Default for ParameterizedDecider {
    fn default() -> Self {
        Self {
            error_weight: 0.7,
            recency_weight: 0.3,
        }
    }
}

impl ParameterizedDecider {
    /// Create with custom weights
    pub fn with_weights(error_weight: f64, recency_weight: f64) -> Self {
        Self {
            error_weight,
            recency_weight,
        }
    }
}

impl Decider for ParameterizedDecider {
    fn decide(&self, context: &DecisionContext, state: &AgentState) -> Action {
        // 1. If there are errors and error_weight is high, focus on errors
        if state.has_errors() && self.error_weight > 0.5 {
            if let Some(errored_file) = state.most_errored_file() {
                return Action::read(errored_file.to_string_lossy())
                    .with_reason(format!("fixing {} errors", state.error_count()));
            }
        }

        // 2. If last action failed, try something different
        if context.last_failed() {
            // Try a different file or approach
            let available = state.available_files(context.agent_id);
            if let Some(file) = available.first() {
                return Action::read(file.to_string_lossy())
                    .with_reason("trying different file after failure");
            }
        }

        // 3. If success rate is low, consider escalation
        if context.recent_success_rate() < 0.3 && context.recent_results.len() >= 3 {
            return Action::new(ActionKind::Escalate)
                .with_reason("low success rate, requesting help");
        }

        // 4. Normal operation: use remaining work or investigate
        if let Some(target) = context.next_work_item() {
            return Action::mutate("Execute", target.clone());
        }

        let available = state.available_files(context.agent_id);
        if let Some(file) = available.first() {
            return Action::read(file.to_string_lossy())
                .with_reason("investigating available file");
        }

        Action::done()
    }

    fn name(&self) -> &'static str {
        "ParameterizedDecider"
    }
}

// ============================================================================
// MurmurationDecider: Swarm-like behavior with collision avoidance
// ============================================================================

/// MurmurationDecider: Swarm behavior for parallel agents
///
/// Implements three rules:
/// 1. Separation: Don't work on the same file as other agents
/// 2. Alignment: Coordinate with nearby agents
/// 3. Cohesion: Move towards the overall goal
#[derive(Debug, Clone)]
pub struct MurmurationDecider {
    /// Weight for separation behavior (0.0 - 1.0)
    pub separation_weight: f64,
}

impl Default for MurmurationDecider {
    fn default() -> Self {
        Self {
            separation_weight: 1.0,
        }
    }
}

impl MurmurationDecider {
    /// Create with custom separation weight
    pub fn with_separation(separation_weight: f64) -> Self {
        Self { separation_weight }
    }
}

impl Decider for MurmurationDecider {
    fn decide(&self, context: &DecisionContext, state: &AgentState) -> Action {
        // 1. Separation: Find an unoccupied, uninvestigated file
        let available = state.available_files(context.agent_id);

        if let Some(file) = available.first() {
            return Action::read(file.to_string_lossy()).with_reason(format!(
                "agent #{} investigating (separation)",
                context.agent_id
            ));
        }

        // 2. All files are occupied or investigated
        if !state.uninvestigated_files().is_empty() {
            // Some files are being investigated by others, wait
            return Action::rest("waiting for other agents");
        }

        // 3. Cohesion: All done, contribute to final goal
        if let Some(target) = context.next_work_item() {
            return Action::mutate("Execute", target.clone())
                .with_reason("cohesion: executing final work");
        }

        Action::done()
    }

    fn name(&self) -> &'static str {
        "MurmurationDecider"
    }
}

// ============================================================================
// Decision Modifier: Adjusts decisions based on conditions
// ============================================================================

/// Trait for modifying decisions based on conditions
///
/// Modifiers are applied after the base decider makes its decision,
/// allowing for layered behavior like "weather awareness" on top of
/// "flocking behavior".
pub trait DecisionModifier: Send + Sync + Debug {
    /// Modify an action based on context and state
    ///
    /// Can return the same action unchanged, modify it, or replace it entirely.
    fn modify(&self, action: Action, context: &DecisionContext, state: &AgentState) -> Action;

    /// Name of this modifier (for logging)
    fn name(&self) -> &'static str;
}

// ============================================================================
// Pre-built Modifiers
// ============================================================================

/// ErrorAwareModifier: Prioritizes files with errors
///
/// Like birds avoiding storms - if there are errors, focus on fixing them.
#[derive(Debug, Clone)]
pub struct ErrorAwareModifier {
    /// Weight for error prioritization (0.0 - 1.0)
    pub weight: f64,
}

impl ErrorAwareModifier {
    pub fn new(weight: f64) -> Self {
        Self { weight }
    }
}

impl DecisionModifier for ErrorAwareModifier {
    fn modify(&self, action: Action, _context: &DecisionContext, state: &AgentState) -> Action {
        // If weight is high and there are errors, redirect to error file
        if self.weight > 0.5 && state.has_errors() {
            if let Some(errored_file) = state.most_errored_file() {
                return Action::read(errored_file.to_string_lossy()).with_reason(format!(
                    "error-aware: {} errors in file",
                    state.error_count()
                ));
            }
        }
        action
    }

    fn name(&self) -> &'static str {
        "ErrorAwareModifier"
    }
}

/// StallDetectionModifier: Escalates when progress stalls
///
/// Like birds changing course when stuck in a thermal.
#[derive(Debug, Clone)]
pub struct StallDetectionModifier {
    /// Number of ticks without progress before escalating
    pub threshold: u64,
}

impl StallDetectionModifier {
    pub fn new(threshold: u64) -> Self {
        Self { threshold }
    }
}

impl DecisionModifier for StallDetectionModifier {
    fn modify(&self, action: Action, context: &DecisionContext, state: &AgentState) -> Action {
        if state.is_stalled(context.tick, self.threshold) {
            return Action::new(ActionKind::Escalate).with_reason(format!(
                "stall-detection: no progress for {} ticks",
                self.threshold
            ));
        }
        action
    }

    fn name(&self) -> &'static str {
        "StallDetectionModifier"
    }
}

/// SuccessRateModifier: Escalates on low success rate
///
/// Like birds seeking shelter when conditions are bad.
#[derive(Debug, Clone)]
pub struct SuccessRateModifier {
    /// Minimum success rate before escalating (0.0 - 1.0)
    pub threshold: f64,
    /// Minimum number of results before checking
    pub min_samples: usize,
}

impl SuccessRateModifier {
    pub fn new(threshold: f64) -> Self {
        Self {
            threshold,
            min_samples: 3,
        }
    }
}

impl DecisionModifier for SuccessRateModifier {
    fn modify(&self, action: Action, context: &DecisionContext, _state: &AgentState) -> Action {
        if context.recent_results.len() >= self.min_samples
            && context.recent_success_rate() < self.threshold
        {
            return Action::new(ActionKind::Escalate).with_reason(format!(
                "success-rate: {:.0}% below threshold",
                context.recent_success_rate() * 100.0
            ));
        }
        action
    }

    fn name(&self) -> &'static str {
        "SuccessRateModifier"
    }
}

/// RetryModifier: Retries on failure with backoff
#[derive(Debug, Clone)]
pub struct RetryModifier {
    /// Maximum retries
    pub max_retries: u32,
}

impl RetryModifier {
    pub fn new(max_retries: u32) -> Self {
        Self { max_retries }
    }
}

impl DecisionModifier for RetryModifier {
    fn modify(&self, action: Action, context: &DecisionContext, _state: &AgentState) -> Action {
        // If last action failed and we haven't exceeded retries, retry
        if context.last_failed() {
            let consecutive_failures = context
                .recent_results
                .iter()
                .rev()
                .take_while(|r| !r.success)
                .count() as u32;

            if consecutive_failures < self.max_retries {
                // Retry the same action
                if let Some(last) = context.last_result() {
                    return last
                        .action
                        .clone()
                        .with_reason(format!("retry: attempt {}", consecutive_failures + 1));
                }
            }
        }
        action
    }

    fn name(&self) -> &'static str {
        "RetryModifier"
    }
}

// ============================================================================
// Composable Decider: Base + Modifiers
// ============================================================================

/// ComposableDecider: Combines a base decider with modifiers
///
/// This enables layered decision-making:
/// - Base decider handles target selection (WHERE to act)
/// - Modifiers adjust behavior based on conditions (HOW to act)
///
/// # Example
///
/// ```rust,ignore
/// let decider = ComposableDecider::new(MurmurationDecider::default())
///     .with_modifier(ErrorAwareModifier::new(0.7))
///     .with_modifier(StallDetectionModifier::new(5));
/// ```
#[derive(Debug)]
pub struct ComposableDecider {
    base: Box<dyn Decider>,
    modifiers: Vec<Box<dyn DecisionModifier>>,
}

impl ComposableDecider {
    /// Create a new composable decider with the given base
    pub fn new(base: impl Decider + 'static) -> Self {
        Self {
            base: Box::new(base),
            modifiers: Vec::new(),
        }
    }

    /// Add a modifier to the chain
    pub fn with_modifier(mut self, modifier: impl DecisionModifier + 'static) -> Self {
        self.modifiers.push(Box::new(modifier));
        self
    }

    /// Add an error-aware modifier
    pub fn error_aware(self, weight: f64) -> Self {
        self.with_modifier(ErrorAwareModifier::new(weight))
    }

    /// Add a stall detection modifier
    pub fn stall_detection(self, threshold: u64) -> Self {
        self.with_modifier(StallDetectionModifier::new(threshold))
    }

    /// Add a success rate modifier
    pub fn success_rate(self, threshold: f64) -> Self {
        self.with_modifier(SuccessRateModifier::new(threshold))
    }

    /// Add a retry modifier
    pub fn with_retry(self, max_retries: u32) -> Self {
        self.with_modifier(RetryModifier::new(max_retries))
    }
}

impl Decider for ComposableDecider {
    fn decide(&self, context: &DecisionContext, state: &AgentState) -> Action {
        // 1. Get base decision
        let mut action = self.base.decide(context, state);

        // 2. Apply modifiers in order
        for modifier in &self.modifiers {
            action = modifier.modify(action, context, state);
        }

        action
    }

    fn name(&self) -> &'static str {
        "ComposableDecider"
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    fn create_test_context() -> DecisionContext {
        DecisionContext::new(0, "rename foo to bar")
            .with_tick(1)
            .with_remaining_work(vec!["task1".to_string(), "task2".to_string()])
    }

    fn create_test_state() -> AgentState {
        let mut state = AgentState::new();
        state.update_file(
            PathBuf::from("a.rs"),
            super::super::state::FileState::new(100, 2000),
        );
        state.update_file(
            PathBuf::from("b.rs"),
            super::super::state::FileState::new(50, 1000),
        );
        state
    }

    #[test]
    fn test_plain_decider() {
        let decider = PlainDecider;
        let context = create_test_context();
        let state = create_test_state();

        let action = decider.decide(&context, &state);
        assert_eq!(action.kind, ActionKind::Mutate);
        assert_eq!(action.target, Some("task1".to_string()));
    }

    #[test]
    fn test_murmuration_decider() {
        let decider = MurmurationDecider::default();
        let context = DecisionContext::new(0, "investigate").with_tick(1);
        let state = create_test_state();

        let action = decider.decide(&context, &state);
        assert_eq!(action.kind, ActionKind::Read);
        assert!(action.target.is_some());
    }

    #[test]
    fn test_parameterized_decider_with_errors() {
        let decider = ParameterizedDecider::default();
        let context = DecisionContext::new(0, "fix errors");

        let mut state = create_test_state();
        state.add_error(super::super::state::ErrorInfo::new(
            PathBuf::from("a.rs"),
            10,
            "error",
        ));

        let action = decider.decide(&context, &state);
        assert_eq!(action.kind, ActionKind::Read);
        // Should target the file with errors
        assert!(action.target.unwrap().contains("a.rs"));
    }

    #[test]
    fn test_composable_decider_basic() {
        // Base: MurmurationDecider
        let decider = ComposableDecider::new(MurmurationDecider::default());

        let context = DecisionContext::new(0, "investigate").with_tick(1);
        let state = create_test_state();

        let action = decider.decide(&context, &state);
        assert_eq!(action.kind, ActionKind::Read);
    }

    #[test]
    fn test_composable_decider_with_error_modifier() {
        // Base: Murmuration + Error awareness
        let decider = ComposableDecider::new(MurmurationDecider::default()).error_aware(0.8);

        let context = DecisionContext::new(0, "investigate").with_tick(1);
        let mut state = create_test_state();

        // Add error to a.rs
        state.add_error(super::super::state::ErrorInfo::new(
            PathBuf::from("a.rs"),
            10,
            "compile error",
        ));

        let action = decider.decide(&context, &state);
        // Should redirect to error file
        assert_eq!(action.kind, ActionKind::Read);
        assert!(action.target.unwrap().contains("a.rs"));
        assert!(action.reason.unwrap().contains("error-aware"));
    }

    #[test]
    fn test_composable_decider_stall_detection() {
        let decider = ComposableDecider::new(PlainDecider).stall_detection(5);

        let context = DecisionContext::new(0, "task")
            .with_tick(10)
            .with_remaining_work(vec!["task1".to_string()]);

        let mut state = create_test_state();
        // Simulate stall: last progress was at tick 0
        state.last_progress_tick = 0;

        let action = decider.decide(&context, &state);
        // Should escalate due to stall
        assert_eq!(action.kind, ActionKind::Escalate);
        assert!(action.reason.unwrap().contains("stall"));
    }

    #[test]
    fn test_composable_decider_chain() {
        // Full chain: Murmuration + Error + Stall + Retry
        let decider = ComposableDecider::new(MurmurationDecider::default())
            .error_aware(0.7)
            .stall_detection(10)
            .with_retry(3);

        let context = DecisionContext::new(0, "investigate").with_tick(1);
        let state = create_test_state();

        // Normal operation - should use base decider
        let action = decider.decide(&context, &state);
        assert_eq!(action.kind, ActionKind::Read);
    }

    #[test]
    fn test_success_rate_modifier() {
        use super::super::action::ActionResult;

        let decider = ComposableDecider::new(PlainDecider).success_rate(0.5);

        // Create context with many failures
        let mut context =
            DecisionContext::new(0, "task").with_remaining_work(vec!["task1".to_string()]);

        // Add 4 failures
        for _ in 0..4 {
            context.add_result(ActionResult::failure(Action::read("test.rs"), "error"));
        }

        let state = create_test_state();
        let action = decider.decide(&context, &state);

        // Should escalate due to low success rate
        assert_eq!(action.kind, ActionKind::Escalate);
        assert!(action.reason.unwrap().contains("success-rate"));
    }
}