minion-engine 0.6.1

AI workflow engine that orchestrates Claude Code CLI — automate code review, refactoring, and PR creation with YAML workflows
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
//! Minion Slack Bot — listens for @minion mentions and dispatches workflows
//!
//! Enable with: cargo install minion-engine --features slack
//!
//! Configuration: ~/.minion/config.toml or environment variables:
//!   SLACK_BOT_TOKEN      — xoxb-... Bot User OAuth Token
//!   SLACK_SIGNING_SECRET — from Slack App → Basic Information → Signing Secret
//!   MINION_WORKFLOWS_DIR — path to workflows/ directory (default: ./workflows)

use std::env;
use std::process::Stdio;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};

use axum::{
    body::Bytes,
    extract::State,
    http::{HeaderMap, StatusCode},
    response::Json,
    routing::post,
    Router,
};
use hmac::{Hmac, Mac};
use serde::{Deserialize, Serialize};
use sha2::Sha256;
use tokio::process::Command;
use tracing::{error, info, warn};

type HmacSha256 = Hmac<Sha256>;

// ── Slack Event Types ───────────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
#[serde(tag = "type")]
enum SlackRequest {
    #[serde(rename = "url_verification")]
    UrlVerification { challenge: String },
    #[serde(rename = "event_callback")]
    EventCallback { event: SlackEvent },
}

#[derive(Debug, Deserialize)]
struct SlackEvent {
    #[serde(rename = "type")]
    event_type: String,
    text: Option<String>,
    channel: Option<String>,
    ts: Option<String>,
    user: Option<String>,
    #[serde(default)]
    bot_id: Option<String>,
}

#[derive(Debug, Serialize)]
struct SlackMessage {
    channel: String,
    text: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    thread_ts: Option<String>,
}

// ── Workflow Routing ────────────────────────────────────────────────────────

struct WorkflowMatch {
    workflow: String,
    target: String,
    description: String,
    /// GitHub repo (owner/repo) extracted from URL — enables multi-repo support
    repo: Option<String>,
}

/// Parse a GitHub URL into (owner/repo, number).
/// Examples:
///   "https://github.com/acme/backend/pull/12" → Some(("acme/backend", "12"))
///   "https://github.com/acme/backend/issues/7" → Some(("acme/backend", "7"))
///   "https://github.com/acme/backend" → Some(("acme/backend", ""))
///   "42" → None (just a number, no repo info)
struct GitHubRef {
    repo: Option<String>,
    number: String,
}

fn extract_github_info(input: &str) -> GitHubRef {
    // Match: https://github.com/owner/repo/pull/N or /issues/N
    let url_re = regex::Regex::new(
        r"https?://github\.com/([^/]+/[^/]+)/(?:pull|issues)/(\d+)"
    ).unwrap();
    if let Some(caps) = url_re.captures(input) {
        return GitHubRef {
            repo: Some(caps[1].to_string()),
            number: caps[2].to_string(),
        };
    }

    // Match: https://github.com/owner/repo (no PR/issue number — for security-audit, generate-docs)
    let repo_re = regex::Regex::new(
        r"https?://github\.com/([^/]+/[^/\s]+)"
    ).unwrap();
    if let Some(caps) = repo_re.captures(input) {
        return GitHubRef {
            repo: Some(caps[1].to_string()),
            number: String::new(),
        };
    }

    // Fallback: just a number or plain string
    GitHubRef {
        repo: None,
        number: input.to_string(),
    }
}

