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
//! ParallelBlueprint: Execution plan with dependency graph and conflict detection
//!
//! ```text
//! Vec<MutationSpec> + DependencyGraph → ParallelBlueprint
//!//!                    ┌───────────────────────┴───────────────────────┐
//!                    ↓                                               ↓
//!          [conflicts.is_empty()]                         [conflicts detected]
//!                    ↓                                               ↓
//!           Autonomous Execution                      Escalate to High-level LLM
//! ```

use super::conflict;
use super::spec::MutationSpec;
use std::collections::{HashMap, HashSet};

/// Parallel execution blueprint
#[derive(Debug, Clone)]
pub struct ParallelBlueprint {
    /// Mutation specifications to execute
    pub mutations: Vec<MutationSpec>,

    /// Dependency graph for ordering
    pub deps: DependencyGraph,

    /// Conflicts detected at plan time
    pub conflicts: Vec<Conflict>,
}

impl ParallelBlueprint {
    /// Create a new empty blueprint
    pub fn new() -> Self {
        Self {
            mutations: vec![],
            deps: DependencyGraph::new(),
            conflicts: vec![],
        }
    }

    /// Create blueprint from mutations (auto-detects conflicts)
    pub fn from_mutations(mutations: Vec<MutationSpec>) -> Self {
        let mut builder = BlueprintBuilder::new();
        for spec in mutations {
            builder.add(spec);
        }
        builder.build()
    }

    /// Check if escalation to high-level LLM is needed
    pub fn needs_escalation(&self) -> bool {
        !self.conflicts.is_empty()
    }

    /// Get mutations ready to execute (all dependencies satisfied)
    pub fn ready_set(&self, completed: &HashSet<usize>) -> Vec<usize> {
        self.deps.ready_set(self.mutations.len(), completed)
    }

    /// Calculate parallelism factor (1.0 = sequential, N = N parallel tracks)
    pub fn parallelism(&self) -> f64 {
        if self.mutations.is_empty() {
            return 1.0;
        }

        let critical_path = self.deps.critical_path_length(self.mutations.len());
        if critical_path == 0 {
            self.mutations.len() as f64
        } else {
            self.mutations.len() as f64 / critical_path as f64
        }
    }

    /// Get topological levels for parallel execution
    pub fn topological_levels(&self) -> Vec<Vec<usize>> {
        self.deps.topological_levels(self.mutations.len())
    }
}

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

/// Dependency graph for mutation ordering
#[derive(Debug, Clone, Default)]
pub struct DependencyGraph {
    /// Forward edges: idx → Vec<depends_on_idx>
    edges: HashMap<usize, Vec<usize>>,
}

impl DependencyGraph {
    pub fn new() -> Self {
        Self::default()
    }

    /// Add dependency: `from` depends on `to` (to must complete before from)
    pub fn add_dependency(&mut self, from: usize, to: usize) {
        self.edges.entry(from).or_default().push(to);
    }

    /// Get all dependencies for a mutation
    pub fn dependencies_of(&self, idx: usize) -> &[usize] {
        self.edges.get(&idx).map(|v| v.as_slice()).unwrap_or(&[])
    }

    /// Check if mutation is ready (all dependencies completed)
    pub fn is_ready(&self, idx: usize, completed: &HashSet<usize>) -> bool {
        self.dependencies_of(idx)
            .iter()
            .all(|dep| completed.contains(dep))
    }

    /// Get all mutations ready to execute
    pub fn ready_set(&self, total: usize, completed: &HashSet<usize>) -> Vec<usize> {
        (0..total)
            .filter(|idx| !completed.contains(idx) && self.is_ready(*idx, completed))
            .collect()
    }

    /// Check if there's an ordering between any pair of indices
    pub fn has_ordering(&self, indices: &[usize]) -> bool {
        for &a in indices {
            for &b in indices {
                if a != b && self.depends_on(a, b) {
                    return true;
                }
            }
        }
        false
    }

    /// Check if `a` depends on `b` (directly or transitively)
    pub fn depends_on(&self, a: usize, b: usize) -> bool {
        let mut visited = HashSet::new();
        self.depends_on_recursive(a, b, &mut visited)
    }

    fn depends_on_recursive(&self, a: usize, b: usize, visited: &mut HashSet<usize>) -> bool {
        if visited.contains(&a) {
            return false;
        }
        visited.insert(a);

        for &dep in self.dependencies_of(a) {
            if dep == b || self.depends_on_recursive(dep, b, visited) {
                return true;
            }
        }
        false
    }

