forge-orchestrator 1.7.0

Orchestration for Claude Code, with Codex CLI as a task runner, on shared repos — single Rust binary, zero deps. Gemini CLI support is in development (build B1, target 2026-10-27).
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
use super::{DriftScore, ForgeBrain, KnowledgeCategory};
use crate::core::task::{AgentType, Task};

/// Rule-based brain — no LLM calls, pure heuristics.
/// This is the free tier / fallback brain.
pub struct RuleBasedBrain;

/// Tasks are user-facing by default. Only tasks matching these internal/infra
/// keywords are excluded from UAT generation. This inverts the old approach
/// (whitelist of UI keywords) which missed entire categories like games,
/// CLIs, APIs, etc.
const NON_USER_FACING_KEYWORDS: &[&str] = &[
    "refactor",
    "ci",
    "pipeline",
    "migration",
    "schema",
    "infrastructure",
    "devops",
    "dockerfile",
    "linter",
    "formatter",
    "dependency",
    "upgrade",
    "internal",
    "scaffolding",
    "boilerplate",
    "config",
    "tooling",
];

/// Returns true if the task is user-facing (should get UAT).
/// Default: true. Only returns false for clearly internal/infra tasks.
pub fn is_user_facing(title: &str, description: &str) -> bool {
    let text = format!("{} {}", title.to_lowercase(), description.to_lowercase());
    !NON_USER_FACING_KEYWORDS
        .iter()
        .any(|kw| contains_word(&text, kw))
}

/// Check if `text` contains `word` as a whole word (bounded by non-alphanumeric or string edges).
fn contains_word(text: &str, word: &str) -> bool {
    for (i, _) in text.match_indices(word) {
        let before_ok = i == 0 || !text.as_bytes()[i - 1].is_ascii_alphanumeric();
        let after = i + word.len();
        let after_ok = after >= text.len() || !text.as_bytes()[after].is_ascii_alphanumeric();
        if before_ok && after_ok {
            return true;
        }
    }
    false
}

/// Generate human-testable acceptance criteria from task title and existing criteria.
pub fn generate_uat_criteria(title: &str, acceptance_criteria: &[String]) -> Vec<String> {
    let title_lower = title.to_lowercase();
    let mut criteria = Vec::new();

    // Keyword-driven human-testable criteria (word-boundary matching)
    if contains_word(&title_lower, "navigation") || contains_word(&title_lower, "menu") {
        criteria.push("Can reach target in 3 clicks or fewer".to_string());
    }
    if contains_word(&title_lower, "button") || contains_word(&title_lower, "form") {
        criteria.push("Interactive elements respond within 200ms".to_string());
    }
    if contains_word(&title_lower, "layout") || contains_word(&title_lower, "responsive") {
        criteria.push("Layout correct at 1920x1080 and 1366x768".to_string());
    }
    if contains_word(&title_lower, "terminal") {
        criteria.push("Terminal output readable with no rendering glitches".to_string());
    }
    if contains_word(&title_lower, "accessibility") {
        criteria.push("All interactive elements are keyboard-navigable".to_string());
    }
    if contains_word(&title_lower, "animation") {
        criteria.push("Animations are smooth with no visual jank".to_string());
    }

    // Generic fallback if no specific criteria matched
    if criteria.is_empty() {
        criteria.push("Feature works as expected from user perspective".to_string());
    }

    // Append non-technical original criteria prefixed with "Verify: "
    for ac in acceptance_criteria {
        let lower = ac.to_lowercase();
        // Skip purely technical criteria
        let is_technical = lower.contains("compile")
            || lower.contains("tests pass")
            || lower.contains("test pass")
            || lower.contains("coverage")
            || lower.contains("lint")
            || lower.contains("no error");
        if !is_technical {
            criteria.push(format!("Verify: {ac}"));
        }
    }

    criteria
}

/// Classify a task's type from its title and description using keyword heuristics.
pub fn classify_task_type(title: &str, description: &str) -> Option<String> {
    let text = format!("{} {}", title.to_lowercase(), description.to_lowercase());

    if text.contains("design")
        || text.contains("architect")
        || text.contains("plan")
        || text.contains("schema")
        || text.contains("strategy")
    {
        return Some("design".into());
    }

    if text.contains("review")
        || text.contains("audit")
        || text.contains("analyze")
        || text.contains("evaluate")
        || text.contains("inspect")
    {
        return Some("review".into());
    }

    if text.contains("test")
        || text.contains("spec")
        || text.contains("coverage")
        || text.contains("assert")
    {
        return Some("test".into());
    }

    if text.contains("document")
        || text.contains("readme")
        || text.contains("docs")
        || text.contains("api doc")
        || text.contains("comment")
    {
        return Some("document".into());
    }

    if text.contains("implement")
        || text.contains("build")
        || text.contains("create")
        || text.contains("add")
        || text.contains("fix")
        || text.contains("refactor")
        || text.contains("code")
        || text.contains("develop")
    {
        return Some("implement".into());
    }

    None
}

