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
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
//! Gitea webhook handler for real-time mention dispatch.
//!
//! Replaces poll-based mention detection with push-based webhook delivery.
//! Gitea sends POST requests on issue comment events, which are parsed
//! for @adf: commands and dispatched immediately.

use axum::{body::Bytes, extract::State, http::StatusCode, routing::post, Router};
use hmac::{Hmac, Mac};
use serde::Deserialize;
use sha2::Sha256;
use tracing::{info, warn};

use crate::adf_commands::AdfCommandParser;
use crate::persona::PersonaRegistry;

type HmacSha256 = Hmac<Sha256>;

/// Gitea webhook payload for issue_comment events.
#[derive(Debug, Deserialize)]
struct GiteaWebhookPayload {
    action: String,
    comment: GiteaComment,
    issue: GiteaIssue,
    repository: GiteaRepository,
}

#[derive(Debug, Deserialize)]
struct GiteaComment {
    id: u64,
    body: String,
    user: GiteaUser,
    created_at: String,
}

#[derive(Debug, Deserialize)]
pub struct GiteaUser {
    pub login: String,
}

#[derive(Debug, Deserialize)]
struct GiteaIssue {
    number: u64,
    title: String,
    state: String,
}

#[derive(Debug, Deserialize)]
pub struct GiteaRepository {
    pub full_name: String,
}

/// Gitea webhook payload for pull_request events.
#[derive(Debug, Deserialize)]
pub struct GiteaPullRequestPayload {
    pub action: String,
    pub number: u64,
    pub pull_request: PullRequestFields,
    pub repository: GiteaRepository,
}

#[derive(Debug, Deserialize)]
pub struct PullRequestFields {
    pub head: PrRef,
    pub base: PrRef,
    pub user: GiteaUser,
    pub title: String,
    pub draft: bool,
    pub additions: u32,
    pub deletions: u32,
}

#[derive(Debug, Deserialize)]
pub struct PrRef {
    pub sha: String,
    #[serde(rename = "ref")]
    pub ref_name: String,
}

/// A dispatch request sent from the webhook handler to the orchestrator.
pub enum WebhookDispatch {
    SpawnAgent {
        agent_name: String,
        /// Project extracted from a qualified `@adf:project/name` mention, or
        /// `None` for unqualified `@adf:name` mentions.
        detected_project: Option<String>,
        issue_number: u64,
        comment_id: u64,
        context: String,
    },
    SpawnPersona {
        persona_name: String,
        issue_number: u64,
        comment_id: u64,
        context: String,
    },
    CompoundReview {
        issue_number: u64,
        comment_id: u64,
    },
    ReviewPr {
        pr_number: u64,
        project: String,
        head_sha: String,
        author_login: String,
        title: String,
        diff_loc: u32,
    },
    /// Push event dispatch — triggers the deterministic `build-runner` agent
    /// (Phase 3 of the ADF replaces-Gitea-Actions plan). The orchestrator's
    /// `handle_push` consumes this and spawns the bash agent that shells out
    /// to `rch exec` for `cargo fmt/clippy/test`.
    Push {
        /// Project id resolved from `repository.full_name` (the repo segment
        /// after the `/`, mirroring the `ReviewPr` derivation).
        project: String,
        /// Full git ref, e.g. `refs/heads/main` or `refs/tags/v1.0.0`.
        ref_name: String,
        /// Parent commit SHA (zeros for branch creation).
        before_sha: String,
        /// New tip commit SHA the build-runner must check out.
        after_sha: String,
        /// `pusher.login` from the Gitea payload, used for audit logging.
        pusher_login: String,
        /// Unique union of `added ∪ removed ∪ modified` paths across all
        /// commits in the payload, in stable insertion order.
        files_changed: Vec<String>,
    },
}

impl WebhookDispatch {
    /// Extract the comment_id from any dispatch variant.
    /// `ReviewPr` dispatches are not associated with a comment — returns 0.
    pub fn comment_id(&self) -> u64 {
        match self {
            Self::SpawnAgent { comment_id, .. } => *comment_id,
            Self::SpawnPersona { comment_id, .. } => *comment_id,
            Self::CompoundReview { comment_id, .. } => *comment_id,
            Self::ReviewPr { .. } => 0,
            Self::Push { .. } => 0,
        }
    }
}

