aegis-orchestrator 0.15.0-pre-alpha

100monkeys.ai AEGIS orchestrator CLI and daemon
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
509
510
511
// Copyright (c) 2026 100monkeys.ai
// SPDX-License-Identifier: AGPL-3.0
//! Built-in templates and deployment logic.

use anyhow::{Context, Result};
use colored::Colorize;
use uuid::Uuid;

use crate::daemon::DaemonClient;

// ─── Templates ──────────────────────────────────────────────────────────────

pub const HELLO_WORLD_TEMPLATE: &str =
    include_str!("../../templates/agents/hello-world-agent.yaml");
pub const CODE_QUALITY_JUDGE_TEMPLATE: &str =
    include_str!("../../templates/agents/code-quality-judge.yaml");
pub const TOOL_CALL_POLICY_JUDGE_TEMPLATE: &str =
    include_str!("../../templates/agents/tool-call-policy-judge.yaml");

pub const WORKFLOW_GENERATOR_WORKFLOW_NAME: &str = "builtin-workflow-generator";
pub const WORKFLOW_GENERATOR_WORKFLOW_TEMPLATE: &str =
    include_str!("../../templates/workflows/builtin-workflow-generator.yaml");

pub const WORKFLOW_GENERATOR_PLANNER_AGENT_NAME: &str = "workflow-generator-planner-agent";
pub const WORKFLOW_GENERATOR_PLANNER_AGENT_TEMPLATE: &str =
    include_str!("../../templates/agents/workflow-generator-planner-agent.yaml");

pub const AGENT_GENERATOR_AGENT_NAME: &str = "agent-creator-agent";
pub const AGENT_GENERATOR_AGENT_TEMPLATE: &str =
    include_str!("../../templates/agents/agent-creator-agent.yaml");

pub const AGENT_GENERATOR_JUDGE_NAME: &str = "agent-generator-judge";
pub const AGENT_GENERATOR_JUDGE_TEMPLATE: &str =
    include_str!("../../templates/agents/agent-generator-judge.yaml");

pub const WORKFLOW_GENERATOR_JUDGE_NAME: &str = "workflow-generator-judge";
pub const WORKFLOW_GENERATOR_JUDGE_TEMPLATE: &str =
    include_str!("../../templates/agents/workflow-generator-judge.yaml");

pub const WORKFLOW_CREATOR_AGENT_NAME: &str = "workflow-creator-validator-agent";
pub const WORKFLOW_CREATOR_AGENT_TEMPLATE: &str =
    include_str!("../../templates/agents/workflow-creator-validator-agent.yaml");

pub const SKILL_VALIDATOR_AGENT_TEMPLATE: &str =
    include_str!("../../templates/agents/skill-validator.yaml");
pub const SKILL_IMPORT_WORKFLOW_TEMPLATE: &str =
    include_str!("../../templates/workflows/skill-import.yaml");

pub const INTENT_EXECUTION_WORKFLOW_NAME: &str = "builtin-intent-to-execution";
pub const INTENT_EXECUTION_WORKFLOW_TEMPLATE: &str =
    include_str!("../../templates/workflows/builtin-intent-to-execution.yaml");

pub const AEGIS_OUTPUT_FORMATTER_AGENT_NAME: &str = "aegis-output-formatter-agent";
pub const AEGIS_OUTPUT_FORMATTER_AGENT_TEMPLATE: &str =
    include_str!("../../templates/agents/aegis-output-formatter-agent.yaml");

pub const AEGIS_PYTHON_EXECUTOR_AGENT_NAME: &str = "aegis-python-executor-agent";
pub const AEGIS_PYTHON_EXECUTOR_AGENT_TEMPLATE: &str =
    include_str!("../../templates/agents/aegis-python-executor-agent.yaml");

pub const AEGIS_JAVASCRIPT_EXECUTOR_AGENT_NAME: &str = "aegis-javascript-executor-agent";
pub const AEGIS_JAVASCRIPT_EXECUTOR_AGENT_TEMPLATE: &str =
    include_str!("../../templates/agents/aegis-javascript-executor-agent.yaml");

pub const AEGIS_BASH_EXECUTOR_AGENT_NAME: &str = "aegis-bash-executor-agent";
pub const AEGIS_BASH_EXECUTOR_AGENT_TEMPLATE: &str =
    include_str!("../../templates/agents/aegis-bash-executor-agent.yaml");

// ─── Canonical Registries ───────────────────────────────────────────────────

