Skip to main content

surjection_core/apply/
mod.rs

1//! Apply engine (SPEC 8): reconcile client files with the store's desired
2//! state through a plan, own exactly what was written (the ledger), commit
3//! every run to the store, and roll a run back.
4//!
5//! - [`render`]: the system layer, rendered per client.
6//! - [`plan`]: the SPEC 8.3 planning table, per file.
7//! - [`exec`]: SPEC 8.4 execution (re-plan, backup, self check, atomic
8//!   compare-and-swap write, ledger, journal) and the apply commit (8.7).
9//! - [`ledger`], [`backup`], [`journal`]: machine-local records.
10//! - [`import`]: native entries into the store (8.6).
11//! - [`rollback`]: one-click rollback of an apply run (8.7).
12//!
13//! Project scopes come from project manifests through [`crate::layering`];
14//! the planner turns them into project and project-local targets.
15
16pub mod backup;
17pub mod cache;
18pub mod discard;
19pub mod exec;
20pub mod import;
21pub mod journal;
22pub mod ledger;
23pub mod plan;
24pub mod render;
25pub mod resolve;
26pub mod rollback;
27pub mod unmanaged;
28
29use std::path::{Path, PathBuf};
30use std::sync::Arc;
31
32use crate::adapters::ADAPTERS;
33use crate::adapters::detect::RegistryProbe;
34use crate::adapters::location::Location;
35use crate::env::{Env, KnownFolder, Os};
36use crate::error::{CoreError, ErrorCode};
37use crate::fs::Fs;
38use crate::paths::SurjectionHome;
39use crate::secrets::delivery::DeliveryEnv;
40use crate::secrets::scanner::SecretMemory;
41
42pub use exec::{
43    ApplyReport, ApplyRequest, ApplyStatus, TargetResult, Touched, apply_in, instant_apply,
44    preview, run,
45};
46pub use plan::{
47    Action, Decision, EntryFilter, EntryPlan, EntryState, OnConflict, Plan, PlanOptions,
48    ProjectSelection, ScopeFilter, TargetFilter, TargetPlan,
49};
50
51/// What an apply runs against.
52#[derive(Clone, Copy)]
53pub struct ApplyEnv<'a> {
54    pub env: &'a Env,
55    pub fs: &'a dyn Fs,
56    pub home: &'a SurjectionHome,
57    /// For `all-detected` enablement; the CLI passes a registry-free probe.
58    pub registry: &'a dyn RegistryProbe,
59    /// Secret providers and the `surject` launcher (SPEC 11.4).
60    pub delivery: &'a DeliveryEnv,
61}
62
63impl<'a> ApplyEnv<'a> {
64    /// The render context; values read while rendering go to `memory` (the
65    /// store's [`SecretMemory`]).
66    pub fn render_cx(&self, memory: Arc<SecretMemory>) -> render::RenderCx<'a> {
67        render::RenderCx {
68            env: self.env,
69            fs: self.fs,
70            surjection_home: &self.home.path,
71            registry: self.registry,
72            delivery: self.delivery,
73            memory,
74            probes: None,
75        }
76    }
77}
78
79/// `.<name>.surjection-<random>.tmp` next to `file` (SPEC 8.4 step 4).
80pub(crate) fn temp_path(file: &Path) -> Result<PathBuf, CoreError> {
81    let mut random = [0u8; 4];
82    getrandom::fill(&mut random).map_err(|err| {
83        CoreError::new(
84            ErrorCode::IoError,
85            format!("cannot read random bytes: {err}"),
86        )
87    })?;
88    let suffix: String = random.iter().map(|byte| format!("{byte:02x}")).collect();
89    let name = file
90        .file_name()
91        .map(|name| name.to_string_lossy().into_owned())
92        .unwrap_or_default();
93    Ok(file.with_file_name(format!(".{name}.surjection-{suffix}.tmp")))
94}
95
96/// Writes a machine-local state file atomically: a temp file in the same
97/// directory, then a replace. Surjection's own files: a failure is always
98/// `io_error`, never `read_only_target` (that names files of the user's
99/// tools, SPEC 8.2).
100pub(crate) fn write_atomic(fs: &dyn Fs, path: &Path, bytes: &[u8]) -> Result<(), CoreError> {
101    write_atomic_with(fs, path, bytes, &|what, at, err| {
102        CoreError::new(ErrorCode::IoError, format!("{what}: {err}")).with_path(at)
103    })
104}
105
106/// [`write_atomic`] for a file of a project (its repository's
107/// `info/exclude`): a write refused as read only is `read_only_target`.
108pub(crate) fn write_atomic_project(
109    fs: &dyn Fs,
110    path: &Path,
111    bytes: &[u8],
112) -> Result<(), CoreError> {
113    write_atomic_with(fs, path, bytes, &|what, at, err| {
114        crate::access::write_error(fs, what, at, &err)
115    })
116}
117
118fn write_atomic_with(
119    fs: &dyn Fs,
120    path: &Path,
121    bytes: &[u8],
122    io: &dyn Fn(&str, &Path, std::io::Error) -> CoreError,
123) -> Result<(), CoreError> {
124    if let Some(dir) = path.parent() {
125        fs.create_dir_all(dir)
126            .map_err(|err| io("cannot create directory", dir, err))?;
127    }
128    let temp = temp_path(path)?;
129    let like = fs.exists(path).then_some(path);
130    fs.write_new(&temp, bytes, like)
131        .map_err(|err| io("cannot write file", &temp, err))?;
132    fs.replace(&temp, path).map_err(|err| {
133        let _ = fs.remove_file(&temp);
134        io("cannot replace file", path, err)
135    })
136}
137
138/// `file` with a placeholder root for the store (`machines/*.applied.toml`
139/// must not hold personal paths): the longest of the project folder
140/// (`<P>/.mcp.json`), the client override variables in force
141/// (`$CODEX_HOME/config.toml`), the Windows app data folders
142/// (`%APPDATA%/Claude/...`), `$XDG_CONFIG_HOME` and `~`. A file under none
143/// of them is `$EXTERNAL/<file name>`.
144pub fn placeholder_path(env: &Env, file: &Path, project: Option<&Path>) -> String {
145    let windows = env.os() == Os::Windows;
146    let spell = |name: &str| {
147        if windows {
148            format!("%{name}%")
149        } else {
150            format!("${name}")
151        }
152    };
153    let mut bases: Vec<(String, PathBuf)> = vec![("~".to_owned(), env.home().to_path_buf())];
154    if let Some(project) = project {
155        bases.push(("<P>".to_owned(), project.to_path_buf()));
156    }
157    if windows {
158        for (name, folder) in [
159            ("APPDATA", KnownFolder::RoamingAppData),
160            ("LOCALAPPDATA", KnownFolder::LocalAppData),
161        ] {
162            if let Some(path) = env.known_folder(folder) {
163                bases.push((spell(name), path.to_path_buf()));
164            }
165        }
166    }
167    let mut vars = vec!["XDG_CONFIG_HOME"];
168    for spec in ADAPTERS {
169        if let Some(mcp) = &spec.mcp {
170            for location in mcp
171                .user
172                .iter()
173                .chain(mcp.project_local)
174                .chain(mcp.user_mirrors)
175            {
176                location_vars(location, &mut vars);
177            }
178        }
179    }
180    for var in vars {
181        if let Some(path) = env
182            .var(var)
183            .map(PathBuf::from)
184            .filter(|path| path.is_absolute())
185        {
186            bases.push((spell(var), path));
187        }
188    }
189    let best = bases
190        .iter()
191        .filter_map(|(name, base)| file.strip_prefix(base).ok().map(|rest| (name, base, rest)))
192        .max_by_key(|(_, base, _)| base.components().count());
193    match best {
194        Some((name, _, rest)) => {
195            let rest: Vec<String> = rest
196                .components()
197                .map(|part| part.as_os_str().to_string_lossy().into_owned())
198                .collect();
199            format!("{name}/{}", rest.join("/"))
200        }
201        None => format!(
202            "{}/{}",
203            spell("EXTERNAL"),
204            file.file_name()
205                .map(|n| n.to_string_lossy().into_owned())
206                .unwrap_or_default()
207        ),
208    }
209}
210
211fn location_vars(location: &Location, out: &mut Vec<&'static str>) {
212    match location {
213        Location::EnvDir { var, fallback, .. } => {
214            if !out.contains(var) {
215                out.push(var);
216            }
217            location_vars(fallback, out);
218        }
219        Location::Glob { base, .. } => location_vars(base, out),
220        _ => {}
221    }
222}