pr_01m47d15m3e54sn21z27rpy5n9/crates/runner/src/main.rs

219 lines8,459 bytesCodeBlame
1//! Runs a coding agent on one pull request and reports back to g1t.
2//!
3//! This is the program a hosted sandbox starts. It clones the pull
4//! request's fork, runs the agent harness headless, streams what the agent
5//! does into the pull request's session as it happens, pushes the result
6//! and marks the pull request ready for review. It talks to g1t only through the public API and git, exactly
7//! as an agent on someone's own machine would.
8//!
9//! `MODE` selects another job instead: `checks` runs acceptance checks,
10//! `update` brings a pull request up to date with its target branch,
11//! `review` has an agent review one, and `revise` sends the author back to
12//! address what the checks or a review found, `plan` turns an outcome
13//! into issues, `queue` builds and checks a state of the merge queue, and
14//! `actions` runs one job of a GitHub Actions workflow.
15//! See the modules of those names.
16//!
17//! Configuration comes from the environment:
18//!
19//! - `G1T_API`, `G1T_TOKEN`, `G1T_USER`: where and who to report as.
20//! - `G1T_REPO`, `PULL_NUMBER`, `GIT_REMOTE`: the pull request and its fork.
21//! - `PROMPT`: what the agent is asked to do.
22//! - `COMMIT_MESSAGE`: used if the agent leaves changes uncommitted.
23//! - `ANTHROPIC_API_KEY`: read by the harness itself.
24
25mod actions;
26mod checks;
27mod deploy;
28mod harness;
29mod plan;
30mod queue;
31mod report;
32mod review;
33mod revise;
34mod steer;
35mod update;
36
37use std::path::Path;
38use std::process::Command;
39
40use anyhow::{Context, Result, bail};
41use base64::Engine;
42use base64::engine::general_purpose::STANDARD;
43
44use report::{Entry, Reporter};
45
46pub(crate) const WORKDIR: &str = "/work/repo";
47
48pub(crate) fn env(name: &str) -> Result<String> {
49 std::env::var(name).with_context(|| format!("{name} is not set"))
50}
51
52/// Runs git and returns its trimmed output, failing on a non-zero exit.
53pub(crate) fn git(dir: &Path, args: &[&str]) -> Result<String> {
54 let output = Command::new("git")
55 .current_dir(dir)
56 .args(args)
57 .output()
58 .context("could not run git")?;
59 if !output.status.success() {
60 bail!(
61 "git {} failed: {}",
62 args.first().unwrap_or(&""),
63 String::from_utf8_lossy(&output.stderr).trim()
64 );
65 }
66 Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
67}
68
69/// A git option that authenticates one command. The credential is passed
70/// per command and never written to the clone's config or its remote URL,
71/// where the agent would find it.
72pub(crate) fn auth_option(user: &str, token: &str) -> String {
73 let credentials = STANDARD.encode(format!("{user}:{token}"));
74 format!("http.extraHeader=Authorization: Basic {credentials}")
75}
76
77/// Clones the fork, runs the agent on `PROMPT`, commits and pushes what it
78/// did, and returns its closing summary.
79pub(crate) fn run(reporter: &mut Reporter) -> Result<String> {
80 let mut prompt = env("PROMPT")?;
81 let remote = env("GIT_REMOTE")?;
82 let auth = auth_option(&env("G1T_USER")?, &env("G1T_TOKEN")?);
83 let workdir = Path::new(WORKDIR);
84
85 if let Ok(model) = std::env::var("AGENT_MODEL_NAME") {
86 reporter.record(Entry::new("note", &format!("Running on {model}.")));
87 }
88 reporter.record(Entry::new("prompt", &prompt));
89 reporter.flush();
90
91 std::fs::create_dir_all("/work")?;
92 git(
93 Path::new("/work"),
94 &["-c", &auth, "clone", "--quiet", &remote, WORKDIR],
95 )
96 .context("could not clone the pull request's fork")?;
97 git(workdir, &["config", "user.name", "g1t agent"])?;
98 git(workdir, &["config", "user.email", "agent@g1t.sh"])?;
99 let branch = git(workdir, &["rev-parse", "--abbrev-ref", "HEAD"])?;
100 let start = git(workdir, &["rev-parse", "HEAD"]).unwrap_or_default();
101
102 // Sent back to work that is already open: start from where the branch it
103 // will land on is now, so what passes here passes there too.
104 if let (Ok(upstream), Ok(upstream_branch)) = (env("UPSTREAM_REMOTE"), env("UPSTREAM_BRANCH")) {
105 git(
106 workdir,
107 &["-c", &auth, "fetch", "--quiet", &upstream, &upstream_branch],
108 )
109 .context("could not fetch the branch this will land on")?;
110 let behind = Command::new("git")
111 .current_dir(workdir)
112 .args(["merge-base", "--is-ancestor", "FETCH_HEAD", "HEAD"])
113 .status()
114 .is_ok_and(|status| !status.success());
115 if behind {
116 let message = format!("Catch up with {upstream_branch}");
117 let merged = Command::new("git")
118 .current_dir(workdir)
119 .args(["merge", "--quiet", "--no-edit", "-m", &message, "FETCH_HEAD"])
120 .status()
121 .is_ok_and(|status| status.success());
122 if merged {
123 reporter.record(Entry::new(
124 "note",
125 &format!("Merged in the latest {upstream_branch} before starting."),
126 ));
127 } else {
128 let files = git(workdir, &["diff", "--name-only", "--diff-filter=U"])?;
129 let files: Vec<&str> = files.lines().collect();
130 reporter.record(Entry::new(
131 "note",
132 &format!(
133 "Merged in the latest {upstream_branch} before starting; {} conflict.",
134 files.join(", ")
135 ),
136 ));
137 prompt.push_str(&format!(
138 "\n\nBefore you started, the latest {upstream_branch} was merged into this branch, and these files conflict: {}. Resolve the conflicts first, keeping what both sides meant, then address the points above. Leave no conflict markers.",
139 files.join(", ")
140 ));
141 }
142 reporter.flush();
143 }
144 }
145
146 let summary = harness::run_claude(workdir, &prompt, reporter)?;
147
148 // Commit whatever the agent left in the working tree.
149 if !git(workdir, &["status", "--porcelain"])?.is_empty() {
150 let message = std::env::var("COMMIT_MESSAGE").unwrap_or_else(|_| "Agent changes".into());
151 git(workdir, &["add", "--all"])?;
152 git(workdir, &["commit", "--quiet", "--message", &message])?;
153 }
154 let head = git(workdir, &["rev-parse", "HEAD"])?;
155 if head == start {
156 // An agent woken to answer usually only answers.
157 if std::env::var("MODE").as_deref() == Ok("answer") {
158 return Ok(summary);
159 }
160 bail!("the agent finished without changing anything");
161 }
162 git(
163 workdir,
164 &[
165 "-c",
166 &auth,
167 "push",
168 "--quiet",
169 "origin",
170 &format!("HEAD:{branch}"),
171 ],
172 )
173 .context("could not push the pull request's commits")?;
174 reporter.record(Entry::new(
175 "note",
176 &format!("Pushed {}.", &head[..head.len().min(12)]),
177 ));
178 Ok(summary)
179}
180
181fn main() {
182 // The same image does the other jobs a sandbox is started for.
183 match std::env::var("MODE").as_deref() {
184 Ok("actions") => std::process::exit(actions::main()),
185 Ok("checks") => std::process::exit(checks::main()),
186 Ok("deploy") => std::process::exit(deploy::main()),
187 Ok("update") => std::process::exit(update::main()),
188 Ok("review") => std::process::exit(review::main()),
189 Ok("revise") => std::process::exit(revise::main()),
190 Ok("answer") => std::process::exit(revise::answer()),
191 Ok("plan") => std::process::exit(plan::main()),
192 Ok("queue") => std::process::exit(queue::main()),
193 Ok("steer") => std::process::exit(steer::main()),
194 _ => {}
195 }
196 let mut reporter = match Reporter::from_env() {
197 Ok(reporter) => reporter,
198 Err(error) => {
199 eprintln!("g1t-runner: {error:#}");
200 std::process::exit(2);
201 }
202 };
203 match run(&mut reporter) {
204 Ok(summary) => {
205 reporter.flush();
206 if let Err(error) = reporter.ready(&summary) {
207 eprintln!("g1t-runner: could not mark the pull request ready: {error:#}");
208 std::process::exit(1);
209 }
210 }
211 Err(error) => {
212 eprintln!("g1t-runner: {error:#}");
213 reporter.record(Entry::new("note", &format!("The run failed: {error:#}")));
214 reporter.flush();
215 let _ = reporter.close();
216 std::process::exit(1);
217 }
218 }
219}