    /// Calculate critical path length
    pub fn critical_path_length(&self, total: usize) -> usize {
        let mut memo: HashMap<usize, usize> = HashMap::new();

        fn dfs(idx: usize, graph: &DependencyGraph, memo: &mut HashMap<usize, usize>) -> usize {
            if let Some(&cached) = memo.get(&idx) {
                return cached;
            }

            let max_dep = graph
                .dependencies_of(idx)
                .iter()
                .map(|&dep| dfs(dep, graph, memo))
                .max()
                .unwrap_or(0);

            let length = max_dep + 1;
            memo.insert(idx, length);
            length
        }

        (0..total)
            .map(|idx| dfs(idx, self, &mut memo))
            .max()
            .unwrap_or(0)
    }

    /// Get topological levels (mutations in same level can run in parallel)
    pub fn topological_levels(&self, total: usize) -> Vec<Vec<usize>> {
        let mut levels: Vec<Vec<usize>> = vec![];
        let mut completed: HashSet<usize> = HashSet::new();

        while completed.len() < total {
            let ready = self.ready_set(total, &completed);
            if ready.is_empty() {
                // Cycle detected or all done
                break;
            }

            for &idx in &ready {
                completed.insert(idx);
            }
            levels.push(ready);
        }

        levels
    }
}

/// Conflict detected during blueprint planning
#[derive(Debug, Clone)]
pub struct Conflict {
    /// Type of conflict
    pub kind: ConflictKind,

    /// Indices of involved mutations
    pub involved: Vec<usize>,

    /// Human-readable question for escalation
    pub question: String,
}

/// Types of conflicts
#[derive(Debug, Clone)]
pub enum ConflictKind {
    /// Same target modified by multiple mutations
    SameTarget { target: String },

    /// Order changes semantics
    OrderDependent { reason: String },

    /// One mutation deletes what another references
    DeleteReference {
        deleted: String,
        referenced_by: String,
    },
}

/// Builder for creating ParallelBlueprint
#[derive(Debug, Default)]
pub struct BlueprintBuilder {
    specs: Vec<MutationSpec>,
    deps: DependencyGraph,
}

impl BlueprintBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a mutation spec
    pub fn add(&mut self, spec: MutationSpec) -> &mut Self {
        self.specs.push(spec);
        self
    }

    /// Add dependency between mutations
    pub fn add_dependency(&mut self, from: usize, to: usize) -> &mut Self {
        self.deps.add_dependency(from, to);
        self
    }

    /// Build the blueprint with conflict detection
    pub fn build(self) -> ParallelBlueprint {
        let conflicts = detect_conflicts(&self.specs, &self.deps);

        ParallelBlueprint {
            mutations: self.specs,
            deps: self.deps,
            conflicts,
        }
    }
}

