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
use super::ToolAdapter;
use crate::core::state::ForgeState;
use crate::core::task::{AgentType, Task};
use std::path::Path;
use std::process::Command;

/// Adapter for the Antigravity CLI (`agy`) — Google's AI coding agent,
/// successor to the retired Gemini CLI (which returns IneligibleTierError).
/// Headless: `agy --print "<prompt>"`, PTY unattended: `agy --dangerously-skip-permissions`
/// Ready pattern "? for shortcuts" disappears to "esc to cancel" during generation
/// and reappears on completion — verified empirically via tmux PTY capture 2026-08-08.
pub struct GeminiAdapter;

impl ToolAdapter for GeminiAdapter {
    fn name(&self) -> &str {
        "antigravity"
    }

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

        // agy does not auto-load any project markdown file; ANTIGRAVITY.md is for documentation.
        let mut content = String::new();
        content.push_str("# ANTIGRAVITY.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("**Agent:** Antigravity CLI (`agy`) — Gemini 3.1 Pro (High)\n\n");
        content.push_str("---\n\n");

        if assigned.is_empty() {
            content.push_str("## Status\n\nNo tasks currently assigned to Antigravity.\n\n");
        } else {
            content.push_str("## Assigned Tasks\n\n");
            for task in &assigned {
                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 c in &task.acceptance_criteria {
                        content.push_str(&format!("- [ ] {c}\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');
                }
            }
        }

        content.push_str("## Guidelines\n\n");
        content.push_str("- Complete tasks one at a time\n");
        content.push_str("- Do NOT modify files outside your assigned task scope\n");
        content.push_str("- Run tests before marking a task complete\n");
        content.push_str("- Check `.forge/state.json` for current orchestration state\n");

        std::fs::write(project_root.join("ANTIGRAVITY.md"), content)?;

        // Pre-register this directory as a trusted workspace so agy's PTY session
        // doesn't block on the folder-trust dialog (--dangerously-skip-permissions
        // does NOT bypass the trust prompt; trustedWorkspaces must be set first).
        let home = std::env::var("HOME").unwrap_or_else(|_| "/root".to_string());
        let settings_path = Path::new(&home)
            .join(".gemini")
            .join("antigravity-cli")
            .join("settings.json");
        add_trusted_workspace(&settings_path, project_root)?;

        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("");
        let prompt = build_gemini_prompt(task, task_type);

        let mut cmd = Command::new("agy");
        // --print = non-interactive (headless) mode — REQUIRED for orchestrated execution
        cmd.args(["--print", &prompt]);
        if permissions == "yolo" {
            // --dangerously-skip-permissions auto-approves all tool calls
            cmd.arg("--dangerously-skip-permissions");
        }
        cmd.current_dir(project_root);

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

        cmd
    }

    /// PTY mode: launch `agy` full TUI. The prompt is typed in 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("agy");
        // Always auto-approve in dashboard PTY — agents cannot wait for approval prompts.
        // (Mirrors Claude's --dangerously-skip-permissions and Codex's --full-auto.)
        cmd.arg("--dangerously-skip-permissions");
        cmd.current_dir(project_root);

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

        cmd
    }

    fn initial_input(&self, task: &Task) -> Option<String> {
        let task_type = task.task_type.as_deref().unwrap_or("");
        let prompt = build_gemini_prompt(task, task_type).replace('\n', " ");
        // \r = Enter to submit the prompt
        Some(format!("{}\r", prompt))
    }

    /// agy shows "? for shortcuts" when idle/ready; switches to "esc to cancel" while generating.
    /// Forge's disappear→reappear heuristic uses this for PTY completion detection.
    fn ready_pattern(&self) -> Option<&str> {
        Some("? for shortcuts")
    }
}

/// Add `workspace` to agy's trusted workspaces at `settings_path`.
/// Exposed as pub(crate) so tests can inject a tempdir path instead of ~/.gemini/...
pub(crate) fn add_trusted_workspace(settings_path: &Path, workspace: &Path) -> anyhow::Result<()> {
    let content = if settings_path.exists() {
        std::fs::read_to_string(settings_path)?
    } else {
        "{}".to_string()
    };

    let mut settings: serde_json::Value =
        serde_json::from_str(&content).unwrap_or(serde_json::Value::Object(Default::default()));

    let workspace_str = workspace.to_string_lossy().into_owned();

    let already_trusted = settings["trustedWorkspaces"]
        .as_array()
        .is_some_and(|arr| arr.iter().any(|v| v.as_str() == Some(&workspace_str)));

    if !already_trusted {
        match settings["trustedWorkspaces"].as_array_mut() {
            Some(arr) => arr.push(serde_json::Value::String(workspace_str)),
            None => {
                settings["trustedWorkspaces"] = serde_json::json!([workspace_str]);
            }
        }
        if let Some(parent) = settings_path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(settings_path, serde_json::to_string_pretty(&settings)?)?;
    }

    Ok(())
}

/// Build a task-type-aware prompt for the Antigravity (agy) agent.
pub(crate) fn build_gemini_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")
        )
    };

    match task_type {
        "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}\
             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\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,
        ),
        "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}\
             Do NOT modify files — this is a read-only review.\n\
             When done, summarize your findings.",
            id = task.id,
            title = task.title,
            desc = task.description,
        ),
        _ => format!(
            "Complete task {id}: {title}\n\nDescription: {desc}\n\n\
             {criteria}\
             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\
             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
    }

    // ── existing prompt tests (unchanged) ──────────────────────────────────

    #[test]
    fn test_gemini_verify_prompt() {
        let task = make_task("verify");
        let prompt = build_gemini_prompt(&task, "verify");
        assert!(prompt.contains("VERIFICATION task"));
        assert!(prompt.contains("ACTIVELY TEST"));
        assert!(prompt.contains("Run the project's test suite"));
    }

    #[test]
    fn test_gemini_implement_prompt_has_test_requirement() {
        let task = make_task("implement");
        let prompt = build_gemini_prompt(&task, "implement");
        assert!(prompt.contains("Write unit tests"));
        assert!(prompt.contains("Run the existing test suite"));
    }

    #[test]
    fn test_gemini_review_prompt_is_readonly() {
        let task = make_task("review");
        let prompt = build_gemini_prompt(&task, "review");
        assert!(prompt.contains("REVIEW task"));
        assert!(prompt.contains("Do NOT modify files"));
    }

    #[test]
    fn test_gemini_default_prompt() {
        let task = make_task("something");
        let prompt = build_gemini_prompt(&task, "something");
        assert!(prompt.contains("T-001"));
        assert!(prompt.contains("Write unit tests"));
    }

    // ── adapter identity ───────────────────────────────────────────────────

    #[test]
    fn test_antigravity_name() {
        assert_eq!(GeminiAdapter.name(), "antigravity");
    }

    // ── headless command contract ──────────────────────────────────────────

    #[test]
    fn test_antigravity_headless_command_uses_agy() {
        let task = make_task("implement");
        let project = std::path::PathBuf::from("/tmp/test-project");
        let cmd = GeminiAdapter.build_command(&task, &project, "api", "normal");
        let prog = format!("{:?}", cmd.get_program());
        assert!(
            prog.contains("agy"),
            "headless command must use agy binary, got: {prog}"
        );
    }

    #[test]
    fn test_antigravity_headless_command_uses_print_flag() {
        let task = make_task("implement");
        let project = std::path::PathBuf::from("/tmp/test-project");
        let cmd = GeminiAdapter.build_command(&task, &project, "api", "normal");
        let args: Vec<_> = cmd
            .get_args()
            .map(|a| a.to_string_lossy().into_owned())
            .collect();
        assert!(
            args.iter().any(|a| a == "--print"),
            "headless command must use --print flag, got: {:?}",
            args
        );
    }

    #[test]
    fn test_antigravity_headless_normal_has_no_skip_permissions() {
        let task = make_task("implement");
        let project = std::path::PathBuf::from("/tmp/test-project");
        let cmd = GeminiAdapter.build_command(&task, &project, "api", "normal");
        let args: Vec<_> = cmd
            .get_args()
            .map(|a| a.to_string_lossy().into_owned())
            .collect();
        assert!(
            !args.iter().any(|a| a == "--dangerously-skip-permissions"),
            "normal permissions must NOT add --dangerously-skip-permissions, got: {:?}",
            args
        );
    }

    #[test]
    fn test_antigravity_headless_yolo_adds_skip_permissions() {
        let task = make_task("implement");
        let project = std::path::PathBuf::from("/tmp/test-project");
        let cmd = GeminiAdapter.build_command(&task, &project, "api", "yolo");
        let args: Vec<_> = cmd
            .get_args()
            .map(|a| a.to_string_lossy().into_owned())
            .collect();
        assert!(
            args.iter().any(|a| a == "--dangerously-skip-permissions"),
            "yolo mode must add --dangerously-skip-permissions, got: {:?}",
            args
        );
    }

    #[test]
    fn test_antigravity_headless_not_legacy_gemini_binary() {
        let task = make_task("implement");
        let project = std::path::PathBuf::from("/tmp/test-project");
        let cmd = GeminiAdapter.build_command(&task, &project, "api", "normal");
        let prog = format!("{:?}", cmd.get_program());
        assert!(
            !prog.contains("gemini"),
            "must NOT use retired gemini binary — use agy, got: {prog}"
        );
    }

    // ── PTY command contract (Stargate) ────────────────────────────────────

    #[test]
    fn test_antigravity_pty_command_uses_agy() {
        let task = make_task("implement");
        let project = std::path::PathBuf::from("/tmp/test-project");
        let cmd = GeminiAdapter.build_command_interactive(&task, &project, "api", "normal");
        let prog = format!("{:?}", cmd.get_program());
        assert!(
            prog.contains("agy"),
            "PTY command must use agy binary, got: {prog}"
        );
    }

    #[test]
    fn test_antigravity_pty_always_skip_permissions() {
        let task = make_task("implement");
        let project = std::path::PathBuf::from("/tmp/test-project");
        let cmd = GeminiAdapter.build_command_interactive(&task, &project, "api", "normal");
        let args: Vec<_> = cmd
            .get_args()
            .map(|a| a.to_string_lossy().into_owned())
            .collect();
        assert!(
            args.iter().any(|a| a == "--dangerously-skip-permissions"),
            "PTY must always include --dangerously-skip-permissions (Stargate contract), got: {:?}",
            args
        );
    }

    // ── ready_pattern contract ─────────────────────────────────────────────

    #[test]
    fn test_antigravity_ready_pattern_is_shortcuts_hint() {
        // "? for shortcuts" empirically verified via tmux PTY capture 2026-08-08:
        // disappears to "esc to cancel" during generation, reappears on completion.
        assert_eq!(GeminiAdapter.ready_pattern(), Some("? for shortcuts"));
    }

    #[test]
    fn test_antigravity_ready_pattern_not_legacy_gemini() {
        assert_ne!(
            GeminiAdapter.ready_pattern(),
            Some("Type your message"),
            "must not use retired Gemini CLI ready pattern"
        );
    }

    // ── trustedWorkspaces setup ────────────────────────────────────────────

    #[test]
    fn test_trusted_workspace_creates_entry() {
        let dir = tempfile::tempdir().unwrap();
        let settings_path = dir.path().join("settings.json");
        let workspace = std::path::PathBuf::from("/tmp/test-workspace");

        add_trusted_workspace(&settings_path, &workspace).unwrap();

        let content = std::fs::read_to_string(&settings_path).unwrap();
        let settings: serde_json::Value = serde_json::from_str(&content).unwrap();
        let trusted = settings["trustedWorkspaces"].as_array().unwrap();
        assert!(
            trusted
                .iter()
                .any(|v| v.as_str() == Some("/tmp/test-workspace")),
            "workspace must appear in trustedWorkspaces"
        );
    }

    #[test]
    fn test_trusted_workspace_idempotent() {
        let dir = tempfile::tempdir().unwrap();
        let settings_path = dir.path().join("settings.json");
        let workspace = std::path::PathBuf::from("/tmp/test-workspace");

        add_trusted_workspace(&settings_path, &workspace).unwrap();
        add_trusted_workspace(&settings_path, &workspace).unwrap();

        let content = std::fs::read_to_string(&settings_path).unwrap();
        let settings: serde_json::Value = serde_json::from_str(&content).unwrap();
        let trusted = settings["trustedWorkspaces"].as_array().unwrap();
        let count = trusted
            .iter()
            .filter(|v| v.as_str() == Some("/tmp/test-workspace"))
            .count();
        assert_eq!(count, 1, "duplicate entries must not be added");
    }

    #[test]
    fn test_trusted_workspace_preserves_existing_entries() {
        let dir = tempfile::tempdir().unwrap();
        let settings_path = dir.path().join("settings.json");

        // Seed with an existing workspace
        let initial = serde_json::json!({ "trustedWorkspaces": ["/existing/path"] });
        std::fs::write(&settings_path, serde_json::to_string(&initial).unwrap()).unwrap();

        let workspace = std::path::PathBuf::from("/tmp/new-workspace");
        add_trusted_workspace(&settings_path, &workspace).unwrap();

        let content = std::fs::read_to_string(&settings_path).unwrap();
        let settings: serde_json::Value = serde_json::from_str(&content).unwrap();
        let trusted = settings["trustedWorkspaces"].as_array().unwrap();
        assert!(
            trusted.iter().any(|v| v.as_str() == Some("/existing/path")),
            "existing entry must be preserved"
        );
        assert!(
            trusted
                .iter()
                .any(|v| v.as_str() == Some("/tmp/new-workspace")),
            "new entry must be added"
        );
    }
}