o7 0.1.1

O7 workflow DSL runner
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
pub mod check;
pub mod config;
pub mod execute;
pub mod invocation;
pub mod prompt;
pub mod types;

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};

use crate::parser::ast::ExecBlock;
use crate::state::types::HarnessEvent;

/// A single harness entry from the config file.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HarnessEntry {
    pub command: String,
    #[serde(default)]
    pub prompt_slot: Option<String>,
    pub args_mapping: String,
    #[serde(default)]
    pub output_mode: Option<HarnessOutputMode>,
    #[serde(default)]
    pub defaults: Option<HashMap<String, String>>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum HarnessOutputMode {
    #[serde(rename = "text")]
    Text,
    #[serde(rename = "stream-json")]
    StreamJson,
}

impl Default for HarnessOutputMode {
    fn default() -> Self {
        Self::Text
    }
}

/// Context for a run: run_id (populated after first event) and project root.
pub struct RunContext {
    pub run_id: Arc<RwLock<Option<String>>>,
    pub project_root: String,
}

#[derive(Clone)]
pub struct HarnessExecutionContext {
    pub run_id: String,
    pub step_path: Vec<String>,
    pub exec_ordinal: usize,
    pub on_harness_event: Option<Arc<dyn Fn(HarnessEvent) + Send + Sync>>,
}

/// The full harness configuration (parsed from .7/harnesses.toml).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HarnessConfig {
    pub harness: HashMap<String, HarnessEntry>,
}

/// A constructed invocation ready for execution.
#[derive(Debug, Clone)]
pub struct ExecInvocation {
    pub command: Vec<String>,
    pub cwd: String,
    pub env: Option<HashMap<String, String>>,
}

/// The result of executing a harness command.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecResult {
    pub exit_code: i32,
    pub stdout: String,
    pub stderr: String,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub harness_events: Vec<HarnessEvent>,
}

/// Parsed check output from a harness execution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CheckOutput {
    pub result: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

/// Parsed match output from a harness execution (variant check).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MatchOutput {
    pub variant: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

/// Resolve a harness by name from the config.
pub fn resolve_harness<'a>(
    config: &'a HarnessConfig,
    name: &str,
) -> Result<&'a HarnessEntry, String> {
    config.harness.get(name).ok_or_else(|| {
        let available: Vec<&String> = config.harness.keys().collect();
        format!(
            "Harness \"{}\" not found. Available: {}",
            name,
            if available.is_empty() {
                "(none)".to_string()
            } else {
                available
                    .iter()
                    .map(|s| s.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            }
        )
    })
}

/// High-level dispatch: given a pre-loaded config, project root, and an exec block,
/// resolve harness and prompt, build invocation, execute it, and return the result.
pub async fn dispatch_exec(
    config: &HarnessConfig,
    project_root: &str,
    exec_block: &ExecBlock,
    run_context: Option<&RunContext>,
    execution_context: Option<&HarnessExecutionContext>,
) -> Result<ExecResult, String> {
    let entry = resolve_harness(config, &exec_block.harness)?;

    let (resolved_prompt_path, temp_path) = if let Some(ref prompt_file) = exec_block.prompt_file {
        (prompt::resolve_prompt(project_root, prompt_file)?, None)
    } else if let Some(ref prompt_content) = exec_block.prompt {
        if entry.prompt_slot.is_none() {
            // No prompt_slot — prompt field is a script path (check-script harness)
            (prompt::resolve_prompt(project_root, prompt_content)?, None)
        } else {
            // Inline prompt: write to a temp file
            let tmp_dir = std::env::temp_dir();
            let tmp_path = tmp_dir.join(format!("o7-prompt-{}.txt", uuid::Uuid::new_v4()));
            std::fs::write(&tmp_path, prompt_content)
                .map_err(|e| format!("Failed to write temp prompt file: {}", e))?;
            let path_str = tmp_path.to_string_lossy().to_string();
            (path_str, Some(tmp_path))
        }
    } else {
        return Err("Exec block must have either prompt or promptFile".to_string());
    };

    let mut inv =
        invocation::build_invocation(entry, exec_block, &resolved_prompt_path, project_root);

    // Inject run context as env vars
    if let Some(ctx) = run_context {
        if let Ok(guard) = ctx.run_id.read() {
            if let Some(ref run_id) = *guard {
                let run_state_dir = format!("{}/.7/runs/{}", ctx.project_root, run_id);
                let env = inv.env.get_or_insert_with(HashMap::new);
                env.insert("RUN_ID".to_string(), run_id.clone());
                env.insert("RUN_STATE_DIR".to_string(), run_state_dir);
            }
        }
    }

    let result = execute::execute(
        &inv,
        execute::ExecuteOptions {
            output_mode: entry.output_mode.unwrap_or(HarnessOutputMode::Text),
            on_event: execution_context.and_then(|ctx| ctx.on_harness_event.clone()),
            step_path: execution_context.map(|ctx| ctx.step_path.clone()),
            exec_ordinal: execution_context.map(|ctx| ctx.exec_ordinal).unwrap_or(0),
        },
    )
    .await;

    // Clean up temp file if created (always, even on error)
    if let Some(ref path) = temp_path {
        let _ = std::fs::remove_file(path);
    }

    result
}

