githubclaw 0.2.2

Near-autonomous AI agents that manage open-source projects end-to-end using GitHub as the single source of truth.
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
//! Agent CLI spawner.
//!
//! Builds the environment variables and command-line arguments needed to launch
//! an agent subprocess (e.g. `claude-code` or `codex`) with the correct
//! prompt, tool permissions, and git identity.

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use crate::agents::parser::AgentDefinition;

/// Embedded gh wrapper script (compiled into the binary).
const GH_WRAPPER_SCRIPT: &str = include_str!("../../scripts/gh");

/// Spawns agent subprocesses with the correct environment and CLI flags.
pub struct AgentSpawner {
    repo_root: PathBuf,
    max_turns: u32,
}

impl AgentSpawner {
    /// Create a new spawner rooted at `repo_root` with the given turn limit.
    pub fn new(repo_root: impl AsRef<Path>, max_turns: u32) -> Self {
        Self {
            repo_root: repo_root.as_ref().to_path_buf(),
            max_turns,
        }
    }

    /// Locate an optional spawn script for the given backend.
    ///
    /// Looks for `.githubclaw/spawn_claude.sh` or `.githubclaw/spawn_codex.sh`
    /// under the repo root, matching the spec and the Python implementation.
    /// Returns `None` if the script does not exist.
    fn get_spawn_script(&self, backend: &str) -> Option<PathBuf> {
        let script_name = match backend {
            "claude-code" => "spawn_claude.sh",
            "codex" => "spawn_codex.sh",
            _ => return None,
        };
        let script = self.repo_root.join(".githubclaw").join(script_name);
        if script.exists() {
            Some(script)
        } else {
            None
        }
    }

    /// Build the full set of environment variables for an agent subprocess.
    ///
    /// Sets git identity, tool permissions, prompt/task info, GithubClaw
    /// metadata, root issue tracking, and gh wrapper PATH injection.
    /// Optionally merges caller-supplied `extra_env`.
    pub fn build_env(
        &self,
        agent_def: &AgentDefinition,
        prompt_file: &Path,
        task_prompt: &str,
        extra_env: Option<&HashMap<String, String>>,
    ) -> HashMap<String, String> {
        let mut env = HashMap::new();
        let prompt_text = std::fs::read_to_string(prompt_file).unwrap_or_default();

        // Git identity
        env.insert("GIT_AUTHOR_NAME".into(), agent_def.git_author_name.clone());
        env.insert(
            "GIT_AUTHOR_EMAIL".into(),
            agent_def.git_author_email.clone(),
        );
        env.insert(
            "GIT_COMMITTER_NAME".into(),
            agent_def.git_author_name.clone(),
        );
        env.insert(
            "GIT_COMMITTER_EMAIL".into(),
            agent_def.git_author_email.clone(),
        );

        // Tool permissions
        let tools = agent_def.active_tools();
        env.insert("ALLOWED_TOOLS".into(), tools.allowed.join(","));
        env.insert("DISALLOWED_TOOLS".into(), tools.disallowed.join(","));

        // Prompt and task
        env.insert(
            "PROMPT_FILE".into(),
            prompt_file.to_string_lossy().into_owned(),
        );
        env.insert("SYSTEM_PROMPT".into(), prompt_text.clone());
        env.insert("TASK_CONTEXT".into(), task_prompt.to_string());
        let task_prompt_value = if agent_def.backend == "codex" {
            prompt_text
        } else {
            task_prompt.to_string()
        };
        env.insert("TASK_PROMPT".into(), task_prompt_value);
        env.insert("MAX_TURNS".into(), self.max_turns.to_string());

        // GithubClaw metadata
        env.insert("GITHUBCLAW_AGENT_TYPE".into(), agent_def.name.clone());
        env.insert("GITHUBCLAW_BACKEND".into(), agent_def.backend.clone());
        env.insert(
            "GITHUBCLAW_REPO_ROOT".into(),
            self.repo_root.to_string_lossy().into_owned(),
        );

        // Root issue tracking for ref #N injection
        // GITHUBCLAW_ROOT_ISSUE is injected by the caller via extra_env

        // gh wrapper PATH injection
        // Prepend the scripts/ directory (containing gh renamed to gh)
        // to PATH so all gh CLI calls go through our wrapper.
        if let Some(wrapper_dir) = self.gh_wrapper_dir() {
            let current_path = std::env::var("PATH").unwrap_or_default();
            env.insert(
                "PATH".into(),
                format!("{}:{}", wrapper_dir.display(), current_path),
            );
            // Tell the wrapper where the real gh binary is
            if let Ok(real_gh) = which::which("gh") {
                env.insert(
                    "GITHUBCLAW_REAL_GH".into(),
                    real_gh.to_string_lossy().into_owned(),
                );
            }
        }

        // Merge extra env (caller overrides take precedence)
        if let Some(extra) = extra_env {
            for (k, v) in extra {
                env.insert(k.clone(), v.clone());
            }
        }

        env
    }

