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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! Persisted state types matching the cross-implementation O7 state format.
//!
//! These types define the JSON schema for run state persistence. They are
//! distinct from the engine's internal types (which use an event-log model)
//! and serve as the cross-implementation contract between TS and Rust runners.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;

/// Run status for persisted state. Includes "pending" which the engine
/// does not use internally but is valid in persisted snapshots.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum RunStatus {
    #[serde(rename = "pending")]
    Pending,
    #[serde(rename = "running")]
    Running,
    #[serde(rename = "completed")]
    Completed,
    #[serde(rename = "failed")]
    Failed,
    #[serde(rename = "paused")]
    Paused,
}

impl fmt::Display for RunStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RunStatus::Pending => write!(f, "pending"),
            RunStatus::Running => write!(f, "running"),
            RunStatus::Completed => write!(f, "completed"),
            RunStatus::Failed => write!(f, "failed"),
            RunStatus::Paused => write!(f, "paused"),
        }
    }
}

/// Step kind in the persisted format.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum StepKind {
    #[serde(rename = "run")]
    Run,
    #[serde(rename = "if")]
    If,
    #[serde(rename = "while")]
    While,
    #[serde(rename = "par-and")]
    ParAnd,
    #[serde(rename = "exec")]
    Exec,
}

/// Step status in the persisted format.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum StepStatusPersisted {
    #[serde(rename = "pending")]
    Pending,
    #[serde(rename = "in_progress")]
    InProgress,
    #[serde(rename = "completed")]
    Completed,
    #[serde(rename = "failed")]
    Failed,
}

/// Branch status in the persisted format.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum BranchStatusPersisted {
    #[serde(rename = "pending")]
    Pending,
    #[serde(rename = "running")]
    Running,
    #[serde(rename = "completed")]
    Completed,
    #[serde(rename = "failed")]
    Failed,
}

/// All safe boundary types from the O7 spec.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum SafeBoundaryType {
    #[serde(rename = "before-step-start")]
    BeforeStepStart,
    #[serde(rename = "after-step-complete")]
    AfterStepComplete,
    #[serde(rename = "before-conditional-body")]
    BeforeConditionalBody,
    #[serde(rename = "after-conditional-body")]
    AfterConditionalBody,
    #[serde(rename = "before-loop-iteration")]
    BeforeLoopIteration,
    #[serde(rename = "after-loop-iteration")]
    AfterLoopIteration,
    #[serde(rename = "after-branch-transition")]
    AfterBranchTransition,
    #[serde(rename = "before-join")]
    BeforeJoin,
    #[serde(rename = "after-join")]
    AfterJoin,
    #[serde(rename = "before-match-arm")]
    BeforeMatchArm,
    #[serde(rename = "after-match-arm")]
    AfterMatchArm,
}

/// Metadata for exec steps.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecMeta {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub harness: Option<String>,
    #[serde(rename = "promptRef", skip_serializing_if = "Option::is_none")]
    pub prompt_ref: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub args: Option<HashMap<String, serde_json::Value>>,
}

/// Result of a check evaluation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CheckResult {
    pub result: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

