terraphim_orchestrator 1.20.1

AI Dark Factory orchestrator wiring spawner, router, supervisor into a reconciliation loop
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
use std::collections::HashMap;

use serde::{Deserialize, Serialize};

/// One row of a matrix expansion: a map of variable name to string value.
/// Used with `{{matrix.<key>}}` template substitution.
pub type MatrixParams = HashMap<String, String>;

/// Maximum number of parameter rows permitted in a single `MatrixConfig`.
/// Prevents runaway sequential execution and unbounded allocation from
/// erroneous or adversarial configs.
pub const MAX_MATRIX_PARAMS: usize = 256;

/// Configuration for matrix (fan-out) expansion of a flow step.
///
/// When present, the step is expanded into N sub-executions, one per entry in
/// `params`. Each sub-execution receives its own `{{matrix.*}}` template
/// variables resolved from the corresponding row.
///
/// # Security
///
/// Matrix param values are substituted verbatim into command strings that are
/// executed via `bash -lc`. **Only use trusted, admin-authored values.**
/// The executor rejects values containing shell metacharacters (`;`, `|`,
/// `&`, `` ` ``, `$`, `>`, `<`, `!`, newlines) to prevent injection.
/// The number of rows is capped at [`MAX_MATRIX_PARAMS`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MatrixConfig {
    /// Ordered list of parameter maps. Each entry produces one sub-execution.
    /// Must not exceed [`MAX_MATRIX_PARAMS`] rows.
    pub params: Vec<MatrixParams>,
    /// Maximum number of sub-executions that may run concurrently.
    /// Defaults to 1 (fully sequential).
    #[serde(default = "default_max_parallel")]
    pub max_parallel: usize,
    /// What to do when one sub-execution fails.
    /// Defaults to `continue` (collect all results before deciding).
    #[serde(default = "default_matrix_fail_strategy")]
    pub fail_strategy: FailStrategy,
}

fn default_max_parallel() -> usize {
    1
}

