Skip to main content

surjection_core/apply/
exec.rs

1//! Execution (SPEC 8.4) and apply commits (SPEC 8.7).
2//!
3//! Per target file, holding the store lock: re-read and re-plan if the file
4//! changed since planning (up to three times), back up the original bytes,
5//! self-check the edited text, write a temp file, compare-and-swap against
6//! the planned bytes, replace, then update the ledger and the journal. A
7//! failed file never stops the others.
8//!
9//! [`apply_in`] runs inside a [`Transaction`]: the run is recorded in
10//! `machines/<machine-id>.applied.toml` and the `Surjection-Apply` trailer of
11//! that transaction's single commit. [`run`] wraps it in its own
12//! transaction, which commits only when a file was written.
13
14use std::collections::HashMap;
15use std::path::{Path, PathBuf};
16use std::thread;
17use std::time::{Duration, Instant};
18
19use crate::access::{self, ReadOnlyKind};
20use crate::adapters::adapter;
21use crate::apply::backup;
22use crate::apply::journal::{FileRecord, Journal, RecordedError};
23use crate::apply::ledger::{EntryKind, Ledger, LedgerEntry, LedgerKey, LedgerSlot, Origin};
24use crate::apply::plan::{
25    self, Action, EntryPlan, EntryState, OpCounts, Plan, PlanOptions, ProjectSelection,
26    ScopeFilter, TargetPlan, read_target,
27};
28use crate::apply::render::{DesiredState, RenderCx};
29use crate::apply::{ApplyEnv, import, placeholder_path, temp_path};
30use crate::error::{CoreError, ErrorCode};
31use crate::formats::{Document, NativeMap, NativeValue};
32use crate::layering::ProjectRepo;
33use crate::model::applied::{AppliedRecord, AppliedTarget, ApplyOutcome, ApplyTrigger};
34use crate::model::ids;
35use crate::model::settings::ApplyMode;
36use crate::model::{SCHEMA_VERSION, TomlDocument};
37use crate::store::{ApplyRef, CommitId, Machine, Operation, Store, Transaction, utc_datetime};
38
39/// Times a file is re-planned after it changed underneath (SPEC 8.4).
40const MAX_REPLANS: u32 = 3;
41/// How long a replace is retried while another process holds the file.
42const LOCK_RETRY: Duration = Duration::from_secs(2);
43
44/// One apply run's inputs.
45#[derive(Debug, Clone)]
46pub struct ApplyRequest {
47    pub options: PlanOptions,
48    pub trigger: ApplyTrigger,
49}
50
51/// What one target got.
52#[derive(Debug, Clone)]
53pub struct TargetResult {
54    pub clients: Vec<&'static str>,
55    pub scope: crate::model::applied::Scope,
56    /// The project of a project or project-local target.
57    pub project_id: Option<String>,
58    /// The project folder `<P>`, when known.
59    pub project: Option<PathBuf>,
60    pub file: PathBuf,
61    /// Operations done (zero when the file was not written).
62    pub counts: OpCounts,
63    pub outcome: ApplyOutcome,
64    /// Why the file failed or is blocked as a whole.
65    pub error: Option<CoreError>,
66    /// The plan the file was executed with (after any re-plan).
67    pub entries: Vec<EntryPlan>,
68    pub written: bool,
69    pub backup: Option<PathBuf>,
70    pub warnings: Vec<CoreError>,
71    /// This account cannot write the file: found by the write probe while
72    /// planning, or the OS refused the write (`read_only_target`, SPEC
73    /// 8.2).
74    pub read_only: Option<ReadOnlyKind>,
75}
76
77impl TargetResult {
78    pub fn unresolved(&self) -> usize {
79        self.entries.iter().filter(|entry| entry.unresolved).count()
80    }
81}
82
83/// The result of an apply run.
84#[derive(Debug, Clone)]
85pub struct ApplyReport {
86    pub apply_id: String,
87    pub trigger: ApplyTrigger,
88    pub outcome: ApplyOutcome,
89    pub targets: Vec<TargetResult>,
90    pub warnings: Vec<CoreError>,
91    /// Store servers changed by `import` resolutions.
92    pub imported: Vec<String>,
93    /// Whether the run was recorded in the store (`applied.toml` and the
94    /// `Surjection-Apply` trailer).
95    pub recorded: bool,
96}
97
98impl ApplyReport {
99    /// Files written.
100    pub fn writes(&self) -> usize {
101        self.targets.iter().filter(|target| target.written).count()
102    }
103
104    /// Entries that need a decision that was not given.
105    pub fn unresolved(&self) -> usize {
106        self.targets.iter().map(TargetResult::unresolved).sum()
107    }
108
109    /// What the run left for the user, most severe first (SPEC 14 exit
110    /// codes 1, 4, 5 and 7; the CLI maps it to its exit code, the app to
111    /// its notice).
112    pub fn status(&self) -> ApplyStatus {
113        status_of(self.targets.iter())
114    }
115
116    /// [`Self::status`] over project `id`'s own targets: what trusting that
117    /// project left, whatever another project still waits for. The instant
118    /// apply after a trust covers the whole machine (#10).
119    pub fn project_status(&self, id: &str) -> ApplyStatus {
120        status_of(
121            self.targets
122                .iter()
123                .filter(|target| target.project_id.as_deref() == Some(id)),
124        )
125    }
126}
127
128fn status_of<'a>(mut targets: impl Iterator<Item = &'a TargetResult> + Clone) -> ApplyStatus {
129    if targets
130        .clone()
131        .any(|target| target.outcome == ApplyOutcome::Failed)
132    {
133        ApplyStatus::FileFailed
134    } else if targets.clone().any(|target| target.unresolved() > 0) {
135        ApplyStatus::NeedsDecision
136    } else if targets
137        .clone()
138        .flat_map(|target| &target.entries)
139        .any(EntryPlan::blocked_by_secret)
140    {
141        ApplyStatus::MissingSecrets
142    } else if targets.any(|target| {
143        target
144            .error
145            .as_ref()
146            .is_some_and(|error| error.code() == ErrorCode::TrustRequired)
147    }) {
148        ApplyStatus::TrustRequired
149    } else {
150        ApplyStatus::Done
151    }
152}
153
154/// What an apply run left for the user ([`ApplyReport::status`]).
155#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
156pub enum ApplyStatus {
157    /// Nothing: every file is written or needed no change.
158    Done,
159    /// A file could not be written.
160    FileFailed,
161    /// Entries need a decision (collision, conflict, drift).
162    NeedsDecision,
163    /// Entries are blocked by secrets this machine cannot provide.
164    MissingSecrets,
165    /// A project waits for its manifests to be trusted.
166    TrustRequired,
167}
168
169/// What a store change touched. Its instant apply plans and writes only
170/// those targets (#15), so an unrelated project waiting for trust, or a
171/// drifted file elsewhere, neither slows the change nor shows in its
172/// result.
173#[derive(Debug, Clone, PartialEq, Eq)]
174pub enum Touched {
175    /// Anything (client preferences, settings, secrets): every target.
176    All,
177    /// These store servers (added, edited, enabled for other clients,
178    /// removed): the targets [`PlanOptions::servers`] selects.
179    Servers(Vec<String>),
180    /// The known project at this folder (trusted, initialized): its
181    /// targets only.
182    Project(PathBuf),
183}
184
185impl Touched {
186    /// The plan that covers what was touched.
187    pub fn options(&self) -> PlanOptions {
188        match self {
189            Touched::All => PlanOptions::default(),
190            Touched::Servers(ids) => PlanOptions {
191                servers: Some(ids.clone()),
192                ..PlanOptions::default()
193            },
194            Touched::Project(root) => PlanOptions {
195                scope: ScopeFilter::Project,
196                projects: ProjectSelection::Only(root.clone()),
197                ..PlanOptions::default()
198            },
199        }
200    }
201}
202
203/// In instant mode (`apply_mode`, the default), applies a staged store edit
204/// inside its transaction, so the edit and its apply are one commit
205/// (SPEC 8.7): the targets the edit `touched`. `None` in review mode. The
206/// desired state is loaded once, for the mode and the plan.
207pub fn instant_apply(
208    tx: &mut Transaction<'_>,
209    ax: &ApplyEnv<'_>,
210    touched: &Touched,
211) -> Result<Option<ApplyReport>, CoreError> {
212    // `surject eject` without filters: this machine is not managed until
213    // the user starts managing again.
214    if crate::eject::status_at(ax.fs, &ax.home.state_dir())?.is_some_and(|ejected| ejected.all()) {
215        return Ok(None);
216    }
217    let machine = tx.machine().id.clone();
218    let desired = DesiredState::load(tx, Some(&machine))?;
219    if desired.apply_mode() != ApplyMode::Instant {
220        return Ok(None);
221    }
222    let request = ApplyRequest {
223        options: touched.options(),
224        trigger: ApplyTrigger::Instant,
225    };
226    apply_with(tx, ax, &request, Some(desired)).map(Some)
227}
228
229/// Plans against the store's working tree (or an empty desired state when
230/// there is no store yet). Read-only: creates no ledger key, lock or file.
231pub fn preview(
232    store: Option<&Store<'_>>,
233    ax: &ApplyEnv<'_>,
234    options: &PlanOptions,
235) -> Result<Plan, CoreError> {
236    let inputs = PlanInputs::load(store, ax)?;
237    plan::plan(
238        &ax.render_cx(inputs.memory),
239        &inputs.desired,
240        &inputs.ledger,
241        &inputs.key,
242        options,
243    )
244}
245
246/// What a read-only plan runs against: the desired state of the store's
247/// working tree, the ledger, its key and the secret memory.
248pub(crate) struct PlanInputs {
249    pub(crate) desired: DesiredState,
250    pub(crate) ledger: Ledger,
251    pub(crate) key: LedgerKey,
252    pub(crate) memory: std::sync::Arc<crate::secrets::scanner::SecretMemory>,
253}
254
255impl PlanInputs {
256    /// Loads the inputs without creating anything (no ledger key, lock or
257    /// file); an empty desired state when there is no store yet.
258    pub(crate) fn load(store: Option<&Store<'_>>, ax: &ApplyEnv<'_>) -> Result<Self, CoreError> {
259        let state_dir = ax.home.state_dir();
260        let machine = Machine::load(ax.fs, &state_dir)?;
261        let desired = match store {
262            Some(store) => DesiredState::load(store, machine.as_ref().map(|m| m.id.as_str()))?,
263            None => DesiredState::empty(),
264        };
265        let ledger = Ledger::load(ax.fs, &state_dir)?;
266        // Without a key file nothing was ever hashed: any key plans the same.
267        let key = match LedgerKey::load(ax.fs, &state_dir)? {
268            Some(key) => key,
269            None => LedgerKey::from_bytes([0; 32]),
270        };
271        let memory = match store {
272            Some(store) => store.secret_memory().clone(),
273            None => std::sync::Arc::new(crate::secrets::scanner::SecretMemory::new()?),
274        };
275        Ok(Self {
276            desired,
277            ledger,
278            key,
279            memory,
280        })
281    }
282}
283
284/// A standalone apply run in its own transaction: one commit when a file
285/// was written, none otherwise (SPEC 8.7).
286pub fn run(
287    store: &Store<'_>,
288    ax: &ApplyEnv<'_>,
289    request: &ApplyRequest,
290) -> Result<(ApplyReport, Option<CommitId>), CoreError> {
291    let operation = Operation::new("apply", "apply");
292    let committed = store.transaction(operation, |tx| apply_in(tx, ax, request))?;
293    Ok((committed.value, committed.commit))
294}
295
296/// Plans against the transaction's view of the store (staged edits
297/// included), executes, and records the run in the transaction: always
298/// when the transaction commits anyway (an instant-mode edit, a rollback),
299/// otherwise only when a file was written. Staged edits are validated and
300/// leak-scanned first, so an edit the commit would refuse never reaches a
301/// client file.
302pub fn apply_in(
303    tx: &mut Transaction<'_>,
304    ax: &ApplyEnv<'_>,
305    request: &ApplyRequest,
306) -> Result<ApplyReport, CoreError> {
307    apply_with(tx, ax, request, None)
308}
309
310/// [`apply_in`] with the transaction's desired state loaded already.
311fn apply_with(
312    tx: &mut Transaction<'_>,
313    ax: &ApplyEnv<'_>,
314    request: &ApplyRequest,
315    desired: Option<DesiredState>,
316) -> Result<ApplyReport, CoreError> {
317    tx.check()?;
318    let state_dir = ax.home.state_dir();
319    let machine = tx.machine().clone();
320    let cx = ax.render_cx(tx.store().secret_memory().clone());
321    let mut ledger = Ledger::load(ax.fs, &state_dir)?;
322    let key = LedgerKey::load_or_create(ax.fs, &state_dir)?;
323
324    let mut desired = match desired {
325        Some(desired) => desired,
326        None => DesiredState::load(tx, Some(&machine.id))?,
327    };
328    let mut plan = plan::plan(&cx, &desired, &ledger, &key, &request.options)?;
329    let mut imported = Vec::new();
330    if plan
331        .targets
332        .iter()
333        .flat_map(|target| &target.entries)
334        .any(import::is_store_resolution)
335    {
336        let resolutions = import::stage_resolutions(tx, &plan, &desired)?;
337        imported = resolutions.changed;
338        desired = DesiredState::load(tx, Some(&machine.id))?;
339        plan = plan::plan(&cx, &desired, &ledger, &key, &request.options)?;
340        // Whatever still asks for an import or a release of a desired
341        // entry could not be staged.
342        for entry in plan
343            .targets
344            .iter_mut()
345            .flat_map(|target| &mut target.entries)
346        {
347            if !import::is_store_resolution(entry) {
348                continue;
349            }
350            let reason = resolutions
351                .failed
352                .iter()
353                .find(|(client, name, _)| {
354                    Some(client.as_str()) == entry.client && *name == entry.name
355                })
356                .map(|(_, _, err)| err.clone());
357            let fallback = if entry.action == Action::Release {
358                "the entry is still desired for this client after the release"
359            } else {
360                "the store definition still renders differently after the import"
361            };
362            entry.action = Action::Skip;
363            entry.unresolved = true;
364            entry.problem =
365                Some(reason.unwrap_or_else(|| CoreError::new(ErrorCode::InvalidValue, fallback)));
366        }
367    }
368
369    let base = tx.store().head()?;
370    let now = ax.env.now();
371    let apply_id = ids::new_ulid(now)?;
372    let mut journal = Journal::start(
373        ax.fs,
374        &state_dir,
375        &apply_id,
376        request.trigger,
377        utc_datetime(now).to_string(),
378    )?;
379    let mut executor = Executor {
380        cx: &cx,
381        ax,
382        key: &key,
383        options: &request.options,
384        run_dir: backup::run_dir(ax.home, now, &apply_id),
385        written_at: utc_datetime(now).to_string(),
386        store_commit: base.short().to_owned(),
387    };
388    let mut targets: Vec<TargetResult> = Vec::with_capacity(plan.targets.len());
389    // SPEC 8.4 step 5: the ownership of a written file is saved right after
390    // it; ledger-only changes (adopt, refresh, forget, release) go with the
391    // next save. `unsaved` are the targets whose changes are not saved yet.
392    let mut unsaved: Vec<usize> = Vec::new();
393    for target in plan.targets {
394        let (mut result, changed) = executor.execute(target, &mut ledger);
395        let index = targets.len();
396        if changed {
397            unsaved.push(index);
398        }
399        if changed && result.written {
400            if let Err(err) = ledger.save(ax.fs, &state_dir) {
401                for earlier in unsaved.drain(..).filter(|earlier| *earlier != index) {
402                    ownership_lost(&mut targets[earlier], &err);
403                    journal.files[earlier] = file_record(&targets[earlier]);
404                }
405                ownership_lost(&mut result, &err);
406            }
407            unsaved.clear();
408        }
409        if let Err(err) = journal.record(ax.fs, &state_dir, file_record(&result)) {
410            // What was done stays owned, whatever stops the run.
411            if !unsaved.is_empty() {
412                let _ = ledger.save(ax.fs, &state_dir);
413            }
414            return Err(err);
415        }
416        targets.push(result);
417    }
418    if !unsaved.is_empty()
419        && let Err(err) = ledger.save(ax.fs, &state_dir)
420    {
421        for index in unsaved {
422            ownership_lost(&mut targets[index], &err);
423            journal.files[index] = file_record(&targets[index]);
424        }
425    }
426    let outcome = run_outcome(&targets);
427    let writes = targets.iter().filter(|target| target.written).count();
428
429    let commits_anyway = tx.has_changes();
430    let recorded = commits_anyway || writes > 0;
431    if recorded {
432        let record = AppliedRecord {
433            schema: SCHEMA_VERSION,
434            machine_id: machine.id.clone(),
435            apply_id: apply_id.clone(),
436            time: utc_datetime(now),
437            store_revision: base.as_str().to_owned(),
438            trigger: request.trigger,
439            outcome,
440            targets: targets
441                .iter()
442                .map(|target| AppliedTarget {
443                    client: target.clients[0].to_owned(),
444                    scope: target.scope,
445                    project_id: target.project_id.clone(),
446                    file: placeholder_path(ax.env, &target.file, target.project.as_deref()),
447                    create: target.counts.create,
448                    update: target.counts.update,
449                    remove: target.counts.remove,
450                    disable: target.counts.disable,
451                    outcome: target.outcome,
452                    extra: toml::Table::new(),
453                })
454                .collect(),
455            extra: toml::Table::new(),
456        };
457        let relative = format!("machines/{}.applied.toml", machine.id);
458        tx.write(&relative, TomlDocument::new(record).to_text()?)?;
459        tx.set_apply(ApplyRef {
460            id: apply_id.clone(),
461            outcome,
462        });
463        if !commits_anyway {
464            tx.set_summary(summary(&targets));
465        }
466    }
467    journal.finish(ax.fs, &state_dir, outcome)?;
468    backup::prune(ax.fs, ax.home, now)?;
469    crate::diagnostics::log::event(
470        "apply",
471        &[
472            ("targets", &targets.len()),
473            ("writes", &writes),
474            ("outcome", &format!("{outcome:?}").to_lowercase()),
475        ],
476    );
477
478    Ok(ApplyReport {
479        apply_id,
480        trigger: request.trigger,
481        outcome,
482        targets,
483        warnings: plan.warnings,
484        imported,
485        recorded,
486    })
487}
488
489/// `apply: 2 files (claude-code, codex)`.
490fn summary(targets: &[TargetResult]) -> String {
491    let written: Vec<&TargetResult> = targets.iter().filter(|target| target.written).collect();
492    let mut clients: Vec<&str> = Vec::new();
493    for target in &written {
494        for client in &target.clients {
495            if !clients.contains(client) {
496                clients.push(client);
497            }
498        }
499    }
500    let files = if written.len() == 1 { "file" } else { "files" };
501    format!("apply: {} {files} ({})", written.len(), clients.join(", "))
502}
503
504/// The outcome of a run from its targets: `ok` when every target is ok,
505/// `failed` or `blocked` when none got anywhere, `partial` otherwise.
506fn run_outcome(targets: &[TargetResult]) -> ApplyOutcome {
507    let count = |outcome| targets.iter().filter(|t| t.outcome == outcome).count();
508    let (ok, partial, failed) = (
509        count(ApplyOutcome::Ok),
510        count(ApplyOutcome::Partial),
511        count(ApplyOutcome::Failed),
512    );
513    if ok == targets.len() {
514        ApplyOutcome::Ok
515    } else if ok + partial == 0 && failed > 0 {
516        ApplyOutcome::Failed
517    } else if ok + partial == 0 {
518        ApplyOutcome::Blocked
519    } else {
520        ApplyOutcome::Partial
521    }
522}
523
524fn file_record(result: &TargetResult) -> FileRecord {
525    FileRecord {
526        clients: result.clients.iter().map(|c| (*c).to_owned()).collect(),
527        scope: result.scope,
528        file: result.file.to_string_lossy().into_owned(),
529        outcome: result.outcome,
530        create: result.counts.create,
531        update: result.counts.update,
532        remove: result.counts.remove,
533        disable: result.counts.disable,
534        written: result.written,
535        backup: result
536            .backup
537            .as_ref()
538            .map(|path| path.to_string_lossy().into_owned()),
539        old_values: false,
540        backup_removed: false,
541        error: result.error.as_ref().map(RecordedError::from),
542    }
543}
544
545struct Executor<'a> {
546    cx: &'a RenderCx<'a>,
547    ax: &'a ApplyEnv<'a>,
548    key: &'a LedgerKey,
549    options: &'a PlanOptions,
550    run_dir: PathBuf,
551    written_at: String,
552    store_commit: String,
553}
554
555impl Executor<'_> {
556    /// Executes one target; also returns whether its ownership changed in
557    /// `ledger`.
558    fn execute(&mut self, plan: TargetPlan, ledger: &mut Ledger) -> (TargetResult, bool) {
559        let mut plan = plan;
560        let mut replans = 0;
561        loop {
562            let current = match read_target(self.ax.fs, &plan.file) {
563                Ok(bytes) => bytes,
564                Err(err) => return (failed(plan, err), false),
565            };
566            if current != plan.before {
567                replans += 1;
568                if replans > MAX_REPLANS {
569                    let err = changed_during_apply(&plan.file);
570                    return (failed(plan, err), false);
571                }
572                plan = self.replan(plan, current, ledger);
573                continue;
574            }
575            if let Some(problem) = plan.problem.clone() {
576                return (
577                    finished(plan, ApplyOutcome::Blocked, Some(problem), false, None),
578                    false,
579                );
580            }
581            if let Err(err) = self.exclude(&plan) {
582                return (failed(plan, err), false);
583            }
584            let Some(after) = plan.after.clone() else {
585                // Ledger-only work (adopt, refresh, forget, release).
586                let changed = self.update_ledger(&plan, ledger);
587                let outcome = entry_outcome(&plan, false);
588                return (finished(plan, outcome, None, false, None), changed);
589            };
590            if let Err(err) = self_check(&plan, &after) {
591                return (failed(plan, err), false);
592            }
593            let backup = match &current {
594                Some(bytes) => {
595                    match backup::save(self.ax.fs, self.ax.home, &self.run_dir, &plan.file, bytes) {
596                        Ok(path) => Some(path),
597                        Err(err) => return (failed(plan, err), false),
598                    }
599                }
600                None => None,
601            };
602            match self.write(&plan, &after) {
603                Ok(true) => {}
604                Ok(false) => {
605                    // Compare-and-swap failed: the file changed after the
606                    // re-read above. Re-plan against what is there now.
607                    replans += 1;
608                    if replans > MAX_REPLANS {
609                        let err = changed_during_apply(&plan.file);
610                        return (failed(plan, err), false);
611                    }
612                    let now = match read_target(self.ax.fs, &plan.file) {
613                        Ok(bytes) => bytes,
614                        Err(err) => return (failed(plan, err), false),
615                    };
616                    plan = self.replan(plan, now, ledger);
617                    continue;
618                }
619                Err(err) => return (failed(plan, err), false),
620            }
621            let changed = self.update_ledger(&plan, ledger);
622            let outcome = entry_outcome(&plan, true);
623            return (finished(plan, outcome, None, true, backup), changed);
624        }
625    }
626
627    fn replan(&self, plan: TargetPlan, bytes: Option<Vec<u8>>, ledger: &Ledger) -> TargetPlan {
628        plan::plan_target(self.cx, plan.input, bytes, ledger, self.key, self.options)
629    }
630
631    /// Temp file, compare-and-swap, replace. `Ok(false)` when the file no
632    /// longer holds the planned bytes; the temp file is removed then.
633    fn write(&self, plan: &TargetPlan, after: &[u8]) -> Result<bool, CoreError> {
634        swap_file(self.ax.fs, &plan.file, plan.before.as_deref(), after)
635    }
636
637    /// SPEC 6.5: a project file that holds private entries and that the
638    /// project's repository does not track is hidden through its
639    /// `info/exclude`, before anything is written and also when nothing
640    /// is (an adopted entry, an earlier failure). A failure fails the
641    /// target: nothing private is written into a file git may pick up.
642    fn exclude(&self, plan: &TargetPlan) -> Result<(), CoreError> {
643        let (true, Some(root)) = (plan.input.exclude, plan.project.as_deref()) else {
644            return Ok(());
645        };
646        if let Some(repo) = ProjectRepo::discover(root)? {
647            repo.exclude(self.ax.fs, &plan.file)?;
648        }
649        Ok(())
650    }
651}
652
653/// SPEC 8.4 step 4: writes `after` to a temp file next to `file` (with the
654/// file's permissions when it exists), checks that `file` still holds
655/// `expected` (compare-and-swap), then replaces it, retrying a Windows
656/// sharing violation for [`LOCK_RETRY`] before `file_locked`. `Ok(false)`
657/// when the file changed; the temp file is removed then.
658pub(crate) fn swap_file(
659    fs: &dyn crate::fs::Fs,
660    file: &Path,
661    expected: Option<&[u8]>,
662    after: &[u8],
663) -> Result<bool, CoreError> {
664    let io = |what: &str, at: &Path, err: std::io::Error| access::write_error(fs, what, at, &err);
665    if let Some(dir) = file.parent() {
666        fs.create_dir_all(dir)
667            .map_err(|err| io("cannot create directory", dir, err))?;
668    }
669    let temp = temp_path(file)?;
670    let like = expected.is_some().then_some(file);
671    fs.write_new(&temp, after, like)
672        .map_err(|err| io("cannot write temp file", &temp, err))?;
673    let discard = || {
674        let _ = fs.remove_file(&temp);
675    };
676    match read_target(fs, file) {
677        Ok(now) if now.as_deref() == expected => {}
678        Ok(_) => {
679            discard();
680            return Ok(false);
681        }
682        Err(err) => {
683            discard();
684            return Err(err);
685        }
686    }
687    let deadline = Instant::now() + LOCK_RETRY;
688    let mut pause = Duration::from_millis(25);
689    loop {
690        match fs.replace(&temp, file) {
691            Ok(()) => return Ok(true),
692            Err(err) if is_sharing_violation(&err) && Instant::now() < deadline => {
693                // Access denied here is also what a read-only file gives
694                // (the read-only attribute, an ACL without DELETE on the
695                // file and FILE_DELETE_CHILD on its folder) as well as a
696                // handle held without delete sharing: only a file the
697                // probe (which asks for write and delete) finds writable is
698                // waited for as a lock.
699                if let Some(kind) = refused(fs, &err, file) {
700                    discard();
701                    return Err(access::read_only_target(kind, file));
702                }
703                thread::sleep(pause.min(deadline.saturating_duration_since(Instant::now())));
704                pause = (pause * 2).min(Duration::from_millis(200));
705            }
706            Err(err) if is_sharing_violation(&err) => {
707                discard();
708                return Err(CoreError::new(
709                    ErrorCode::FileLocked,
710                    format!(
711                        "another process kept the file open for {} s: {err}",
712                        LOCK_RETRY.as_secs()
713                    ),
714                )
715                .with_path(file));
716            }
717            Err(err) => {
718                discard();
719                return Err(io("cannot replace file", file, err));
720            }
721        }
722    }
723}
724
725impl Executor<'_> {
726    /// Records every entry's new ownership state in `ledger` (saved once
727    /// after the run, see [`apply_in`]). Returns whether it changed.
728    fn update_ledger(&self, plan: &TargetPlan, ledger: &mut Ledger) -> bool {
729        let file = plan.file.to_string_lossy().into_owned();
730        let slot = LedgerSlot {
731            scope: plan.scope,
732            project_id: plan.project_id.as_deref(),
733            file: &file,
734            container: &plan.pointer,
735        };
736        let known = ledger.slot_entries(&slot);
737        // What this batch did to a key so far, for a later entry of the
738        // same key (duplicate keys in a file): its origin, `None` once
739        // removed.
740        let mut done: HashMap<String, Option<Option<Origin>>> = HashMap::new();
741        let mut changes: Vec<(String, Option<LedgerEntry>)> = Vec::new();
742        for entry in &plan.entries {
743            let origin = match entry.action {
744                Action::Create => Some(Origin::Created),
745                Action::Adopt | Action::AdoptOverwrite => Some(Origin::Adopted),
746                Action::Update | Action::Disable | Action::Refresh => Some(
747                    match done.get(&entry.name) {
748                        Some(origin) => origin.flatten(),
749                        None => known.get(&entry.name).and_then(|known| known.origin),
750                    }
751                    .unwrap_or(Origin::Created),
752                ),
753                Action::Remove | Action::Forget | Action::Release => {
754                    done.insert(entry.name.clone(), None);
755                    changes.push((entry.name.clone(), None));
756                    None
757                }
758                Action::None | Action::Import | Action::Skip => None,
759            };
760            let Some(origin) = origin else {
761                continue;
762            };
763            let (Some(client), Some(value)) = (entry.client, &entry.written) else {
764                continue;
765            };
766            let written_hash = match plan.kind {
767                EntryKind::McpEntry => match plan::canonical(client, value) {
768                    Some(canonical) => Some(self.key.hash(&canonical)),
769                    None => continue,
770                },
771                // A list member is its own value.
772                EntryKind::ListMember => None,
773            };
774            let row = LedgerEntry {
775                kind: plan.kind,
776                client: client.to_owned(),
777                scope: plan.scope,
778                project_id: plan.project_id.clone(),
779                file: file.clone(),
780                container: plan.pointer.clone(),
781                key: entry.name.clone(),
782                server_id: entry.server_id.clone(),
783                origin: Some(origin),
784                written_hash,
785                written_at: Some(self.written_at.clone()),
786                store_commit: Some(self.store_commit.clone()),
787                delivery: entry.delivery.map(str::to_owned),
788                extra: serde_json::Map::new(),
789            };
790            done.insert(entry.name.clone(), Some(Some(origin)));
791            changes.push((entry.name.clone(), Some(row)));
792        }
793        drop(known);
794        ledger.update_slot(&slot, changes)
795    }
796}
797
798fn changed_during_apply(file: &Path) -> CoreError {
799    CoreError::new(
800        ErrorCode::FileChangedDuringApply,
801        format!(
802            "the file kept changing during apply ({MAX_REPLANS} re-plans); it was left as it is"
803        ),
804    )
805    .with_path(file)
806}
807
808/// The outcome of a target that was executed: blocked or unresolved
809/// entries make it `partial` when something was done, `blocked` otherwise.
810fn entry_outcome(plan: &TargetPlan, wrote: bool) -> ApplyOutcome {
811    let stuck = plan
812        .entries
813        .iter()
814        .any(|entry| entry.state == EntryState::Blocked || entry.unresolved);
815    let did = wrote
816        || plan.entries.iter().any(|entry| {
817            matches!(
818                entry.action,
819                Action::Adopt | Action::Refresh | Action::Forget | Action::Release
820            )
821        });
822    match (stuck, did) {
823        (false, _) => ApplyOutcome::Ok,
824        (true, true) => ApplyOutcome::Partial,
825        (true, false) => ApplyOutcome::Blocked,
826    }
827}
828
829fn finished(
830    mut plan: TargetPlan,
831    outcome: ApplyOutcome,
832    error: Option<CoreError>,
833    written: bool,
834    backup: Option<PathBuf>,
835) -> TargetResult {
836    if written {
837        plan.warnings
838            .extend(restart_required(&plan.clients, &plan.file));
839    }
840    TargetResult {
841        counts: if written {
842            plan.counts()
843        } else {
844            OpCounts::default()
845        },
846        clients: plan.clients,
847        scope: plan.scope,
848        project_id: plan.project_id,
849        project: plan.project,
850        file: plan.file,
851        outcome,
852        error,
853        entries: plan.entries,
854        written,
855        backup,
856        warnings: plan.warnings,
857        read_only: plan.read_only,
858    }
859}
860
861/// `restart_required` for each client of a written file that reads it only
862/// at launch (Claude Desktop, gate V2 AP-6).
863fn restart_required(clients: &[&'static str], file: &Path) -> Vec<CoreError> {
864    clients
865        .iter()
866        .filter_map(|&client| adapter(client))
867        .filter(|spec| {
868            spec.mcp
869                .as_ref()
870                .is_some_and(|mcp| mcp.caps.restart_required)
871        })
872        .map(|spec| {
873            CoreError::new(
874                ErrorCode::RestartRequired,
875                format!(
876                    "{0} reads this file only at launch: fully quit {0} (also from the system \
877                     tray or menu bar) and start it again to load the change",
878                    spec.display_name
879                ),
880            )
881            .with_path(file)
882        })
883        .collect()
884}
885
886/// A target whose new ownership could not be saved: it fails, and what was
887/// written stays written (with its backup and restart notes).
888fn ownership_lost(target: &mut TargetResult, err: &CoreError) {
889    target.outcome = ApplyOutcome::Failed;
890    target.error = Some(err.clone());
891    target.counts = OpCounts::default();
892}
893
894fn failed(mut plan: TargetPlan, err: CoreError) -> TargetResult {
895    // A write the OS refused as read only: blocked like a file the probe
896    // found read only, never a failure; the run goes on (SPEC 8.2). The
897    // file is marked read only only when the refused write was its own
898    // (the file, its temp file, a folder on its way); a read-only
899    // `info/exclude` blocks the target without blaming its file.
900    if let Some(kind) = err.read_only() {
901        if err.path().is_some_and(|at| own_write(&plan.file, at)) {
902            plan.read_only = Some(kind);
903        }
904        for entry in &mut plan.entries {
905            if entry.action.writes() {
906                entry.state = EntryState::Blocked;
907                entry.action = Action::None;
908                entry.unresolved = false;
909                entry.problem = Some(err.clone());
910            }
911        }
912        return finished(plan, ApplyOutcome::Blocked, Some(err), false, None);
913    }
914    finished(plan, ApplyOutcome::Failed, Some(err), false, None)
915}
916
917/// Whether a write at `at` was one of `file`'s own: the file, a sibling
918/// (its temp file) or a folder on its way.
919fn own_write(file: &Path, at: &Path) -> bool {
920    at == file || at.parent() == file.parent() || file.starts_with(at)
921}
922
923/// Of a replace refused with access denied on Windows, the kind of
924/// read-only file it hit, when the write probe finds `file` read only;
925/// `None` for a file another process holds (retried, then
926/// `file_locked`).
927#[cfg(windows)]
928fn refused(fs: &dyn crate::fs::Fs, err: &std::io::Error, file: &Path) -> Option<ReadOnlyKind> {
929    if err.raw_os_error() != Some(5) {
930        return None;
931    }
932    fs.write_probe().and_then(|probe| probe(file).read_only())
933}
934
935#[cfg(not(windows))]
936fn refused(_fs: &dyn crate::fs::Fs, _err: &std::io::Error, _file: &Path) -> Option<ReadOnlyKind> {
937    None
938}
939
940#[cfg(windows)]
941fn is_sharing_violation(err: &std::io::Error) -> bool {
942    // ERROR_ACCESS_DENIED (a handle without FILE_SHARE_DELETE),
943    // ERROR_SHARING_VIOLATION, ERROR_LOCK_VIOLATION.
944    matches!(err.raw_os_error(), Some(5 | 32 | 33))
945}
946
947#[cfg(not(windows))]
948fn is_sharing_violation(_err: &std::io::Error) -> bool {
949    false
950}
951
952/// SPEC 8.4 step 3: the edited text parses, owned entries read back as
953/// planned, and everything else (other entries of the container and
954/// everything outside it) is unchanged.
955fn self_check(plan: &TargetPlan, after: &[u8]) -> Result<(), CoreError> {
956    let fail = |detail: String| {
957        Err(CoreError::new(ErrorCode::SelfCheckFailed, detail).with_path(&plan.file))
958    };
959    let format = plan.input.target.format;
960    if plan.kind == EntryKind::ListMember {
961        return self_check_list(plan, after);
962    }
963    let after_doc = match Document::parse(after, format) {
964        Ok(doc) => doc,
965        Err(err) => return fail(format!("the edited file does not parse: {err}")),
966    };
967    let before_doc = match &plan.before {
968        Some(bytes) => Document::parse(bytes, format)?,
969        None => plan.input.target.new_document(),
970    };
971    let container: Vec<&str> = plan.container.iter().map(String::as_str).collect();
972    let mut planned: Vec<&str> = Vec::new();
973    for entry in &plan.entries {
974        planned.push(&entry.name);
975        let got = after_doc.get(&container, &entry.name)?;
976        let ok = match entry.action {
977            Action::Create | Action::Update | Action::AdoptOverwrite | Action::Disable => {
978                match (entry.client, &entry.written, &got) {
979                    (Some(client), Some(want), Some(got)) => {
980                        plan::canonical(client, got) == plan::canonical(client, want)
981                    }
982                    _ => false,
983                }
984            }
985            Action::Remove => got.is_none(),
986            _ => got == entry.observed,
987        };
988        if !ok {
989            return fail(format!(
990                "entry {:?} does not read back as planned",
991                entry.name
992            ));
993        }
994    }
995    for name in before_doc.list(&container)? {
996        if !planned.contains(&name.as_str())
997            && before_doc.get(&container, &name)? != after_doc.get(&container, &name)?
998        {
999            return fail(format!("entry {name:?} is not owned but changed"));
1000        }
1001    }
1002    if outside(&before_doc, &container)? != outside(&after_doc, &container)? {
1003        return fail("something outside the server container changed".to_owned());
1004    }
1005    Ok(())
1006}
1007
1008/// [`self_check`] of a list target: planned members are present or absent
1009/// as planned, every other member and everything outside the list is
1010/// unchanged.
1011fn self_check_list(plan: &TargetPlan, after: &[u8]) -> Result<(), CoreError> {
1012    let fail = |detail: String| {
1013        Err(CoreError::new(ErrorCode::SelfCheckFailed, detail).with_path(&plan.file))
1014    };
1015    let format = plan.input.target.format;
1016    let after_doc = match Document::parse(after, format) {
1017        Ok(doc) => doc,
1018        Err(err) => return fail(format!("the edited file does not parse: {err}")),
1019    };
1020    let before_doc = match &plan.before {
1021        Some(bytes) => Document::parse(bytes, format)?,
1022        None => plan.input.target.new_document(),
1023    };
1024    let list: Vec<&str> = plan.container.iter().map(String::as_str).collect();
1025    let before = plan::list_members(&before_doc, &list)?;
1026    let after_members = plan::list_members(&after_doc, &list)?;
1027    for entry in &plan.entries {
1028        let want = match entry.action {
1029            Action::Create => true,
1030            Action::Remove => false,
1031            _ => before.contains(&entry.name),
1032        };
1033        if after_members.contains(&entry.name) != want {
1034            return fail(format!(
1035                "list member {:?} does not read back as planned",
1036                entry.name
1037            ));
1038        }
1039    }
1040    let others = |members: &[String]| -> Vec<String> {
1041        members
1042            .iter()
1043            .filter(|member| !plan.entries.iter().any(|entry| entry.name == **member))
1044            .cloned()
1045            .collect()
1046    };
1047    if others(&before) != others(&after_members) {
1048        return fail("a list member that is not owned changed".to_owned());
1049    }
1050    if outside(&before_doc, &list)? != outside(&after_doc, &list)? {
1051        return fail("something outside the list changed".to_owned());
1052    }
1053    Ok(())
1054}
1055
1056/// The whole document without the container at `path` (and the empty
1057/// objects that held only it). For a list keyed by a `[field]` segment
1058/// (Continue's `mcpServers`), only the items the container addresses by
1059/// name are taken out: items without a scalar `field`, items that are not
1060/// mappings and later items repeating a name stay, so a change to them
1061/// fails the check.
1062fn outside(doc: &Document, path: &[&str]) -> Result<NativeValue, CoreError> {
1063    let mut root = document_value(doc)?;
1064    strip_container(&mut root, path);
1065    Ok(root)
1066}
1067
1068/// The whole document as one value.
1069pub(crate) fn document_value(doc: &Document) -> Result<NativeValue, CoreError> {
1070    let mut root = NativeMap::new();
1071    for key in doc.list(&[])? {
1072        if let Some(value) = doc.get(&[], &key)? {
1073            root.insert(key, value);
1074        }
1075    }
1076    Ok(NativeValue::Object(root))
1077}
1078
1079/// Takes the container at `path` out of `root` (a [`document_value`]), as
1080/// [`outside`] describes.
1081pub(crate) fn strip_container(root: &mut NativeValue, path: &[&str]) {
1082    let keys = crate::formats::mapping_path(path);
1083    let Some(segment) = path.get(keys.len()) else {
1084        remove_path(root, keys);
1085        return;
1086    };
1087    let field = &segment[1..segment.len() - 1];
1088    let empty = match value_at_mut(root, keys) {
1089        Some(NativeValue::Array(items)) => {
1090            let mut seen: Vec<NativeValue> = Vec::new();
1091            items.retain(|item| {
1092                let name = item
1093                    .as_object()
1094                    .and_then(|entry| entry.get(field))
1095                    .filter(|name| !matches!(name, NativeValue::Array(_) | NativeValue::Object(_)));
1096                match name {
1097                    Some(name) if !seen.contains(name) => {
1098                        seen.push(name.clone());
1099                        false
1100                    }
1101                    _ => true,
1102                }
1103            });
1104            items.is_empty()
1105        }
1106        Some(NativeValue::Object(map)) => map.is_empty(),
1107        Some(NativeValue::Null) => true,
1108        _ => false,
1109    };
1110    if empty {
1111        remove_path(root, keys);
1112    }
1113}
1114
1115/// The value at `path` in nested objects.
1116fn value_at_mut<'v>(value: &'v mut NativeValue, path: &[&str]) -> Option<&'v mut NativeValue> {
1117    path.iter().try_fold(value, |value, key| match value {
1118        NativeValue::Object(map) => map.get_mut(key),
1119        _ => None,
1120    })
1121}
1122
1123/// Removes `path` from `value`, then each ancestor left empty.
1124fn remove_path(value: &mut NativeValue, path: &[&str]) -> bool {
1125    let NativeValue::Object(map) = value else {
1126        return false;
1127    };
1128    match path {
1129        [] => false,
1130        [last] => {
1131            map.remove(last);
1132            map.is_empty()
1133        }
1134        [first, rest @ ..] => {
1135            let Some(child) = map.get_mut(first) else {
1136                return false;
1137            };
1138            if remove_path(child, rest) {
1139                map.remove(first);
1140            }
1141            map.is_empty()
1142        }
1143    }
1144}
1145
1146// The self-check rejects bad writes the editors never make, so its
1147// container comparison is tested here rather than through an apply.
1148#[cfg(test)]
1149mod tests {
1150    use super::outside;
1151    use crate::formats::{Document, Format};
1152
1153    const CONTINUE: &[&str] = &["mcpServers", "[name]"];
1154
1155    const BEFORE: &str = "name: Local\nmcpServers:\n  - name: files\n    command: npx\n  - uses: owner/block\n  - just-text\n  - name: files\n    command: duplicate\n";
1156
1157    fn same_outside(before: &str, after: &str) -> bool {
1158        let parse = |text: &str| Document::parse(text.as_bytes(), Format::Yaml).unwrap();
1159        outside(&parse(before), CONTINUE).unwrap() == outside(&parse(after), CONTINUE).unwrap()
1160    }
1161
1162    #[test]
1163    fn named_list_items_are_the_only_ones_left_out() {
1164        // Owned, named items may change, come and go.
1165        assert!(same_outside(
1166            BEFORE,
1167            &BEFORE.replace("command: npx", "command: bunx")
1168        ));
1169        assert!(same_outside(
1170            BEFORE,
1171            &format!("{BEFORE}  - name: search\n    url: https://x.example.com\n")
1172        ));
1173        assert!(same_outside(
1174            "name: Local\n",
1175            "name: Local\nmcpServers:\n  - name: a\n"
1176        ));
1177        assert!(same_outside("mcpServers:\n", "mcpServers:\n  - name: a\n"));
1178        // Items without a scalar name, non-mappings and later duplicates
1179        // are compared like everything else outside the container.
1180        assert!(!same_outside(
1181            BEFORE,
1182            &BEFORE.replace("owner/block", "owner/other")
1183        ));
1184        assert!(!same_outside(
1185            BEFORE,
1186            &BEFORE.replace("just-text", "other-text")
1187        ));
1188        assert!(!same_outside(
1189            BEFORE,
1190            &BEFORE.replace("duplicate", "changed")
1191        ));
1192        assert!(!same_outside(
1193            BEFORE,
1194            &BEFORE.replace("  - just-text\n", "")
1195        ));
1196        assert!(!same_outside(
1197            BEFORE,
1198            &BEFORE.replace("name: Local", "name: Other")
1199        ));
1200    }
1201}