impl ForgeBrain for RuleBasedBrain {
    fn decompose_plan(
        &self,
        spec: &str,
        _available_tools: &[AgentType],
        start_id: u32,
    ) -> anyhow::Result<Vec<Task>> {
        // Check if codebase inventory is present
        let inventory_files = extract_inventory_files(spec);

        // Simple heuristic: split spec by markdown headers into tasks
        let mut tasks = Vec::new();
        let mut task_num = start_id;

        for line in spec.lines() {
            if let Some(header) = line.strip_prefix("## ") {
                let title = header.trim();

                // Skip inventory section headers
                if title == "Source Files" || title == "Test Files" {
                    continue;
                }

                // If we have an inventory, check if this feature already exists
                if !inventory_files.is_empty() {
                    let title_lower = title.to_lowercase().replace([' ', '-'], "_");
                    let already_exists = inventory_files.iter().any(|f| {
                        let f_lower = f.to_lowercase();
                        // Check if any source file name matches the heading
                        f_lower.contains(&title_lower)
                            || title_lower
                                .split('_')
                                .any(|word| word.len() > 3 && f_lower.contains(word))
                    });
                    if already_exists {
                        // Create a review task instead of implement
                        let id = format!("T-{task_num:03}");
                        let desc = format!("Review existing implementation of: {title}");
                        let mut task = Task::new(&id, title, &desc);
                        task.task_type = Some("review".into());
                        tasks.push(task);
                        task_num += 1;
                        continue;
                    }
                }

                let id = format!("T-{task_num:03}");
                let desc = format!("Implement: {title}");
                let mut task = Task::new(&id, title, &desc);
                task.task_type = classify_task_type(title, &desc);
                tasks.push(task);
                task_num += 1;
            }
        }

        // If no headers found, create a single task
        if tasks.is_empty() {
            tasks.push(Task::new(
                format!("T-{start_id:03}"),
                "Implement specification",
                spec.chars().take(500).collect::<String>(),
            ));
        }

        Ok(tasks)
    }

    fn assign_task(&self, task: &Task, available_tools: &[AgentType]) -> anyhow::Result<AgentType> {
        if available_tools.is_empty() {
            return Ok(AgentType::Any);
        }

        let title_lower = task.title.to_lowercase();
        let desc_lower = task.description.to_lowercase();
        let text = format!("{title_lower} {desc_lower}");

        // Keyword-based assignment heuristics (check title + description)
        if text.contains("architect")
            || text.contains("design")
            || text.contains("plan")
            || text.contains("review")
            || text.contains("evaluate")
            || text.contains("decide")
            || text.contains("strategy")
        {
            // Architecture/strategy tasks → Claude (strongest reasoning)
            if available_tools.contains(&AgentType::Claude) {
                return Ok(AgentType::Claude);
            }
        }

        if text.contains("implement")
            || text.contains("code")
            || text.contains("build")
            || text.contains("refactor")
            || text.contains("create")
            || text.contains("add")
            || text.contains("fix")
            || text.contains("develop")
            || text.contains("write code")
        {
            // Implementation tasks → Codex (fast code generation)
            if available_tools.contains(&AgentType::Codex) {
                return Ok(AgentType::Codex);
            }
        }

        if text.contains("test")
            || text.contains("doc")
            || text.contains("document")
            || text.contains("documentation")
            || text.contains("report")
            || text.contains("summary")
            || text.contains("validate")
            || text.contains("verify")
            || text.contains("quality")
            || text.contains("coverage")
        {
            // Testing/docs/validation → Gemini (good at structured output)
            if available_tools.contains(&AgentType::Gemini) {
                return Ok(AgentType::Gemini);
            }
        }

        // Round-robin fallback: distribute by task ID number
        let task_num: usize = task.id.trim_start_matches("T-").parse().unwrap_or(0);
        let idx = task_num % available_tools.len();
        Ok(available_tools[idx].clone())
    }