struct BuiltinTemplateSpec {
    category: &'static str,
    file_name: &'static str,
    content: &'static str,
}

/// Canonical registry of all built-in agent templates for deployment.
pub const BUILTIN_AGENTS: &[(&str, &str)] = &[
    ("hello-world-agent", HELLO_WORLD_TEMPLATE),
    ("code-quality-judge", CODE_QUALITY_JUDGE_TEMPLATE),
    ("tool-call-policy-judge", TOOL_CALL_POLICY_JUDGE_TEMPLATE),
    (
        WORKFLOW_GENERATOR_PLANNER_AGENT_NAME,
        WORKFLOW_GENERATOR_PLANNER_AGENT_TEMPLATE,
    ),
    (AGENT_GENERATOR_AGENT_NAME, AGENT_GENERATOR_AGENT_TEMPLATE),
    (AGENT_GENERATOR_JUDGE_NAME, AGENT_GENERATOR_JUDGE_TEMPLATE),
    (
        WORKFLOW_GENERATOR_JUDGE_NAME,
        WORKFLOW_GENERATOR_JUDGE_TEMPLATE,
    ),
    (WORKFLOW_CREATOR_AGENT_NAME, WORKFLOW_CREATOR_AGENT_TEMPLATE),
    ("skill-validator", SKILL_VALIDATOR_AGENT_TEMPLATE),
    (
        AEGIS_OUTPUT_FORMATTER_AGENT_NAME,
        AEGIS_OUTPUT_FORMATTER_AGENT_TEMPLATE,
    ),
    (
        AEGIS_PYTHON_EXECUTOR_AGENT_NAME,
        AEGIS_PYTHON_EXECUTOR_AGENT_TEMPLATE,
    ),
    (
        AEGIS_JAVASCRIPT_EXECUTOR_AGENT_NAME,
        AEGIS_JAVASCRIPT_EXECUTOR_AGENT_TEMPLATE,
    ),
    (
        AEGIS_BASH_EXECUTOR_AGENT_NAME,
        AEGIS_BASH_EXECUTOR_AGENT_TEMPLATE,
    ),
];

/// Canonical registry of all built-in workflow templates.
pub const BUILTIN_WORKFLOWS: &[(&str, &str)] = &[
    (
        WORKFLOW_GENERATOR_WORKFLOW_NAME,
        WORKFLOW_GENERATOR_WORKFLOW_TEMPLATE,
    ),
    ("skill-import", SKILL_IMPORT_WORKFLOW_TEMPLATE),
    (
        INTENT_EXECUTION_WORKFLOW_NAME,
        INTENT_EXECUTION_WORKFLOW_TEMPLATE,
    ),
];

/// All builtin templates that should be synced to disk.
const BUILTIN_TEMPLATES: &[BuiltinTemplateSpec] = &[
    BuiltinTemplateSpec {
        category: "agents",
        file_name: "hello-world-agent.yaml",
        content: HELLO_WORLD_TEMPLATE,
    },
    BuiltinTemplateSpec {
        category: "agents",
        file_name: "code-quality-judge.yaml",
        content: CODE_QUALITY_JUDGE_TEMPLATE,
    },
    BuiltinTemplateSpec {
        category: "agents",
        file_name: "tool-call-policy-judge.yaml",
        content: TOOL_CALL_POLICY_JUDGE_TEMPLATE,
    },
    BuiltinTemplateSpec {
        category: "agents",
        file_name: "workflow-generator-planner-agent.yaml",
        content: WORKFLOW_GENERATOR_PLANNER_AGENT_TEMPLATE,
    },
    BuiltinTemplateSpec {
        category: "agents",
        file_name: "agent-creator-agent.yaml",
        content: AGENT_GENERATOR_AGENT_TEMPLATE,
    },
    BuiltinTemplateSpec {
        category: "agents",
        file_name: "agent-generator-judge.yaml",
        content: AGENT_GENERATOR_JUDGE_TEMPLATE,
    },
    BuiltinTemplateSpec {
        category: "agents",
        file_name: "workflow-generator-judge.yaml",
        content: WORKFLOW_GENERATOR_JUDGE_TEMPLATE,
    },
    BuiltinTemplateSpec {
        category: "agents",
        file_name: "workflow-creator-validator-agent.yaml",
        content: WORKFLOW_CREATOR_AGENT_TEMPLATE,
    },
    BuiltinTemplateSpec {
        category: "agents",
        file_name: "skill-validator.yaml",
        content: SKILL_VALIDATOR_AGENT_TEMPLATE,
    },
    BuiltinTemplateSpec {
        category: "agents",
        file_name: "aegis-output-formatter-agent.yaml",
        content: AEGIS_OUTPUT_FORMATTER_AGENT_TEMPLATE,
    },
    BuiltinTemplateSpec {
        category: "agents",
        file_name: "aegis-python-executor-agent.yaml",
        content: AEGIS_PYTHON_EXECUTOR_AGENT_TEMPLATE,
    },
    BuiltinTemplateSpec {
        category: "agents",
        file_name: "aegis-javascript-executor-agent.yaml",
        content: AEGIS_JAVASCRIPT_EXECUTOR_AGENT_TEMPLATE,
    },
    BuiltinTemplateSpec {
        category: "agents",
        file_name: "aegis-bash-executor-agent.yaml",
        content: AEGIS_BASH_EXECUTOR_AGENT_TEMPLATE,
    },
    BuiltinTemplateSpec {
        category: "workflows",
        file_name: "builtin-workflow-generator.yaml",
        content: WORKFLOW_GENERATOR_WORKFLOW_TEMPLATE,
    },
    BuiltinTemplateSpec {
        category: "workflows",
        file_name: "skill-import.yaml",
        content: SKILL_IMPORT_WORKFLOW_TEMPLATE,
    },
    BuiltinTemplateSpec {
        category: "workflows",
        file_name: "builtin-intent-to-execution.yaml",
        content: INTENT_EXECUTION_WORKFLOW_TEMPLATE,
    },
];

