1use 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
20pub 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#[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
50pub 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
82fn 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 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 return Ok(old_target
165 .snippet(&entry.name, value)
166 .map(|text| target.mask(&text)));
167 }
168 }
169 }
170 }
171 Ok(None)
172}
173
174pub 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#[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 tx.set_summary(summary);
230 Ok(report)
231 })?;
232 Ok((committed.value, committed.commit))
233}
234
235fn 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}