    fn evaluate_drift(&self, _work_summary: &str, _vision: &str) -> anyhow::Result<DriftScore> {
        // Rule-based brain can't evaluate drift without LLM
        // Return a neutral score
        Ok(DriftScore {
            score: 0.0,
            explanation: "Drift evaluation requires an LLM brain. Set brain to claude or gemini for intelligent drift detection.".into(),
        })
    }

    fn route_knowledge(&self, content: &str) -> anyhow::Result<KnowledgeCategory> {
        let lower = content.to_lowercase();

        // Keyword-based classification
        if lower.contains("research")
            || lower.contains("finding")
            || lower.contains("discovered")
            || lower.contains("learned that")
        {
            return Ok(KnowledgeCategory::Research);
        }

        if lower.contains("decided")
            || lower.contains("decision")
            || lower.contains("chose")
            || lower.contains("adr")
        {
            return Ok(KnowledgeCategory::Decision);
        }

        if lower.contains("lesson")
            || lower.contains("mistake")
            || lower.contains("bug")
            || lower.contains("fix")
        {
            return Ok(KnowledgeCategory::Learning);
        }

        if lower.contains("pattern")
            || lower.contains("convention")
            || lower.contains("best practice")
        {
            return Ok(KnowledgeCategory::Pattern);
        }

        Ok(KnowledgeCategory::Unknown)
    }
}

