flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/crates/runner/src/main.rs

261 lines10,683 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//!
29//! Given a command instead (`register`, `run`, `service`, `remove`,
30//! `update`, `version`), it is a self-hosted runner on someone's own
31//! machine, which runs work in these modes: see `selfhosted`.
32
33mod abuse;
34mod actions;
35mod checks;
36mod clone;
37mod confidence;
38mod deploy;
39mod guard;
40mod harness;
41mod learned;
42mod mergecheck;
43mod plan;
44mod progress;
45mod queue;
46mod reply;
47mod report;
48mod review;
49mod revise;
50mod selfhosted;
51mod steer;
52mod update;
53
54use std::path::Path;
55use std::process::Command;
56
57use anyhow::{Context, Result, bail};
58use base64::Engine;
59use base64::engine::general_purpose::STANDARD;
60
61use report::{Entry, Reporter};
62
63pub(crate) const WORKDIR: &str = "/work/repo";
64
65pub(crate) fn env(name: &str) -> Result<String> {
66 std::env::var(name).with_context(|| format!("{name} is not set"))
67}
68
69/// Runs git and returns its trimmed output, failing on a non-zero exit.
70pub(crate) fn git(dir: &Path, args: &[&str]) -> Result<String> {
71 let output = Command::new("git")
72 .current_dir(dir)
73 .args(args)
74 .output()
75 .context("could not run git")?;
76 if !output.status.success() {
77 bail!(
78 "git {} failed: {}",
79 args.first().unwrap_or(&""),
80 String::from_utf8_lossy(&output.stderr).trim()
81 );
82 }
83 Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
84}
85
86/// A git option that authenticates one command. The credential is passed
87/// per command and never written to the clone's config or its remote URL,
88/// where the agent would find it.
89pub(crate) fn auth_option(user: &str, token: &str) -> String {
90 let credentials = STANDARD.encode(format!("{user}:{token}"));
91 format!("http.extraHeader=Authorization: Basic {credentials}")
92}
93
94/// Clones the fork, runs the agent on `PROMPT`, commits and pushes what it
95/// did, and returns its closing summary.
96pub(crate) fn run(reporter: &mut Reporter) -> Result<String> {
97 let mut prompt = env("PROMPT")?;
98 let remote = env("GIT_REMOTE")?;
99 let auth = auth_option(&env("G1T_USER")?, &env("G1T_TOKEN")?);
100 let workdir = Path::new(WORKDIR);
101
102 if let Ok(model) = std::env::var("AGENT_MODEL_NAME") {
103 reporter.record(Entry::new("note", &format!("Running on {model}.")));
104 }
105 reporter.record(Entry::new("prompt", &prompt));
106 reporter.flush();
107
108 std::fs::create_dir_all("/work")?;
109 clone::clone(Path::new("/work"), &auth, &[], &remote, WORKDIR).context("could not clone the pull request's fork")?;
110 git(workdir, &["config", "user.name", "g1t agent"])?;
111 git(workdir, &["config", "user.email", "agent@g1t.sh"])?;
112 let branch = git(workdir, &["rev-parse", "--abbrev-ref", "HEAD"])?;
113 let start = git(workdir, &["rev-parse", "HEAD"]).unwrap_or_default();
114
115 // Sent back to work that is already open: start from where the branch it
116 // will land on is now, so what passes here passes there too.
117 if let (Ok(upstream), Ok(upstream_branch)) = (env("UPSTREAM_REMOTE"), env("UPSTREAM_BRANCH")) {
118 clone::fetch(workdir, &auth, &upstream, &upstream_branch).context("could not fetch the branch this will land on")?;
119 // Shallow: deep enough to tell whether it is behind, and to merge.
120 clone::share_history(workdir, &auth, &[("origin", branch.as_str()), (upstream.as_str(), upstream_branch.as_str())], "HEAD", "FETCH_HEAD")?;
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 self-hosted runner's commands; the modes below are what it, and
198 // g1t's sandboxes, run work with.
199 let args: Vec<String> = std::env::args().skip(1).collect();
200 if selfhosted::is_command(&args) {
201 std::process::exit(selfhosted::main(args));
202 }
203 // A guarded sandbox's HTTPS is re-signed on its way out: trust that
204 // before anything is fetched. The guard hook runs before every tool
205 // call, so it skips this.
206 if std::env::var("MODE").as_deref() == Ok("guard") {
207 std::process::exit(guard::hook_main());
208 }
209 guard::trust_egress_ca();
210 // Watches for mining for as long as the sandbox runs (abuse.rs). Not in
211 // the hooks the harness runs after every tool call.
212 if std::env::var("MODE").as_deref() != Ok("steer") {
213 abuse::watch();
214 }
215 // The same image does the other jobs a sandbox is started for.
216 match std::env::var("MODE").as_deref() {
217 Ok("actions") => std::process::exit(actions::main()),
218 Ok("checks") => std::process::exit(checks::main()),
219 Ok("deploy") => std::process::exit(deploy::main()),
220 Ok("update") => std::process::exit(update::main()),
221 Ok("review") => std::process::exit(review::main()),
222 Ok("revise") => std::process::exit(revise::main()),
223 Ok("answer") => std::process::exit(revise::answer()),
224 Ok("plan") => std::process::exit(plan::main()),
225 Ok("reply") => std::process::exit(reply::main()),
226 Ok("queue") => std::process::exit(queue::main()),
227 Ok("mergecheck") => std::process::exit(mergecheck::main()),
228 Ok("steer") => std::process::exit(steer::main()),
229 _ => {}
230 }
231 let mut reporter = match Reporter::from_env() {
232 Ok(reporter) => reporter,
233 Err(error) => {
234 eprintln!("g1t-runner: {error:#}");
235 std::process::exit(2);
236 }
237 };
238 match run(&mut reporter) {
239 Ok(summary) => {
240 reporter.flush();
241 if let Err(error) = reporter.ready(&summary) {
242 eprintln!("g1t-runner: could not mark the pull request ready: {error:#}");
243 std::process::exit(1);
244 }
245 }
246 Err(error) => {
247 eprintln!("g1t-runner: {error:#}");
248 // Stopped at a cap: like a person's stop, the pull request is
249 // left open for a person, not closed.
250 if guard::is_halt(&error) {
251 reporter.record(Entry::new("note", &format!("g1t stopped the agent: {error:#}.")));
252 reporter.flush();
253 std::process::exit(1);
254 }
255 reporter.record(Entry::new("note", &format!("The run failed: {error:#}")));
256 reporter.flush();
257 let _ = reporter.close();
258 std::process::exit(1);
259 }
260 }
261}