fn deserialize_null_default_vec<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
where
    D: serde::Deserializer<'de>,
    T: serde::Deserialize<'de>,
{
    Option::<Vec<T>>::deserialize(deserializer).map(|v| v.unwrap_or_default())
}

fn deserialize_null_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
where
    D: serde::Deserializer<'de>,
    T: serde::Deserialize<'de> + Default,
{
    Option::<T>::deserialize(deserializer).map(|v| v.unwrap_or_default())
}

/// Gitea webhook payload for `push` events (Phase 3).
#[derive(Debug, Deserialize)]
pub struct GiteaPushPayload {
    #[serde(rename = "ref")]
    pub ref_name: String,
    pub before: String,
    pub after: String,
    #[serde(default, deserialize_with = "deserialize_null_default")]
    pub pusher: GiteaPusher,
    pub repository: GiteaRepository,
    #[serde(default, deserialize_with = "deserialize_null_default_vec")]
    pub commits: Vec<GiteaPushCommit>,
}

#[derive(Debug, Default, Deserialize)]
pub struct GiteaPusher {
    #[serde(default)]
    pub login: String,
}

#[derive(Debug, Deserialize)]
pub struct GiteaPushCommit {
    #[serde(default, deserialize_with = "deserialize_null_default_vec")]
    pub added: Vec<String>,
    #[serde(default, deserialize_with = "deserialize_null_default_vec")]
    pub removed: Vec<String>,
    #[serde(default, deserialize_with = "deserialize_null_default_vec")]
    pub modified: Vec<String>,
}

/// Shared state for the webhook handler.
#[derive(Clone)]
pub struct WebhookState {
    pub agent_names: Vec<String>,
    pub persona_registry: std::sync::Arc<PersonaRegistry>,
    pub dispatch_tx: tokio::sync::mpsc::Sender<WebhookDispatch>,
    pub secret: Option<String>,
    pub project_by_repo: std::collections::HashMap<String, String>,
}

/// Create the webhook router.
pub fn webhook_router(state: WebhookState) -> Router {
    Router::new()
        .route("/webhooks/gitea", post(handle_gitea_webhook))
        .with_state(state)
}