/// Extract file paths from codebase inventory section if present.
fn extract_inventory_files(spec: &str) -> Vec<String> {
    let marker = "EXISTING CODEBASE INVENTORY:";
    let Some(idx) = spec.find(marker) else {
        return Vec::new();
    };
    let inventory_section = &spec[idx..];
    inventory_section
        .lines()
        .filter_map(|line| {
            let trimmed = line.trim().strip_prefix("- ")?;
            // Lines like "src/foo.rs (42 lines)" — extract the path part
            let path = trimmed.split(' ').next()?;
            if path.contains('.') {
                Some(path.to_string())
            } else {
                None
            }
        })
        .collect()
}

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

    #[test]
    fn test_assign_architecture_to_claude() {
        let brain = RuleBasedBrain;
        let task = Task::new("T-001", "Design the API architecture", "...");
        let tools = vec![AgentType::Claude, AgentType::Codex];
        let result = brain.assign_task(&task, &tools).unwrap();
        assert_eq!(result, AgentType::Claude);
    }

    #[test]
    fn test_assign_implementation_to_codex() {
        let brain = RuleBasedBrain;
        let task = Task::new("T-002", "Implement the login endpoint", "...");
        let tools = vec![AgentType::Claude, AgentType::Codex];
        let result = brain.assign_task(&task, &tools).unwrap();
        assert_eq!(result, AgentType::Codex);
    }

    #[test]
    fn test_route_knowledge_research() {
        let brain = RuleBasedBrain;
        let result = brain
            .route_knowledge("Research finding: Codex CLI supports MCP server mode")
            .unwrap();
        assert_eq!(result, KnowledgeCategory::Research);
    }

    #[test]
    fn test_route_knowledge_decision() {
        let brain = RuleBasedBrain;
        let result = brain
            .route_knowledge("We decided to use Rust for the orchestrator")
            .unwrap();
        assert_eq!(result, KnowledgeCategory::Decision);
    }

    #[test]
    fn test_assign_testing_to_gemini() {
        let brain = RuleBasedBrain;
        let task = Task::new("T-003", "Write unit tests for auth module", "...");
        let tools = vec![AgentType::Claude, AgentType::Codex, AgentType::Gemini];
        let result = brain.assign_task(&task, &tools).unwrap();
        assert_eq!(result, AgentType::Gemini);
    }

    #[test]
    fn test_assign_docs_to_gemini() {
        let brain = RuleBasedBrain;
        let task = Task::new("T-004", "API documentation update", "Update the API docs");
        let tools = vec![AgentType::Claude, AgentType::Codex, AgentType::Gemini];
        let result = brain.assign_task(&task, &tools).unwrap();
        assert_eq!(result, AgentType::Gemini);
    }

    #[test]
    fn test_fallback_round_robin() {
        let brain = RuleBasedBrain;
        // "Setup" doesn't match any keyword heuristic — falls through to round-robin
        let task1 = Task::new("T-003", "Setup environment", "Configure dev setup");
        let task2 = Task::new("T-004", "Setup environment", "Configure dev setup");
        let tools = vec![AgentType::Claude, AgentType::Codex, AgentType::Gemini];
        let r1 = brain.assign_task(&task1, &tools).unwrap(); // 3 % 3 = 0 → Claude
        let r2 = brain.assign_task(&task2, &tools).unwrap(); // 4 % 3 = 1 → Codex
        assert_eq!(r1, AgentType::Claude);
        assert_eq!(r2, AgentType::Codex);
    }

    #[test]
    fn test_decompose_plan_from_headers() {
        let brain = RuleBasedBrain;
        let spec = "# My Project\n## Authentication\n## Database\n## API endpoints\n";
        let tasks = brain.decompose_plan(spec, &[AgentType::Claude], 1).unwrap();
        assert_eq!(tasks.len(), 3);
        assert_eq!(tasks[0].title, "Authentication");
        assert_eq!(tasks[1].title, "Database");
    }

    #[test]
    fn test_decompose_plan_with_start_id_offset() {
        let brain = RuleBasedBrain;
        let spec = "## Caching\n## Monitoring\n";
        let tasks = brain.decompose_plan(spec, &[AgentType::Claude], 5).unwrap();
        assert_eq!(tasks.len(), 2);
        assert_eq!(tasks[0].id, "T-005");
        assert_eq!(tasks[1].id, "T-006");
    }

    #[test]
    fn test_decompose_plan_fallback_uses_start_id() {
        let brain = RuleBasedBrain;
        // No ## headers → single fallback task
        let spec = "Just a plain spec with no headers.";
        let tasks = brain
            .decompose_plan(spec, &[AgentType::Claude], 10)
            .unwrap();
        assert_eq!(tasks.len(), 1);
        assert_eq!(tasks[0].id, "T-010");
    }

    #[test]
    fn test_is_user_facing_positive() {
        assert!(is_user_facing(
            "Add dashboard sidebar",
            "Create navigation component"
        ));
        assert!(is_user_facing("Fix button styles", "Update CSS"));
        assert!(is_user_facing(
            "Terminal improvements",
            "Improve terminal output"
        ));
        assert!(is_user_facing("Create login form", "Authentication form"));
        assert!(is_user_facing(
            "Layout restructure",
            "Update the page layout"
        ));
    }

    #[test]
    fn test_is_user_facing_negative() {
        // Only clearly internal/infra tasks are non-user-facing
        assert!(!is_user_facing(
            "Refactor auth module",
            "Clean up internal code"
        ));
        assert!(!is_user_facing("Update CI pipeline", "Fix GitHub Actions"));
        assert!(!is_user_facing(
            "Dockerfile optimization",
            "Reduce image size"
        ));
        assert!(!is_user_facing(
            "Dependency upgrade",
            "Bump all packages to latest"
        ));
        assert!(!is_user_facing(
            "Database migration",
            "Add new schema columns"
        ));
    }

    #[test]
    fn test_is_user_facing_games_and_features() {
        // The old heuristic missed entire categories. Games, CLIs, APIs
        // are all user-facing and must get UAT tasks.
        assert!(is_user_facing(
            "Design High Score Feature",
            "Add high score tracking"
        ));
        assert!(is_user_facing(
            "Implement Combo Multiplier",
            "Combo system for scoring"
        ));
        assert!(is_user_facing(
            "Add caching layer",
            "Redis integration for faster responses"
        ));
        assert!(is_user_facing(
            "Optimize database queries",
            "Improve SQL performance"
        ));
    }

    #[test]
    fn test_uat_criteria_skips_technical() {
        let criteria = generate_uat_criteria(
            "Add navigation menu",
            &[
                "Menu items are visible".to_string(),
                "All tests pass".to_string(), // technical → skip
                "Code compiles without errors".to_string(), // technical → skip
                "Links work correctly".to_string(),
            ],
        );

        // Should have: "Can reach target in 3 clicks" + "Verify: Menu items are visible" + "Verify: Links work correctly"
        assert!(criteria.iter().any(|c| c.contains("3 clicks")));
        assert!(criteria.iter().any(|c| c.starts_with("Verify: Menu items")));
        assert!(criteria.iter().any(|c| c.starts_with("Verify: Links work")));
        // Should NOT have technical criteria
        assert!(!criteria.iter().any(|c| c.contains("tests pass")));
        assert!(!criteria.iter().any(|c| c.contains("compiles")));
    }
}