Skip to main content

surjection_core/apply/
resolve.rs

1//! The drift resolver (SPEC 8.2, 8.6, 13.4): one entry that needs a
2//! decision (`drifted`, `conflict`, `missing`, `collision`), shown as last
3//! written, as in the file now and as desired, and resolved through the
4//! planner's per-entry [`Decision`] in one store commit.
5
6use crate::adapters::mapper::Canonical;
7use crate::apply::exec::PlanInputs;
8use crate::apply::ledger::{EntryKind, LedgerKey, LedgerSlot};
9use crate::apply::plan::{
10    self, Decision, EntryPlan, EntryState, OnConflict, PlanOptions, ProjectSelection, ScopeFilter,
11    TargetFilter, TargetPlan,
12};
13use crate::apply::render::DesiredState;
14use crate::apply::{ApplyEnv, ApplyReport, ApplyRequest, apply_in};
15use crate::error::CoreError;
16use crate::formats::NativeValue;
17use crate::model::applied::{ApplyTrigger, Scope};
18use crate::store::{CommitId, LogFilter, Machine, Operation, Store};
19
20/// What the resolver showed for `entry`, as one keyed hash: its state, the
21/// entry in the file and the desired entry (canonical forms). A resolution
22/// is carried out only while the entry still has this fingerprint, so an
23/// action never applies to content the user did not see. Keyed with the
24/// ledger key (inline entries hold secret values); without one yet, with
25/// the zero key a read-only plan uses.
26pub fn fingerprint(ax: &ApplyEnv<'_>, entry: &EntryPlan) -> Result<String, CoreError> {
27    let key = LedgerKey::load(ax.fs, &ax.home.state_dir())?
28        .unwrap_or_else(|| LedgerKey::from_bytes([0; 32]));
29    let value = NativeValue::Array(vec![
30        NativeValue::String(entry.state.as_str().to_owned()),
31        NativeValue::String(entry.client.unwrap_or_default().to_owned()),
32        NativeValue::String(entry.name.clone()),
33        entry.observed.clone().unwrap_or(NativeValue::Null),
34        entry.desired.clone().unwrap_or(NativeValue::Null),
35    ]);
36    Ok(key.hash(&Canonical::of(&value)))
37}
38
39/// The three columns of the resolver, each rendered as the file writes the
40/// entry ([`TargetPlan::snippet`]) and masked; `None` where there is
41/// nothing (no file entry, nothing desired) or, for `last_written`, when it
42/// cannot be recovered.
43#[derive(Debug, Clone, Default)]
44pub struct ThreeWay {
45    pub last_written: Option<String>,
46    pub current: Option<String>,
47    pub desired: Option<String>,
48}
49
50/// The resolver's columns for `entry` of `target` (a target of the current
51/// plan). What Surjection last wrote is not kept, only its keyed hash: for a
52/// `drifted` entry it is the desired entry (the planner found their hashes
53/// equal); otherwise it is rendered again from the store commit the
54/// ledger names, and shown only when its hash matches the ledger's. A
55/// collision was never written.
56pub fn three_way(
57    store: Option<&Store<'_>>,
58    ax: &ApplyEnv<'_>,
59    target: &TargetPlan,
60    entry: &EntryPlan,
61) -> Result<ThreeWay, CoreError> {
62    let render = |value: &Option<NativeValue>| {
63        value
64            .as_ref()
65            .and_then(|value| target.snippet(&entry.name, value))
66    };
67    let last_written = match entry.state {
68        EntryState::Collision => None,
69        EntryState::Drifted if entry.desired.is_some() => render(&entry.desired),
70        _ => match store {
71            Some(store) => recovered(store, ax, target, entry)?,
72            None => None,
73        },
74    };
75    Ok(ThreeWay {
76        last_written,
77        current: render(&entry.observed),
78        desired: render(&entry.desired),
79    })
80}
81
82/// What Surjection last wrote for `entry`, rendered again from the store and
83/// shown only when the rendering hashes to the ledger's recorded hash. The
84/// ledger names the store commit the apply started from; an apply inside
85/// a store edit (instant mode) wrote what the next commit holds, so that
86/// commit is tried first, then the named one.
87fn recovered(
88    store: &Store<'_>,
89    ax: &ApplyEnv<'_>,
90    target: &TargetPlan,
91    entry: &EntryPlan,
92) -> Result<Option<String>, CoreError> {
93    let Some(client) = entry.client else {
94        return Ok(None);
95    };
96    let inputs = PlanInputs::load(Some(store), ax)?;
97    let file = target.file.to_string_lossy();
98    let slot = LedgerSlot {
99        scope: target.scope,
100        project_id: target.project_id.as_deref(),
101        file: &file,
102        container: &target.pointer,
103    };
104    let row = inputs
105        .ledger
106        .get(&slot, &entry.name)
107        .filter(|row| row.kind == EntryKind::McpEntry && row.client == client);
108    let Some((hash, commit)) =
109        row.and_then(|row| row.written_hash.as_ref().zip(row.store_commit.as_ref()))
110    else {
111        return Ok(None);
112    };
113    // A commit that is gone (a rewritten store) recovers nothing.
114    let Ok(base) = store.resolve(commit) else {
115        return Ok(None);
116    };
117    let log = store.log(&LogFilter::default())?;
118    let mut candidates = Vec::new();
119    if let Some(index) = log.iter().position(|logged| logged.id == base)
120        && index > 0
121    {
122        candidates.push(log[index - 1].id.clone());
123    }
124    candidates.push(base);
125
126    let machine = Machine::load(ax.fs, &ax.home.state_dir())?;
127    let options = PlanOptions {
128        scope: match target.scope {
129            Scope::User => ScopeFilter::System,
130            Scope::Project | Scope::ProjectLocal => ScopeFilter::Project,
131        },
132        projects: match &target.project {
133            Some(root) => ProjectSelection::Only(root.clone()),
134            None => ProjectSelection::All,
135        },
136        targets: Some(vec![filter_of(target)]),
137        ..PlanOptions::default()
138    };
139    let cx = ax.render_cx(inputs.memory.clone());
140    for id in candidates {
141        let revision = store.revision(&id)?;
142        let Ok(desired) = DesiredState::load(&revision, machine.as_ref().map(|m| m.id.as_str()))
143        else {
144            continue;
145        };
146        let old = plan::plan(&cx, &desired, &inputs.ledger, &inputs.key, &options)?;
147        for old_target in old
148            .targets
149            .iter()
150            .filter(|old| old.pointer == target.pointer)
151        {
152            for old_entry in &old_target.entries {
153                if old_entry.name != entry.name || old_entry.client != Some(client) {
154                    continue;
155                }
156                let Some(value) = &old_entry.desired else {
157                    continue;
158                };
159                let matches = plan::canonical(client, value)
160                    .is_some_and(|canonical| inputs.key.hash(&canonical) == *hash);
161                if matches {
162                    // Masked by both plans: the values that commit renders
163                    // inline and those the current plan knows.
164                    return Ok(old_target
165                        .snippet(&entry.name, value)
166                        .map(|text| target.mask(&text)));
167                }
168            }
169        }
170    }
171    Ok(None)
172}
173
174/// The filter that selects `target` alone.
175pub fn filter_of(target: &TargetPlan) -> TargetFilter {
176    TargetFilter {
177        scope: target.scope,
178        project: target.project.clone(),
179        file: target.file.clone(),
180    }
181}
182
183/// Resolves entry `name` of `client` in the target `filter` selects with
184/// `resolution`, applying only that file, in one store transaction: a
185/// commit when the store or a client file changes (an import edits the
186/// server, a release this machine's overlay, an overwrite writes the
187/// file), none otherwise. Inside the transaction the entry is planned
188/// again and must still have the [`fingerprint`] `expected` (what the
189/// resolver showed); otherwise `entry_changed` and nothing is done.
190/// Summaries: `adopt: <client>/<name> drift` for an import of a changed
191/// entry (SPEC 8.6), else `resolve: <action> <client>/<name>`.
192#[allow(clippy::too_many_arguments)]
193pub fn resolve(
194    store: &Store<'_>,
195    ax: &ApplyEnv<'_>,
196    filter: TargetFilter,
197    client: &str,
198    name: &str,
199    state: EntryState,
200    resolution: OnConflict,
201    expected: &str,
202) -> Result<(ApplyReport, Option<CommitId>), CoreError> {
203    let entry = format!("{client}/{name}");
204    let summary = match (resolution, state) {
205        (OnConflict::Import, EntryState::Missing) => format!("resolve: respect deletion {entry}"),
206        (OnConflict::Import, EntryState::Collision) => format!("adopt: {entry} (import theirs)"),
207        (OnConflict::Import, _) => format!("adopt: {entry} drift"),
208        (other, _) => format!("resolve: {} {entry}", other.as_str()),
209    };
210    let request = ApplyRequest {
211        options: PlanOptions {
212            on_conflict: OnConflict::Ask,
213            decisions: vec![Decision {
214                client: client.to_owned(),
215                name: name.to_owned(),
216                resolution,
217            }],
218            targets: Some(vec![filter.clone()]),
219            ..PlanOptions::default()
220        },
221        trigger: ApplyTrigger::Review,
222    };
223    let operation = Operation::new("entry.resolve", summary.clone());
224    let committed = store.transaction(operation, |tx| {
225        check_unchanged(tx, ax, &filter, client, name, expected)?;
226        let report = apply_in(tx, ax, &request)?;
227        // The apply names a file-only run `apply: ...`; the commit is the
228        // resolution.
229        tx.set_summary(summary);
230        Ok(report)
231    })?;
232    Ok((committed.value, committed.commit))
233}
234
235/// `entry_changed` unless entry `name` of `client` in the target `filter`
236/// selects, planned against the transaction's view of the store, still has
237/// the fingerprint `expected`.
238fn check_unchanged(
239    tx: &crate::store::Transaction<'_>,
240    ax: &ApplyEnv<'_>,
241    filter: &TargetFilter,
242    client: &str,
243    name: &str,
244    expected: &str,
245) -> Result<(), CoreError> {
246    let state_dir = ax.home.state_dir();
247    let desired = DesiredState::load(tx, Some(&tx.machine().id))?;
248    let ledger = crate::apply::ledger::Ledger::load(ax.fs, &state_dir)?;
249    let key = LedgerKey::load(ax.fs, &state_dir)?.unwrap_or_else(|| LedgerKey::from_bytes([0; 32]));
250    let cx = ax.render_cx(tx.store().secret_memory().clone());
251    let options = PlanOptions {
252        targets: Some(vec![filter.clone()]),
253        ..PlanOptions::default()
254    };
255    let now = plan::plan(&cx, &desired, &ledger, &key, &options)?;
256    let entry = now
257        .targets
258        .iter()
259        .flat_map(|target| &target.entries)
260        .find(|entry| entry.name == name && entry.client == Some(client));
261    let same = match entry {
262        Some(entry) => fingerprint(ax, entry)? == expected,
263        None => false,
264    };
265    if same {
266        Ok(())
267    } else {
268        Err(CoreError::new(
269            crate::error::ErrorCode::EntryChanged,
270            format!(
271                "{client}/{name} changed since the resolver showed it; nothing was done. Open it \
272                 again to see the current versions"
273            ),
274        ))
275    }
276}