fn route_message(text: &str) -> Option<WorkflowMatch> {
    let text = text.to_lowercase();

    // Remove bot mention like <@U12345>
    let clean = regex::Regex::new(r"<@[A-Z0-9]+>")
        .unwrap()
        .replace_all(&text, "")
        .trim()
        .to_string();

    // Remove Slack URL formatting: <https://url> → https://url
    let clean = regex::Regex::new(r"<(https?://[^>|]+)(?:\|[^>]*)?>")
        .unwrap()
        .replace_all(&clean, "$1")
        .to_string();

    // fix issue #N or fix issue URL
    if let Some(caps) = regex::Regex::new(r"fix\s+issue\s+[#]?(\S+)")
        .unwrap()
        .captures(&clean)
    {
        let info = extract_github_info(&caps[1]);
        return Some(WorkflowMatch {
            workflow: "fix-issue.yaml".to_string(),
            target: info.number,
            repo: info.repo,
            description: "Fix GitHub issue".to_string(),
        });
    }

    // review pr #N or review PR URL
    if let Some(caps) = regex::Regex::new(r"review\s+(?:pr|pull\s*request)\s+[#]?(\S+)")
        .unwrap()
        .captures(&clean)
    {
        let info = extract_github_info(&caps[1]);
        return Some(WorkflowMatch {
            workflow: "code-review.yaml".to_string(),
            target: info.number,
            repo: info.repo,
            description: "Code review".to_string(),
        });
    }

    // security audit <repo-or-path-or-url>
    if let Some(caps) = regex::Regex::new(r"security\s+audit\s+(\S+)")
        .unwrap()
        .captures(&clean)
    {
        let info = extract_github_info(&caps[1]);
        return Some(WorkflowMatch {
            workflow: "security-audit.yaml".to_string(),
            target: if info.number.is_empty() { ".".to_string() } else { info.number },
            repo: info.repo,
            description: "Security audit".to_string(),
        });
    }

    // generate docs <repo-or-path-or-url>
    if let Some(caps) = regex::Regex::new(r"generate\s+docs?\s+(\S+)")
        .unwrap()
        .captures(&clean)
    {
        let info = extract_github_info(&caps[1]);
        return Some(WorkflowMatch {
            workflow: "generate-docs.yaml".to_string(),
            target: if info.number.is_empty() { ".".to_string() } else { info.number },
            repo: info.repo,
            description: "Generate documentation".to_string(),
        });
    }

    // fix ci <pr-url-or-number>
    if let Some(caps) = regex::Regex::new(r"fix\s+ci\s+(\S+)")
        .unwrap()
        .captures(&clean)
    {
        let info = extract_github_info(&caps[1]);
        return Some(WorkflowMatch {
            workflow: "fix-ci.yaml".to_string(),
            target: info.number,
            repo: info.repo,
            description: "Fix CI failures".to_string(),
        });
    }

    None
}

// ── App State ───────────────────────────────────────────────────────────────

#[derive(Clone)]
struct AppState {
    bot_token: String,
    signing_secret: String,
    workflows_dir: String,
    http: reqwest::Client,
}

// ── Signature Verification ──────────────────────────────────────────────────

fn verify_slack_signature(secret: &str, headers: &HeaderMap, body: &[u8]) -> bool {
    let timestamp = match headers.get("x-slack-request-timestamp") {
        Some(v) => v.to_str().unwrap_or(""),
        None => return false,
    };
    let signature = match headers.get("x-slack-signature") {
        Some(v) => v.to_str().unwrap_or(""),
        None => return false,
    };

    if let Ok(ts) = timestamp.parse::<u64>() {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();
        if now.abs_diff(ts) > 300 {
            warn!("Slack request timestamp too old");
            return false;
        }
    }

    let sig_basestring = format!("v0:{}:{}", timestamp, String::from_utf8_lossy(body));
    let mut mac = HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC key");
    mac.update(sig_basestring.as_bytes());
    let expected = format!("v0={}", hex::encode(mac.finalize().into_bytes()));

    signature == expected
}

// ── Slack API Helpers ───────────────────────────────────────────────────────

async fn post_message(state: &AppState, msg: &SlackMessage) {
    let resp = state
        .http
        .post("https://slack.com/api/chat.postMessage")
        .bearer_auth(&state.bot_token)
        .json(msg)
        .send()
        .await;

    match resp {
        Ok(r) => {
            if !r.status().is_success() {
                error!("Slack API error: {}", r.status());
            }
        }
        Err(e) => error!("Failed to post Slack message: {}", e),
    }
}

// ── Workflow Execution ──────────────────────────────────────────────────────