// ─── Deployment Logic ───────────────────────────────────────────────────────

pub async fn deploy_all_builtins(client: &DaemonClient, force: bool) -> Result<()> {
    for (name, template) in BUILTIN_AGENTS {
        deploy_builtin_agent(client, name, template, force).await?;
    }
    for (name, template) in BUILTIN_WORKFLOWS {
        deploy_builtin_workflow(client, name, template, force).await?;
    }
    Ok(())
}

fn resolve_stack_root(config_path: Option<&std::path::PathBuf>) -> std::path::PathBuf {
    config_path
        .and_then(|config| config.parent().map(|parent| parent.to_path_buf()))
        .or_else(|| dirs_next::home_dir().map(|home| home.join(".aegis")))
        .unwrap_or_else(|| std::path::PathBuf::from(".aegis"))
}

pub fn resolve_templates_root(config_path: Option<&std::path::PathBuf>) -> std::path::PathBuf {
    resolve_stack_root(config_path).join("templates")
}

pub fn resolve_generated_root(config_path: Option<&std::path::PathBuf>) -> std::path::PathBuf {
    resolve_stack_root(config_path).join("generated")
}

pub fn sync_generator_templates_to_disk(templates_root: &std::path::Path) -> Result<()> {
    for spec in BUILTIN_TEMPLATES {
        persist_template(templates_root, spec.category, spec.file_name, spec.content)?;
    }
    Ok(())
}

fn persist_template(
    templates_root: &std::path::Path,
    category: &str,
    file_name: &str,
    content: &str,
) -> Result<()> {
    let dir = templates_root.join(category);
    std::fs::create_dir_all(&dir)
        .with_context(|| format!("Failed to create template directory {}", dir.display()))?;
    let file_path = dir.join(file_name);
    std::fs::write(&file_path, content)
        .with_context(|| format!("Failed to write bundled template {}", file_path.display()))?;
    Ok(())
}

async fn deploy_builtin_agent(
    client: &DaemonClient,
    name: &str,
    template_yaml: &str,
    force: bool,
) -> Result<Uuid> {
    let manifest: aegis_orchestrator_sdk::AgentManifest =
        serde_yaml::from_str(template_yaml).context("Failed to parse built-in template YAML")?;
    manifest
        .validate()
        .map_err(|e| anyhow::anyhow!("Built-in template validation failed: {e}"))?;

    if !force {
        if let Some(id) = client.lookup_agent(&manifest.metadata.name).await? {
            println!(
                "  {} Reusing existing built-in agent '{}' (id: {}) without verifying version; \
                 use --force to redeploy from the bundled template if needed.",
                "".dimmed(),
                manifest.metadata.name.cyan(),
                id
            );
            return Ok(id);
        }
    }

    println!(
        "  {} Deploying built-in agent: {}",
        "".dimmed(),
        name.cyan()
    );

    client
        .deploy_agent(manifest, force, Some("global"))
        .await
        .context("Failed to deploy built-in template")
}

