g1t/crates/runner/src/main.rs

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