async fn run_workflow(state: Arc<AppState>, channel: String, thread_ts: String, wf: WorkflowMatch) {
    let workflow_path = format!("{}/{}", state.workflows_dir, wf.workflow);

    let repo_label = wf.repo.as_deref().unwrap_or("(local CWD)");
    post_message(
        &state,
        &SlackMessage {
            channel: channel.clone(),
            text: format!(
                "🚀 Starting *{}* — `{}`\nRepo: `{}`\nTarget: `{}`\nWorkflow: `{}`",
                wf.description, wf.workflow, repo_label, wf.target, workflow_path
            ),
            thread_ts: Some(thread_ts.clone()),
        },
    )
    .await;

    let minion_bin = which_minion();

    info!(
        workflow = %wf.workflow,
        target = %wf.target,
        repo = ?wf.repo,
        bin = %minion_bin,
        "Launching workflow"
    );

    let enhanced_path = format!(
        "{}/.cargo/bin:/usr/local/bin:/opt/homebrew/bin:{}",
        env::var("HOME").unwrap_or_default(),
        env::var("PATH").unwrap_or_default()
    );

    // Build command args: add --repo if we extracted owner/repo from URL
    let mut cmd_args = vec!["execute".to_string(), workflow_path.clone()];
    if let Some(ref repo) = wf.repo {
        cmd_args.extend(["--repo".to_string(), repo.clone()]);
    }
    cmd_args.extend(["--".to_string(), wf.target.clone()]);

    let result = Command::new(&minion_bin)
        .args(&cmd_args)
        .envs(std::env::vars())
        .env("PATH", &enhanced_path) // Must come AFTER envs() to override the inherited PATH
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .await;

    let (status_emoji, summary) = match result {
        Ok(output) => {
            let stdout = String::from_utf8_lossy(&output.stdout);
            let stderr = String::from_utf8_lossy(&output.stderr);
            let combined = if stdout.len() > 1500 {
                format!("...{}", &stdout[stdout.len() - 1500..])
            } else {
                stdout.to_string()
            };

            if output.status.success() {
                ("", format!("Workflow completed successfully!\n```\n{}\n```", combined))
            } else {
                let err_tail = if stderr.len() > 1000 {
                    format!("...{}", &stderr[stderr.len() - 1000..])
                } else {
                    stderr.to_string()
                };
                (
                    "",
                    format!(
                        "Workflow failed (exit code {})\n```\n{}\n```\nStderr:\n```\n{}\n```",
                        output.status.code().unwrap_or(-1),
                        combined,
                        err_tail
                    ),
                )
            }
        }
        Err(e) => ("💥", format!("Failed to spawn minion: {}", e)),
    };

    post_message(
        &state,
        &SlackMessage {
            channel,
            text: format!("{} *{}* finished\n{}", status_emoji, wf.description, summary),
            thread_ts: Some(thread_ts),
        },
    )
    .await;
}

fn which_minion() -> String {
    if let Ok(home) = env::var("HOME") {
        let cargo_bin = format!("{}/.cargo/bin/minion", home);
        if std::path::Path::new(&cargo_bin).exists() {
            return cargo_bin;
        }
    }
    "minion".to_string()
}

// ── HTTP Handler ────────────────────────────────────────────────────────────

