terraphim_orchestrator 1.20.3

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
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
//! Direct dispatch listener via Unix domain socket.
//!
//! Provides a low-latency dispatch path for `adf-ctl --local trigger --direct`
//! that bypasses the HTTP webhook roundtrip and HMAC verification.  The listener
//! accepts JSON commands on a Unix domain socket and forwards them to the
//! orchestrator's event loop as `WebhookDispatch::SpawnAgent` events.

use std::collections::HashSet;
use std::path::PathBuf;

use tokio::net::UnixListener;
use tracing::{error, info};

use crate::agent_runner::SyntheticEvent;
use crate::webhook::WebhookDispatch;

const MAX_COMMAND_SIZE: u64 = 8192;

/// JSON command received from adf-ctl over the Unix domain socket.
#[derive(Debug, serde::Deserialize)]
pub struct DispatchCommand {
    /// Agent name to spawn (must match a configured agent name).
    pub agent: String,
    /// Optional project hint for project-qualified agent resolution.
    #[serde(default)]
    pub project: Option<String>,
    /// Optional context string appended to the agent mention.
    #[serde(default)]
    pub context: Option<String>,
    /// Optional synthetic event for event-only agents.
    #[serde(default)]
    pub synthetic_event: Option<SyntheticEvent>,
}

/// Index of valid agent names for direct dispatch validation.
///
/// Allows the UDS listener to synchronously reject invalid project-qualified
/// dispatches rather than returning ok and later being dropped by the orchestrator.
#[derive(Debug, Clone)]
pub struct DirectDispatchAgentIndex {
    bare_names: HashSet<String>,
    qualified_names: HashSet<(String, String)>,
}

impl DirectDispatchAgentIndex {
    pub fn from_agents(agents: &[crate::config::AgentDefinition]) -> Self {
        let bare_names: HashSet<String> = agents
            .iter()
            .filter(|a| a.project.is_none())
            .map(|a| a.name.clone())
            .collect();
        let qualified_names: HashSet<(String, String)> = agents
            .iter()
            .filter_map(|a| a.project.clone().map(|p| (p, a.name.clone())))
            .collect();
        Self {
            bare_names,
            qualified_names,
        }
    }

    pub fn is_valid(&self, project: Option<&str>, agent: &str) -> bool {
        match project {
            Some(p) => self
                .qualified_names
                .contains(&(p.to_string(), agent.to_string())),
            None => self.bare_names.contains(agent),
        }
    }
}

/// JSON response written back to adf-ctl.
#[derive(Debug, serde::Serialize)]
pub struct DispatchResponse {
    pub status: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

impl DispatchResponse {
    pub fn ok() -> Self {
        Self {
            status: "ok".to_string(),
            message: None,
        }
    }

