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
//! Webhook and direct-dispatch capability for `AgentOrchestrator`: handling
//! immediate dispatch requests from the webhook endpoint, direct dispatches,
//! and reading the current git HEAD. Split from lib.rs as part of the Gitea
//! #1910 god-file decomposition; behaviour unchanged.
#![allow(clippy::too_many_lines)]

use std::time::Duration;

use tracing::{error, info, warn};

use crate::{
    AgentOrchestrator, OrchestratorError, ScheduleEvent, agent_key, dispatcher, mention,
    mention_chain, webhook,
};

impl AgentOrchestrator {
    /// Get current HEAD commit hash.
    pub(crate) async fn get_current_head(&self) -> Result<String, OrchestratorError> {
        let output = tokio::time::timeout(
            Duration::from_secs(5),
            tokio::process::Command::new("git")
                .args(["rev-parse", "HEAD"])
                .current_dir(&self.config.working_dir)
                .output(),
        )
        .await
        .map_err(|_| OrchestratorError::Config("git rev-parse HEAD timed out after 5s".into()))?
        .map_err(OrchestratorError::from)?;

        if output.status.success() {
            Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
        } else {
            Err(OrchestratorError::Config(
                "git rev-parse HEAD failed".into(),
            ))
        }
    }

    /// Handle a dispatch request received from the webhook endpoint.
    /// This is the webhook equivalent of poll_mentions but immediate.
    pub(crate) async fn handle_webhook_dispatch(&mut self, dispatch: webhook::WebhookDispatch) {
        // Rate limiting: check concurrent mention-spawned agents
        let mention_cfg = match self.config.mentions.as_ref() {
            Some(cfg) => cfg,
            None => return,
        };

        let active_mention_agents = self
            .active_agents
            .values()
            .filter(|a| a.spawned_by_mention)
            .count() as u32;

        if active_mention_agents >= mention_cfg.max_concurrent_mention_agents {
            warn!(
                active = active_mention_agents,
                max = mention_cfg.max_concurrent_mention_agents,
                "webhook dispatch rejected: mention agents at capacity"
            );
            return;
        }

        let agents = self.config.agents.clone();
        let agent_names: Vec<String> = agents.iter().map(|a| a.name.clone()).collect();
        let max_mention_depth = mention_cfg.max_mention_depth;

        match dispatch {
            webhook::WebhookDispatch::SpawnAgent {
                agent_name,
                detected_project,
                issue_number,
                comment_id,
                context,
                synthetic_event: _,
            } => {
                info!(
                    agent = %agent_name,
                    project = ?detected_project,
                    issue = issue_number,
                    comment_id = comment_id,
                    "webhook: dispatching agent spawn"
                );

                // Use project-aware resolver. For webhook dispatches we don't know which
                // project's repo the webhook came from, so we use LEGACY_PROJECT_ID as the
                // hint for unqualified mentions; qualified mentions carry detected_project.
                if let Some(def) = mention::resolve_mention(
                    detected_project.as_deref(),
                    dispatcher::LEGACY_PROJECT_ID,
                    &agent_name,
                    &agents,
                ) {
                    // Event-only agents (e.g. build-runner) must not be dispatched
                    // from comment mentions. They are spawned by handle_push or
                    // other event handlers with the appropriate context env vars.
                    // Rejecting here prevents ghost-issue posts and wasted spawns.
                    if def.event_only {
                        info!(
                            agent = %agent_name,
                            issue = issue_number,
                            comment_id = comment_id,
                            "webhook dispatch rejected: agent is event-only (push/event-driven), not mention-dispatchable"
                        );
                        return;
                    }

                    // Dedup: check Gitea assignment + active_agents before spawning
                    if self.should_skip_dispatch(&agent_name, issue_number).await {
                        return;
                    }

                    let chain_id = ulid::Ulid::new().to_string();
                    let depth: u32 = 0;
                    let parent_agent = String::new();

                    if let Err(e) = mention_chain::MentionChainTracker::check(
                        depth,
                        &parent_agent,
                        &agent_name,
                        max_mention_depth,
                    ) {
                        warn!(
                            agent = %agent_name,
                            chain_id = %chain_id,
                            depth,
                            error = %e,
                            "webhook mention chain check rejected dispatch"
                        );
                        if let Some(ref poster) = self.output_poster {
                            let body = format!(
                                "## Mention Dispatch Blocked\n\n\
                                Agent `{}` was not spawned: {}.\n\n\
                                _Webhook chain `{}` blocked._",
                                agent_name, e, chain_id
                            );
                            if let Err(pe) = poster.post_raw(issue_number, &body).await {
                                warn!(error = %pe, "failed to post webhook chain rejection comment");
                            }
                        }
                        return;
                    }

                    let ctx_args = mention_chain::MentionContextArgs {
                        parent_agent: parent_agent.clone(),
                        issue_number,
                        comment_body: context.clone(),
                        depth,
                        chain_id: chain_id.clone(),
                        available_agents: agent_names
                            .iter()
                            .filter(|n| *n != &agent_name)
                            .cloned()
                            .collect(),
                    };
                    let chain_ctx = mention_chain::MentionChainTracker::build_context(
                        &ctx_args,
                        max_mention_depth,
                    );

                    let mut mention_def = def.clone();
                    mention_def.task = format!("{}\n\n{}", def.task, chain_ctx);
                    mention_def.gitea_issue = Some(issue_number);

                    if let Err(e) = self.spawn_agent(&mention_def).await {
                        error!(agent = %agent_name, issue = issue_number, error = %e, "webhook: failed to spawn agent");
                    } else if let Some(agent) = self.active_agents.get_mut(&agent_key(&mention_def))
                    {
                        agent.spawned_by_mention = true;
                        agent.mention_chain_id = Some(chain_id);
                        agent.mention_depth = Some(depth);
                        agent.mention_parent_agent = None;
                    }
                }
            }
            webhook::WebhookDispatch::SpawnPersona {
                persona_name,
                issue_number,
                comment_id: _,
                context,
            } => {
                if let Some((agent_name, _)) = mention::resolve_persona_mention(
                    &persona_name,
                    &agents,
                    &self.persona_registry,
                    &context,
                ) {
                    info!(
                        persona = %persona_name,
                        agent = %agent_name,
                        issue = issue_number,
                        "webhook: dispatching persona-resolved agent"
                    );

                    if let Some(def) = agents.iter().find(|a| a.name == agent_name).cloned() {
                        // Event-only agents must not be dispatched via persona-mention
                        // either. Same rationale as the SpawnAgent arm.
                        if def.event_only {
                            info!(
                                persona = %persona_name,
                                agent = %agent_name,
                                issue = issue_number,
                                "webhook dispatch rejected: persona-resolved agent is event-only (push/event-driven), not mention-dispatchable"
                            );
                            return;
                        }

                        // Dedup: check Gitea assignment + active_agents before spawning
                        if self.should_skip_dispatch(&agent_name, issue_number).await {
                            return;
                        }

                        let chain_id = ulid::Ulid::new().to_string();
                        let depth: u32 = 0;
                        let parent_agent = String::new();

                        if let Err(e) = mention_chain::MentionChainTracker::check(
                            depth,
                            &parent_agent,
                            &agent_name,
                            max_mention_depth,
                        ) {
                            warn!(
                                agent = %agent_name,
                                chain_id = %chain_id,
                                depth,
                                error = %e,
                                "webhook mention chain check rejected persona dispatch"
                            );
                            if let Some(ref poster) = self.output_poster {
                                let body = format!(
                                    "## Mention Dispatch Blocked\n\n\
                                    Agent `{}` (via persona) was not spawned: {}.\n\n\
                                    _Webhook chain `{}` blocked._",
                                    agent_name, e, chain_id
                                );
                                if let Err(pe) = poster.post_raw(issue_number, &body).await {
                                    warn!(error = %pe, "failed to post webhook chain rejection comment");
                                }
                            }
                            return;
                        }

                        let ctx_args = mention_chain::MentionContextArgs {
                            parent_agent: parent_agent.clone(),
                            issue_number,
                            comment_body: context.clone(),
                            depth,
                            chain_id: chain_id.clone(),
                            available_agents: agent_names
                                .iter()
                                .filter(|n| *n != &agent_name)
                                .cloned()
                                .collect(),
                        };
                        let chain_ctx = mention_chain::MentionChainTracker::build_context(
                            &ctx_args,
                            max_mention_depth,
                        );

                        let mut mention_def = def.clone();
                        mention_def.task = format!("{}\n\n{}", def.task, chain_ctx);
                        mention_def.gitea_issue = Some(issue_number);

                        if let Err(e) = self.spawn_agent(&mention_def).await {
                            error!(agent = %agent_name, issue = issue_number, error = %e, "webhook: failed to spawn agent");
                        } else if let Some(agent) =
                            self.active_agents.get_mut(&agent_key(&mention_def))
                        {
                            agent.spawned_by_mention = true;
                            agent.mention_chain_id = Some(chain_id);
                            agent.mention_depth = Some(depth);
                            agent.mention_parent_agent = None;
                        }
                    }
                }
            }
            webhook::WebhookDispatch::CompoundReview {
                issue_number,
                comment_id,
            } => {
                info!(
                    issue = issue_number,
                    comment_id = comment_id,
                    "webhook: compound review triggered"
                );
                self.handle_schedule_event(ScheduleEvent::CompoundReview)
                    .await;

                // Post acknowledgment via existing output_poster
                if let Some(ref poster) = self.output_poster {
                    let ack_body = format!(
                        "## Compound Review Triggered (webhook)\n\n\
                        Manual trigger received from issue #{} comment {}.\n\
                        Running 6-agent review swarm now...",
                        issue_number, comment_id
                    );
                    if let Err(e) = poster.post_raw(issue_number, &ack_body).await {
                        warn!(error = %e, "failed to post compound review acknowledgment");
                    }
                }
            }
            webhook::WebhookDispatch::ReviewPr {
                pr_number,
                project,
                head_sha,
                author_login,
                title,
                diff_loc,
            } => {
                info!(
                    pr = pr_number,
                    project = %project,
                    head_sha = %head_sha,
                    author = %author_login,
                    diff_loc = diff_loc,
                    "webhook: enqueuing ReviewPr dispatch task"
                );
                self.dispatcher.enqueue(dispatcher::DispatchTask::ReviewPr {
                    pr_number,
                    project,
                    head_sha,
                    author_login,
                    title,
                    diff_loc,
                });
            }
            webhook::WebhookDispatch::Push {
                project,
                ref_name,
                before_sha,
                after_sha,
                pusher_login,
                files_changed,
            } => {
                info!(
                    project = %project,
                    ref_name = %ref_name,
                    after_sha = %after_sha,
                    pusher = %pusher_login,
                    files = files_changed.len(),
                    "webhook: enqueuing Push dispatch task"
                );
                self.dispatcher.enqueue(dispatcher::DispatchTask::Push {
                    project,
                    ref_name,
                    before_sha,
                    after_sha,
                    pusher_login,
                    files_changed,
                });
            }
        }
    }

