Skip to main content

base/frozen/
mod.rs

1//! Session-start frozen environment snapshot — the data sources for system prompt
2//! segments [4] and [5].
3//!
4//! All git subcommands have a 1.5 s timeout; failures silently skip the
5//! related field. **Not refreshed during a session** —
6//! mid-session git commits are not updated.
7
8use 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/// 一段 AGENTS.md 文件(路径 + 内容)。多条按"远到近"顺序排列。
16#[derive(Debug, Clone)]
17pub struct MemoryFileEntry {
18    pub path: PathBuf,
19    pub content: String,
20}
21
22/// Git status output character limit.
23const MAX_GIT_STATUS_CHARS: usize = 2000;
24
25/// How long each git subcommand collecting the context may take.
26const GIT_TIMEOUT: Duration = Duration::from_millis(1500);
27
28/// 会话级冻结的环境信息。一次会话只算一次;turn 之间不变。
29#[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    /// 这台机器上用户的 home 目录——和 `platform`/`shell` 一样是**环境事实**,
42    /// 进 system prompt 给模型交代环境,不是 Agix 存东西的地方(那些根一律
43    /// 由调用方注入,见 [`crate::paths::ConfigPaths`])。收进快照而不是在拼
44    /// prompt 时现读,是因为快照可以被测试替换,而 env 不能。
45    pub home_dir: Option<String>,
46    pub today: String,
47    pub memory_blocks: Vec<MemoryFileEntry>,
48    pub user_email: Option<String>,
49    /// 模型写记忆的目录,即 [`crate::memory::MemoryStore::for_paths`] 的全局一层。
50    pub memory_dir: PathBuf,
51    /// 全局与项目两层 `MEMORY.md` 合起来的索引(截到 8 KB),场景的 `memory`
52    /// 提醒带的就是它。
53    pub memory_index: Option<String>,
54    /// Memory file paths already surfaced in prior turns. Used to deduplicate
55    /// and avoid re-injecting the same memories every turn.
56    pub already_surfaced: std::collections::HashSet<String>,
57    /// output style 已加载的内容(`name` 来自 EngineConfig,
58    /// 由 `collect_output_style` 从 user/project 级别 `output-styles/<name>.md`
59    /// 读取)。None = 没指定或文件不存在。
60    pub output_style: Option<OutputStyle>,
61}
62
63/// 一个 output-style 文件的加载结果。注入 system prompt 时用。
64#[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    /// `~/.agix/scenes/<scope>/output-styles/<name>.md`
75    User,
76    /// `<cwd>/<project dir>/output-styles/<name>.md`
77    Project,
78}
79
80/// FrozenContext 收集选项。
81#[derive(Debug, Clone, Default)]
82pub struct CollectOptions {
83    /// 是否在 cwd 之上向上爬找 `AGENTS.md`(含 git root)。默认 true。
84    /// monorepo 子目录不想吃父级 monorepo 上下文时设为 false。
85    pub walk_up_claude_md: bool,
86
87    /// 启动时按名称加载 output style(先项目级再用户级)。
88    /// None = 不加载。
89    pub output_style: Option<String>,
90
91    /// cwd 不是项目(无项目会话的专属工作目录):不跑 git、不找 `AGENTS.md`,
92    /// 项目级的 skills 与 output style 也没有。
93    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
106/// The git-derived subset of `FrozenContext` — factored out so
107/// `FrozenContext::refresh_git` can re-run just this part instead of the
108/// whole `collect_environment`, which also reads the platform and the date.
109struct 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
133/// `git <args>` in `cwd`: its trimmed stdout, or `None` on any failure,
134/// timeout, non-zero exit or empty output.
135async 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
147/// Whether `cwd` is in a work tree, as git says; `Err` when the engine may
148/// not run git there at all.
149async 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
165/// The branch checked out in `cwd`: from git, or where the engine may not run
166/// git, from the repository's `HEAD` file.
167async 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
188/// A worktree has `.git` as a file holding a `gitdir:` line, not a directory.
189async 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
198/// `origin/HEAD` if there is one, else whichever of `main` / `master` exists.
199async 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/// The user's home directory and shell name on this machine.
235#[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        // The engine may not run this repository's git: its branch is all
255        // the snapshot takes, read from `HEAD`.
256        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    /// 收集环境快照里不依赖指令文件、记忆库的那部分:git、平台、home、日期、
299    /// 邮箱、记忆目录。AGENTS.md、记忆索引、output style 由 runtime 填。
300    /// 所有 IO 错误都吞掉转 None / 默认值;这个函数不该 panic、不该 fail。
301    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    /// Re-run just the git-derived fields (branch/status/log/worktree-ness),
349    /// leaving memory/skills/output-style untouched. Exists to partially
350    /// relax this module's "not refreshed during a session" characteristic
351    /// for the one field that goes stale fastest in a long-running session —
352    /// callers are expected to invoke this only after detecting a
353    /// git-mutating command in the turn just completed (see
354    /// `runtime::turn`'s caller), not on every turn: a git status/log/branch
355    /// re-derivation is real subprocess I/O (bounded by the same 1.5s
356    /// per-subcommand timeout `collect_environment` uses), not free.
357    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    /// Re-derive only `git_status` and `git_branch` — the two fields that get
369    /// re-shown to the model on *every* turn (`git_status` through the
370    /// per-turn `<system-reminder>`, `git_branch` through the scene's `<env>`
371    /// block) and therefore the two that must not be a session-start
372    /// snapshot.
373    ///
374    /// A stale git status is worse than an absent one: the model does not
375    /// treat it as a possibly-outdated hint, it treats it as current fact, so
376    /// after a commit it keeps reasoning about files that are no longer dirty
377    /// and re-suggesting work that is already done. The wider
378    /// [`FrozenContext::refresh_git`] fixes that too, but it is called only
379    /// after the *model itself* runs a git-mutating `Bash` command — which
380    /// misses every ordinary cause of drift: the user committing in another
381    /// terminal, an editor writing a file, and the model's own `Write`/`Edit`
382    /// calls, none of which go through `Bash`.
383    ///
384    /// Two subcommands rather than [`refresh_git`](Self::refresh_git)'s six:
385    /// `git log`/`main-branch detection`/`user.name` do not appear in
386    /// anything injected per turn and change far more slowly, so paying for
387    /// them every turn buys nothing. Skips all I/O when the session is not in
388    /// a git repository at all — the common non-repo case stays free.
389    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    /// Roots under a tempdir. Tests never inherit the running user's home.
409    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    /// Nothing scripted: every git the engine asks for fails, as it does
421    /// outside a repository.
422    fn no_git() -> EngineExec {
423        EngineExec::new(
424            crate::interface::exec::ExecProviders::in_process(),
425            Default::default(),
426            Default::default(),
427        )
428    }
429
430    /// The git context is whatever the session's providers answer: its git
431    /// through `exec.process`, its `.git` through `exec.filesystem`.
432    #[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    /// An untrusted project's repository, no sandbox: no git runs, the branch
473    /// comes from `HEAD`.
474    #[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); // YYYY-MM-DD
521                                        // 不在 git 仓库下,is_git=false 且 git_* 字段都 None
522        assert!(!ctx.is_git);
523        assert!(ctx.git_status.is_none());
524    }
525
526    /// Outside a git repository the refresh must cost nothing and invent
527    /// nothing — the common non-repo session pays no subprocess per turn.
528    #[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}