/// Handle incoming Gitea webhook.
async fn handle_gitea_webhook(
    State(state): State<WebhookState>,
    headers: axum::http::HeaderMap,
    body: Bytes,
) -> StatusCode {
    // 1. Validate HMAC signature if secret is configured
    if let Some(ref secret) = state.secret {
        let sig_header = headers
            .get("X-Gitea-Signature")
            .or_else(|| headers.get("X-Hub-Signature-256"));

        match sig_header.and_then(|h| h.to_str().ok()) {
            Some(sig) => {
                if !verify_signature(secret, &body, sig) {
                    warn!("webhook signature verification failed");
                    return StatusCode::UNAUTHORIZED;
                }
            }
            None => {
                warn!("webhook secret configured but no signature header present");
                return StatusCode::BAD_REQUEST;
            }
        }
    }

    // 2. Route by event type header
    let event_type = headers
        .get("X-Gitea-Event")
        .and_then(|h| h.to_str().ok())
        .unwrap_or("issue_comment");

    if event_type == "pull_request" {
        return handle_pull_request_event(&state, &body).await;
    }

    // Push events (Phase 3): explicit `X-Gitea-Event: push` header, or fall
    // back to JSON shape detection (presence of `ref` + `before` + `after` +
    // `commits`) for clients that omit the header. Falls through to the
    // legacy issue-comment parser otherwise.
    if event_type == "push" || looks_like_push_payload(&body) {
        return handle_push_event(&state, &body).await;
    }

    // 3. Parse payload
    let payload: GiteaWebhookPayload = match serde_json::from_slice(&body) {
        Ok(p) => p,
        Err(e) => {
            warn!(error = %e, "failed to parse webhook payload");
            return StatusCode::BAD_REQUEST;
        }
    };

    info!(
        repo = %payload.repository.full_name,
        issue = payload.issue.number,
        issue_title = %payload.issue.title,
        issue_state = %payload.issue.state,
        comment_id = payload.comment.id,
        author = %payload.comment.user.login,
        created_at = %payload.comment.created_at,
        action = %payload.action,
        "received webhook event"
    );

    // 3. Only handle created comments (ignore edited/deleted)
    if payload.action != "created" {
        return StatusCode::OK;
    }

    // 4. Extract @adf: commands using existing parser
    let persona_names: Vec<String> = state
        .persona_registry
        .persona_names()
        .into_iter()
        .map(|s| s.to_string())
        .collect();
    let parser = AdfCommandParser::new(&state.agent_names, &persona_names);

    // Parse all mention tokens first to capture project prefixes from qualified
    // mentions (`@adf:project/name`) before the Aho-Corasick parser strips them.
    let mention_tokens = crate::mention::parse_mention_tokens(&payload.comment.body);
    // Map agent_name -> detected project for unqualified mentions resolved by parser.
    // Derive the project from the webhook's repository full name (e.g. zestic-ai/odilo -> odilo).
    let repo_derived_project: Option<String> = state
        .project_by_repo
        .get(&payload.repository.full_name)
        .cloned();
    let unqualified_project_map: std::collections::HashMap<String, Option<String>> = mention_tokens
        .iter()
        .filter(|t| t.project.is_none())
        .map(|t| (t.agent.clone(), repo_derived_project.clone()))
        .collect();

    let commands = parser.parse_commands(
        &payload.comment.body,
        payload.issue.number,
        payload.comment.id,
    );

    // Collect qualified tokens that AdfCommandParser cannot match (it only knows
    // `@adf:{name}` patterns and `@adf:project/name` is not a substring of those).
    let qualified_dispatches: Vec<WebhookDispatch> = mention_tokens
        .into_iter()
        .filter(|t| t.project.is_some())
        .map(|t| WebhookDispatch::SpawnAgent {
            detected_project: t.project,
            agent_name: t.agent,
            issue_number: payload.issue.number,
            comment_id: payload.comment.id,
            context: String::new(),
        })
        .collect();

    if commands.is_empty() && qualified_dispatches.is_empty() {
        return StatusCode::OK;
    }

    // 5. Dispatch each command to the orchestrator
    let mut commands_dispatched: u32 = 0;
    for cmd in commands {
        let dispatch = match cmd {
            crate::adf_commands::AdfCommand::SpawnAgent {
                agent_name,
                issue_number,
                comment_id,
                context,
            } => WebhookDispatch::SpawnAgent {
                detected_project: unqualified_project_map.get(&agent_name).cloned().flatten(),
                agent_name,
                issue_number,
                comment_id,
                context,
            },
            crate::adf_commands::AdfCommand::SpawnPersona {
                persona_name,
                issue_number,
                comment_id,
                context,
            } => WebhookDispatch::SpawnPersona {
                persona_name,
                issue_number,
                comment_id,
                context,
            },
            crate::adf_commands::AdfCommand::CompoundReview {
                issue_number,
                comment_id,
            } => WebhookDispatch::CompoundReview {
                issue_number,
                comment_id,
            },
            crate::adf_commands::AdfCommand::Unknown { raw } => {
                warn!(raw = %raw, "unknown ADF command from webhook");
                continue;
            }
        };

        if let Err(e) = state.dispatch_tx.send(dispatch).await {
            warn!(error = %e, "failed to send webhook dispatch to orchestrator");
            return StatusCode::SERVICE_UNAVAILABLE;
        }
        commands_dispatched += 1;
    }

    // Dispatch qualified mentions separately (AdfCommandParser can't see `@adf:proj/name`).
    for dispatch in qualified_dispatches {
        if let Err(e) = state.dispatch_tx.send(dispatch).await {
            warn!(error = %e, "failed to send qualified mention dispatch to orchestrator");
            return StatusCode::SERVICE_UNAVAILABLE;
        }
        commands_dispatched += 1;
    }

    info!(
        repo = %payload.repository.full_name,
        issue = payload.issue.number,
        comment_id = payload.comment.id,
        author = %payload.comment.user.login,
        commands = commands_dispatched,
        "webhook dispatch complete"
    );
    StatusCode::ACCEPTED
}

