summaryrefslogtreecommitdiff
path: root/makima/src/daemon/chain/runner.rs
blob: dfbcfa7629f7fd83060e18a4d9d95789d7b8f476 (plain) (blame)
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
//! Chain runner - creates and orchestrates contracts from chain definitions.
//!
//! Handles the lifecycle of a chain:
//! 1. Parse chain definition
//! 2. Validate DAG
//! 3. Create chain record
//! 4. Create contracts in dependency order
//! 5. Monitor and trigger dependent contracts

use std::collections::HashMap;
use std::path::Path;
use thiserror::Error;

use super::dag::{topological_sort, validate_dag, DagError};
use super::parser::{parse_chain_file, ChainDefinition, ParseError};
use crate::db::models::{
    AddChainRepositoryRequest, CreateChainContractRequest, CreateChainDeliverableRequest,
    CreateChainRequest, CreateChainTaskRequest,
};

/// Error type for chain runner operations.
#[derive(Error, Debug)]
pub enum RunnerError {
    #[error("Parse error: {0}")]
    Parse(#[from] ParseError),

    #[error("DAG error: {0}")]
    Dag(#[from] DagError),

    #[error("API error: {0}")]
    Api(String),

    #[error("Contract creation failed: {0}")]
    ContractCreation(String),
}

/// Chain runner for creating and managing chains.
pub struct ChainRunner {
    /// Base API URL
    api_url: String,
    /// API key for authentication
    api_key: String,
}

impl ChainRunner {
    /// Create a new chain runner.
    pub fn new(api_url: String, api_key: String) -> Self {
        Self { api_url, api_key }
    }

    /// Load and validate a chain from a YAML file.
    pub fn load_chain<P: AsRef<Path>>(&self, path: P) -> Result<ChainDefinition, RunnerError> {
        let chain = parse_chain_file(path)?;
        validate_dag(&chain)?;
        Ok(chain)
    }

    /// Convert a chain definition to a CreateChainRequest for API submission.
    pub fn to_create_request(&self, chain: &ChainDefinition) -> CreateChainRequest {
        let contracts: Vec<CreateChainContractRequest> = chain
            .contracts
            .iter()
            .map(|c| CreateChainContractRequest {
                name: c.name.clone(),
                description: c.description.clone(),
                contract_type: Some(c.contract_type.clone()),
                initial_phase: None,
                phases: c.phases.clone(),
                depends_on: c.depends_on.clone(),
                tasks: c.tasks.as_ref().map(|tasks| {
                    tasks
                        .iter()
                        .map(|t| CreateChainTaskRequest {
                            name: t.name.clone(),
                            plan: t.plan.clone(),
                        })
                        .collect()
                }),
                deliverables: c.deliverables.as_ref().map(|dels| {
                    dels.iter()
                        .map(|d| CreateChainDeliverableRequest {
                            id: d.id.clone(),
                            name: d.name.clone(),
                            priority: Some(d.priority.clone()),
                        })
                        .collect()
                }),
                editor_x: None,
                editor_y: None,
            })
            .collect();

        let (loop_enabled, loop_max_iterations, loop_progress_check) =
            match &chain.loop_config {
                Some(lc) => (
                    Some(lc.enabled),
                    Some(lc.max_iterations),
                    lc.progress_check.clone(),
                ),
                None => (None, None, None),
            };

        // Convert repository definitions to API format
        let repositories: Vec<AddChainRepositoryRequest> = chain
            .repositories
            .iter()
            .map(|r| AddChainRepositoryRequest {
                name: r.name.clone(),
                repository_url: r.repository_url.clone(),
                local_path: r.local_path.clone(),
                source_type: r.source_type.clone(),
                is_primary: r.is_primary,
            })
            .collect();

        CreateChainRequest {
            name: chain.name.clone(),
            description: chain.description.clone(),
            repositories: if repositories.is_empty() {
                None
            } else {
                Some(repositories)
            },
            loop_enabled,
            loop_max_iterations,
            loop_progress_check,
            contracts: Some(contracts),
        }
    }

    /// Get contracts in topological order (for display/debugging).
    pub fn get_execution_order<'a>(
        &self,
        chain: &'a ChainDefinition,
    ) -> Result<Vec<&'a str>, RunnerError> {
        Ok(topological_sort(chain)?)
    }