    pub fn error(msg: &str) -> Self {
        Self {
            status: "error".to_string(),
            message: Some(msg.to_string()),
        }
    }
}

/// Start the Unix domain socket listener for direct dispatch.
//
///
///
/// The listener task:
///
/// 1. Removes any stale socket file at `socket_path`.
/// 2. Binds and listens on the socket path.
/// 3. For each incoming connection:
///    a. Reads a single JSON command from the stream.
///    b. Validates the agent name against `agent_names`.
///    c. Sends `WebhookDispatch::SpawnAgent` to `dispatch_tx`.
///    d. Writes a JSON response back to the client.
/// 4. Logs errors and continues accepting connections.
///
/// The socket is cleaned up automatically when the listener task is dropped.
#[cfg(unix)]
fn remove_stale_socket_if_present(socket_path: &std::path::Path) -> std::io::Result<()> {
    use std::os::unix::fs::FileTypeExt;
    match std::fs::symlink_metadata(socket_path) {
        Ok(metadata) if metadata.file_type().is_socket() => std::fs::remove_file(socket_path),
        Ok(_) => Err(std::io::Error::new(
            std::io::ErrorKind::AlreadyExists,
            "direct dispatch path exists and is not a socket",
        )),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(e) => Err(e),
    }
}

pub fn start_direct_dispatch_listener(
    socket_path: PathBuf,
    dispatch_tx: tokio::sync::mpsc::Sender<WebhookDispatch>,
    agent_index: DirectDispatchAgentIndex,
) -> tokio::task::JoinHandle<()> {
    tokio::spawn(async move {
        if let Err(e) = remove_stale_socket_if_present(&socket_path) {
            error!(
                path = %socket_path.display(),
                error = %e,
                "failed to prepare direct dispatch socket path"
            );
            return;
        }

        let listener = match UnixListener::bind(&socket_path) {
            Ok(l) => l,
            Err(e) => {
                error!(
                    path = %socket_path.display(),
                    error = %e,
                    "failed to bind direct dispatch socket"
                );
                return;
            }
        };

        // Apply restrictive permissions: owner read/write only (0600).
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            if let Err(e) =
                std::fs::set_permissions(&socket_path, std::fs::Permissions::from_mode(0o600))
            {
                tracing::warn!(
                    path = %socket_path.display(),
                    error = %e,
                    "could not set permissions on direct dispatch socket"
                );
            }
        }

        info!(
            path = %socket_path.display(),
            "direct dispatch socket listening"
        );

        loop {
            match listener.accept().await {
                Ok((stream, _)) => {
                    let dispatch_tx = dispatch_tx.clone();
                    let agent_index = agent_index.clone();
                    tokio::spawn(async move {
                        if let Err(e) = handle_connection(stream, &dispatch_tx, &agent_index).await
                        {
                            error!(error = %e, "direct dispatch connection error");
                        }
                    });
                }
                Err(e) => {
                    error!(error = %e, "failed to accept direct dispatch connection");
                }
            }
        }
    })
}

async fn handle_connection(
    stream: tokio::net::UnixStream,
    dispatch_tx: &tokio::sync::mpsc::Sender<WebhookDispatch>,
    agent_index: &DirectDispatchAgentIndex,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    use tokio::io::{AsyncBufReadExt, AsyncReadExt};

    let (read_half, write_half) = stream.into_split();
    let mut reader = tokio::io::BufReader::new(read_half.take(MAX_COMMAND_SIZE));
    let mut line = String::new();

    let bytes_read = reader.read_line(&mut line).await?;
    if bytes_read == 0 {
        return Ok(());
    }

    let cmd: DispatchCommand = match serde_json::from_str(line.trim()) {
        Ok(cmd) => cmd,
        Err(e) => {
            let response = DispatchResponse::error(&format!("invalid JSON: {}", e));
            write_response(write_half, response).await?;
            return Ok(());
        }
    };

    if !agent_index.is_valid(cmd.project.as_deref(), &cmd.agent) {
        let msg = match cmd.project.as_deref() {
            Some(p) => format!("unknown project-qualified agent: {}/{}", p, cmd.agent),
            None => format!("unknown agent: {}", cmd.agent),
        };
        let response = DispatchResponse::error(&msg);
        write_response(write_half, response).await?;
        return Ok(());
    }

    let dispatch = WebhookDispatch::SpawnAgent {
        agent_name: cmd.agent.clone(),
        detected_project: cmd.project.clone(),
        issue_number: 0,
        comment_id: 0,
        context: cmd.context.unwrap_or_default(),
        synthetic_event: cmd.synthetic_event.clone(),
    };

    if dispatch_tx.send(dispatch).await.is_err() {
        let response = DispatchResponse::error("orchestrator channel closed");
        write_response(write_half, response).await?;
        return Ok(());
    }

    let response = DispatchResponse::ok();
    write_response(write_half, response).await?;
    Ok(())
}