    /// Get or create the gh wrapper directory.
    ///
    /// Extracts the embedded gh wrapper script to a stable temp directory
    /// so it's always available regardless of where the binary is installed.
    /// The wrapper is placed at `~/.githubclaw/bin/gh`.
    fn gh_wrapper_dir(&self) -> Option<PathBuf> {
        let wrapper_dir = crate::config::global_config_dir().join("bin");
        let wrapper_path = wrapper_dir.join("gh");

        // Only write if missing or outdated
        if !wrapper_path.exists() {
            if std::fs::create_dir_all(&wrapper_dir).is_err() {
                return None;
            }
            if std::fs::write(&wrapper_path, GH_WRAPPER_SCRIPT).is_err() {
                return None;
            }
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let _ =
                    std::fs::set_permissions(&wrapper_path, std::fs::Permissions::from_mode(0o755));
            }
        }

        Some(wrapper_dir)
    }

    /// Build the command-line arguments for launching the agent.
    ///
    /// Returns a `Vec<String>` where the first element is the program and the
    /// rest are arguments.
    ///
    /// # Errors
    ///
    /// Returns an error if the backend is not recognized.
    pub fn build_command(
        &self,
        agent_def: &AgentDefinition,
        prompt_file: &Path,
        task_prompt: &str,
    ) -> Result<Vec<String>, String> {
        // If a spawn script override exists, use it. All config is passed via
        // environment variables (build_env), so no extra CLI args are needed.
        if let Some(script_path) = self.get_spawn_script(&agent_def.backend) {
            return Ok(vec![
                "bash".to_string(),
                script_path.to_string_lossy().into_owned(),
            ]);
        }

        let prompt_path = prompt_file.to_string_lossy().into_owned();

        match agent_def.backend.as_str() {
            "claude-code" => {
                let mut cmd = vec![
                    "claude".to_string(),
                    "-p".to_string(),
                    "--prompt-file".to_string(),
                    prompt_path,
                    "--max-turns".to_string(),
                    self.max_turns.to_string(),
                ];
                if !task_prompt.is_empty() {
                    cmd.push("--task".to_string());
                    cmd.push(task_prompt.to_string());
                }
                Ok(cmd)
            }
            "codex" => {
                let mut cmd = vec![
                    "codex".to_string(),
                    "--prompt-file".to_string(),
                    prompt_path,
                ];
                if !task_prompt.is_empty() {
                    cmd.push("--task".to_string());
                    cmd.push(task_prompt.to_string());
                }
                Ok(cmd)
            }
            other => Err(format!("unknown backend: {}", other)),
        }
    }

    // spawn() will be async in the real implementation.
    // For now we only expose build_env and build_command for testing.
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agents::parser::{AgentDefinition, ToolPermissions};
    use crate::constants::DEFAULT_AGENT_MAX_TURNS;
    use std::collections::HashMap;
    use tempfile::TempDir;

    /// Helper: build a minimal agent definition with sensible defaults.
    fn make_agent_def(backend: &str) -> AgentDefinition {
        let mut tools = HashMap::new();
        tools.insert(
            backend.to_string(),
            ToolPermissions {
                allowed: vec!["Read".into(), "Write".into()],
                disallowed: vec!["Shell".into()],
            },
        );
        AgentDefinition {
            name: "coder".into(),
            backend: backend.into(),
            git_author_name: "Test Bot".into(),
            git_author_email: "bot@test.local".into(),
            timeout: None,
            tools,
            instruction_body: "Do the work.".into(),
        }
    }

    // 1. build_env sets git author fields
    #[test]
    fn build_env_sets_git_author_fields() {
        let tmp = TempDir::new().unwrap();
        let spawner = AgentSpawner::new(tmp.path(), DEFAULT_AGENT_MAX_TURNS);
        let def = make_agent_def("claude-code");
        let prompt = tmp.path().join("prompt.md");

        let env = spawner.build_env(&def, &prompt, "fix bug", None);

        assert_eq!(env["GIT_AUTHOR_NAME"], "Test Bot");
        assert_eq!(env["GIT_AUTHOR_EMAIL"], "bot@test.local");
        assert_eq!(env["GIT_COMMITTER_NAME"], "Test Bot");
        assert_eq!(env["GIT_COMMITTER_EMAIL"], "bot@test.local");
    }

    // 2. build_env sets tool permissions
    #[test]
    fn build_env_sets_tool_permissions() {
        let tmp = TempDir::new().unwrap();
        let spawner = AgentSpawner::new(tmp.path(), 100);
        let def = make_agent_def("claude-code");
        let prompt = tmp.path().join("prompt.md");
        std::fs::write(&prompt, "System prompt text").unwrap();

        let env = spawner.build_env(&def, &prompt, "task", None);

        assert_eq!(env["ALLOWED_TOOLS"], "Read,Write");
        assert_eq!(env["DISALLOWED_TOOLS"], "Shell");
        assert_eq!(env["SYSTEM_PROMPT"], "System prompt text");
        assert_eq!(env["TASK_CONTEXT"], "task");
    }

    // 3. build_env sets prompt and task info
    #[test]
    fn build_env_sets_prompt_and_task_info() {
        let tmp = TempDir::new().unwrap();
        let spawner = AgentSpawner::new(tmp.path(), 50);
        let def = make_agent_def("codex");
        let prompt = tmp.path().join("prompt.md");
        std::fs::write(&prompt, "full prompt").unwrap();

        let env = spawner.build_env(&def, &prompt, "implement caching", None);

        assert_eq!(env["PROMPT_FILE"], prompt.to_string_lossy().as_ref());
        assert_eq!(env["SYSTEM_PROMPT"], "full prompt");
        assert_eq!(env["TASK_CONTEXT"], "implement caching");
        assert_eq!(env["TASK_PROMPT"], "full prompt");
        assert_eq!(env["MAX_TURNS"], "50");
        assert_eq!(env["GITHUBCLAW_AGENT_TYPE"], "coder");
        assert_eq!(env["GITHUBCLAW_BACKEND"], "codex");
        assert_eq!(
            env["GITHUBCLAW_REPO_ROOT"],
            tmp.path().to_string_lossy().as_ref()
        );
    }

    // 4. build_env merges extra_env
    #[test]
    fn build_env_merges_extra_env() {
        let tmp = TempDir::new().unwrap();
        let spawner = AgentSpawner::new(tmp.path(), 100);
        let def = make_agent_def("claude-code");
        let prompt = tmp.path().join("prompt.md");
        std::fs::write(&prompt, "System prompt text").unwrap();

        let mut extra = HashMap::new();
        extra.insert("CUSTOM_VAR".into(), "custom_value".into());
        extra.insert("GIT_AUTHOR_NAME".into(), "Override Bot".into());

        let env = spawner.build_env(&def, &prompt, "task", Some(&extra));

        assert_eq!(env["CUSTOM_VAR"], "custom_value");
        // Extra env overrides built-in values
        assert_eq!(env["GIT_AUTHOR_NAME"], "Override Bot");
    }

    // 5. build_command for claude-code backend
    #[test]
    fn build_command_claude_code() {
        let tmp = TempDir::new().unwrap();
        let spawner = AgentSpawner::new(tmp.path(), 200);
        let def = make_agent_def("claude-code");
        let prompt = tmp.path().join("prompt.md");

        let cmd = spawner.build_command(&def, &prompt, "fix the bug").unwrap();

        assert_eq!(cmd[0], "claude");
        assert!(cmd.contains(&"-p".to_string()));
        assert!(cmd.contains(&"--prompt-file".to_string()));
        assert!(cmd.contains(&"--max-turns".to_string()));
        assert!(cmd.contains(&"200".to_string()));
        assert!(cmd.contains(&"--task".to_string()));
        assert!(cmd.contains(&"fix the bug".to_string()));
    }

    // 6. build_command for codex backend
    #[test]
    fn build_command_codex() {
        let tmp = TempDir::new().unwrap();
        let spawner = AgentSpawner::new(tmp.path(), 100);
        let def = make_agent_def("codex");
        let prompt = tmp.path().join("prompt.md");

        let cmd = spawner
            .build_command(&def, &prompt, "implement feature")
            .unwrap();

        assert_eq!(cmd[0], "codex");
        assert!(cmd.contains(&"--prompt-file".to_string()));
        assert!(cmd.contains(&"--task".to_string()));
        assert!(cmd.contains(&"implement feature".to_string()));
        // codex should NOT have -p or --max-turns
        assert!(!cmd.contains(&"-p".to_string()));
        assert!(!cmd.contains(&"--max-turns".to_string()));
    }

    // 7. build_command for unknown backend returns error
    #[test]
    fn build_command_unknown_backend_errors() {
        let tmp = TempDir::new().unwrap();
        let spawner = AgentSpawner::new(tmp.path(), 100);
        let def = make_agent_def("unknown-backend");
        let prompt = tmp.path().join("prompt.md");

        let result = spawner.build_command(&def, &prompt, "task");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("unknown backend"));
    }

    // 8. get_spawn_script returns None when no script exists
    #[test]
    fn get_spawn_script_returns_none_when_missing() {
        let tmp = TempDir::new().unwrap();
        let spawner = AgentSpawner::new(tmp.path(), 100);

        assert!(spawner.get_spawn_script("claude-code").is_none());
        assert!(spawner.get_spawn_script("codex").is_none());
    }

    // 9. get_spawn_script returns path when script exists
    #[test]
    fn get_spawn_script_returns_path_when_exists() {
        let tmp = TempDir::new().unwrap();
        let claw_dir = tmp.path().join(".githubclaw");
        std::fs::create_dir_all(&claw_dir).unwrap();

        let script_path = claw_dir.join("spawn_claude.sh");
        std::fs::write(&script_path, "#!/bin/bash\necho hello").unwrap();

        let spawner = AgentSpawner::new(tmp.path(), 100);
        let result = spawner.get_spawn_script("claude-code");
        assert!(result.is_some());
        assert_eq!(result.unwrap(), script_path);
    }

    // 10. build_command uses spawn script override when present
    #[test]
    fn build_command_uses_spawn_script_override() {
        let tmp = TempDir::new().unwrap();
        let claw_dir = tmp.path().join(".githubclaw");
        std::fs::create_dir_all(&claw_dir).unwrap();

        let script_path = claw_dir.join("spawn_claude.sh");
        std::fs::write(&script_path, "#!/bin/bash\nexec claude").unwrap();

        let spawner = AgentSpawner::new(tmp.path(), 200);
        let def = make_agent_def("claude-code");
        let prompt = tmp.path().join("prompt.md");

        let cmd = spawner.build_command(&def, &prompt, "fix the bug").unwrap();
        assert_eq!(cmd[0], "bash");
        assert_eq!(cmd[1], script_path.to_string_lossy().as_ref());
        assert_eq!(cmd.len(), 2);
    }
}