g1t/crates/runner/src/main.rs

255 lines10,060 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,
14//! `mergecheck` finds out whether a pull request merges cleanly, and
15//! `actions` runs one job of a GitHub Actions workflow.
16//! See the modules of those names.
17//!
18//! Configuration comes from the environment:
19//!
20//! - `G1T_API`, `G1T_TOKEN`, `G1T_USER`: where and who to report as.
21//! - `G1T_REPO`, `PULL_NUMBER`, `GIT_REMOTE`: the pull request and its fork.
22//! - `PROMPT`: what the agent is asked to do.
23//! - `COMMIT_MESSAGE`: used if the agent leaves changes uncommitted.
24//! - `ANTHROPIC_API_KEY`: read by the harness itself.
25//!
26//! Every mode runs with the mining watch in `abuse`: a sandbox that looks
27//! like it is mining stops itself and exits with `abuse::EXIT_CODE`.
28
29mod abuse;
30mod actions;
31mod checks;
32mod confidence;
33mod deploy;
34mod guard;
35mod harness;
36mod learned;
37mod mergecheck;
38mod plan;
39mod progress;
40mod queue;
41mod reply;
42mod report;
43mod review;
44mod revise;
45mod steer;
46mod update;
47
48use std::path::Path;
49use std::process::Command;
50
51use anyhow::{Context, Result, bail};
52use base64::Engine;
53use base64::engine::general_purpose::STANDARD;
54
55use report::{Entry, Reporter};
56
57pub(crate) const WORKDIR: &str = "/work/repo";
58
59pub(crate) fn env(name: &str) -> Result<String> {
60 std::env::var(name).with_context(|| format!("{name} is not set"))
61}
62
63/// Runs git and returns its trimmed output, failing on a non-zero exit.
64pub(crate) fn git(dir: &Path, args: &[&str]) -> Result<String> {
65 let output = Command::new("git")
66 .current_dir(dir)
67 .args(args)
68 .output()
69 .context("could not run git")?;
70 if !output.status.success() {
71 bail!(
72 "git {} failed: {}",
73 args.first().unwrap_or(&""),
74 String::from_utf8_lossy(&output.stderr).trim()
75 );
76 }
77 Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
78}
79
80/// A git option that authenticates one command. The credential is passed
81/// per command and never written to the clone's config or its remote URL,
82/// where the agent would find it.
83pub(crate) fn auth_option(user: &str, token: &str) -> String {
84 let credentials = STANDARD.encode(format!("{user}:{token}"));
85 format!("http.extraHeader=Authorization: Basic {credentials}")
86}
87
88/// Clones the fork, runs the agent on `PROMPT`, commits and pushes what it
89/// did, and returns its closing summary.
90pub(crate) fn run(reporter: &mut Reporter) -> Result<String> {
91 let mut prompt = env("PROMPT")?;
92 let remote = env("GIT_REMOTE")?;
93 let auth = auth_option(&env("G1T_USER")?, &env("G1T_TOKEN")?);
94 let workdir = Path::new(WORKDIR);
95
96 if let Ok(model) = std::env::var("AGENT_MODEL_NAME") {
97 reporter.record(Entry::new("note", &format!("Running on {model}.")));
98 }
99 reporter.record(Entry::new("prompt", &prompt));
100 reporter.flush();
101
102 std::fs::create_dir_all("/work")?;
103 git(
104 Path::new("/work"),
105 &["-c", &auth, "clone", "--quiet", &remote, WORKDIR],
106 )
107 .context("could not clone the pull request's fork")?;
108 git(workdir, &["config", "user.name", "g1t agent"])?;
109 git(workdir, &["config", "user.email", "agent@g1t.sh"])?;
110 let branch = git(workdir, &["rev-parse", "--abbrev-ref", "HEAD"])?;
111 let start = git(workdir, &["rev-parse", "HEAD"]).unwrap_or_default();
112
113 // Sent back to work that is already open: start from where the branch it
114 // will land on is now, so what passes here passes there too.
115 if let (Ok(upstream), Ok(upstream_branch)) = (env("UPSTREAM_REMOTE"), env("UPSTREAM_BRANCH")) {
116 git(
117 workdir,
118 &["-c", &auth, "fetch", "--quiet", &upstream, &upstream_branch],
119 )
120 .context("could not fetch the branch this will land on")?;
121 let behind = Command::new("git")
122 .current_dir(workdir)
123 .args(["merge-base", "--is-ancestor", "FETCH_HEAD", "HEAD"])
124 .status()
125 .is_ok_and(|status| !status.success());
126 if behind {
127 let message = format!("Catch up with {upstream_branch}");
128 let merged = Command::new("git")
129 .current_dir(workdir)
130 .args(["merge", "--quiet", "--no-edit", "-m", &message, "FETCH_HEAD"])
131 .status()
132 .is_ok_and(|status| status.success());
133 if merged {
134 reporter.record(Entry::new(
135 "note",
136 &format!("Merged in the latest {upstream_branch} before starting."),
137 ));
138 } else {
139 let files = git(workdir, &["diff", "--name-only", "--diff-filter=U"])?;
140 let files: Vec<&str> = files.lines().collect();
141 reporter.record(Entry::new(
142 "note",
143 &format!(
144 "Merged in the latest {upstream_branch} before starting; {} conflict.",
145 files.join(", ")
146 ),
147 ));
148 prompt.push_str(&format!(
149 "\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.",
150 files.join(", ")
151 ));
152 }
153 reporter.flush();
154 }
155 }
156
157 // The agent is asked what it learned, which goes to memory, and how sure
158 // it is of its change, which g1t weighs with what it observes. Neither
159 // stays in the summary.
160 let asked = confidence::ask(&learned::ask(&prompt));
161 let summary = confidence::finish(learned::finish(harness::run_claude(workdir, &asked, reporter)?));
162
163 // Commit whatever the agent left in the working tree.
164 if !git(workdir, &["status", "--porcelain"])?.is_empty() {
165 let message = std::env::var("COMMIT_MESSAGE").unwrap_or_else(|_| "Agent changes".into());
166 git(workdir, &["add", "--all"])?;
167 git(workdir, &["commit", "--quiet", "--message", &message])?;
168 }
169 let head = git(workdir, &["rev-parse", "HEAD"])?;
170 if head == start {
171 // An agent woken to answer usually only answers.
172 if std::env::var("MODE").as_deref() == Ok("answer") {
173 return Ok(summary);
174 }
175 bail!("the agent finished without changing anything");
176 }
177 git(
178 workdir,
179 &[
180 "-c",
181 &auth,
182 "push",
183 "--quiet",
184 "origin",
185 &format!("HEAD:{branch}"),
186 ],
187 )
188 .context("could not push the pull request's commits")?;
189 reporter.record(Entry::new(
190 "note",
191 &format!("Pushed {}.", &head[..head.len().min(12)]),
192 ));
193 Ok(summary)
194}
195
196fn main() {
197 // A guarded sandbox's HTTPS is re-signed on its way out: trust that
198 // before anything is fetched. The guard hook runs before every tool
199 // call, so it skips this.
200 if std::env::var("MODE").as_deref() == Ok("guard") {
201 std::process::exit(guard::hook_main());
202 }
203 guard::trust_egress_ca();
204 // Watches for mining for as long as the sandbox runs (abuse.rs). Not in
205 // the hooks the harness runs after every tool call.
206 if std::env::var("MODE").as_deref() != Ok("steer") {
207 abuse::watch();
208 }
209 // The same image does the other jobs a sandbox is started for.
210 match std::env::var("MODE").as_deref() {
211 Ok("actions") => std::process::exit(actions::main()),
212 Ok("checks") => std::process::exit(checks::main()),
213 Ok("deploy") => std::process::exit(deploy::main()),
214 Ok("update") => std::process::exit(update::main()),
215 Ok("review") => std::process::exit(review::main()),
216 Ok("revise") => std::process::exit(revise::main()),
217 Ok("answer") => std::process::exit(revise::answer()),
218 Ok("plan") => std::process::exit(plan::main()),
219 Ok("reply") => std::process::exit(reply::main()),
220 Ok("queue") => std::process::exit(queue::main()),
221 Ok("mergecheck") => std::process::exit(mergecheck::main()),
222 Ok("steer") => std::process::exit(steer::main()),
223 _ => {}
224 }
225 let mut reporter = match Reporter::from_env() {
226 Ok(reporter) => reporter,
227 Err(error) => {
228 eprintln!("g1t-runner: {error:#}");
229 std::process::exit(2);
230 }
231 };
232 match run(&mut reporter) {
233 Ok(summary) => {
234 reporter.flush();
235 if let Err(error) = reporter.ready(&summary) {
236 eprintln!("g1t-runner: could not mark the pull request ready: {error:#}");
237 std::process::exit(1);
238 }
239 }
240 Err(error) => {
241 eprintln!("g1t-runner: {error:#}");
242 // Stopped at a cap: like a person's stop, the pull request is
243 // left open for a person, not closed.
244 if guard::is_halt(&error) {
245 reporter.record(Entry::new("note", &format!("g1t stopped the agent: {error:#}.")));
246 reporter.flush();
247 std::process::exit(1);
248 }
249 reporter.record(Entry::new("note", &format!("The run failed: {error:#}")));
250 reporter.flush();
251 let _ = reporter.close();
252 std::process::exit(1);
253 }
254 }
255}