async fn write_response(
    mut writer: tokio::net::unix::OwnedWriteHalf,
    response: DispatchResponse,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    use tokio::io::AsyncWriteExt;
    let json = serde_json::to_string(&response)?;
    writer.write_all(json.as_bytes()).await?;
    writer.write_all(b"\n").await?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio::net::UnixStream;
    use tokio::sync::mpsc;

    #[cfg(unix)]
    async fn wait_for_socket(path: &std::path::Path) {
        use std::os::unix::fs::FileTypeExt;
        for _ in 0..50 {
            if path.exists()
                && path
                    .metadata()
                    .map(|m| m.file_type().is_socket())
                    .unwrap_or(false)
            {
                return;
            }
            tokio::task::yield_now().await;
        }
        panic!("socket was not created at {}", path.display());
    }

    #[cfg(unix)]
    async fn send_command(path: &std::path::Path, json: &str) -> serde_json::Value {
        let stream =
            tokio::time::timeout(std::time::Duration::from_secs(2), UnixStream::connect(path))
                .await
                .expect("socket connect timed out")
                .expect("socket connect failed");

        let mut stream = tokio::io::BufReader::new(stream);
        tokio::time::timeout(std::time::Duration::from_secs(2), async {
            use tokio::io::{AsyncReadExt, AsyncWriteExt};
            let stream = stream.get_mut();
            stream
                .write_all(json.as_bytes())
                .await
                .expect("write failed");
            stream.write_all(b"\n").await.expect("newline failed");
            let mut response = String::new();
            stream
                .read_to_string(&mut response)
                .await
                .expect("read failed");
            serde_json::from_str(response.trim()).expect("invalid JSON response")
        })
        .await
        .expect("send_command timed out")
    }

    #[test]
    fn test_dispatch_command_deserialize() {
        let json = r#"{"agent": "meta-learning", "context": "test context"}"#;
        let cmd: DispatchCommand = serde_json::from_str(json).unwrap();
        assert_eq!(cmd.agent, "meta-learning");
        assert_eq!(cmd.context, Some("test context".to_string()));
    }

    #[test]
    fn test_dispatch_command_deserialize_no_context() {
        let json = r#"{"agent": "meta-learning"}"#;
        let cmd: DispatchCommand = serde_json::from_str(json).unwrap();
        assert_eq!(cmd.agent, "meta-learning");
        assert_eq!(cmd.context, None);
    }

    #[test]
    fn test_dispatch_response_ok() {
        let response = DispatchResponse::ok();
        let json = serde_json::to_string(&response).unwrap();
        assert_eq!(json, r#"{"status":"ok"}"#);
    }

    #[test]
    fn test_dispatch_response_error() {
        let response = DispatchResponse::error("unknown agent: foo");
        let json = serde_json::to_string(&response).unwrap();
        assert_eq!(json, r#"{"status":"error","message":"unknown agent: foo"}"#);
    }

    #[cfg(unix)]
    #[test]
    fn test_remove_stale_socket_rejects_regular_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("not-a-socket.txt");
        std::fs::write(&path, "hello").unwrap();
        let result = super::remove_stale_socket_if_present(&path);
        assert!(result.is_err(), "regular file should not be removed");
        assert!(
            path.exists(),
            "regular file must still exist after rejected removal"
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_remove_stale_socket_removes_nonexistent() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("does-not-exist");
        let result = super::remove_stale_socket_if_present(&path);
        assert!(result.is_ok(), "nonexistent path should be fine");
    }

    #[cfg(unix)]
    #[test]
    fn test_dispatch_command_agent_validation_logic() {
        use std::collections::HashSet;
        let valid_agents: HashSet<String> =
            ["meta-learning".to_string(), "sentinel".to_string()].into();

        let cmd_valid: DispatchCommand =
            serde_json::from_str(r#"{"agent":"meta-learning","context":"test"}"#).unwrap();
        assert!(
            valid_agents.contains(&cmd_valid.agent),
            "meta-learning should be valid"
        );

        let cmd_unknown: DispatchCommand =
            serde_json::from_str(r#"{"agent":"unknown-agent","context":""}"#).unwrap();
        assert!(
            !valid_agents.contains(&cmd_unknown.agent),
            "unknown-agent should be rejected"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn test_direct_dispatch_socket_valid_agent_round_trip() {
        use std::collections::HashSet;
        let dir = tempfile::tempdir().unwrap();
        let socket_path = dir.path().join("adf.sock");
        let (tx, mut rx) = mpsc::channel::<WebhookDispatch>(1);
        let bare_names: HashSet<String> = ["meta-learning".to_string()].into_iter().collect();
        let agent_index = super::DirectDispatchAgentIndex {
            bare_names,
            qualified_names: HashSet::new(),
        };

        let handle = start_direct_dispatch_listener(socket_path.clone(), tx, agent_index);
        wait_for_socket(&socket_path).await;

        let response = send_command(
            &socket_path,
            r#"{"agent":"meta-learning","context":"test"}"#,
        )
        .await;
        assert_eq!(response["status"], "ok", "expected ok response");

        let dispatch = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
            .await
            .expect("dispatch receive timed out")
            .expect("dispatch channel closed");

        match dispatch {
            WebhookDispatch::SpawnAgent {
                agent_name,
                context,
                issue_number,
                comment_id,
                ..
            } => {
                assert_eq!(agent_name, "meta-learning");
                assert_eq!(context, "test");
                assert_eq!(issue_number, 0);
                assert_eq!(comment_id, 0);
            }
            other => panic!("unexpected dispatch: {other:?}"),
        }

        handle.abort();
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn test_direct_dispatch_socket_unknown_agent_returns_error() {
        use std::collections::HashSet;
        let dir = tempfile::tempdir().unwrap();
        let socket_path = dir.path().join("adf.sock");
        let (tx, mut rx) = mpsc::channel::<WebhookDispatch>(1);
        let bare_names: HashSet<String> = ["meta-learning".to_string()].into_iter().collect();
        let agent_index = super::DirectDispatchAgentIndex {
            bare_names,
            qualified_names: HashSet::new(),
        };

        let handle = start_direct_dispatch_listener(socket_path.clone(), tx, agent_index);
        wait_for_socket(&socket_path).await;

        let response = send_command(&socket_path, r#"{"agent":"unknown-agent"}"#).await;
        assert_eq!(
            response["status"], "error",
            "expected error response for unknown agent"
        );
        assert!(
            response["message"]
                .as_str()
                .unwrap()
                .contains("unknown agent"),
            "error message should mention unknown agent"
        );
        assert!(
            rx.try_recv().is_err(),
            "unknown agent must not emit a dispatch"
        );

        handle.abort();
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn test_direct_dispatch_socket_project_qualified_agent_round_trip() {
        use std::collections::HashSet;
        let dir = tempfile::tempdir().unwrap();
        let socket_path = dir.path().join("adf.sock");
        let (tx, mut rx) = mpsc::channel::<WebhookDispatch>(1);
        let qualified_names: HashSet<(String, String)> =
            [("terraphim-ai".to_string(), "build-runner".to_string())]
                .into_iter()
                .collect();
        let agent_index = super::DirectDispatchAgentIndex {
            bare_names: HashSet::new(),
            qualified_names,
        };

        let handle = start_direct_dispatch_listener(socket_path.clone(), tx, agent_index);
        wait_for_socket(&socket_path).await;

        let response = send_command(
            &socket_path,
            r#"{"project":"terraphim-ai","agent":"build-runner","context":"test"}"#,
        )
        .await;
        assert_eq!(response["status"], "ok", "expected ok response");

        let dispatch = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
            .await
            .expect("dispatch receive timed out")
            .expect("dispatch channel closed");

        let WebhookDispatch::SpawnAgent {
            agent_name,
            detected_project,
            context,
            ..
        } = dispatch
        else {
            unreachable!("direct dispatch emits only SpawnAgent variants");
        };
        assert_eq!(agent_name, "build-runner");
        assert_eq!(detected_project.as_deref(), Some("terraphim-ai"));
        assert_eq!(context, "test");

        handle.abort();
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn test_direct_dispatch_socket_bad_project_returns_error() {
        use std::collections::HashSet;
        let dir = tempfile::tempdir().unwrap();
        let socket_path = dir.path().join("adf.sock");
        let (tx, mut rx) = mpsc::channel::<WebhookDispatch>(1);
        let qualified_names: HashSet<(String, String)> =
            [("terraphim-ai".to_string(), "build-runner".to_string())]
                .into_iter()
                .collect();
        let agent_index = super::DirectDispatchAgentIndex {
            bare_names: HashSet::new(),
            qualified_names,
        };

        let handle = start_direct_dispatch_listener(socket_path.clone(), tx, agent_index);
        wait_for_socket(&socket_path).await;

        let response = send_command(
            &socket_path,
            r#"{"project":"bad-project","agent":"build-runner"}"#,
        )
        .await;
        assert_eq!(
            response["status"], "error",
            "expected error response for bad project"
        );
        assert!(
            response["message"]
                .as_str()
                .unwrap()
                .contains("unknown project-qualified agent: bad-project/build-runner"),
            "error message should mention project-qualified agent"
        );
        assert!(
            rx.try_recv().is_err(),
            "bad project-qualified agent must not emit a dispatch"
        );

        handle.abort();
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn test_direct_dispatch_rejects_oversized_command() {
        use std::collections::HashSet;
        let dir = tempfile::tempdir().unwrap();
        let socket_path = dir.path().join("adf.sock");
        let (tx, _rx) = mpsc::channel::<WebhookDispatch>(1);
        let bare_names: HashSet<String> = ["meta-learning".to_string()].into_iter().collect();
        let agent_index = super::DirectDispatchAgentIndex {
            bare_names,
            qualified_names: HashSet::new(),
        };

        let handle = start_direct_dispatch_listener(socket_path.clone(), tx, agent_index);
        wait_for_socket(&socket_path).await;

        let oversized = "x".repeat(16384);
        let stream = tokio::time::timeout(
            std::time::Duration::from_secs(2),
            tokio::net::UnixStream::connect(&socket_path),
        )
        .await
        .expect("connect timed out")
        .expect("connect failed");

        use tokio::io::AsyncWriteExt;
        let (_, mut write_half) = stream.into_split();
        let _ = write_half.write_all(oversized.as_bytes()).await;
        drop(write_half);

        tokio::task::yield_now().await;

        let response = send_command(
            &socket_path,
            r#"{"agent":"meta-learning","context":"after-oversize"}"#,
        )
        .await;
        assert_eq!(
            response["status"], "ok",
            "listener must survive oversized input"
        );

        handle.abort();
    }

    #[test]
    fn test_direct_dispatch_agent_index_bare_agent() {
        let agents = vec![crate::config::AgentDefinition {
            name: "meta-learning".to_string(),
            layer: crate::config::AgentLayer::Growth,
            cli_tool: "claude".to_string(),
            task: "do stuff".to_string(),
            schedule: None,
            model: None,
            default_tier: None,
            capabilities: vec![],
            max_memory_bytes: None,
            budget_monthly_cents: None,
            provider: None,
            persona: None,
            terraphim_role: None,
            skill_chain: vec![],
            sfia_skills: vec![],
            fallback_provider: None,
            fallback_model: None,
            grace_period_secs: None,
            max_cpu_seconds: None,
            pre_check: None,
            gitea_issue: None,
            event_only: false,
            project: None,
            evolution_enabled: false,
            rlm_enabled: None,
            bypass_kg_routing: false,
            enabled: true,
        }];
        let index = super::DirectDispatchAgentIndex::from_agents(&agents);
        assert!(index.is_valid(None, "meta-learning"));
        assert!(!index.is_valid(None, "unknown-agent"));
    }

    #[test]
    fn test_direct_dispatch_agent_index_qualified_agent() {
        let agents = vec![crate::config::AgentDefinition {
            name: "build-runner".to_string(),
            layer: crate::config::AgentLayer::Core,
            cli_tool: "claude".to_string(),
            task: "run builds".to_string(),
            schedule: None,
            model: None,
            default_tier: None,
            capabilities: vec![],
            max_memory_bytes: None,
            budget_monthly_cents: None,
            provider: None,
            persona: None,
            terraphim_role: None,
            skill_chain: vec![],
            sfia_skills: vec![],
            fallback_provider: None,
            fallback_model: None,
            grace_period_secs: None,
            max_cpu_seconds: None,
            pre_check: None,
            gitea_issue: None,
            event_only: false,
            project: Some("terraphim-ai".to_string()),
            evolution_enabled: false,
            rlm_enabled: None,
            bypass_kg_routing: false,
            enabled: true,
        }];
        let index = super::DirectDispatchAgentIndex::from_agents(&agents);
        assert!(index.is_valid(Some("terraphim-ai"), "build-runner"));
        assert!(!index.is_valid(Some("terraphim-ai"), "unknown-agent"));
        assert!(!index.is_valid(Some("other-project"), "build-runner"));
        assert!(!index.is_valid(None, "build-runner"));
    }
}