async fn slack_events(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    body: Bytes,
) -> Result<Json<serde_json::Value>, StatusCode> {
    if !verify_slack_signature(&state.signing_secret, &headers, &body) {
        warn!("Invalid Slack signature");
        return Err(StatusCode::UNAUTHORIZED);
    }

    let request: SlackRequest = serde_json::from_slice(&body).map_err(|e| {
        error!("Failed to parse Slack event: {}", e);
        StatusCode::BAD_REQUEST
    })?;

    match request {
        SlackRequest::UrlVerification { challenge } => {
            info!("Slack URL verification challenge received");
            Ok(Json(serde_json::json!({ "challenge": challenge })))
        }
        SlackRequest::EventCallback { event } => {
            if event.bot_id.is_some() {
                return Ok(Json(serde_json::json!({"ok": true})));
            }

            if event.event_type == "app_mention" {
                if let (Some(text), Some(channel), Some(ts)) =
                    (event.text, event.channel, event.ts)
                {
                    info!(
                        user = ?event.user,
                        channel = %channel,
                        text = %text,
                        "Received app_mention"
                    );

                    match route_message(&text) {
                        Some(wf) => {
                            let state = Arc::clone(&state);
                            let ch = channel.clone();
                            let thread = ts.clone();
                            tokio::spawn(async move {
                                run_workflow(state, ch, thread, wf).await;
                            });
                        }
                        None => {
                            let state_ref = &*state;
                            post_message(
                                state_ref,
                                &SlackMessage {
                                    channel,
                                    text: "🤔 I didn't understand that command. Try:\n\
                                        • `@minion fix issue https://github.com/owner/repo/issues/10`\n\
                                        • `@minion review pr https://github.com/owner/repo/pull/42`\n\
                                        • `@minion security audit https://github.com/owner/repo`\n\
                                        • `@minion generate docs https://github.com/owner/repo`\n\
                                        • `@minion fix ci https://github.com/owner/repo/pull/8`\n\
                                        \nYou can also use just numbers (e.g. `fix issue #10`) if the bot is running inside the repo."
                                        .to_string(),
                                    thread_ts: Some(ts),
                                },
                            )
                            .await;
                        }
                    }
                }
            }

            Ok(Json(serde_json::json!({"ok": true})))
        }
    }
}

async fn health() -> &'static str {
    "minion-slack ok"
}

// ── Public entry point ──────────────────────────────────────────────────────

/// Load config from ~/.minion/config.toml, falling back to env vars.
fn load_slack_config() -> (String, String, String) {
    // Try config file first
    let config_path = dirs::home_dir()
        .unwrap_or_default()
        .join(".minion/config.toml");

    let (file_token, file_secret, file_dir) = if config_path.exists() {
        let content = std::fs::read_to_string(&config_path).unwrap_or_default();
        let parsed: toml::Value = toml::from_str(&content).unwrap_or(toml::Value::Table(Default::default()));
        let slack = parsed.get("slack");
        (
            slack
                .and_then(|s| s.get("bot_token"))
                .and_then(|v| v.as_str())
                .map(String::from),
            slack
                .and_then(|s| s.get("signing_secret"))
                .and_then(|v| v.as_str())
                .map(String::from),
            parsed
                .get("core")
                .and_then(|c| c.get("workflows_dir"))
                .and_then(|v| v.as_str())
                .map(String::from),
        )
    } else {
        (None, None, None)
    };

    let token = env::var("SLACK_BOT_TOKEN")
        .ok()
        .or(file_token)
        .expect("SLACK_BOT_TOKEN must be set (env var or ~/.minion/config.toml)");

    let secret = env::var("SLACK_SIGNING_SECRET")
        .ok()
        .or(file_secret)
        .expect("SLACK_SIGNING_SECRET must be set (env var or ~/.minion/config.toml)");

    let workflows_dir = env::var("MINION_WORKFLOWS_DIR")
        .ok()
        .or(file_dir)
        .unwrap_or_else(|| "./workflows".to_string());

    (token, secret, workflows_dir)
}

/// Start the Slack bot server on the given port.
pub async fn start_server(port: u16) -> anyhow::Result<()> {
    let (bot_token, signing_secret, workflows_dir) = load_slack_config();

    info!(workflows_dir = %workflows_dir, port = port, "Starting Minion Slack Bot");

    println!();
    println!("\x1b[1m🤖 Minion Slack Bot\x1b[0m");
    println!("  Workflows: {}", workflows_dir);
    println!("  Port:      {}", port);
    println!();
    println!("\x1b[2mWaiting for Slack events... (Ctrl+C to stop)\x1b[0m");
    println!();

    let state = Arc::new(AppState {
        bot_token,
        signing_secret,
        workflows_dir,
        http: reqwest::Client::new(),
    });

    let app = Router::new()
        .route("/slack/events", post(slack_events))
        .route("/health", axum::routing::get(health))
        .with_state(state);

    let addr = format!("0.0.0.0:{}", port);
    let listener = tokio::net::TcpListener::bind(&addr).await?;
    info!("Listening on {}", addr);

    axum::serve(listener, app).await?;
    Ok(())
}