/// Details about a step or branch failure.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FailureDetails {
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timestamp: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct HarnessEvent {
    pub sequence: usize,
    #[serde(rename = "execOrdinal")]
    pub exec_ordinal: usize,
    pub stream: HarnessEventStream,
    pub kind: HarnessEventKind,
    pub raw: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parsed: Option<serde_json::Value>,
    #[serde(rename = "stepPath", skip_serializing_if = "Option::is_none")]
    pub step_path: Option<Vec<String>>,
    #[serde(rename = "boundaryIndex", skip_serializing_if = "Option::is_none")]
    pub boundary_index: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timestamp: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum HarnessEventStream {
    #[serde(rename = "stdout")]
    Stdout,
    #[serde(rename = "stderr")]
    Stderr,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum HarnessEventKind {
    #[serde(rename = "json")]
    Json,
    #[serde(rename = "text")]
    Text,
    #[serde(rename = "status")]
    Status,
    #[serde(rename = "error")]
    Error,
}

/// Persisted step state snapshot.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StepStatePersisted {
    pub name: String,
    pub kind: StepKind,
    pub status: StepStatusPersisted,
    #[serde(rename = "execMeta", skip_serializing_if = "Option::is_none")]
    pub exec_meta: Option<ExecMeta>,
    #[serde(rename = "checkResult", skip_serializing_if = "Option::is_none")]
    pub check_result: Option<CheckResult>,
    #[serde(rename = "failureDetails", skip_serializing_if = "Option::is_none")]
    pub failure_details: Option<FailureDetails>,
    #[serde(rename = "startedAt", skip_serializing_if = "Option::is_none")]
    pub started_at: Option<String>,
    #[serde(rename = "completedAt", skip_serializing_if = "Option::is_none")]
    pub completed_at: Option<String>,
}

/// Persisted branch state snapshot.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BranchState {
    #[serde(rename = "workflowName")]
    pub workflow_name: String,
    pub status: BranchStatusPersisted,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output: Option<serde_json::Value>,
    #[serde(rename = "failureDetails", skip_serializing_if = "Option::is_none")]
    pub failure_details: Option<FailureDetails>,
}

/// A safe boundary where the engine can pause/resume.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SafeBoundary {
    #[serde(rename = "type")]
    pub boundary_type: SafeBoundaryType,
    #[serde(rename = "stepPath")]
    pub step_path: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timestamp: Option<String>,
    pub index: usize,
}

/// Entry in the execution call stack.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CallStackEntry {
    pub workflow: String,
    #[serde(rename = "stepIndex")]
    pub step_index: usize,
}

/// Collected output from a parallel branch.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CollectedOutput {
    pub workflow: String,
    pub output: serde_json::Value,
}

/// The full persisted run state snapshot, matching the cross-implementation JSON schema.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PersistedRunState {
    #[serde(rename = "schemaVersion")]
    pub schema_version: u32,
    #[serde(rename = "runId")]
    pub run_id: String,
    pub timestamp: String,
    #[serde(rename = "rootWorkflow")]
    pub root_workflow: String,
    pub status: RunStatus,
    #[serde(rename = "callStack")]
    pub call_stack: Vec<CallStackEntry>,
    pub steps: HashMap<String, StepStatePersisted>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub branches: Option<HashMap<String, Vec<BranchState>>>,
    #[serde(rename = "collectedOutputs", skip_serializing_if = "Option::is_none")]
    pub collected_outputs: Option<HashMap<String, Vec<CollectedOutput>>>,
    #[serde(rename = "harnessEventLog", skip_serializing_if = "Option::is_none")]
    pub harness_event_log: Option<Vec<HarnessEvent>>,
    #[serde(rename = "safeBoundaries")]
    pub safe_boundaries: Vec<SafeBoundary>,
    #[serde(rename = "currentBoundaryIndex")]
    pub current_boundary_index: i64,
    /// The full event log for round-trip fidelity.
    #[serde(rename = "eventLog", skip_serializing_if = "Option::is_none")]
    pub event_log: Option<Vec<crate::engine::types::ExecutionEvent>>,
}

