terraphim_orchestrator 1.20.2

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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
//! Project-scoped registry for ADF agent definitions.
//!
//! This module is a read-only index over the already merged
//! [`OrchestratorConfig`]. It does not load
//! TOML, merge project sources, spawn agents, or post statuses.

use std::collections::{BTreeMap, BTreeSet};

use crate::config::{AgentDefinition, OrchestratorConfig};
use crate::error::OrchestratorError;

/// Scope component for an agent's configured identity.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum AgentScope {
    /// Legacy single-project mode. No `[[projects]]` are configured.
    Legacy,
    /// Multi-project mode, keyed by `Project.id`.
    Project(String),
}

impl AgentScope {
    /// Build a scope from an optional project id.
    pub fn from_project(project: Option<&str>) -> Self {
        match project {
            Some(project) => Self::Project(project.to_string()),
            None => Self::Legacy,
        }
    }

    /// Human-readable scope name for diagnostics.
    pub fn label(&self) -> &str {
        match self {
            Self::Legacy => "<legacy>",
            Self::Project(project) => project.as_str(),
        }
    }
}

/// Stable key for a registered agent definition.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AgentKey {
    pub scope: AgentScope,
    pub name: String,
}

impl AgentKey {
    pub fn new(scope: AgentScope, name: impl Into<String>) -> Self {
        Self {
            scope,
            name: name.into(),
        }
    }

    pub fn project(project: impl Into<String>, name: impl Into<String>) -> Self {
        Self::new(AgentScope::Project(project.into()), name)
    }

    pub fn legacy(name: impl Into<String>) -> Self {
        Self::new(AgentScope::Legacy, name)
    }
}

impl std::fmt::Display for AgentKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}:{}", self.scope.label(), self.name)
    }
}

/// Source attribution for an agent entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AgentSource {
    /// The entry came from the merged `OrchestratorConfig`.
    ConfigMerged,
}

/// Registry entry for an agent definition.
#[derive(Debug, Clone)]
pub struct RegisteredAgent {
    pub key: AgentKey,
    pub definition: AgentDefinition,
    pub source: AgentSource,
}

impl RegisteredAgent {
    pub fn project_id(&self) -> Option<&str> {
        self.definition.project.as_deref()
    }

    pub fn event_only(&self) -> bool {
        self.definition.event_only
    }
}

/// Read-only index of all effective agents after config merging.
#[derive(Debug, Clone, Default)]
pub struct AgentRegistry {
    by_key: BTreeMap<AgentKey, RegisteredAgent>,
    by_project: BTreeMap<AgentScope, BTreeSet<String>>,
}

impl AgentRegistry {
    /// Build the registry from the already merged config.
    pub fn from_config(config: &OrchestratorConfig) -> Result<Self, OrchestratorError> {
        let mut registry = Self::default();

        for agent in &config.agents {
            // Register under the agent's primary scope, then under each
            // `extra_projects` entry (#2175) so one definition can serve
            // multiple projects. Each scope is a distinct key, so a verdict
            // agent registered for N projects yields N lookup entries.
            let primary = AgentScope::from_project(agent.project.as_deref());
            let mut scopes = vec![primary];
            for pid in &agent.extra_projects {
                scopes.push(AgentScope::Project(pid.clone()));
            }

            for scope in scopes {
                let key = AgentKey::new(scope.clone(), agent.name.clone());

                if registry.by_key.contains_key(&key) {
                    return Err(OrchestratorError::Config(format!(
                        "duplicate agent '{}' in project '{}'",
                        agent.name,
                        scope.label()
                    )));
                }

                registry
                    .by_project
                    .entry(scope)
                    .or_default()
                    .insert(agent.name.clone());
                registry.by_key.insert(
                    key.clone(),
                    RegisteredAgent {
                        key,
                        definition: agent.clone(),
                        source: AgentSource::ConfigMerged,
                    },
                );
            }
        }

        Ok(registry)
    }

    /// Number of registered agents.
    pub fn len(&self) -> usize {
        self.by_key.len()
    }

    pub fn is_empty(&self) -> bool {
        self.by_key.is_empty()
    }

