Skip to main content

session_core/
turn_checkpoints.rs

1//! Working-tree checkpoints of a root's turns (Rust-only feature; see docs/rust-rewrite/features.md): each root turn
2//! records the working tree as an unreferenced commit (crates/delegation `checkpoints`) under its key
3//! (crates/session-journal `checkpoints`), before the turn runs: the native root under its prompt entry
4//! (crate::core), an external root (`ultron claude`) under its turn id.
5//!
6//! Settings: `checkpoints.enabled` (default true; only Git or jj working trees record anything),
7//! `checkpoints.maxFiles`, `checkpoints.maxFileBytes`. Off while the shell sandbox is on (`sandbox.mode` other than
8//! `off`): the checkpoint's Git runs on the host, outside the sandbox, and would obey hooks, filters and the
9//! fsmonitor that sandboxed code can write into the repository's config (Mirror disables checkpoints in a sandbox
10//! for the same reason).
11
12use crate::durable_store::{SharedSession, lock};
13use crate::lane::Lane;
14use delegation::checkpoints::{self as vcs, Capture, Checkpoint, Limits};
15use serde_json::{Value, json};
16use session_journal::checkpoints as stored;
17use std::path::PathBuf;
18
19/// What a turn's checkpoint needs: where, under which settings, with which `jj` (from the session's PATH).
20pub struct TurnCheckpoints {
21    pub session: SharedSession,
22    pub cwd: PathBuf,
23    /// The merged settings' `checkpoints` object.
24    pub settings: Value,
25    pub sandboxed: bool,
26    pub jj: Option<PathBuf>,
27}
28
29impl TurnCheckpoints {
30    /// The checkpoints of `lane`'s turns in `cwd`, under the merged `settings`, with `jj` from the session's `path`.
31    pub fn of_lane(session: SharedSession, cwd: PathBuf, settings: &Value, lane: &Lane, path: Option<&str>) -> Self {
32        let sandboxed = lane
33            .stack
34            .host
35            .launcher()
36            .is_some_and(|launcher| launcher.mode != sandbox::settings::Mode::Off);
37        TurnCheckpoints {
38            session,
39            cwd,
40            settings: settings["checkpoints"].clone(),
41            sandboxed,
42            jj: on_path(path, "jj"),
43        }
44    }
45
46    pub fn enabled(&self) -> bool {
47        self.settings["enabled"] != false && !self.sandboxed
48    }
49
50    pub fn limits(&self) -> Limits {
51        let defaults = Limits::default();
52        Limits {
53            max_files: self.settings["maxFiles"]
54                .as_u64()
55                .map_or(defaults.max_files, |n| n as usize),
56            max_file_bytes: self.settings["maxFileBytes"]
57                .as_u64()
58                .unwrap_or(defaults.max_file_bytes),
59        }
60    }
61
62    /// Record the working tree for the turn `key` before it runs, the record naming the turn as `field` (`entryId`
63    /// or `turn`). Never fails the turn: a tree that could not be recorded keeps a note instead.
64    pub fn record(&self, field: &str, key: &str) {
65        if !self.enabled() || key.is_empty() {
66            return;
67        }
68        let previous = stored::latest_taken(&lock(&self.session)).and_then(|v| Checkpoint::from_json(&v));
69        let captured = vcs::capture(&self.cwd, previous.as_ref(), &self.limits(), self.jj.as_deref());
70        let mut value = match captured {
71            Ok(Capture::Outside) => return,
72            Ok(Capture::Taken(checkpoint)) => checkpoint.to_json(),
73            Ok(Capture::Unchanged(checkpoint)) => {
74                let mut value = checkpoint.to_json();
75                value["unchanged"] = json!(true);
76                value
77            }
78            Ok(Capture::Skipped(note)) | Err(note) => json!({"skipped": note}),
79        };
80        value["kind"] = json!("turn");
81        value[field] = json!(key);
82        value["createdAt"] = json!(jsrt::date::now_ms());
83        let _ = stored::put(&mut lock(&self.session), key, value);
84    }
85}
86
87/// The first executable `name` on `path` (the session's PATH, never the process's).
88pub fn on_path(path: Option<&str>, name: &str) -> Option<PathBuf> {
89    use std::os::unix::fs::PermissionsExt;
90    std::env::split_paths(path?)
91        .map(|dir| dir.join(name))
92        .find(|candidate| {
93            std::fs::metadata(candidate).is_ok_and(|meta| meta.is_file() && meta.permissions().mode() & 0o111 != 0)
94        })
95}