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

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
Agents and memory, checks and conflicts, profiles, slug renames, custom domains13//! into issues, `queue` builds and checks a state of the merge queue,
14//! `mergecheck` finds out whether a pull request merges cleanly, and
GitHub Actions on g1t, part two: running workflows15//! `actions` runs one job of a GitHub Actions workflow.
Agents as a team: lifecycle, merge queue, billing and a new shell16//! See the modules of those names.
Acceptance checks in sandboxes, line comments and review verdicts17//!
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)18//! Configuration comes from the environment:
19//!
20//! - `G1T_API`, `G1T_TOKEN`, `G1T_USER`: where and who to report as.
Issues and pull requests replace intents and attempts21//! - `G1T_REPO`, `PULL_NUMBER`, `GIT_REMOTE`: the pull request and its fork.
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)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
GitHub Actions on g1t, part two: running workflows26mod actions;
Acceptance checks in sandboxes, line comments and review verdicts27mod checks;
Deployments: a preview for every pull request, production on g1t.page28mod deploy;
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)29mod harness;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains30mod mergecheck;
Agents as a team: lifecycle, merge queue, billing and a new shell31mod plan;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains32mod progress;
Agents as a team: lifecycle, merge queue, billing and a new shell33mod queue;
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)34mod report;
Agents as a team: lifecycle, merge queue, billing and a new shell35mod review;
36mod revise;
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request37mod steer;
Agents as a team: lifecycle, merge queue, billing and a new shell38mod update;
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)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
Acceptance checks in sandboxes, line comments and review verdicts49pub(crate) const WORKDIR: &str = "/work/repo";
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)50
Acceptance checks in sandboxes, line comments and review verdicts51pub(crate) fn env(name: &str) -> Result<String> {
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)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.
Acceptance checks in sandboxes, line comments and review verdicts56pub(crate) fn git(dir: &Path, args: &[&str]) -> Result<String> {
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)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.
Acceptance checks in sandboxes, line comments and review verdicts75pub(crate) fn auth_option(user: &str, token: &str) -> String {
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)76 let credentials = STANDARD.encode(format!("{user}:{token}"));
77 format!("http.extraHeader=Authorization: Basic {credentials}")
78}
79
Agents as a team: lifecycle, merge queue, billing and a new shell80/// 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")?;
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)84 let remote = env("GIT_REMOTE")?;
85 let auth = auth_option(&env("G1T_USER")?, &env("G1T_TOKEN")?);
86 let workdir = Path::new(WORKDIR);
87
Show the model behind each choice; toolchains in the sandbox88 if let Ok(model) = std::env::var("AGENT_MODEL_NAME") {
89 reporter.record(Entry::new("note", &format!("Running on {model}.")));
90 }
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)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 )
Issues and pull requests replace intents and attempts99 .context("could not clone the pull request's fork")?;
Diffs on attempts; hosted agent presented as the g1t agent100 git(workdir, &["config", "user.name", "g1t agent"])?;
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)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
Agents as a team: lifecycle, merge queue, billing and a new shell105 // 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
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)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 {
Agents asked while not at work are woken to answer159 // An agent woken to answer usually only answers.
160 if std::env::var("MODE").as_deref() == Ok("answer") {
161 return Ok(summary);
162 }
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)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 )
Issues and pull requests replace intents and attempts176 .context("could not push the pull request's commits")?;
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)177 reporter.record(Entry::new(
178 "note",
Issues and pull requests replace intents and attempts179 &format!("Pushed {}.", &head[..head.len().min(12)]),
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)180 ));
181 Ok(summary)
182}
183
184fn main() {
Agents as a team: lifecycle, merge queue, billing and a new shell185 // The same image does the other jobs a sandbox is started for.
186 match std::env::var("MODE").as_deref() {
GitHub Actions on g1t, part two: running workflows187 Ok("actions") => std::process::exit(actions::main()),
Agents as a team: lifecycle, merge queue, billing and a new shell188 Ok("checks") => std::process::exit(checks::main()),
Deployments: a preview for every pull request, production on g1t.page189 Ok("deploy") => std::process::exit(deploy::main()),
Agents as a team: lifecycle, merge queue, billing and a new shell190 Ok("update") => std::process::exit(update::main()),
191 Ok("review") => std::process::exit(review::main()),
192 Ok("revise") => std::process::exit(revise::main()),
Agents asked while not at work are woken to answer193 Ok("answer") => std::process::exit(revise::answer()),
Agents as a team: lifecycle, merge queue, billing and a new shell194 Ok("plan") => std::process::exit(plan::main()),
195 Ok("queue") => std::process::exit(queue::main()),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains196 Ok("mergecheck") => std::process::exit(mergecheck::main()),
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request197 Ok("steer") => std::process::exit(steer::main()),
Agents as a team: lifecycle, merge queue, billing and a new shell198 _ => {}
Acceptance checks in sandboxes, line comments and review verdicts199 }
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)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();
Issues and pull requests replace intents and attempts210 if let Err(error) = reporter.ready(&summary) {
211 eprintln!("g1t-runner: could not mark the pull request ready: {error:#}");
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)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();
Issues and pull requests replace intents and attempts219 let _ = reporter.close();
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)220 std::process::exit(1);
221 }
222 }
223}