    /// Lookup by explicit key.
    pub fn get(&self, key: &AgentKey) -> Option<&RegisteredAgent> {
        self.by_key.get(key)
    }

    /// Lookup a project-scoped agent by project id and name.
    pub fn lookup_project(&self, project: &str, name: &str) -> Option<&RegisteredAgent> {
        self.get(&AgentKey::project(project, name))
    }

    /// Lookup a legacy single-project agent by name.
    pub fn lookup_legacy(&self, name: &str) -> Option<&RegisteredAgent> {
        self.get(&AgentKey::legacy(name))
    }

    /// Lookup with an optional project id, mirroring `AgentDefinition.project`.
    pub fn lookup(&self, project: Option<&str>, name: &str) -> Option<&RegisteredAgent> {
        self.get(&AgentKey::new(AgentScope::from_project(project), name))
    }

    /// List registered agent names for a scope in sorted order.
    pub fn names_for_scope(&self, scope: &AgentScope) -> Vec<&str> {
        self.by_project
            .get(scope)
            .map(|names| names.iter().map(String::as_str).collect())
            .unwrap_or_default()
    }
}

#[cfg(test)]
mod tests {
    use super::{AgentKey, AgentRegistry, AgentScope};
    use crate::config::OrchestratorConfig;
    use crate::error::OrchestratorError;

    fn config_from(toml: &str) -> Result<OrchestratorConfig, OrchestratorError> {
        OrchestratorConfig::from_toml(toml)
    }

    #[test]
    fn registry_builds_legacy_agents() -> Result<(), Box<dyn std::error::Error>> {
        let config = config_from(
            r#"
working_dir = "/tmp/t"

[nightwatch]

[compound_review]
schedule = "0 2 * * *"
repo_path = "/tmp/repo"

[[agents]]
name = "legacy-agent"
layer = "Safety"
cli_tool = "echo"
task = "legacy"
"#,
        )?;

        let registry = AgentRegistry::from_config(&config)?;
        let agent = registry.lookup_legacy("legacy-agent").ok_or_else(|| {
            std::io::Error::new(std::io::ErrorKind::NotFound, "missing legacy-agent")
        })?;
        assert_eq!(agent.key, AgentKey::legacy("legacy-agent"));
        assert_eq!(agent.project_id(), None);
        assert_eq!(
            registry.names_for_scope(&AgentScope::Legacy),
            vec!["legacy-agent"]
        );
        Ok(())
    }

    #[test]
    fn registry_allows_same_name_across_projects() -> Result<(), Box<dyn std::error::Error>> {
        let config = config_from(
            r#"
working_dir = "/tmp/t"

[nightwatch]

[compound_review]
schedule = "0 2 * * *"
repo_path = "/tmp/repo"

[[projects]]
id = "alpha"
working_dir = "/tmp/alpha"

[[projects]]
id = "beta"
working_dir = "/tmp/beta"

[[agents]]
name = "build-runner"
layer = "Growth"
cli_tool = "echo"
task = "alpha-build"
project = "alpha"
event_only = true

[[agents]]
name = "build-runner"
layer = "Growth"
cli_tool = "echo"
task = "beta-build"
project = "beta"
event_only = true
"#,
        )?;

        let registry = AgentRegistry::from_config(&config)?;
        assert_eq!(registry.len(), 2);
        let alpha_runner = registry
            .lookup_project("alpha", "build-runner")
            .ok_or_else(|| {
                std::io::Error::new(std::io::ErrorKind::NotFound, "missing alpha build-runner")
            })?;
        let beta_runner = registry
            .lookup_project("beta", "build-runner")
            .ok_or_else(|| {
                std::io::Error::new(std::io::ErrorKind::NotFound, "missing beta build-runner")
            })?;
        assert_eq!(alpha_runner.definition.task, "alpha-build");
        assert_eq!(beta_runner.definition.task, "beta-build");
        assert!(registry.lookup_legacy("build-runner").is_none());
        Ok(())
    }

