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

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