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

209 lines8,031 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Issues and pull requests replace intents and attempts1//! Runs a coding agent on one pull request and reports back to g1t.
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)2//!
Issues and pull requests replace intents and attempts3//! 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
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)7//! as an agent on someone's own machine would.
8//!
Agents as a team: lifecycle, merge queue, billing and a new shell9//! `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, and `queue` builds and checks a state of the merge queue.
14//! See the modules of those names.
Acceptance checks in sandboxes, line comments and review verdicts15//!
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)16//! Configuration comes from the environment:
17//!
18//! - `G1T_API`, `G1T_TOKEN`, `G1T_USER`: where and who to report as.
Issues and pull requests replace intents and attempts19//! - `G1T_REPO`, `PULL_NUMBER`, `GIT_REMOTE`: the pull request and its fork.
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)20//! - `PROMPT`: what the agent is asked to do.
21//! - `COMMIT_MESSAGE`: used if the agent leaves changes uncommitted.
22//! - `ANTHROPIC_API_KEY`: read by the harness itself.
23
Acceptance checks in sandboxes, line comments and review verdicts24mod checks;
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)25mod harness;
Agents as a team: lifecycle, merge queue, billing and a new shell26mod plan;
27mod queue;
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)28mod report;
Agents as a team: lifecycle, merge queue, billing and a new shell29mod review;
30mod revise;
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request31mod steer;
Agents as a team: lifecycle, merge queue, billing and a new shell32mod update;
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)33
34use std::path::Path;
35use std::process::Command;
36
37use anyhow::{Context, Result, bail};
38use base64::Engine;
39use base64::engine::general_purpose::STANDARD;
40
41use report::{Entry, Reporter};
42
Acceptance checks in sandboxes, line comments and review verdicts43pub(crate) const WORKDIR: &str = "/work/repo";
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)44
Acceptance checks in sandboxes, line comments and review verdicts45pub(crate) fn env(name: &str) -> Result<String> {
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)46 std::env::var(name).with_context(|| format!("{name} is not set"))
47}
48
49/// Runs git and returns its trimmed output, failing on a non-zero exit.
Acceptance checks in sandboxes, line comments and review verdicts50pub(crate) fn git(dir: &Path, args: &[&str]) -> Result<String> {
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)51 let output = Command::new("git")
52 .current_dir(dir)
53 .args(args)
54 .output()
55 .context("could not run git")?;
56 if !output.status.success() {
57 bail!(
58 "git {} failed: {}",
59 args.first().unwrap_or(&""),
60 String::from_utf8_lossy(&output.stderr).trim()
61 );
62 }
63 Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
64}
65
66/// A git option that authenticates one command. The credential is passed
67/// per command and never written to the clone's config or its remote URL,
68/// where the agent would find it.
Acceptance checks in sandboxes, line comments and review verdicts69pub(crate) fn auth_option(user: &str, token: &str) -> String {
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)70 let credentials = STANDARD.encode(format!("{user}:{token}"));
71 format!("http.extraHeader=Authorization: Basic {credentials}")
72}
73
Agents as a team: lifecycle, merge queue, billing and a new shell74/// Clones the fork, runs the agent on `PROMPT`, commits and pushes what it
75/// did, and returns its closing summary.
76pub(crate) fn run(reporter: &mut Reporter) -> Result<String> {
77 let mut prompt = env("PROMPT")?;
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)78 let remote = env("GIT_REMOTE")?;
79 let auth = auth_option(&env("G1T_USER")?, &env("G1T_TOKEN")?);
80 let workdir = Path::new(WORKDIR);
81
Show the model behind each choice; toolchains in the sandbox82 if let Ok(model) = std::env::var("AGENT_MODEL_NAME") {
83 reporter.record(Entry::new("note", &format!("Running on {model}.")));
84 }
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)85 reporter.record(Entry::new("prompt", &prompt));
86 reporter.flush();
87
88 std::fs::create_dir_all("/work")?;
89 git(
90 Path::new("/work"),
91 &["-c", &auth, "clone", "--quiet", &remote, WORKDIR],
92 )
Issues and pull requests replace intents and attempts93 .context("could not clone the pull request's fork")?;
Diffs on attempts; hosted agent presented as the g1t agent94 git(workdir, &["config", "user.name", "g1t agent"])?;
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)95 git(workdir, &["config", "user.email", "agent@g1t.sh"])?;
96 let branch = git(workdir, &["rev-parse", "--abbrev-ref", "HEAD"])?;
97 let start = git(workdir, &["rev-parse", "HEAD"]).unwrap_or_default();
98
Agents as a team: lifecycle, merge queue, billing and a new shell99 // Sent back to work that is already open: start from where the branch it
100 // will land on is now, so what passes here passes there too.
101 if let (Ok(upstream), Ok(upstream_branch)) = (env("UPSTREAM_REMOTE"), env("UPSTREAM_BRANCH")) {
102 git(
103 workdir,
104 &["-c", &auth, "fetch", "--quiet", &upstream, &upstream_branch],
105 )
106 .context("could not fetch the branch this will land on")?;
107 let behind = Command::new("git")
108 .current_dir(workdir)
109 .args(["merge-base", "--is-ancestor", "FETCH_HEAD", "HEAD"])
110 .status()
111 .is_ok_and(|status| !status.success());
112 if behind {
113 let message = format!("Catch up with {upstream_branch}");
114 let merged = Command::new("git")
115 .current_dir(workdir)
116 .args(["merge", "--quiet", "--no-edit", "-m", &message, "FETCH_HEAD"])
117 .status()
118 .is_ok_and(|status| status.success());
119 if merged {
120 reporter.record(Entry::new(
121 "note",
122 &format!("Merged in the latest {upstream_branch} before starting."),
123 ));
124 } else {
125 let files = git(workdir, &["diff", "--name-only", "--diff-filter=U"])?;
126 let files: Vec<&str> = files.lines().collect();
127 reporter.record(Entry::new(
128 "note",
129 &format!(
130 "Merged in the latest {upstream_branch} before starting; {} conflict.",
131 files.join(", ")
132 ),
133 ));
134 prompt.push_str(&format!(
135 "\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.",
136 files.join(", ")
137 ));
138 }
139 reporter.flush();
140 }
141 }
142
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)143 let summary = harness::run_claude(workdir, &prompt, reporter)?;
144
145 // Commit whatever the agent left in the working tree.
146 if !git(workdir, &["status", "--porcelain"])?.is_empty() {
147 let message = std::env::var("COMMIT_MESSAGE").unwrap_or_else(|_| "Agent changes".into());
148 git(workdir, &["add", "--all"])?;
149 git(workdir, &["commit", "--quiet", "--message", &message])?;
150 }
151 let head = git(workdir, &["rev-parse", "HEAD"])?;
152 if head == start {
153 bail!("the agent finished without changing anything");
154 }
155 git(
156 workdir,
157 &[
158 "-c",
159 &auth,
160 "push",
161 "--quiet",
162 "origin",
163 &format!("HEAD:{branch}"),
164 ],
165 )
Issues and pull requests replace intents and attempts166 .context("could not push the pull request's commits")?;
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)167 reporter.record(Entry::new(
168 "note",
Issues and pull requests replace intents and attempts169 &format!("Pushed {}.", &head[..head.len().min(12)]),
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)170 ));
171 Ok(summary)
172}
173
174fn main() {
Agents as a team: lifecycle, merge queue, billing and a new shell175 // The same image does the other jobs a sandbox is started for.
176 match std::env::var("MODE").as_deref() {
177 Ok("checks") => std::process::exit(checks::main()),
178 Ok("update") => std::process::exit(update::main()),
179 Ok("review") => std::process::exit(review::main()),
180 Ok("revise") => std::process::exit(revise::main()),
181 Ok("plan") => std::process::exit(plan::main()),
182 Ok("queue") => std::process::exit(queue::main()),
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request183 Ok("steer") => std::process::exit(steer::main()),
Agents as a team: lifecycle, merge queue, billing and a new shell184 _ => {}
Acceptance checks in sandboxes, line comments and review verdicts185 }
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)186 let mut reporter = match Reporter::from_env() {
187 Ok(reporter) => reporter,
188 Err(error) => {
189 eprintln!("g1t-runner: {error:#}");
190 std::process::exit(2);
191 }
192 };
193 match run(&mut reporter) {
194 Ok(summary) => {
195 reporter.flush();
Issues and pull requests replace intents and attempts196 if let Err(error) = reporter.ready(&summary) {
197 eprintln!("g1t-runner: could not mark the pull request ready: {error:#}");
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)198 std::process::exit(1);
199 }
200 }
201 Err(error) => {
202 eprintln!("g1t-runner: {error:#}");
203 reporter.record(Entry::new("note", &format!("The run failed: {error:#}")));
204 reporter.flush();
Issues and pull requests replace intents and attempts205 let _ = reporter.close();
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)206 std::process::exit(1);
207 }
208 }
209}