    /// #2175: one agent with `extra_projects` is registered (and thus
    /// lookup-able) under its primary project AND every extra project, so a
    /// shared verdict agent can gate multiple polyrepos without duplicating
    /// its template per project.
    #[test]
    fn registry_registers_agent_under_extra_projects() -> Result<(), Box<dyn std::error::Error>> {
        let config = config_from(
            r#"
working_dir = "/tmp/t"

[nightwatch]

[compound_review]
schedule = "0 2 * * *"
repo_path = "/tmp/repo"

[[projects]]
id = "alpha"
working_dir = "/tmp/alpha"

[[projects]]
id = "beta"
working_dir = "/tmp/beta"

[[projects]]
id = "gamma"
working_dir = "/tmp/gamma"

[[agents]]
name = "pr-verifier"
layer = "Growth"
cli_tool = "echo"
task = "verify"
project = "alpha"
extra_projects = ["beta", "gamma"]
"#,
        )?;

        let registry = AgentRegistry::from_config(&config)?;
        // One definition -> three registrations (alpha, beta, gamma).
        assert_eq!(registry.len(), 3);
        for project in ["alpha", "beta", "gamma"] {
            let agent = registry
                .lookup_project(project, "pr-verifier")
                .ok_or_else(|| {
                    std::io::Error::new(
                        std::io::ErrorKind::NotFound,
                        format!("missing pr-verifier for {project}"),
                    )
                })?;
            assert_eq!(agent.definition.task, "verify");
            assert_eq!(agent.key, AgentKey::project(project, "pr-verifier"));
        }
        // Not a legacy/global agent.
        assert!(registry.lookup_legacy("pr-verifier").is_none());
        Ok(())
    }

    /// #2175: an `extra_projects` entry that does not reference a known
    /// project id is rejected at load time (same rule as `project`).
    #[test]
    fn config_rejects_unknown_extra_project() {
        let config = config_from(
            r#"
working_dir = "/tmp/t"

[nightwatch]

[compound_review]
schedule = "0 2 * * *"
repo_path = "/tmp/repo"

[[projects]]
id = "alpha"
working_dir = "/tmp/alpha"

[[agents]]
name = "pr-verifier"
layer = "Growth"
cli_tool = "echo"
task = "verify"
project = "alpha"
extra_projects = ["does-not-exist"]
"#,
        )
        .expect("config parses; validation is separate");
        let result = config.validate();
        assert!(
            matches!(result, Err(OrchestratorError::UnknownAgentProject { .. })),
            "unknown extra_projects id must be rejected by validate(), got {result:?}"
        );
    }

    #[test]
    fn registry_rejects_duplicate_agent_in_same_scope() -> Result<(), Box<dyn std::error::Error>> {
        let config = config_from(
            r#"
working_dir = "/tmp/t"

[nightwatch]

[compound_review]
schedule = "0 2 * * *"
repo_path = "/tmp/repo"

[[agents]]
name = "dupe"
layer = "Safety"
cli_tool = "echo"
task = "first"

[[agents]]
name = "dupe"
layer = "Safety"
cli_tool = "echo"
task = "second"
"#,
        )?;

        let err = AgentRegistry::from_config(&config)
            .err()
            .ok_or_else(|| std::io::Error::other("expected duplicate agent error"))?;
        assert!(err.to_string().contains("duplicate agent 'dupe'"));
        Ok(())
    }

    #[test]
    fn names_for_scope_returns_sorted_names() -> Result<(), Box<dyn std::error::Error>> {
        let config = config_from(
            r#"
working_dir = "/tmp/t"

[nightwatch]

[compound_review]
schedule = "0 2 * * *"
repo_path = "/tmp/repo"

[[projects]]
id = "alpha"
working_dir = "/tmp/alpha"

[[agents]]
name = "zeta"
layer = "Safety"
cli_tool = "echo"
task = "z"
project = "alpha"

[[agents]]
name = "alpha"
layer = "Safety"
cli_tool = "echo"
task = "a"
project = "alpha"
"#,
        )?;

        let registry = AgentRegistry::from_config(&config)?;
        assert_eq!(
            registry.names_for_scope(&AgentScope::Project("alpha".to_string())),
            vec!["alpha", "zeta"]
        );
        Ok(())
    }
}