forge-orchestrator 1.6.3

Orchestrate Claude Code, Codex CLI, and Gemini CLI on shared repos — single Rust binary, zero deps.
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
use super::ToolAdapter;
use crate::core::state::ForgeState;
use crate::core::task::Task;
use regex::Regex;
use std::path::Path;
use std::process::Command;
use std::sync::LazyLock;

pub struct ClaudeAdapter;

// --- Round-7 EXACT statusline patterns (FPL ruling: the regex IS the spec, no predicate latitude).
// A Claude reading requires ALL THREE to match on one captured line. Compiled once.

/// (1) Versioned model-token bracket, matched against a WHOLE `[...]` token: model words, then a
/// SPACE, then a version number, optional `:effort`. The space before the version digits makes the
/// digit a SEPARATE version token — so `[Opus 4.8:high]` and `[Fable 5]` match while `[worker5]`
/// (digit glued onto letters) does not.
///
/// FPL's round-7 regex text was `^\[[A-Za-z][A-Za-z ]*[0-9]+…` (no space), which — traced — DOES
/// match `[worker5]`; the accompanying ruling ("the digit must be a SEPARATE version token preceded
/// by space — enforce the space before the digit… rejects [worker5]") requires the space, so the
/// literal ` ` is present before `[0-9]+`. This is the one deviation from the typed regex, made to
/// satisfy FPL's own `[worker5]` → n/a control; flagged on re-signal.
static VERSIONED_MODEL: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^\[[A-Za-z][A-Za-z ]* [0-9]+(\.[0-9]+)?(:(low|medium|high|xhigh|max))?\]$")
        .unwrap()
});