/// Handle Gitea `pull_request` event. Returns 200 for all parse/skip cases
/// (Gitea retries on non-2xx, causing spam).
pub async fn handle_pull_request_event(state: &WebhookState, body: &[u8]) -> StatusCode {
    let payload: GiteaPullRequestPayload = match serde_json::from_slice(body) {
        Ok(p) => p,
        Err(e) => {
            warn!(error = %e, "failed to parse pull_request webhook payload");
            return StatusCode::OK;
        }
    };

    let action = payload.action.as_str();

    // Only enqueue for review-triggering actions on non-draft PRs.
    let is_review_action = matches!(
        action,
        "opened" | "synchronize" | "reopened" | "ready_for_review"
    );

    if !is_review_action || payload.pull_request.draft {
        info!(
            action = action,
            draft = payload.pull_request.draft,
            pr = payload.number,
            "skipped_pr_webhook"
        );
        return StatusCode::OK;
    }

    // Derive project from `owner/repo` → `repo`.
    let project = payload
        .repository
        .full_name
        .split('/')
        .next_back()
        .unwrap_or(&payload.repository.full_name)
        .to_string();

    let diff_loc = payload
        .pull_request
        .additions
        .saturating_add(payload.pull_request.deletions);

    let dispatch = WebhookDispatch::ReviewPr {
        pr_number: payload.number,
        project,
        head_sha: payload.pull_request.head.sha.clone(),
        author_login: payload.pull_request.user.login.clone(),
        title: payload.pull_request.title.clone(),
        diff_loc,
    };

    info!(
        pr = payload.number,
        action = action,
        author = %payload.pull_request.user.login,
        "webhook: enqueuing ReviewPr dispatch"
    );

    match state.dispatch_tx.send(dispatch).await {
        Ok(()) => StatusCode::ACCEPTED,
        Err(e) => {
            warn!(error = %e, "failed to send ReviewPr dispatch");
            StatusCode::SERVICE_UNAVAILABLE
        }
    }
}

/// JSON-shape sniffer for `push` events when the `X-Gitea-Event` header is
/// missing. Returns true when the body parses as an object containing the
/// trio of `ref`, `before`, `after` and a `commits` array — the unique
/// fingerprint of a Gitea push payload.
fn looks_like_push_payload(body: &[u8]) -> bool {
    let v: serde_json::Value = match serde_json::from_slice(body) {
        Ok(v) => v,
        Err(_) => return false,
    };
    v.get("ref").is_some()
        && v.get("before").is_some()
        && v.get("after").is_some()
        && v.get("commits").map(|c| c.is_array()).unwrap_or(false)
}

/// Aggregate `added ∪ removed ∪ modified` paths across all commits in a push
/// payload, deduplicating while preserving first-seen insertion order.
pub fn aggregate_files_changed(commits: &[GiteaPushCommit]) -> Vec<String> {
    let mut seen = std::collections::HashSet::new();
    let mut out = Vec::new();
    for c in commits {
        for path in c
            .added
            .iter()
            .chain(c.removed.iter())
            .chain(c.modified.iter())
        {
            if seen.insert(path.clone()) {
                out.push(path.clone());
            }
        }
    }
    out
}

