pr_01m47d15m3e54sn21z27rpy5n9/crates/runner/src/main.rs

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