async fn deploy_builtin_workflow(
    client: &DaemonClient,
    name: &str,
    template_yaml: &str,
    force: bool,
) -> Result<()> {
    if !force && client.describe_workflow(name).await.is_ok() {
        println!(
            "  {} Reusing existing built-in workflow '{}' without verifying version; \
             use --force to redeploy from the bundled template if needed.",
            "".dimmed(),
            name.cyan(),
        );
        return Ok(());
    }

    println!(
        "  {} Deploying built-in workflow: {}",
        "".dimmed(),
        name.cyan()
    );

    // Validate template before deployment.
    let workflow =
        aegis_orchestrator_core::infrastructure::workflow_parser::WorkflowParser::parse_yaml(
            template_yaml,
        )
        .context("Failed to parse built-in workflow template YAML")?;
    aegis_orchestrator_core::domain::workflow::WorkflowValidator::check_for_cycles(&workflow)
        .context("Built-in workflow template failed cycle validation")?;

    client
        .deploy_workflow_manifest_with_force_and_scope(template_yaml, force, Some("global"))
        .await
        .context("Failed to deploy built-in workflow template")
}

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

    #[test]
    fn workflow_generator_template_uses_nested_output_fields() {
        let workflow: serde_yaml::Value =
            serde_yaml::from_str(WORKFLOW_GENERATOR_WORKFLOW_TEMPLATE).unwrap();
        let states = &workflow["spec"]["states"];

        let generate_missing_agents_input = states["GENERATE_MISSING_AGENTS"]["input"]
            .as_str()
            .expect("GENERATE_MISSING_AGENTS input should be a string");
        assert!(
            generate_missing_agents_input.contains("{{PLAN.output}}"),
            "GENERATE_MISSING_AGENTS should reference the planner state's output payload"
        );
        assert!(
            generate_missing_agents_input.contains("missing_judge_agents"),
            "GENERATE_MISSING_AGENTS should mention missing judge agents"
        );

        let generate_and_register_workflow_input = states["GENERATE_AND_REGISTER_WORKFLOW"]
            ["input"]
            .as_str()
            .expect("GENERATE_AND_REGISTER_WORKFLOW input should be a string");
        assert!(
            generate_and_register_workflow_input.contains("{{PLAN.output}}"),
            "GENERATE_AND_REGISTER_WORKFLOW should reference the planner state's output payload"
        );
        assert!(
            generate_and_register_workflow_input.contains("{{GENERATE_MISSING_AGENTS.output}}"),
            "GENERATE_AND_REGISTER_WORKFLOW should reference the agent generation state's output payload"
        );
        assert!(
            generate_and_register_workflow_input.contains("resolved existing judge agents"),
            "GENERATE_AND_REGISTER_WORKFLOW should require resolved judge agents"
        );
    }

    #[test]
    fn agent_creator_template_requires_full_sequence_before_deploying() {
        assert!(
            AGENT_GENERATOR_AGENT_TEMPLATE.contains("HARD PRECONDITION"),
            "agent creator template should make the required sequence a hard precondition"
        );
        assert!(
            AGENT_GENERATOR_AGENT_TEMPLATE.contains(
                "Do not call `aegis.agent.create` or `aegis.agent.update` from a draft manifest"
            ),
            "agent creator template should forbid deployment from unvalidated drafts"
        );
        assert!(
            AGENT_GENERATOR_AGENT_TEMPLATE
                .contains("Skipping, reordering, or collapsing steps 1–8 is a policy violation"),
            "agent creator template should reject shortcutting the required workflow"
        );
    }

    #[test]
    fn workflow_creator_template_requires_full_sequence_before_deploying() {
        assert!(
            WORKFLOW_CREATOR_AGENT_TEMPLATE.contains("HARD PRECONDITION"),
            "workflow creator template should make the required sequence a hard precondition"
        );
        assert!(
            WORKFLOW_CREATOR_AGENT_TEMPLATE.contains(
                "Do not call `aegis.workflow.create` or `aegis.workflow.update` from a draft manifest"
            ),
            "workflow creator template should forbid deployment from unvalidated drafts"
        );
        assert!(
            WORKFLOW_CREATOR_AGENT_TEMPLATE
                .contains("Skipping, reordering, or collapsing steps 1–5 is a policy violation"),
            "workflow creator template should reject shortcutting the required workflow"
        );
        assert!(
            WORKFLOW_CREATOR_AGENT_TEMPLATE
                .contains("Always run workflow validation before any create or update call"),
            "workflow creator template should require workflow validation before deployment"
        );
    }

    #[test]
    fn workflow_generator_planner_template_includes_judge_dependencies() {
        assert!(
            WORKFLOW_GENERATOR_PLANNER_AGENT_TEMPLATE.contains("required_judge_agents"),
            "planner template should explicitly model required judge dependencies"
        );
        assert!(
            WORKFLOW_GENERATOR_PLANNER_AGENT_TEMPLATE.contains("missing_judge_agents"),
            "planner template should explicitly model missing judge dependencies"
        );
        assert!(
            WORKFLOW_GENERATOR_PLANNER_AGENT_TEMPLATE.contains("judge_generation_prompts"),
            "planner template should provide prompts for missing judges"
        );
    }

    #[test]
    fn workflow_generator_validator_template_uses_resolved_judge_agents() {
        assert!(
            WORKFLOW_CREATOR_AGENT_TEMPLATE.contains("Resolve judge names"),
            "workflow creator template should require resolved judge names"
        );
        assert!(
            WORKFLOW_CREATOR_AGENT_TEMPLATE.contains("judge_agents"),
            "workflow creator template should still pass explicit judge agents to workflow.create"
        );
    }

    #[test]
    fn workflow_generator_judge_template_handles_missing_audit_history_conservatively() {
        assert!(
            WORKFLOW_GENERATOR_JUDGE_TEMPLATE
                .contains("If tool call history is missing, treat that as insufficient evidence"),
            "judge template should not claim validation failure without audit evidence"
        );
        assert!(
            WORKFLOW_GENERATOR_JUDGE_TEMPLATE.contains(
                "A deployment call without a prior `aegis.schema.get`, `aegis.schema.validate`, and `aegis.workflow.validate` in the same run"
            ),
            "judge template should treat a missing workflow validation sequence as a hard process failure"
        );
    }

    #[test]
    fn agent_generator_judge_template_treats_missing_schema_history_as_hard_failure() {
        assert!(
            AGENT_GENERATOR_JUDGE_TEMPLATE.contains(
                "A deployment call without a prior `aegis.schema.get` and `aegis.schema.validate` in the same run"
            ),
            "agent judge template should treat a missing schema sequence as a hard process failure"
        );
    }

    #[test]
    fn workflow_generator_template_remains_three_stage() {
        let workflow: serde_yaml::Value =
            serde_yaml::from_str(WORKFLOW_GENERATOR_WORKFLOW_TEMPLATE).unwrap();
        let states = workflow["spec"]["states"]
            .as_mapping()
            .expect("workflow states should be a mapping");

        assert!(states.contains_key(&serde_yaml::Value::from("PLAN")));
        assert!(states.contains_key(&serde_yaml::Value::from("GENERATE_MISSING_AGENTS")));
        assert!(states.contains_key(&serde_yaml::Value::from("GENERATE_AND_REGISTER_WORKFLOW")));
    }

    #[test]
    fn all_builtin_agent_templates_parse_successfully() {
        for (name, yaml) in BUILTIN_AGENTS {
            let manifest: aegis_orchestrator_sdk::AgentManifest = serde_yaml::from_str(yaml)
                .unwrap_or_else(|e| panic!("Failed to parse builtin agent '{}': {}", name, e));
            manifest
                .validate()
                .unwrap_or_else(|e| panic!("Builtin agent '{}' failed validation: {}", name, e));
        }
    }

    #[test]
    fn all_builtin_workflow_templates_parse_successfully() {
        for (name, yaml) in BUILTIN_WORKFLOWS {
            aegis_orchestrator_core::infrastructure::workflow_parser::WorkflowParser::parse_yaml(
                yaml,
            )
            .unwrap_or_else(|e| panic!("Failed to parse builtin workflow '{}': {}", name, e));
        }
    }

    #[test]
    fn generated_root_uses_config_parent_directory() {
        let config_path = std::path::PathBuf::from("/tmp/custom-stack/aegis-config.yaml");
        let generated_root = resolve_generated_root(Some(&config_path));
        assert_eq!(
            generated_root,
            std::path::PathBuf::from("/tmp/custom-stack/generated")
        );
    }
}