use crate::engine_exec::{read_head, EngineExec, EngineExecError, GitAccess};
use crate::paths::ConfigPaths;
use crate::text::truncate_chars;
use std::path::{Path, PathBuf};
use std::time::Duration;
use time::format_description::well_known::Iso8601;
#[derive(Debug, Clone)]
pub struct MemoryFileEntry {
pub path: PathBuf,
pub content: String,
}
const MAX_GIT_STATUS_CHARS: usize = 2000;
const GIT_TIMEOUT: Duration = Duration::from_millis(1500);
#[derive(Debug, Clone, Default)]
pub struct FrozenContext {
pub cwd: PathBuf,
pub is_git: bool,
pub is_worktree: bool,
pub git_branch: Option<String>,
pub git_main_branch: Option<String>,
pub git_user_name: Option<String>,
pub git_status: Option<String>,
pub git_log: Option<String>,
pub platform: String,
pub shell: Option<String>,
pub home_dir: Option<String>,
pub today: String,
pub memory_blocks: Vec<MemoryFileEntry>,
pub user_email: Option<String>,
pub memory_dir: PathBuf,
pub memory_index: Option<String>,
pub already_surfaced: std::collections::HashSet<String>,
pub output_style: Option<OutputStyle>,
}
#[derive(Debug, Clone)]
pub struct OutputStyle {
pub name: String,
pub source: OutputStyleSource,
pub content: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum OutputStyleSource {
User,
Project,
}
#[derive(Debug, Clone, Default)]
pub struct CollectOptions {
pub walk_up_claude_md: bool,
pub output_style: Option<String>,
pub outside_project: bool,
}
impl CollectOptions {
pub fn defaults() -> Self {
Self {
walk_up_claude_md: true,
output_style: None,
outside_project: false,
}
}
}
struct GitFields {
is_git: bool,
is_worktree: bool,
git_branch: Option<String>,
git_main_branch: Option<String>,
git_user_name: Option<String>,
git_status: Option<String>,
git_log: Option<String>,
}
impl GitFields {
fn none() -> Self {
Self {
is_git: false,
is_worktree: false,
git_branch: None,
git_main_branch: None,
git_user_name: None,
git_status: None,
git_log: None,
}
}
}
async fn run_git_text(engine: &EngineExec, cwd: &Path, args: &[&str]) -> Option<String> {
let out = engine
.git(cwd, GitAccess::ReadOnly, args, GIT_TIMEOUT)
.await
.ok()?;
if !out.status.success {
return None;
}
let s = out.stdout_lossy().trim().to_string();
(!s.is_empty()).then_some(s)
}
async fn run_git_check(engine: &EngineExec, cwd: &Path) -> Result<bool, EngineExecError> {
match engine
.git(
cwd,
GitAccess::ReadOnly,
&["rev-parse", "--is-inside-work-tree"],
GIT_TIMEOUT,
)
.await
{
Err(refused @ EngineExecError::Refused(_)) => Err(refused),
Err(_) => Ok(false),
Ok(out) => Ok(out.status.success && out.stdout_lossy().trim() == "true"),
}
}
async fn current_branch(engine: &EngineExec, cwd: &Path) -> Option<String> {
match engine
.git(
cwd,
GitAccess::ReadOnly,
&["symbolic-ref", "--short", "HEAD"],
GIT_TIMEOUT,
)
.await
{
Err(EngineExecError::Refused(_)) => {
read_head(&*engine.exec().filesystem, cwd).await?.branch
}
Err(_) => None,
Ok(out) => {
let branch = out.stdout_lossy().trim().to_string();
(out.status.success && !branch.is_empty()).then_some(branch)
}
}
}
async fn is_worktree(engine: &EngineExec, cwd: &Path) -> bool {
engine
.exec()
.filesystem
.read_to_string(&cwd.join(".git"))
.await
.is_ok_and(|content| content.trim().starts_with("gitdir:"))
}
async fn detect_main_branch(engine: &EngineExec, cwd: &Path) -> Option<String> {
if let Some(out) = run_git_text(
engine,
cwd,
&["symbolic-ref", "--short", "refs/remotes/origin/HEAD"],
)
.await
{
if let Some(name) = out.strip_prefix("origin/") {
return Some(name.to_string());
}
return Some(out);
}
for &cand in &["main", "master"] {
let exists = engine
.git(
cwd,
GitAccess::ReadOnly,
&[
"show-ref",
"--verify",
"--quiet",
&format!("refs/heads/{cand}"),
],
GIT_TIMEOUT,
)
.await
.is_ok_and(|out| out.status.success);
if exists {
return Some(cand.to_string());
}
}
None
}
#[expect(
clippy::disallowed_methods,
reason = "the shell is a fact about the machine the prompt describes"
)]
fn home_and_shell() -> (Option<String>, Option<String>) {
let home_dir = crate::paths::home_dir().map(|h| h.display().to_string());
let shell = std::env::var("SHELL").ok().map(|p| {
Path::new(&p)
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or(p)
});
(home_dir, shell)
}
async fn collect_git_fields(engine_git: &EngineExec, cwd: &Path) -> GitFields {
match run_git_check(engine_git, cwd).await {
Ok(true) => {}
Ok(false) => return GitFields::none(),
Err(_) => {
let Some(head) = read_head(&*engine_git.exec().filesystem, cwd).await else {
return GitFields::none();
};
return GitFields {
is_git: true,
is_worktree: head.linked,
git_branch: head.branch,
..GitFields::none()
};
}
}
let is_git = true;
let is_worktree = is_worktree(engine_git, cwd).await;
let git_branch = current_branch(engine_git, cwd).await;
let git_main_branch = detect_main_branch(engine_git, cwd).await;
let git_user_name = run_git_text(engine_git, cwd, &["config", "user.name"]).await;
let git_status = run_git_text(
engine_git,
cwd,
&["--no-optional-locks", "status", "--short"],
)
.await
.map(|s| truncate_chars(&s, MAX_GIT_STATUS_CHARS, "\n... (truncated)"));
let git_log = run_git_text(
engine_git,
cwd,
&["--no-optional-locks", "log", "--oneline", "-n", "5"],
)
.await;
GitFields {
is_git,
is_worktree,
git_branch,
git_main_branch,
git_user_name,
git_status,
git_log,
}
}
impl FrozenContext {
pub async fn collect_environment(
cwd: PathBuf,
opts: &CollectOptions,
paths: &ConfigPaths,
environment: &dyn crate::interface::environment::Environment,
engine_git: &EngineExec,
) -> Self {
let project = (!opts.outside_project).then_some(cwd.as_path());
let git = match project {
Some(project) => collect_git_fields(engine_git, project).await,
None => GitFields::none(),
};
let (home_dir, shell) = home_and_shell();
let today = environment
.now()
.format(&Iso8601::DATE)
.unwrap_or_else(|_| "unknown".to_string());
let user_email = if git.is_git {
run_git_text(engine_git, &cwd, &["config", "user.email"]).await
} else {
None
};
Self {
is_git: git.is_git,
is_worktree: git.is_worktree,
git_branch: git.git_branch,
git_main_branch: git.git_main_branch,
git_user_name: git.git_user_name,
git_status: git.git_status,
git_log: git.git_log,
platform: std::env::consts::OS.to_string(),
shell,
home_dir,
today,
user_email,
memory_dir: paths.global_memory_dir(),
cwd,
..Self::default()
}
}
}
impl FrozenContext {
pub async fn refresh_git(&mut self, engine_git: &EngineExec) {
let git = collect_git_fields(engine_git, &self.cwd).await;
self.is_git = git.is_git;
self.is_worktree = git.is_worktree;
self.git_branch = git.git_branch;
self.git_main_branch = git.git_main_branch;
self.git_user_name = git.git_user_name;
self.git_status = git.git_status;
self.git_log = git.git_log;
}
pub async fn refresh_git_status(&mut self, engine_git: &EngineExec) {
if !self.is_git {
return;
}
self.git_branch = current_branch(engine_git, &self.cwd).await;
self.git_status = run_git_text(
engine_git,
&self.cwd,
&["--no-optional-locks", "status", "--short"],
)
.await
.map(|s| truncate_chars(&s, MAX_GIT_STATUS_CHARS, "\n... (truncated)"));
}
}
#[cfg(test)]
mod tests {
use super::*;
fn test_paths(root: &Path) -> ConfigPaths {
ConfigPaths::new(
root.join(".agix"),
root.join(".agix"),
"code",
Default::default(),
)
}
use tempfile::TempDir;
fn no_git() -> EngineExec {
EngineExec::new(
crate::interface::exec::ExecProviders::in_process(),
Default::default(),
Default::default(),
)
}
#[tokio::test]
async fn the_git_context_comes_from_the_sessions_providers() {
use crate::engine_exec::ENGINE_GIT_OPTIONS;
use crate::interface::exec::in_process::{
InMemoryFileSystem, ScriptedProcess, ScriptedRun,
};
let dir = TempDir::new().unwrap();
let git = |args: &str| format!("git {} {args}", ENGINE_GIT_OPTIONS.join(" "));
let process = ScriptedProcess::new()
.with(
git("rev-parse --is-inside-work-tree"),
ScriptedRun::ok("true\n"),
)
.with(git("symbolic-ref --short HEAD"), ScriptedRun::ok("topic\n"))
.with(
git("--no-optional-locks status --short"),
ScriptedRun::ok(" M a.rs\n"),
);
let exec = crate::interface::exec::ExecProviders {
process: std::sync::Arc::new(process.clone()),
filesystem: std::sync::Arc::new(
InMemoryFileSystem::new().with_file(dir.path().join(".git"), "gitdir: /x\n"),
),
..crate::interface::exec::ExecProviders::in_process()
};
let ctx = FrozenContext::collect_environment(
dir.path().to_path_buf(),
&CollectOptions::defaults(),
&test_paths(dir.path()),
&crate::interface::environment::SystemEnvironment,
&EngineExec::new(exec, Default::default(), Default::default()),
)
.await;
assert!(ctx.is_git);
assert!(ctx.is_worktree);
assert_eq!(ctx.git_branch.as_deref(), Some("topic"));
assert_eq!(ctx.git_status.as_deref(), Some("M a.rs"));
assert!(process.seen().iter().all(|argv| argv.starts_with(&git(""))));
}
#[tokio::test]
async fn an_untrusted_repository_outside_a_sandbox_gives_only_its_branch() {
use crate::interface::exec::in_process::{InMemoryFileSystem, ScriptedProcess};
let dir = TempDir::new().unwrap();
let process = ScriptedProcess::new();
let exec = crate::interface::exec::ExecProviders {
process: std::sync::Arc::new(process.clone()),
filesystem: std::sync::Arc::new(
InMemoryFileSystem::new()
.with_file(dir.path().join(".git/HEAD"), "ref: refs/heads/topic\n"),
),
..crate::interface::exec::ExecProviders::in_process()
};
let engine = EngineExec::new(
exec,
crate::engine_exec::Confinement::Unconfined,
crate::permission::ProjectTrust::Untrusted,
);
let mut ctx = FrozenContext::collect_environment(
dir.path().to_path_buf(),
&CollectOptions::defaults(),
&test_paths(dir.path()),
&crate::interface::environment::SystemEnvironment,
&engine,
)
.await;
assert!(ctx.is_git);
assert_eq!(ctx.git_branch.as_deref(), Some("topic"));
assert!(ctx.git_status.is_none() && ctx.git_log.is_none() && ctx.user_email.is_none());
ctx.refresh_git_status(&engine).await;
assert_eq!(ctx.git_branch.as_deref(), Some("topic"));
assert!(process.seen().is_empty(), "git ran: {:?}", process.seen());
}
#[tokio::test]
async fn collects_basic_fields_for_arbitrary_dir() {
let dir = TempDir::new().unwrap();
let ctx = FrozenContext::collect_environment(
dir.path().to_path_buf(),
&CollectOptions::defaults(),
&test_paths(dir.path()),
&crate::interface::environment::SystemEnvironment,
&no_git(),
)
.await;
assert!(!ctx.platform.is_empty());
assert!(ctx.today.len() == 10); assert!(!ctx.is_git);
assert!(ctx.git_status.is_none());
}
#[tokio::test]
async fn refresh_git_status_is_a_noop_outside_a_repo() {
let dir = TempDir::new().unwrap();
let mut ctx = FrozenContext::collect_environment(
dir.path().to_path_buf(),
&CollectOptions::defaults(),
&test_paths(dir.path()),
&crate::interface::environment::SystemEnvironment,
&no_git(),
)
.await;
assert!(!ctx.is_git);
ctx.refresh_git_status(&no_git()).await;
assert!(ctx.git_status.is_none());
assert!(ctx.git_branch.is_none());
}
}