/// Handle Gitea `push` event (Phase 3). Returns 200 for parse/skip cases so
/// Gitea does not retry-spam on malformed bodies; emits `ACCEPTED` once a
/// `WebhookDispatch::Push` has been forwarded to the orchestrator.
pub async fn handle_push_event(state: &WebhookState, body: &[u8]) -> StatusCode {
    let payload: GiteaPushPayload = match serde_json::from_slice(body) {
        Ok(p) => p,
        Err(e) => {
            warn!(error = %e, "failed to parse push webhook payload");
            return StatusCode::OK;
        }
    };

    // Derive project from `owner/repo` → `repo`, mirroring the ReviewPr path.
    let project = payload
        .repository
        .full_name
        .split('/')
        .next_back()
        .unwrap_or(&payload.repository.full_name)
        .to_string();

    let files_changed = aggregate_files_changed(&payload.commits);

    let dispatch = WebhookDispatch::Push {
        project,
        ref_name: payload.ref_name.clone(),
        before_sha: payload.before.clone(),
        after_sha: payload.after.clone(),
        pusher_login: payload.pusher.login.clone(),
        files_changed,
    };

    info!(
        repo = %payload.repository.full_name,
        ref_name = %payload.ref_name,
        before = %payload.before,
        after = %payload.after,
        pusher = %payload.pusher.login,
        commits = payload.commits.len(),
        "webhook: enqueuing Push dispatch"
    );

    match state.dispatch_tx.send(dispatch).await {
        Ok(()) => StatusCode::ACCEPTED,
        Err(e) => {
            warn!(error = %e, "failed to send Push dispatch");
            StatusCode::SERVICE_UNAVAILABLE
        }
    }
}

/// Verify HMAC-SHA256 signature.
pub fn verify_signature(secret: &str, body: &[u8], signature: &str) -> bool {
    let mut mac =
        HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC can take key of any size");
    mac.update(body);
    let result = mac.finalize();
    let expected = result.into_bytes();

    // Strip "sha256=" prefix if present
    let sig_bytes: Vec<u8> =
        match hex::decode(signature.strip_prefix("sha256=").unwrap_or(signature)) {
            Ok(b) => b,
            Err(_) => return false,
        };

    expected.len() == sig_bytes.len() && expected.iter().zip(sig_bytes.iter()).all(|(a, b)| a == b)
}

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

    #[test]
    fn test_verify_signature_valid() {
        let secret = "test-secret";
        let body = b"hello world";
        let mut mac = HmacSha256::new_from_slice(secret.as_bytes()).unwrap();
        mac.update(body);
        let result = mac.finalize();
        let sig = hex::encode(result.into_bytes());
        assert!(verify_signature(secret, body, &sig));
    }

    #[test]
    fn test_verify_signature_invalid() {
        assert!(!verify_signature("secret", b"body", "deadbeef"));
    }

    #[test]
    fn test_verify_signature_with_prefix() {
        let secret = "test-secret";
        let body = b"hello world";
        let mut mac = HmacSha256::new_from_slice(secret.as_bytes()).unwrap();
        mac.update(body);
        let result = mac.finalize();
        let sig = format!("sha256={}", hex::encode(result.into_bytes()));
        assert!(verify_signature(secret, body, &sig));
    }

    #[test]
    fn test_push_commit_null_file_arrays() {
        let payload = r#"{"ref":"refs/heads/main","before":"aaa","after":"bbb","repository":{"full_name":"test/repo"},"commits":[{"added":null,"removed":null,"modified":null}]}"#;
        let parsed: GiteaPushPayload =
            serde_json::from_str(payload).expect("should parse null arrays");
        assert!(parsed.commits[0].added.is_empty());
        assert!(parsed.commits[0].removed.is_empty());
        assert!(parsed.commits[0].modified.is_empty());
    }

    #[test]
    fn test_push_commit_empty_file_arrays() {
        let payload = r#"{"ref":"refs/heads/main","before":"aaa","after":"bbb","repository":{"full_name":"test/repo"},"commits":[{"added":[],"removed":[],"modified":[]}]}"#;
        let parsed: GiteaPushPayload =
            serde_json::from_str(payload).expect("should parse empty arrays");
        assert!(parsed.commits[0].added.is_empty());
    }

    #[test]
    fn test_push_commit_normal_file_arrays() {
        let payload = r#"{"ref":"refs/heads/main","before":"aaa","after":"bbb","repository":{"full_name":"test/repo"},"commits":[{"added":["foo.rs"],"removed":[],"modified":["bar.rs"]}]}"#;
        let parsed: GiteaPushPayload =
            serde_json::from_str(payload).expect("should parse populated arrays");
        assert_eq!(parsed.commits[0].added, vec!["foo.rs"]);
        assert_eq!(parsed.commits[0].modified, vec!["bar.rs"]);
    }
}