1use crate::engine_exec::{read_head, EngineExec, EngineExecError, GitAccess};
9use crate::paths::ConfigPaths;
10use crate::text::truncate_chars;
11use std::path::{Path, PathBuf};
12use std::time::Duration;
13use time::format_description::well_known::Iso8601;
14
15#[derive(Debug, Clone)]
17pub struct MemoryFileEntry {
18 pub path: PathBuf,
19 pub content: String,
20}
21
22const MAX_GIT_STATUS_CHARS: usize = 2000;
24
25const GIT_TIMEOUT: Duration = Duration::from_millis(1500);
27
28#[derive(Debug, Clone, Default)]
30pub struct FrozenContext {
31 pub cwd: PathBuf,
32 pub is_git: bool,
33 pub is_worktree: bool,
34 pub git_branch: Option<String>,
35 pub git_main_branch: Option<String>,
36 pub git_user_name: Option<String>,
37 pub git_status: Option<String>,
38 pub git_log: Option<String>,
39 pub platform: String,
40 pub shell: Option<String>,
41 pub home_dir: Option<String>,
46 pub today: String,
47 pub memory_blocks: Vec<MemoryFileEntry>,
48 pub user_email: Option<String>,
49 pub memory_dir: PathBuf,
51 pub memory_index: Option<String>,
54 pub already_surfaced: std::collections::HashSet<String>,
57 pub output_style: Option<OutputStyle>,
61}
62
63#[derive(Debug, Clone)]
65pub struct OutputStyle {
66 pub name: String,
67 pub source: OutputStyleSource,
68 pub content: String,
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72#[non_exhaustive]
73pub enum OutputStyleSource {
74 User,
76 Project,
78}
79
80#[derive(Debug, Clone, Default)]
82pub struct CollectOptions {
83 pub walk_up_claude_md: bool,
86
87 pub output_style: Option<String>,
90
91 pub outside_project: bool,
94}
95
96impl CollectOptions {
97 pub fn defaults() -> Self {
98 Self {
99 walk_up_claude_md: true,
100 output_style: None,
101 outside_project: false,
102 }
103 }
104}
105
106struct GitFields {
110 is_git: bool,
111 is_worktree: bool,
112 git_branch: Option<String>,
113 git_main_branch: Option<String>,
114 git_user_name: Option<String>,
115 git_status: Option<String>,
116 git_log: Option<String>,
117}
118
119impl GitFields {
120 fn none() -> Self {
121 Self {
122 is_git: false,
123 is_worktree: false,
124 git_branch: None,
125 git_main_branch: None,
126 git_user_name: None,
127 git_status: None,
128 git_log: None,
129 }
130 }
131}
132
133async fn run_git_text(engine: &EngineExec, cwd: &Path, args: &[&str]) -> Option<String> {
136 let out = engine
137 .git(cwd, GitAccess::ReadOnly, args, GIT_TIMEOUT)
138 .await
139 .ok()?;
140 if !out.status.success {
141 return None;
142 }
143 let s = out.stdout_lossy().trim().to_string();
144 (!s.is_empty()).then_some(s)
145}
146
147async fn run_git_check(engine: &EngineExec, cwd: &Path) -> Result<bool, EngineExecError> {
150 match engine
151 .git(
152 cwd,
153 GitAccess::ReadOnly,
154 &["rev-parse", "--is-inside-work-tree"],
155 GIT_TIMEOUT,
156 )
157 .await
158 {
159 Err(refused @ EngineExecError::Refused(_)) => Err(refused),
160 Err(_) => Ok(false),
161 Ok(out) => Ok(out.status.success && out.stdout_lossy().trim() == "true"),
162 }
163}
164
165async fn current_branch(engine: &EngineExec, cwd: &Path) -> Option<String> {
168 match engine
169 .git(
170 cwd,
171 GitAccess::ReadOnly,
172 &["symbolic-ref", "--short", "HEAD"],
173 GIT_TIMEOUT,
174 )
175 .await
176 {
177 Err(EngineExecError::Refused(_)) => {
178 read_head(&*engine.exec().filesystem, cwd).await?.branch
179 }
180 Err(_) => None,
181 Ok(out) => {
182 let branch = out.stdout_lossy().trim().to_string();
183 (out.status.success && !branch.is_empty()).then_some(branch)
184 }
185 }
186}
187
188async fn is_worktree(engine: &EngineExec, cwd: &Path) -> bool {
190 engine
191 .exec()
192 .filesystem
193 .read_to_string(&cwd.join(".git"))
194 .await
195 .is_ok_and(|content| content.trim().starts_with("gitdir:"))
196}
197
198async fn detect_main_branch(engine: &EngineExec, cwd: &Path) -> Option<String> {
200 if let Some(out) = run_git_text(
201 engine,
202 cwd,
203 &["symbolic-ref", "--short", "refs/remotes/origin/HEAD"],
204 )
205 .await
206 {
207 if let Some(name) = out.strip_prefix("origin/") {
208 return Some(name.to_string());
209 }
210 return Some(out);
211 }
212 for &cand in &["main", "master"] {
213 let exists = engine
214 .git(
215 cwd,
216 GitAccess::ReadOnly,
217 &[
218 "show-ref",
219 "--verify",
220 "--quiet",
221 &format!("refs/heads/{cand}"),
222 ],
223 GIT_TIMEOUT,
224 )
225 .await
226 .is_ok_and(|out| out.status.success);
227 if exists {
228 return Some(cand.to_string());
229 }
230 }
231 None
232}
233
234#[expect(
236 clippy::disallowed_methods,
237 reason = "the shell is a fact about the machine the prompt describes"
238)]
239fn home_and_shell() -> (Option<String>, Option<String>) {
240 let home_dir = crate::paths::home_dir().map(|h| h.display().to_string());
241 let shell = std::env::var("SHELL").ok().map(|p| {
242 Path::new(&p)
243 .file_name()
244 .map(|n| n.to_string_lossy().to_string())
245 .unwrap_or(p)
246 });
247 (home_dir, shell)
248}
249
250async fn collect_git_fields(engine_git: &EngineExec, cwd: &Path) -> GitFields {
251 match run_git_check(engine_git, cwd).await {
252 Ok(true) => {}
253 Ok(false) => return GitFields::none(),
254 Err(_) => {
257 let Some(head) = read_head(&*engine_git.exec().filesystem, cwd).await else {
258 return GitFields::none();
259 };
260 return GitFields {
261 is_git: true,
262 is_worktree: head.linked,
263 git_branch: head.branch,
264 ..GitFields::none()
265 };
266 }
267 }
268 let is_git = true;
269 let is_worktree = is_worktree(engine_git, cwd).await;
270 let git_branch = current_branch(engine_git, cwd).await;
271 let git_main_branch = detect_main_branch(engine_git, cwd).await;
272 let git_user_name = run_git_text(engine_git, cwd, &["config", "user.name"]).await;
273 let git_status = run_git_text(
274 engine_git,
275 cwd,
276 &["--no-optional-locks", "status", "--short"],
277 )
278 .await
279 .map(|s| truncate_chars(&s, MAX_GIT_STATUS_CHARS, "\n... (truncated)"));
280 let git_log = run_git_text(
281 engine_git,
282 cwd,
283 &["--no-optional-locks", "log", "--oneline", "-n", "5"],
284 )
285 .await;
286 GitFields {
287 is_git,
288 is_worktree,
289 git_branch,
290 git_main_branch,
291 git_user_name,
292 git_status,
293 git_log,
294 }
295}
296
297impl FrozenContext {
298 pub async fn collect_environment(
302 cwd: PathBuf,
303 opts: &CollectOptions,
304 paths: &ConfigPaths,
305 environment: &dyn crate::interface::environment::Environment,
306 engine_git: &EngineExec,
307 ) -> Self {
308 let project = (!opts.outside_project).then_some(cwd.as_path());
309 let git = match project {
310 Some(project) => collect_git_fields(engine_git, project).await,
311 None => GitFields::none(),
312 };
313
314 let (home_dir, shell) = home_and_shell();
315
316 let today = environment
317 .now()
318 .format(&Iso8601::DATE)
319 .unwrap_or_else(|_| "unknown".to_string());
320
321 let user_email = if git.is_git {
322 run_git_text(engine_git, &cwd, &["config", "user.email"]).await
323 } else {
324 None
325 };
326
327 Self {
328 is_git: git.is_git,
329 is_worktree: git.is_worktree,
330 git_branch: git.git_branch,
331 git_main_branch: git.git_main_branch,
332 git_user_name: git.git_user_name,
333 git_status: git.git_status,
334 git_log: git.git_log,
335 platform: std::env::consts::OS.to_string(),
336 shell,
337 home_dir,
338 today,
339 user_email,
340 memory_dir: paths.global_memory_dir(),
341 cwd,
342 ..Self::default()
343 }
344 }
345}
346
347impl FrozenContext {
348 pub async fn refresh_git(&mut self, engine_git: &EngineExec) {
358 let git = collect_git_fields(engine_git, &self.cwd).await;
359 self.is_git = git.is_git;
360 self.is_worktree = git.is_worktree;
361 self.git_branch = git.git_branch;
362 self.git_main_branch = git.git_main_branch;
363 self.git_user_name = git.git_user_name;
364 self.git_status = git.git_status;
365 self.git_log = git.git_log;
366 }
367
368 pub async fn refresh_git_status(&mut self, engine_git: &EngineExec) {
390 if !self.is_git {
391 return;
392 }
393 self.git_branch = current_branch(engine_git, &self.cwd).await;
394 self.git_status = run_git_text(
395 engine_git,
396 &self.cwd,
397 &["--no-optional-locks", "status", "--short"],
398 )
399 .await
400 .map(|s| truncate_chars(&s, MAX_GIT_STATUS_CHARS, "\n... (truncated)"));
401 }
402}
403
404#[cfg(test)]
405mod tests {
406 use super::*;
407
408 fn test_paths(root: &Path) -> ConfigPaths {
410 ConfigPaths::new(
411 root.join(".agix"),
412 root.join(".agix"),
413 "code",
414 Default::default(),
415 )
416 }
417
418 use tempfile::TempDir;
419
420 fn no_git() -> EngineExec {
423 EngineExec::new(
424 crate::interface::exec::ExecProviders::in_process(),
425 Default::default(),
426 Default::default(),
427 )
428 }
429
430 #[tokio::test]
433 async fn the_git_context_comes_from_the_sessions_providers() {
434 use crate::engine_exec::ENGINE_GIT_OPTIONS;
435 use crate::interface::exec::in_process::{
436 InMemoryFileSystem, ScriptedProcess, ScriptedRun,
437 };
438 let dir = TempDir::new().unwrap();
439 let git = |args: &str| format!("git {} {args}", ENGINE_GIT_OPTIONS.join(" "));
440 let process = ScriptedProcess::new()
441 .with(
442 git("rev-parse --is-inside-work-tree"),
443 ScriptedRun::ok("true\n"),
444 )
445 .with(git("symbolic-ref --short HEAD"), ScriptedRun::ok("topic\n"))
446 .with(
447 git("--no-optional-locks status --short"),
448 ScriptedRun::ok(" M a.rs\n"),
449 );
450 let exec = crate::interface::exec::ExecProviders {
451 process: std::sync::Arc::new(process.clone()),
452 filesystem: std::sync::Arc::new(
453 InMemoryFileSystem::new().with_file(dir.path().join(".git"), "gitdir: /x\n"),
454 ),
455 ..crate::interface::exec::ExecProviders::in_process()
456 };
457 let ctx = FrozenContext::collect_environment(
458 dir.path().to_path_buf(),
459 &CollectOptions::defaults(),
460 &test_paths(dir.path()),
461 &crate::interface::environment::SystemEnvironment,
462 &EngineExec::new(exec, Default::default(), Default::default()),
463 )
464 .await;
465 assert!(ctx.is_git);
466 assert!(ctx.is_worktree);
467 assert_eq!(ctx.git_branch.as_deref(), Some("topic"));
468 assert_eq!(ctx.git_status.as_deref(), Some("M a.rs"));
469 assert!(process.seen().iter().all(|argv| argv.starts_with(&git(""))));
470 }
471
472 #[tokio::test]
475 async fn an_untrusted_repository_outside_a_sandbox_gives_only_its_branch() {
476 use crate::interface::exec::in_process::{InMemoryFileSystem, ScriptedProcess};
477 let dir = TempDir::new().unwrap();
478 let process = ScriptedProcess::new();
479 let exec = crate::interface::exec::ExecProviders {
480 process: std::sync::Arc::new(process.clone()),
481 filesystem: std::sync::Arc::new(
482 InMemoryFileSystem::new()
483 .with_file(dir.path().join(".git/HEAD"), "ref: refs/heads/topic\n"),
484 ),
485 ..crate::interface::exec::ExecProviders::in_process()
486 };
487 let engine = EngineExec::new(
488 exec,
489 crate::engine_exec::Confinement::Unconfined,
490 crate::permission::ProjectTrust::Untrusted,
491 );
492 let mut ctx = FrozenContext::collect_environment(
493 dir.path().to_path_buf(),
494 &CollectOptions::defaults(),
495 &test_paths(dir.path()),
496 &crate::interface::environment::SystemEnvironment,
497 &engine,
498 )
499 .await;
500 assert!(ctx.is_git);
501 assert_eq!(ctx.git_branch.as_deref(), Some("topic"));
502 assert!(ctx.git_status.is_none() && ctx.git_log.is_none() && ctx.user_email.is_none());
503 ctx.refresh_git_status(&engine).await;
504 assert_eq!(ctx.git_branch.as_deref(), Some("topic"));
505 assert!(process.seen().is_empty(), "git ran: {:?}", process.seen());
506 }
507
508 #[tokio::test]
509 async fn collects_basic_fields_for_arbitrary_dir() {
510 let dir = TempDir::new().unwrap();
511 let ctx = FrozenContext::collect_environment(
512 dir.path().to_path_buf(),
513 &CollectOptions::defaults(),
514 &test_paths(dir.path()),
515 &crate::interface::environment::SystemEnvironment,
516 &no_git(),
517 )
518 .await;
519 assert!(!ctx.platform.is_empty());
520 assert!(ctx.today.len() == 10); assert!(!ctx.is_git);
523 assert!(ctx.git_status.is_none());
524 }
525
526 #[tokio::test]
529 async fn refresh_git_status_is_a_noop_outside_a_repo() {
530 let dir = TempDir::new().unwrap();
531 let mut ctx = FrozenContext::collect_environment(
532 dir.path().to_path_buf(),
533 &CollectOptions::defaults(),
534 &test_paths(dir.path()),
535 &crate::interface::environment::SystemEnvironment,
536 &no_git(),
537 )
538 .await;
539 assert!(!ctx.is_git);
540 ctx.refresh_git_status(&no_git()).await;
541 assert!(ctx.git_status.is_none());
542 assert!(ctx.git_branch.is_none());
543 }
544}