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

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