pr_01m47d15m3e54sn21z27rpy5n9/crates/runner/src/main.rs

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