/// Detect conflicts in mutation list using conflict::specs_conflict
fn detect_conflicts(specs: &[MutationSpec], deps: &DependencyGraph) -> Vec<Conflict> {
    let mut conflicts = vec![];

    // Use conflict::find_conflicting_pairs for pair-wise conflict detection
    let conflicting_pairs = conflict::find_conflicting_pairs(specs);

    for (i, j) in conflicting_pairs {
        // Skip if dependency ordering exists
        if deps.has_ordering(&[i, j]) {
            continue;
        }

        // Create conflict record
        conflicts.push(Conflict {
            kind: ConflictKind::SameTarget {
                target: format!("spec[{}] vs spec[{}]", i, j),
            },
            involved: vec![i, j],
            question: format!(
                "Specs {} and {} conflict without defined order. Which should be applied first?",
                i, j
            ),
        });
    }

    conflicts
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::executor::spec::{MutationTargetSymbol, Scope};
    use ryo_symbol::SymbolId;

    /// Create a dummy SymbolId for testing
    fn dummy_id(index: u32) -> SymbolId {
        SymbolId::parse(&format!("{}v1", index)).expect("valid dummy id")
    }

    #[test]
    fn test_dependency_graph_ready_set() {
        let mut deps = DependencyGraph::new();
        // 0 depends on nothing
        // 1 depends on 0
        // 2 depends on nothing
        deps.add_dependency(1, 0);

        let completed = HashSet::new();
        let ready = deps.ready_set(3, &completed);
        assert!(ready.contains(&0));
        assert!(!ready.contains(&1)); // depends on 0
        assert!(ready.contains(&2));

        let mut completed = HashSet::new();
        completed.insert(0);
        let ready = deps.ready_set(3, &completed);
        assert!(ready.contains(&1)); // now ready
        assert!(ready.contains(&2));
    }

    #[test]
    fn test_topological_levels() {
        let mut deps = DependencyGraph::new();
        // Level 0: 0, 2
        // Level 1: 1 (depends on 0)
        // Level 2: 3 (depends on 1)
        deps.add_dependency(1, 0);
        deps.add_dependency(3, 1);

        let levels = deps.topological_levels(4);
        assert_eq!(levels.len(), 3);
        assert!(levels[0].contains(&0));
        assert!(levels[0].contains(&2));
        assert!(levels[1].contains(&1));
        assert!(levels[2].contains(&3));
    }

    #[test]
    fn test_same_target_conflict_detection() {
        let specs = vec![
            MutationSpec::ChangeVisibility {
                target: MutationTargetSymbol::ById(dummy_id(1)),
                visibility: crate::executor::spec::Visibility::Pub,
            },
            MutationSpec::AddDerive {
                target: MutationTargetSymbol::ById(dummy_id(1)),
                derives: vec!["Debug".to_string()],
            },
        ];

        let blueprint = ParallelBlueprint::from_mutations(specs);
        // Both target "Config" without ordering - should conflict
        assert!(!blueprint.conflicts.is_empty());
    }

    #[test]
    fn test_rename_chain_conflict() {
        use ryo_symbol::{SymbolKind, SymbolPath, SymbolRegistry};

        // Create dummy symbol IDs for testing
        let mut registry = SymbolRegistry::new();
        let path_a = SymbolPath::parse("test_crate::A").unwrap();
        let symbol_a = registry.register(path_a, SymbolKind::Struct).unwrap();

        let specs = vec![
            MutationSpec::Rename {
                target: MutationTargetSymbol::ById(symbol_a),
                to: "B".to_string(),
                scope: Scope::Project,
            },
            MutationSpec::Rename {
                target: MutationTargetSymbol::ById(symbol_a),
                to: "C".to_string(),
                scope: Scope::Project,
            },
        ];

        let blueprint = ParallelBlueprint::from_mutations(specs);
        // Two renames on same target should conflict
        assert!(
            !blueprint.conflicts.is_empty(),
            "Expected conflict for two renames on same target"
        );
    }

    #[test]
    fn test_no_conflict_with_ordering() {
        use ryo_symbol::{SymbolKind, SymbolPath, SymbolRegistry};

        // Create dummy symbol IDs for testing
        let mut registry = SymbolRegistry::new();
        let path_a = SymbolPath::parse("test_crate::A").unwrap();
        let path_b = SymbolPath::parse("test_crate::B").unwrap();
        let symbol_a = registry.register(path_a, SymbolKind::Struct).unwrap();
        let _symbol_b = registry.register(path_b, SymbolKind::Struct).unwrap();

        let mut builder = BlueprintBuilder::new();
        builder.add(MutationSpec::Rename {
            target: MutationTargetSymbol::ById(symbol_a),
            to: "B".to_string(),
            scope: Scope::Project,
        });
        builder.add(MutationSpec::Rename {
            target: MutationTargetSymbol::ById(symbol_a),
            to: "C".to_string(),
            scope: Scope::Project,
        });
        // Explicit ordering: 1 depends on 0
        builder.add_dependency(1, 0);

        let blueprint = builder.build();
        // With ordering, no conflict
        assert!(blueprint.conflicts.is_empty());
    }

    #[test]
    fn test_delete_reference_conflict() {
        use ryo_source::ItemKind;

        let specs = vec![
            MutationSpec::RemoveItem {
                target: MutationTargetSymbol::ById(dummy_id(1)),
                item_kind: ItemKind::Struct,
            },
            MutationSpec::AddDerive {
                target: MutationTargetSymbol::ById(dummy_id(1)),
                derives: vec!["Debug".to_string()],
            },
        ];

        let blueprint = ParallelBlueprint::from_mutations(specs);
        // RemoveItem + AddDerive on same target should conflict
        assert!(
            !blueprint.conflicts.is_empty(),
            "Expected conflict: RemoveItem + AddDerive on same target"
        );
    }

    #[test]
    fn test_visibility_conflict() {
        use crate::executor::spec::Visibility;

        let specs = vec![
            MutationSpec::ChangeVisibility {
                target: MutationTargetSymbol::ById(dummy_id(1)),
                visibility: Visibility::Pub,
            },
            MutationSpec::ChangeVisibility {
                target: MutationTargetSymbol::ById(dummy_id(1)),
                visibility: Visibility::PubCrate,
            },
        ];

        let blueprint = ParallelBlueprint::from_mutations(specs);
        // Both try to change Config's visibility to different values
        assert!(!blueprint.conflicts.is_empty());
    }

    #[test]
    fn test_visibility_no_conflict_same_value() {
        use crate::executor::spec::Visibility;

        let specs = vec![
            MutationSpec::ChangeVisibility {
                target: MutationTargetSymbol::ById(dummy_id(1)),
                visibility: Visibility::Pub,
            },
            MutationSpec::ChangeVisibility {
                target: MutationTargetSymbol::ById(dummy_id(1)),
                visibility: Visibility::Pub,
            },
        ];

        let blueprint = ParallelBlueprint::from_mutations(specs);
        // Same visibility - no conflict (idempotent)
        let vis_conflicts: Vec<_> = blueprint
            .conflicts
            .iter()
            .filter(|c| {
                matches!(c.kind, ConflictKind::SameTarget { ref target } if target == "Config")
                    && c.question.contains("visibility")
            })
            .collect();
        assert!(vis_conflicts.is_empty());
    }
}