fn default_matrix_fail_strategy() -> FailStrategy {
    FailStrategy::Continue
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlowDefinition {
    pub name: String,
    /// Project this flow belongs to. Required -- flows are per-project only (D14).
    /// Must match a `Project.id` when projects are defined.
    pub project: String,
    #[serde(default)]
    pub schedule: Option<String>, // cron expression
    pub repo_path: String,
    #[serde(default = "default_base_branch")]
    pub base_branch: String,
    /// Global flow timeout in seconds. If the entire flow exceeds this, it is aborted.
    #[serde(default = "default_flow_timeout")]
    pub timeout_secs: u64,
    #[serde(default)]
    pub steps: Vec<FlowStepDef>,
}

fn default_base_branch() -> String {
    "main".to_string()
}

fn default_flow_timeout() -> u64 {
    3600 // 1 hour default
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlowStepDef {
    pub name: String,
    pub kind: StepKind,
    /// Shell command (for action steps).
    #[serde(default)]
    pub command: Option<String>,
    /// CLI tool binary (for agent steps).
    #[serde(default)]
    pub cli_tool: Option<String>,
    /// Model override (for agent steps).
    #[serde(default)]
    pub model: Option<String>,
    /// Inline task/prompt (for agent steps).
    #[serde(default)]
    pub task: Option<String>,
    /// Path to external markdown prompt file (for agent steps). Takes precedence over task.
    #[serde(default)]
    pub task_file: Option<String>,
    /// Gate condition expression (for gate steps).
    #[serde(default)]
    pub condition: Option<String>,
    /// Timeout in seconds for this step.
    #[serde(default = "default_timeout")]
    pub timeout_secs: u64,
    /// What to do when this step fails.
    #[serde(default)]
    pub on_fail: FailStrategy,
    /// LLM provider (for agent steps).
    #[serde(default)]
    pub provider: Option<String>,
    /// Persona name (for agent steps).
    #[serde(default)]
    pub persona: Option<String>,
    /// Matrix configuration. When set, this step is expanded into N sub-executions,
    /// one per entry in `matrix.params`.
    #[serde(default)]
    pub matrix: Option<MatrixConfig>,
}

fn default_timeout() -> u64 {
    600
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StepKind {
    Action,
    Agent,
    Gate,
    Checkpoint,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FailStrategy {
    #[default]
    Abort,
    SkipFailed,
    Continue,
}

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

    #[test]
    fn test_matrix_config_parse() {
        let toml_str = r#"
name = "experiment"
project = "default"
repo_path = "/tmp/repo"

[[steps]]
name = "run-model"
kind = "agent"
cli_tool = "claude"
task = "run task with {{matrix.model}} using prompt {{matrix.prompt}}"

[steps.matrix]
max_parallel = 2
fail_strategy = "continue"

[[steps.matrix.params]]
model = "sonnet"
prompt = "caution-first"

[[steps.matrix.params]]
model = "haiku"
prompt = "fast"
"#;

        let flow: FlowDefinition = toml::from_str(toml_str).unwrap();
        assert_eq!(flow.steps.len(), 1);

        let step = &flow.steps[0];
        let matrix = step.matrix.as_ref().expect("matrix should be present");
        assert_eq!(matrix.params.len(), 2);
        assert_eq!(matrix.max_parallel, 2);
        assert_eq!(matrix.fail_strategy, FailStrategy::Continue);

        assert_eq!(matrix.params[0]["model"], "sonnet");
        assert_eq!(matrix.params[0]["prompt"], "caution-first");
        assert_eq!(matrix.params[1]["model"], "haiku");
        assert_eq!(matrix.params[1]["prompt"], "fast");
    }

    #[test]
    fn test_matrix_config_defaults() {
        let toml_str = r#"
name = "test"
project = "default"
repo_path = "/tmp"

[[steps]]
name = "step"
kind = "action"
command = "echo {{matrix.val}}"

[[steps.matrix.params]]
val = "hello"
"#;

        let flow: FlowDefinition = toml::from_str(toml_str).unwrap();
        let matrix = flow.steps[0].matrix.as_ref().unwrap();
        assert_eq!(matrix.max_parallel, 1); // default
        assert_eq!(matrix.fail_strategy, FailStrategy::Continue); // default
    }

    #[test]
    fn test_step_without_matrix_is_none() {
        let toml_str = r#"
name = "test"
project = "default"
repo_path = "/tmp"

[[steps]]
name = "plain"
kind = "action"
command = "echo hello"
"#;

        let flow: FlowDefinition = toml::from_str(toml_str).unwrap();
        assert!(flow.steps[0].matrix.is_none());
    }

    #[test]
    fn test_flow_config_parse_minimal() {
        let toml_str = r#"
name = "test-flow"
project = "default"
repo_path = "/tmp/repo"

[[steps]]
name = "build"
kind = "action"
command = "cargo build"
"#;

        let flow: FlowDefinition = toml::from_str(toml_str).unwrap();
        assert_eq!(flow.name, "test-flow");
        assert_eq!(flow.project, "default");
        assert_eq!(flow.repo_path, "/tmp/repo");
        assert_eq!(flow.base_branch, "main"); // default
        assert!(flow.schedule.is_none());
        assert_eq!(flow.steps.len(), 1);

        let step = &flow.steps[0];
        assert_eq!(step.name, "build");
        assert_eq!(step.kind, StepKind::Action);
        assert_eq!(step.command, Some("cargo build".to_string()));
        assert_eq!(step.timeout_secs, 600); // default
        assert_eq!(step.on_fail, FailStrategy::Abort); // default
        assert!(step.matrix.is_none());
    }

    #[test]
    fn test_flow_config_parse_full() {
        let toml_str = r#"
name = "compound-review-v2"
project = "terraphim"
schedule = "0 2 * * *"
repo_path = "/home/user/project"
base_branch = "develop"

[[steps]]
name = "gather-changes"
kind = "action"
command = "git diff main..HEAD"
timeout_secs = 300
on_fail = "abort"

[[steps]]
name = "analyze-architecture"
kind = "agent"
cli_tool = "claude"
model = "sonnet"
task = "Review the architecture changes"
task_file = "/prompts/arch.md"
timeout_secs = 900
on_fail = "skip_failed"
provider = "anthropic"
persona = "architect"

[[steps]]
name = "check-quality"
kind = "agent"
cli_tool = "opencode"
model = "k2p5"
task = "Check code quality"
timeout_secs = 600
on_fail = "continue"
provider = "kimi-for-coding"

[[steps]]
name = "gate-approval"
kind = "gate"
condition = "steps.analyze-architecture.exit_code == 0"

[[steps]]
name = "checkpoint-state"
kind = "checkpoint"
"#;

        let flow: FlowDefinition = toml::from_str(toml_str).unwrap();
        assert_eq!(flow.name, "compound-review-v2");
        assert_eq!(flow.schedule, Some("0 2 * * *".to_string()));
        assert_eq!(flow.repo_path, "/home/user/project");
        assert_eq!(flow.base_branch, "develop");
        assert_eq!(flow.steps.len(), 5);

        // Action step
        let action_step = &flow.steps[0];
        assert_eq!(action_step.name, "gather-changes");
        assert_eq!(action_step.kind, StepKind::Action);
        assert_eq!(action_step.command, Some("git diff main..HEAD".to_string()));
        assert_eq!(action_step.timeout_secs, 300);
        assert_eq!(action_step.on_fail, FailStrategy::Abort);

        // Agent step with all fields
        let agent_step = &flow.steps[1];
        assert_eq!(agent_step.name, "analyze-architecture");
        assert_eq!(agent_step.kind, StepKind::Agent);
        assert_eq!(agent_step.cli_tool, Some("claude".to_string()));
        assert_eq!(agent_step.model, Some("sonnet".to_string()));
        assert_eq!(
            agent_step.task,
            Some("Review the architecture changes".to_string())
        );
        assert_eq!(agent_step.task_file, Some("/prompts/arch.md".to_string()));
        assert_eq!(agent_step.timeout_secs, 900);
        assert_eq!(agent_step.on_fail, FailStrategy::SkipFailed);
        assert_eq!(agent_step.provider, Some("anthropic".to_string()));
        assert_eq!(agent_step.persona, Some("architect".to_string()));

        // Second agent step
        let agent_step2 = &flow.steps[2];
        assert_eq!(agent_step2.name, "check-quality");
        assert_eq!(agent_step2.kind, StepKind::Agent);
        assert_eq!(agent_step2.on_fail, FailStrategy::Continue);

        // Gate step
        let gate_step = &flow.steps[3];
        assert_eq!(gate_step.name, "gate-approval");
        assert_eq!(gate_step.kind, StepKind::Gate);
        assert_eq!(
            gate_step.condition,
            Some("steps.analyze-architecture.exit_code == 0".to_string())
        );

        // Checkpoint step
        let checkpoint_step = &flow.steps[4];
        assert_eq!(checkpoint_step.name, "checkpoint-state");
        assert_eq!(checkpoint_step.kind, StepKind::Checkpoint);
    }

    #[test]
    fn test_step_kind_serde() {
        // Test serialization
        assert_eq!(
            serde_json::to_string(&StepKind::Action).unwrap(),
            "\"action\""
        );
        assert_eq!(
            serde_json::to_string(&StepKind::Agent).unwrap(),
            "\"agent\""
        );
        assert_eq!(serde_json::to_string(&StepKind::Gate).unwrap(), "\"gate\"");
        assert_eq!(
            serde_json::to_string(&StepKind::Checkpoint).unwrap(),
            "\"checkpoint\""
        );

        // Test deserialization
        assert_eq!(
            serde_json::from_str::<StepKind>("\"action\"").unwrap(),
            StepKind::Action
        );
        assert_eq!(
            serde_json::from_str::<StepKind>("\"agent\"").unwrap(),
            StepKind::Agent
        );
        assert_eq!(
            serde_json::from_str::<StepKind>("\"gate\"").unwrap(),
            StepKind::Gate
        );
        assert_eq!(
            serde_json::from_str::<StepKind>("\"checkpoint\"").unwrap(),
            StepKind::Checkpoint
        );
    }

    #[test]
    fn test_fail_strategy_default() {
        // Test that default is Abort
        let strategy: FailStrategy = Default::default();
        assert_eq!(strategy, FailStrategy::Abort);

        // Test deserialization with default
        let toml_str = r#"
name = "test"
kind = "action"
"#;
        let step: FlowStepDef = toml::from_str(toml_str).unwrap();
        assert_eq!(step.on_fail, FailStrategy::Abort);
    }

    #[test]
    fn test_fail_strategy_variants() {
        // Test all variants serialize/deserialize correctly
        assert_eq!(
            serde_json::to_string(&FailStrategy::Abort).unwrap(),
            "\"abort\""
        );
        assert_eq!(
            serde_json::to_string(&FailStrategy::SkipFailed).unwrap(),
            "\"skip_failed\""
        );
        assert_eq!(
            serde_json::to_string(&FailStrategy::Continue).unwrap(),
            "\"continue\""
        );

        assert_eq!(
            serde_json::from_str::<FailStrategy>("\"abort\"").unwrap(),
            FailStrategy::Abort
        );
        assert_eq!(
            serde_json::from_str::<FailStrategy>("\"skip_failed\"").unwrap(),
            FailStrategy::SkipFailed
        );
        assert_eq!(
            serde_json::from_str::<FailStrategy>("\"continue\"").unwrap(),
            FailStrategy::Continue
        );
    }
}