/// Summary of a run for listing purposes.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunSummary {
    #[serde(rename = "runId")]
    pub run_id: String,
    pub timestamp: String,
    #[serde(rename = "rootWorkflow")]
    pub root_workflow: String,
    pub status: RunStatus,
}

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

    #[test]
    fn test_run_status_display() {
        assert_eq!(format!("{}", RunStatus::Pending), "pending");
        assert_eq!(format!("{}", RunStatus::Running), "running");
        assert_eq!(format!("{}", RunStatus::Completed), "completed");
        assert_eq!(format!("{}", RunStatus::Failed), "failed");
        assert_eq!(format!("{}", RunStatus::Paused), "paused");
    }

    #[test]
    fn test_run_status_serialization() {
        assert_eq!(
            serde_json::to_string(&RunStatus::Pending).unwrap(),
            "\"pending\""
        );
        assert_eq!(
            serde_json::to_string(&RunStatus::Running).unwrap(),
            "\"running\""
        );
        assert_eq!(
            serde_json::to_string(&RunStatus::Completed).unwrap(),
            "\"completed\""
        );
        assert_eq!(
            serde_json::to_string(&RunStatus::Failed).unwrap(),
            "\"failed\""
        );
        assert_eq!(
            serde_json::to_string(&RunStatus::Paused).unwrap(),
            "\"paused\""
        );
    }

    #[test]
    fn test_run_status_deserialization() {
        let pending: RunStatus = serde_json::from_str("\"pending\"").unwrap();
        assert_eq!(pending, RunStatus::Pending);
        let running: RunStatus = serde_json::from_str("\"running\"").unwrap();
        assert_eq!(running, RunStatus::Running);
    }

    #[test]
    fn test_step_kind_serialization() {
        assert_eq!(serde_json::to_string(&StepKind::Run).unwrap(), "\"run\"");
        assert_eq!(serde_json::to_string(&StepKind::If).unwrap(), "\"if\"");
        assert_eq!(
            serde_json::to_string(&StepKind::While).unwrap(),
            "\"while\""
        );
        assert_eq!(
            serde_json::to_string(&StepKind::ParAnd).unwrap(),
            "\"par-and\""
        );
        assert_eq!(serde_json::to_string(&StepKind::Exec).unwrap(), "\"exec\"");
    }

    #[test]
    fn test_safe_boundary_type_all_9_variants() {
        // Verify all safe boundary types serialize correctly
        let types = vec![
            (SafeBoundaryType::BeforeStepStart, "before-step-start"),
            (SafeBoundaryType::AfterStepComplete, "after-step-complete"),
            (
                SafeBoundaryType::BeforeConditionalBody,
                "before-conditional-body",
            ),
            (
                SafeBoundaryType::AfterConditionalBody,
                "after-conditional-body",
            ),
            (
                SafeBoundaryType::BeforeLoopIteration,
                "before-loop-iteration",
            ),
            (SafeBoundaryType::AfterLoopIteration, "after-loop-iteration"),
            (
                SafeBoundaryType::AfterBranchTransition,
                "after-branch-transition",
            ),
            (SafeBoundaryType::BeforeJoin, "before-join"),
            (SafeBoundaryType::AfterJoin, "after-join"),
            (SafeBoundaryType::BeforeMatchArm, "before-match-arm"),
            (SafeBoundaryType::AfterMatchArm, "after-match-arm"),
        ];
        for (variant, expected) in types {
            let json = serde_json::to_string(&variant).unwrap();
            assert_eq!(json, format!("\"{}\"", expected));
            let deserialized: SafeBoundaryType = serde_json::from_str(&json).unwrap();
            assert_eq!(deserialized, variant);
        }
    }

    #[test]
    fn test_persisted_run_state_roundtrip() {
        let state = PersistedRunState {
            schema_version: 1,
            run_id: "run-123".to_string(),
            timestamp: "2026-04-09T00:00:00Z".to_string(),
            root_workflow: "main".to_string(),
            status: RunStatus::Completed,
            call_stack: vec![CallStackEntry {
                workflow: "main".to_string(),
                step_index: 0,
            }],
            steps: {
                let mut m = HashMap::new();
                m.insert(
                    "main/deploy".to_string(),
                    StepStatePersisted {
                        name: "deploy".to_string(),
                        kind: StepKind::Exec,
                        status: StepStatusPersisted::Completed,
                        exec_meta: Some(ExecMeta {
                            harness: Some("claude".to_string()),
                            prompt_ref: None,
                            args: None,
                        }),
                        check_result: None,
                        failure_details: None,
                        started_at: Some("2026-04-09T00:00:01Z".to_string()),
                        completed_at: Some("2026-04-09T00:00:02Z".to_string()),
                    },
                );
                m
            },
            branches: None,
            collected_outputs: None,
            harness_event_log: None,
            safe_boundaries: vec![SafeBoundary {
                boundary_type: SafeBoundaryType::BeforeStepStart,
                step_path: vec!["main".to_string(), "deploy".to_string()],
                timestamp: None,
                index: 0,
            }],
            current_boundary_index: 0,
            event_log: None,
        };

        let json = serde_json::to_string_pretty(&state).unwrap();
        let deserialized: PersistedRunState = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.run_id, "run-123");
        assert_eq!(deserialized.schema_version, 1);
        assert_eq!(deserialized.status, RunStatus::Completed);
        assert_eq!(deserialized.call_stack.len(), 1);
        assert_eq!(deserialized.steps.len(), 1);
        assert_eq!(deserialized.safe_boundaries.len(), 1);
        assert_eq!(deserialized.current_boundary_index, 0);
    }

    #[test]
    fn test_persisted_run_state_json_field_names() {
        let state = PersistedRunState {
            schema_version: 1,
            run_id: "r1".to_string(),
            timestamp: "t".to_string(),
            root_workflow: "main".to_string(),
            status: RunStatus::Running,
            call_stack: vec![],
            steps: HashMap::new(),
            branches: None,
            collected_outputs: None,
            harness_event_log: None,
            safe_boundaries: vec![],
            current_boundary_index: -1,
            event_log: None,
        };
        let json = serde_json::to_string(&state).unwrap();
        // Verify camelCase field names in JSON
        assert!(json.contains("\"schemaVersion\""), "json: {}", json);
        assert!(json.contains("\"runId\""), "json: {}", json);
        assert!(json.contains("\"rootWorkflow\""), "json: {}", json);
        assert!(json.contains("\"callStack\""), "json: {}", json);
        assert!(json.contains("\"safeBoundaries\""), "json: {}", json);
        assert!(json.contains("\"currentBoundaryIndex\""), "json: {}", json);
        // Optional fields should be absent when None
        assert!(!json.contains("\"branches\""), "json: {}", json);
        assert!(!json.contains("\"collectedOutputs\""), "json: {}", json);
        assert!(!json.contains("\"eventLog\""), "json: {}", json);
    }

    #[test]
    fn test_step_state_persisted_json_field_names() {
        let step = StepStatePersisted {
            name: "deploy".to_string(),
            kind: StepKind::Exec,
            status: StepStatusPersisted::InProgress,
            exec_meta: Some(ExecMeta {
                harness: Some("claude".to_string()),
                prompt_ref: Some("prompts/deploy.md".to_string()),
                args: None,
            }),
            check_result: None,
            failure_details: None,
            started_at: Some("2026-04-09T00:00:00Z".to_string()),
            completed_at: None,
        };
        let json = serde_json::to_string(&step).unwrap();
        assert!(json.contains("\"execMeta\""), "json: {}", json);
        assert!(json.contains("\"promptRef\""), "json: {}", json);
        assert!(json.contains("\"startedAt\""), "json: {}", json);
        // None fields should be absent
        assert!(!json.contains("\"checkResult\""), "json: {}", json);
        assert!(!json.contains("\"failureDetails\""), "json: {}", json);
        assert!(!json.contains("\"completedAt\""), "json: {}", json);
    }

    #[test]
    fn test_branch_state_serialization() {
        let branch = BranchState {
            workflow_name: "branch-a".to_string(),
            status: BranchStatusPersisted::Completed,
            output: Some(serde_json::json!({"result": "ok"})),
            failure_details: None,
        };
        let json = serde_json::to_string(&branch).unwrap();
        assert!(
            json.contains("\"workflowName\":\"branch-a\""),
            "json: {}",
            json
        );
        assert!(json.contains("\"status\":\"completed\""), "json: {}", json);
    }

    #[test]
    fn test_run_summary_serialization() {
        let summary = RunSummary {
            run_id: "run-1".to_string(),
            timestamp: "2026-04-09T00:00:00Z".to_string(),
            root_workflow: "main".to_string(),
            status: RunStatus::Completed,
        };
        let json = serde_json::to_string(&summary).unwrap();
        assert!(json.contains("\"runId\""), "json: {}", json);
        assert!(json.contains("\"rootWorkflow\""), "json: {}", json);
    }
}