pr_01m47d24b0e6n91zwymwxg0vpx/crates/runner/src/main.rs

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