/// Dispatch an exec block and extract check output from the result.
pub async fn dispatch_check(
    config: &HarnessConfig,
    project_root: &str,
    exec_block: &ExecBlock,
    run_context: Option<&RunContext>,
) -> Result<CheckOutput, String> {
    let result = dispatch_exec(config, project_root, exec_block, run_context, None).await?;
    check::parse_check_result(&result.stdout)
}

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

    #[test]
    fn test_resolve_harness_found() {
        let mut harness_map = HashMap::new();
        harness_map.insert(
            "echo-test".to_string(),
            HarnessEntry {
                command: "echo".to_string(),
                prompt_slot: Some("-p".to_string()),
                args_mapping: "flags".to_string(),
                output_mode: None,
                defaults: None,
            },
        );
        let config = HarnessConfig {
            harness: harness_map,
        };
        let entry = resolve_harness(&config, "echo-test").unwrap();
        assert_eq!(entry.command, "echo");
    }

    #[test]
    fn test_resolve_harness_not_found() {
        let config = HarnessConfig {
            harness: HashMap::new(),
        };
        let result = resolve_harness(&config, "missing");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.contains("Harness \"missing\" not found"));
        assert!(err.contains("(none)"));
    }

    #[test]
    fn test_resolve_harness_not_found_shows_available() {
        let mut harness_map = HashMap::new();
        harness_map.insert(
            "claude".to_string(),
            HarnessEntry {
                command: "claude".to_string(),
                prompt_slot: Some("-p".to_string()),
                args_mapping: "flags".to_string(),
                output_mode: None,
                defaults: None,
            },
        );
        let config = HarnessConfig {
            harness: harness_map,
        };
        let result = resolve_harness(&config, "missing");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.contains("Harness \"missing\" not found"));
        assert!(err.contains("claude"));
    }

    #[tokio::test]
    async fn test_dispatch_exec_no_prompt() {
        let config = HarnessConfig {
            harness: HashMap::new(),
        };
        let exec_block = ExecBlock {
            harness: "test".to_string(),
            prompt: None,
            prompt_file: None,
            args: None,
            line: 1,
            column: 1,
        };
        let result = dispatch_exec(&config, "/nonexistent", &exec_block, None, None).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_dispatch_exec_missing_harness() {
        let config = HarnessConfig {
            harness: HashMap::new(),
        };
        let exec_block = ExecBlock {
            harness: "test".to_string(),
            prompt: Some("do something".to_string()),
            prompt_file: None,
            args: None,
            line: 1,
            column: 1,
        };
        let result = dispatch_exec(&config, "/nonexistent", &exec_block, None, None).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("not found"));
    }

    #[tokio::test]
    async fn test_dispatch_exec_inline_prompt() {
        use std::fs;
        use tempfile::TempDir;

        let dir = TempDir::new().unwrap();
        let dot7 = dir.path().join(".7");
        fs::create_dir_all(&dot7).unwrap();
        fs::write(
            dot7.join("harnesses.toml"),
            r#"
[harness.echo-test]
command = "echo"
prompt_slot = ""
args_mapping = "flags"
"#,
        )
        .unwrap();

        let config = config::load_harness_config(dir.path().to_str().unwrap()).unwrap();

        let exec_block = ExecBlock {
            harness: "echo-test".to_string(),
            prompt: Some("hello world".to_string()),
            prompt_file: None,
            args: None,
            line: 1,
            column: 1,
        };

        let result = dispatch_exec(
            &config,
            dir.path().to_str().unwrap(),
            &exec_block,
            None,
            None,
        )
        .await;
        assert!(result.is_ok(), "dispatch_exec failed: {:?}", result);
        let exec_result = result.unwrap();
        assert_eq!(exec_result.exit_code, 0);
    }

    #[tokio::test]
    async fn test_dispatch_exec_with_prompt_file() {
        use std::fs;
        use tempfile::TempDir;

        let dir = TempDir::new().unwrap();
        let dot7 = dir.path().join(".7");
        fs::create_dir_all(&dot7).unwrap();
        fs::write(
            dot7.join("harnesses.toml"),
            r#"
[harness.echo-test]
command = "echo"
prompt_slot = ""
args_mapping = "flags"
"#,
        )
        .unwrap();

        let prompts_dir = dir.path().join("prompts");
        fs::create_dir_all(&prompts_dir).unwrap();
        fs::write(prompts_dir.join("test.md"), "test prompt content").unwrap();

        let config = config::load_harness_config(dir.path().to_str().unwrap()).unwrap();

        let exec_block = ExecBlock {
            harness: "echo-test".to_string(),
            prompt: None,
            prompt_file: Some("test.md".to_string()),
            args: None,
            line: 1,
            column: 1,
        };

        let result = dispatch_exec(
            &config,
            dir.path().to_str().unwrap(),
            &exec_block,
            None,
            None,
        )
        .await;
        assert!(result.is_ok(), "dispatch_exec failed: {:?}", result);
    }

    #[tokio::test]
    async fn test_check_script_dispatch_without_prompt_slot() {
        use std::fs;
        use tempfile::TempDir;

        let dir = TempDir::new().unwrap();
        let dot7 = dir.path().join(".7");
        fs::create_dir_all(&dot7).unwrap();
        fs::write(
            dot7.join("harnesses.toml"),
            r#"
[harness.check-script]
command = "bash"
args_mapping = "flags"
"#,
        )
        .unwrap();

        // Create a simple check script
        let scripts_dir = dir.path().join("scripts");
        fs::create_dir_all(&scripts_dir).unwrap();
        let script = scripts_dir.join("check.sh");
        fs::write(&script, "#!/bin/bash\necho '{\"result\": false}'").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
        }

        let config = config::load_harness_config(dir.path().to_str().unwrap()).unwrap();
        let exec_block = ExecBlock {
            harness: "check-script".to_string(),
            prompt: Some("scripts/check.sh".to_string()),
            prompt_file: None,
            args: None,
            line: 1,
            column: 1,
        };

        let result = dispatch_exec(
            &config,
            dir.path().to_str().unwrap(),
            &exec_block,
            None,
            None,
        )
        .await;
        assert!(result.is_ok(), "dispatch failed: {:?}", result);
        let exec_result = result.unwrap();
        assert_eq!(exec_result.exit_code, 0);
        let parsed: serde_json::Value = serde_json::from_str(&exec_result.stdout.trim()).unwrap();
        assert_eq!(parsed["result"], false);
    }

    #[tokio::test]
    async fn test_run_context_injects_env_vars() {
        use std::fs;
        use std::sync::{Arc, RwLock};
        use tempfile::TempDir;

        let dir = TempDir::new().unwrap();
        let dot7 = dir.path().join(".7");
        fs::create_dir_all(&dot7).unwrap();
        fs::write(
            dot7.join("harnesses.toml"),
            r#"
[harness.check-script]
command = "bash"
args_mapping = "flags"
"#,
        )
        .unwrap();

        let scripts_dir = dir.path().join("scripts");
        fs::create_dir_all(&scripts_dir).unwrap();
        fs::write(
            scripts_dir.join("env-check.sh"),
            "#!/bin/bash\necho \"{\\\"run_id\\\": \\\"$RUN_ID\\\", \\\"state_dir\\\": \\\"$RUN_STATE_DIR\\\"}\"",
        ).unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(
                scripts_dir.join("env-check.sh"),
                fs::Permissions::from_mode(0o755),
            )
            .unwrap();
        }

        let config = config::load_harness_config(dir.path().to_str().unwrap()).unwrap();
        let run_context = RunContext {
            run_id: Arc::new(RwLock::new(Some("test-run-123".to_string()))),
            project_root: dir.path().to_str().unwrap().to_string(),
        };

        let exec_block = ExecBlock {
            harness: "check-script".to_string(),
            prompt: Some("scripts/env-check.sh".to_string()),
            prompt_file: None,
            args: None,
            line: 1,
            column: 1,
        };

        let result = dispatch_exec(
            &config,
            dir.path().to_str().unwrap(),
            &exec_block,
            Some(&run_context),
            None,
        )
        .await;
        assert!(result.is_ok());
        let exec_result = result.unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&exec_result.stdout.trim()).unwrap();
        assert_eq!(parsed["run_id"], "test-run-123");
    }
}