    /// Generate ASCII visualization of the chain DAG.
    pub fn visualize_dag(&self, chain: &ChainDefinition) -> String {
        use super::dag::get_contract_depths;

        let depths = get_contract_depths(chain);
        let mut lines: Vec<String> = vec![];

        lines.push(format!("Chain: {}", chain.name));
        if let Some(desc) = &chain.description {
            lines.push(format!("  {}", desc));
        }
        lines.push(String::new());

        // Group contracts by depth
        let mut by_depth: HashMap<usize, Vec<&str>> = HashMap::new();
        for contract in &chain.contracts {
            let depth = depths.get(contract.name.as_str()).copied().unwrap_or(0);
            by_depth.entry(depth).or_default().push(&contract.name);
        }

        // Find max depth
        let max_depth = by_depth.keys().max().copied().unwrap_or(0);

        // Build visualization
        for depth in 0..=max_depth {
            if let Some(contracts) = by_depth.get(&depth) {
                let contract_strs: Vec<String> = contracts
                    .iter()
                    .map(|name| format!("[{}]", name))
                    .collect();

                let indent = "  ".repeat(depth);
                lines.push(format!("{}{}", indent, contract_strs.join("  ")));

                // Draw arrows to next level
                if depth < max_depth {
                    if let Some(next_contracts) = by_depth.get(&(depth + 1)) {
                        // Find which contracts connect to the next level
                        for next in next_contracts {
                            let next_contract = chain
                                .contracts
                                .iter()
                                .find(|c| c.name.as_str() == *next)
                                .unwrap();

                            if let Some(deps) = &next_contract.depends_on {
                                for dep in deps {
                                    if contracts.contains(&dep.as_str()) {
                                        let arrow_indent = "  ".repeat(depth);
                                        lines.push(format!("{}  │", arrow_indent));
                                        lines.push(format!("{}  ▼", arrow_indent));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        lines.join("\n")
    }
}

/// Compute editor positions for contracts based on DAG layout.
///
/// Returns a map of contract name to (x, y) positions suitable for
/// the GUI editor.
pub fn compute_editor_positions(chain: &ChainDefinition) -> HashMap<String, (f64, f64)> {
    use super::dag::get_contract_depths;

    let depths = get_contract_depths(chain);
    let mut positions: HashMap<String, (f64, f64)> = HashMap::new();

    // Group by depth
    let mut by_depth: HashMap<usize, Vec<&str>> = HashMap::new();
    for contract in &chain.contracts {
        let depth = depths.get(contract.name.as_str()).copied().unwrap_or(0);
        by_depth.entry(depth).or_default().push(&contract.name);
    }

    // Compute positions: x based on depth, y based on index within depth
    let x_spacing = 250.0;
    let y_spacing = 150.0;

    for (depth, contracts) in &by_depth {
        let x = (*depth as f64) * x_spacing + 100.0;
        for (i, name) in contracts.iter().enumerate() {
            let y = (i as f64) * y_spacing + 100.0;
            positions.insert(name.to_string(), (x, y));
        }
    }

    positions
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::daemon::chain::parser::parse_chain_yaml;

    #[test]
    fn test_to_create_request() {
        let yaml = r#"
name: Test Chain
description: A test chain
repo: https://github.com/test/repo
contracts:
  - name: Research
    type: simple
    phases: [plan, execute]
    tasks:
      - name: Analyze
        plan: "Analyze the codebase"
    deliverables:
      - id: analysis
        name: Analysis Doc
        priority: required
  - name: Implement
    depends_on: [Research]
    tasks:
      - name: Build
        plan: "Build the feature"
loop:
  enabled: true
  max_iterations: 5
  progress_check: "Check completion"
"#;
        let chain = parse_chain_yaml(yaml).unwrap();
        let runner = ChainRunner::new("http://localhost".to_string(), "key".to_string());
        let request = runner.to_create_request(&chain);

        assert_eq!(request.name, "Test Chain");
        assert_eq!(request.description, Some("A test chain".to_string()));
        assert_eq!(
            request.repository_url,
            Some("https://github.com/test/repo".to_string())
        );
        assert_eq!(request.loop_enabled, Some(true));
        assert_eq!(request.loop_max_iterations, Some(5));

        let contracts = request.contracts.unwrap();
        assert_eq!(contracts.len(), 2);
        assert_eq!(contracts[0].name, "Research");
        assert_eq!(contracts[0].phases, Some(vec!["plan".to_string(), "execute".to_string()]));
        assert_eq!(
            contracts[1].depends_on,
            Some(vec!["Research".to_string()])
        );
    }

    #[test]
    fn test_get_execution_order() {
        let yaml = r#"
name: Order Test
contracts:
  - name: C
    depends_on: [B]
    tasks:
      - name: Task
        plan: "Do C"
  - name: A
    tasks:
      - name: Task
        plan: "Do A"
  - name: B
    depends_on: [A]
    tasks:
      - name: Task
        plan: "Do B"
"#;
        let chain = parse_chain_yaml(yaml).unwrap();
        let runner = ChainRunner::new("http://localhost".to_string(), "key".to_string());
        let order = runner.get_execution_order(&chain).unwrap();

        let pos_a = order.iter().position(|&n| n == "A").unwrap();
        let pos_b = order.iter().position(|&n| n == "B").unwrap();
        let pos_c = order.iter().position(|&n| n == "C").unwrap();

        assert!(pos_a < pos_b);
        assert!(pos_b < pos_c);
    }

    #[test]
    fn test_visualize_dag() {
        let yaml = r#"
name: Visual Test
description: Test visualization
contracts:
  - name: A
    tasks:
      - name: Task
        plan: "Do A"
  - name: B
    depends_on: [A]
    tasks:
      - name: Task
        plan: "Do B"
"#;
        let chain = parse_chain_yaml(yaml).unwrap();
        let runner = ChainRunner::new("http://localhost".to_string(), "key".to_string());
        let viz = runner.visualize_dag(&chain);

        assert!(viz.contains("Chain: Visual Test"));
        assert!(viz.contains("[A]"));
        assert!(viz.contains("[B]"));
    }

    #[test]
    fn test_compute_editor_positions() {
        let yaml = r#"
name: Position Test
contracts:
  - name: A
    tasks:
      - name: Task
        plan: "Do A"
  - name: B
    depends_on: [A]
    tasks:
      - name: Task
        plan: "Do B"
  - name: C
    depends_on: [A]
    tasks:
      - name: Task
        plan: "Do C"
"#;
        let chain = parse_chain_yaml(yaml).unwrap();
        let positions = compute_editor_positions(&chain);

        // A should be at depth 0 (x = 100)
        let (a_x, _) = positions.get("A").unwrap();
        assert_eq!(*a_x, 100.0);

        // B and C should be at depth 1 (x = 350)
        let (b_x, _) = positions.get("B").unwrap();
        let (c_x, _) = positions.get("C").unwrap();
        assert_eq!(*b_x, 350.0);
        assert_eq!(*c_x, 350.0);
    }
}