    pub(crate) async fn handle_direct_dispatch(&mut self, dispatch: webhook::WebhookDispatch) {
        match dispatch {
            webhook::WebhookDispatch::SpawnAgent {
                agent_name,
                detected_project,
                context,
                synthetic_event,
                ..
            } => {
                // Use project-aware resolution for qualified agent names.
                let def = mention::resolve_mention(
                    detected_project.as_deref(),
                    dispatcher::LEGACY_PROJECT_ID,
                    &agent_name,
                    &self.config.agents,
                );

                let def = match def {
                    Some(def) => def,
                    None => {
                        // Fallback to simple name lookup for legacy compatibility.
                        warn!(agent = %agent_name, "direct dispatch: agent not found in config");
                        return;
                    }
                };

                if !def.enabled {
                    info!(agent = %agent_name, "direct dispatch rejected: agent is disabled");
                    return;
                }

                let mut direct_def = def.clone();
                if !context.is_empty() {
                    direct_def.task =
                        format!("{}\n\n[direct dispatch context]\n{}", def.task, context);
                }

                if def.event_only {
                    info!(
                        agent = %agent_name,
                        event = ?synthetic_event,
                        "direct dispatch override: spawning event_only agent locally"
                    );
                } else {
                    info!(agent = %agent_name, "direct dispatch: spawning agent");
                }
                if let Err(e) = self
                    .spawn_agent_with_event(&direct_def, synthetic_event.as_ref())
                    .await
                {
                    error!(agent = %agent_name, error = %e, "direct dispatch: failed to spawn agent");
                }
            }
            other => {
                warn!(dispatch = ?other, "direct dispatch ignored unsupported dispatch type");
            }
        }
    }
}