/// (2) Sibling rate-limit gauge — `5h:NN%` or `7d:NN%`. The `%` is MANDATORY, so `5h:3` fails.
/// Verbatim from the ruling.
static SIBLING_GAUGE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(^|\s)(5h|7d):[0-9]{1,3}%(\(|\s|$)").unwrap());

/// (3) The `ctx:NN%` gauge itself. Verbatim from the ruling.
static CTX_GAUGE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(^|\s)ctx:[0-9]{1,3}%").unwrap());

impl ToolAdapter for ClaudeAdapter {
    fn name(&self) -> &str {
        "claude"
    }

    /// Extract Claude's `ctx:NN%` (context USED) only when a line matches ALL THREE round-7 exact
    /// patterns: [`CTX_GAUGE`] AND [`SIBLING_GAUGE`] AND a whole bracket matching [`VERSIONED_MODEL`].
    /// The `5h:`/`7d:` and versioned-token requirements are the co-occurring redundancy only a real
    /// statusline satisfies, so `[worker5] ctx:42% 5h:3` (no `%` on the sibling gauge, digit glued to
    /// the bracket word), `[INFO] [priority:high] ctx:42%` and `[INFO] [12:30] ctx:42%` are all n/a
    /// BY CONSTRUCTION. Value read via `pct_after` after `ctx:` (the gauge regex guarantees it).
    fn parse_ctx_pct(&self, statusline: &str) -> Option<u8> {
        for line in statusline.lines() {
            let lower = line.to_lowercase();
            // (3) ctx gauge AND (2) sibling gauge, on the lowercased line.
            if !CTX_GAUGE.is_match(&lower) || !SIBLING_GAUGE.is_match(&lower) {
                continue;
            }
            // (1) at least one WHOLE bracket is a versioned model token (original case, for [A-Za-z]).
            let has_versioned_model = super::bracket_contents(line)
                .iter()
                .any(|c| VERSIONED_MODEL.is_match(&format!("[{c}]")));
            if has_versioned_model {
                return super::pct_after(&lower, "ctx:");
            }
        }
        None
    }

    fn render_config(
        &self,
        state: &ForgeState,
        tasks: &[Task],
        project_root: &Path,
    ) -> anyhow::Result<()> {
        let assigned_tasks: Vec<&Task> = tasks
            .iter()
            .filter(|t| {
                t.assigned_to
                    .as_ref()
                    .is_some_and(|a| *a == crate::core::task::AgentType::Claude)
            })
            .collect();

        let mut content = String::new();
        content.push_str("# CLAUDE.md (Auto-generated by Forge Orchestrator)\n\n");
        content.push_str(&format!("**Project:** {}\n", state.project_name));
        content.push_str(&format!(
            "**Last updated:** {}\n\n",
            state.updated_at.format("%Y-%m-%d %H:%M UTC")
        ));
        content.push_str("---\n\n");

        // Current task assignments
        if assigned_tasks.is_empty() {
            content.push_str("## Status\n\nNo tasks currently assigned to Claude.\n\n");
        } else {
            content.push_str("## Assigned Tasks\n\n");
            for task in &assigned_tasks {
                content.push_str(&format!(
                    "### {}: {}\n\n{}\n\n",
                    task.id, task.title, task.description
                ));
                if !task.acceptance_criteria.is_empty() {
                    content.push_str("**Acceptance Criteria:**\n");
                    for criterion in &task.acceptance_criteria {
                        content.push_str(&format!("- [ ] {criterion}\n"));
                    }
                    content.push('\n');
                }
                if !task.locked_files.is_empty() {
                    content.push_str("**Files you may modify:**\n");
                    for file in &task.locked_files {
                        content.push_str(&format!("- `{file}`\n"));
                    }
                    content.push('\n');
                }
            }
        }

        // Governance rules
        content.push_str("## Governance\n\n");
        content.push_str("- Report task completion via MCP: `forge_complete_task()`\n");
        content.push_str("- Do NOT modify files outside your locked file list\n");
        content.push_str("- Run tests before marking task complete\n");
        content.push_str("- Check `.forge/state.json` for current orchestration state\n\n");

        let claude_md_path = project_root.join("CLAUDE.md");
        std::fs::write(claude_md_path, content)?;
        Ok(())
    }

    fn build_command(
        &self,
        task: &Task,
        project_root: &Path,
        auth_mode: &str,
        permissions: &str,
    ) -> Command {
        let task_type = task.task_type.as_deref().unwrap_or("");

        // Build task-type-aware prompt
        let prompt = build_prompt(task, task_type);

        let mut cmd = Command::new("claude");
        cmd.args(["-p", &prompt, "--output-format", "stream-json", "--verbose"])
            .current_dir(project_root);

        // Smart permissions: scoped --allowedTools instead of blunt --dangerously-skip-permissions
        if permissions == "yolo" {
            match task_type {
                "implement" => {
                    cmd.args(["--allowedTools", "Write,Edit,Read,Glob,Grep,Bash"]);
                }
                "review" | "test" | "verify" => {
                    cmd.args(["--allowedTools", "Read,Glob,Grep,Bash"]);
                }
                "document" => {
                    cmd.args(["--allowedTools", "Write,Edit,Read,Glob,Grep"]);
                }
                // design + unknown: full autonomy (may need any tool)
                _ => {
                    cmd.args(["--dangerously-skip-permissions"]);
                }
            }
        }

        // Task-type-aware turn limits
        match task_type {
            "review" | "test" | "verify" => {
                cmd.args(["--max-turns", "20"]);
            }
            "design" => {
                cmd.args(["--max-turns", "30"]);
            }
            _ => {}
        }

        if auth_mode == "subscription" {
            cmd.env_remove("ANTHROPIC_API_KEY");
        }

        cmd
    }

    /// Interactive PTY mode: launch `claude` (full TUI) instead of `claude -p`.
    /// The prompt is typed into the TUI via initial_input() after startup.
    fn build_command_interactive(
        &self,
        _task: &Task,
        project_root: &Path,
        auth_mode: &str,
        _permissions: &str,
    ) -> Command {
        let mut cmd = Command::new("claude");
        // No -p flag — launches full interactive TUI
        // No --output-format, no --verbose
        // Always skip permissions in dashboard PTY mode — agents need full autonomy
        // to execute tasks without blocking on permission prompts
        cmd.arg("--dangerously-skip-permissions");
        cmd.current_dir(project_root);

        if auth_mode == "subscription" {
            cmd.env_remove("ANTHROPIC_API_KEY");
        }

        cmd
    }

    /// Provide the task prompt to be typed into the Claude TUI after it initializes.
    /// Newlines are flattened to spaces — raw \n in a PTY can trigger premature
    /// submission or put Claude's TUI into multi-line mode where \r adds a line
    /// instead of submitting.
    fn initial_input(&self, task: &Task) -> Option<String> {
        let task_type = task.task_type.as_deref().unwrap_or("");
        let prompt = build_prompt(task, task_type).replace('\n', " ");
        // \r = Enter to submit the prompt
        Some(format!("{}\r", prompt))
    }

    /// Claude Code TUI shows "shift+tab to cycle" in the permission indicator
    /// at the bottom when ready for input.
    fn ready_pattern(&self) -> Option<&str> {
        Some("to cycle")
    }
}

/// Build a task-type-aware prompt for Claude.
/// Exposed for testing via `pub(crate)`.
pub(crate) fn build_prompt(task: &Task, task_type: &str) -> String {
    let criteria = if task.acceptance_criteria.is_empty() {
        String::new()
    } else {
        format!(
            "Acceptance criteria:\n{}\n\n",
            task.acceptance_criteria
                .iter()
                .map(|c| format!("- {c}"))
                .collect::<Vec<_>>()
                .join("\n")
        )
    };

    let files = if task.locked_files.is_empty() {
        String::new()
    } else {
        format!(
            "Files in scope:\n{}\n\n",
            task.locked_files
                .iter()
                .map(|f| format!("- {f}"))
                .collect::<Vec<_>>()
                .join("\n")
        )
    };

    match task_type {
        "design" => format!(
            "You are working on task {id}: {title}\n\n\
             This is a DESIGN task. Focus on architecture and system design.\n\n\
             Description: {desc}\n\n\
             {criteria}{files}\
             Think through the design carefully. Consider trade-offs, edge cases, \
             and how this fits into the broader system. Produce clear, actionable \
             design documents or code structures.\n\n\
             When done, summarize your design decisions and rationale.",
            id = task.id,
            title = task.title,
            desc = task.description,
        ),
        "review" => format!(
            "You are working on task {id}: {title}\n\n\
             This is a REVIEW task. Analyze the code without making changes.\n\n\
             Description: {desc}\n\n\
             {criteria}{files}\
             Read the relevant code, identify issues, and provide a clear \
             assessment. Do NOT modify files — this is a read-only review.\n\n\
             When done, summarize your findings.",
            id = task.id,
            title = task.title,
            desc = task.description,
        ),
        "verify" => format!(
            "You are working on task {id}: {title}\n\n\
             This is a VERIFICATION task. You must ACTIVELY TEST the code, not just read it.\n\n\
             Description: {desc}\n\n\
             {criteria}{files}\
             Required verification steps:\n\
             1. Run the project's test suite (e.g. `npm test`, `pytest`, `cargo test`)\n\
             2. Run the type checker (e.g. `tsc --noEmit`, `mypy`, `cargo clippy`)\n\
             3. Check that all new/modified files have corresponding test files\n\
             4. Verify test mocks match production code shapes (interceptors, constructors, etc.)\n\
             5. Run the linter (e.g. `eslint`, `ruff`, `cargo fmt --check`)\n\
             6. If this task touches auth/routing/middleware, also run E2E tests\n\
             7. If Playwright/E2E tests exist, run them and check for browser console errors:\n\
                - Use `page.on('console', ...)` and `page.on('pageerror', ...)` to capture errors\n\
                - Zero uncaught exceptions and pageerrors = pass\n\n\
             Report your findings: what passed, what failed, what's missing.\n\
             If tests fail or coverage is missing, report the specific failures.",
            id = task.id,
            title = task.title,
            desc = task.description,
        ),
        "test" => format!(
            "You are working on task {id}: {title}\n\n\
             This is a TESTING task. Focus on test coverage and quality.\n\n\
             Description: {desc}\n\n\
             {criteria}{files}\
             Write thorough tests with edge cases. Run existing tests to verify \
             nothing breaks.\n\n\
             When done, summarize what tests you added and their results.",
            id = task.id,
            title = task.title,
            desc = task.description,
        ),
        "document" => format!(
            "You are working on task {id}: {title}\n\n\
             This is a DOCUMENTATION task. Focus on clarity and completeness.\n\n\
             Description: {desc}\n\n\
             {criteria}{files}\
             Write clear, accurate documentation. Include examples where helpful.\n\n\
             When done, summarize what you documented.",
            id = task.id,
            title = task.title,
            desc = task.description,
        ),
        _ => format!(
            "You are working on task {id}: {title}\n\n\
             Description: {desc}\n\n\
             {criteria}{files}\
             IMPORTANT: Before marking this task complete:\n\
             - Write unit tests for any new files you create\n\
             - Run the existing test suite to verify nothing breaks\n\
             - Run the type checker if the project has one\n\
             - If you modify a file that has a corresponding .test file, update the test mocks\n\n\
             Complete this task. When done, summarize what you did.",
            id = task.id,
            title = task.title,
            desc = task.description,
        ),
    }
}

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

    fn make_task(task_type: &str) -> Task {
        let mut task = Task::new("T-001", "Add login form", "Implement the login UI");
        task.task_type = Some(task_type.to_string());
        task.acceptance_criteria = vec!["Form validates email".to_string()];
        task.locked_files = vec!["src/login.rs".to_string()];
        task
    }

    #[test]
    fn test_verify_prompt_contains_verification_task() {
        let task = make_task("verify");
        let prompt = build_prompt(&task, "verify");
        assert!(
            prompt.contains("VERIFICATION task"),
            "verify prompt must contain 'VERIFICATION task'"
        );
    }

    #[test]
    fn test_verify_prompt_contains_test_suite_instruction() {
        let task = make_task("verify");
        let prompt = build_prompt(&task, "verify");
        assert!(
            prompt.contains("Run the project's test suite"),
            "verify prompt must instruct running the test suite"
        );
    }

    #[test]
    fn test_verify_prompt_contains_actively_test() {
        let task = make_task("verify");
        let prompt = build_prompt(&task, "verify");
        assert!(
            prompt.contains("ACTIVELY TEST"),
            "verify prompt must say ACTIVELY TEST"
        );
    }

    #[test]
    fn test_implement_prompt_contains_write_unit_tests() {
        let task = make_task("implement");
        let prompt = build_prompt(&task, "implement");
        assert!(
            prompt.contains("Write unit tests"),
            "implement/default prompt must contain 'Write unit tests'"
        );
    }

    #[test]
    fn test_implement_prompt_contains_run_test_suite() {
        let task = make_task("implement");
        let prompt = build_prompt(&task, "implement");
        assert!(
            prompt.contains("Run the existing test suite"),
            "implement/default prompt must instruct running tests"
        );
    }

    #[test]
    fn test_default_prompt_works_for_unknown_type() {
        let task = make_task("something_unknown");
        let prompt = build_prompt(&task, "something_unknown");
        assert!(prompt.contains("T-001"));
        assert!(prompt.contains("Add login form"));
        assert!(prompt.contains("Write unit tests"));
    }

    #[test]
    fn test_review_prompt_unchanged() {
        let task = make_task("review");
        let prompt = build_prompt(&task, "review");
        assert!(
            prompt.contains("REVIEW task"),
            "review prompt must still say REVIEW task"
        );
        assert!(
            prompt.contains("Do NOT modify files"),
            "review prompt must still be read-only"
        );
        assert!(
            !prompt.contains("VERIFICATION"),
            "review prompt must NOT contain VERIFICATION"
        );
    }

    #[test]
    fn test_verify_prompt_includes_criteria_and_files() {
        let task = make_task("verify");
        let prompt = build_prompt(&task, "verify");
        assert!(
            prompt.contains("Form validates email"),
            "verify prompt must include acceptance criteria"
        );
        assert!(
            prompt.contains("src/login.rs"),
            "verify prompt must include locked files"
        );
    }

    #[test]
    fn test_design_prompt_unchanged() {
        let task = make_task("design");
        let prompt = build_prompt(&task, "design");
        assert!(prompt.contains("DESIGN task"));
        assert!(!prompt.contains("VERIFICATION"));
    }
}