Skip to main content

lean_ctx_cloud/
resolution.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Local vault resolutions that no longer fit their checkout (dogfood
3//! 5.11.: one repository split across two vaults without a warning).
4//!
5//! `projects.json` ([`VaultMap`]) remembers which vault Cloud resolved for a
6//! checkout. That memory goes stale when
7//! - the link file now names another vault (`cloud link` after `cloud
8//!   connect`, or a pulled commit that changed `.lean-ctx-cloud.json`), or
9//! - the checkout's identity changed: a `.lean-ctx-id` that an earlier
10//!   `cloud link` wrote (32 random hex characters) no longer outranks the git
11//!   origin ([`crate::vault::project_identity`]), so every checkout of one
12//!   origin is one repository again.
13//!
14//! A stale record is never used: it is dropped, and the next resolve maps
15//! the checkout again (with the person's first-share consent where the gate
16//! holds). When Cloud still answers with another vault than the link file
17//! names, the resolve is refused ([`refuse_unlinked`]): nothing syncs into
18//! a vault the link file does not name.
19
20use std::path::Path;
21
22use lean_ctx::core::pathutil::same_project;
23use lean_ctx_protocol::cloud::status::CloudStatusVaultMismatchV1;
24use lean_ctx_protocol::cloud::vault::{VaultRefV1, stable_identity};
25
26use super::CloudError;
27use super::link::read_link;
28use super::state::CloudStore;
29use super::vault::{VaultMap, VaultRecord, project_identity};
30
31/// Why a recorded resolution does not fit the checkout any more.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub enum StaleReason {
34    /// The link file names `linked` (`ns/name`).
35    Link { linked: String },
36    /// The checkout's identity is not the one the record was resolved for.
37    Identity,
38}
39
40/// A resolution of `root` to `resolved` (`ns/name`) that does not hold.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct Stale {
43    pub root: String,
44    pub resolved: String,
45    pub reason: StaleReason,
46}
47
48impl Stale {
49    /// The linked vault, when the link file is the reason.
50    pub fn linked(&self) -> Option<&str> {
51        match &self.reason {
52            StaleReason::Link { linked } => Some(linked),
53            StaleReason::Identity => None,
54        }
55    }
56
57    /// `vault_mismatch` of `cloud status --json`.
58    pub fn wire(&self) -> CloudStatusVaultMismatchV1 {
59        CloudStatusVaultMismatchV1 {
60            project_root: self.root.clone(),
61            resolved: self.resolved.clone(),
62            linked: self.linked().map(str::to_string),
63            reason: match self.reason {
64                StaleReason::Link { .. } => "link",
65                StaleReason::Identity => "identity",
66            }
67            .into(),
68        }
69    }
70
71    /// One line for people (status, connect, link, sync).
72    pub fn describe(&self) -> String {
73        match &self.reason {
74            StaleReason::Link { linked } => format!(
75                "this machine resolved {} to the vault {}, but its link file names {linked}",
76                self.root, self.resolved
77            ),
78            StaleReason::Identity => format!(
79                "this machine resolved {} to the vault {} under an identity the checkout no longer has (a `.lean-ctx-id` written by an earlier `cloud link`; the git origin counts now)",
80                self.root, self.resolved
81            ),
82        }
83    }
84}
85
86fn address(record: &VaultRecord) -> String {
87    format!("{}/{}", record.ns, record.name)
88}
89
90/// The record `root` uses (its own, or its main checkout's), its key and
91/// the recorded root it was found by.
92fn recorded<'a>(map: &'a VaultMap, root: &Path) -> Option<(&'a str, &'a VaultRecord, String)> {
93    let find = |root: &str| {
94        map.vaults.iter().find_map(|(key, record)| {
95            record
96                .roots
97                .iter()
98                .find(|known| same_project(known, root))
99                .map(|known| (key.as_str(), record, known.clone()))
100        })
101    };
102    let root_str = root.to_string_lossy();
103    find(&root_str).or_else(|| {
104        let main = super::link::main_worktree_root(root)?;
105        find(&main.to_string_lossy())
106    })
107}
108
109/// Whether the recorded resolution of `root` is stale. Local files only;
110/// changes nothing.
111pub fn stale_for_root(map: &VaultMap, root: &Path) -> Option<Stale> {
112    let (key, record, _) = recorded(map, root)?;
113    let resolved = address(record);
114    let stale = |reason| Stale {
115        root: root.to_string_lossy().into_owned(),
116        resolved: resolved.clone(),
117        reason,
118    };
119    // A damaged link file is refused where the link is used; here it says
120    // nothing about the record.
121    if let Ok(Some(link)) = read_link(root)
122        && (link.vault.ns != record.ns || link.vault.name != record.name)
123    {
124        return Some(stale(StaleReason::Link {
125            linked: format!("{}/{}", link.vault.ns, link.vault.name),
126        }));
127    }
128    let current = project_identity(root).map(|identity| stable_identity(&identity));
129    if current.is_some_and(|current| current != key) {
130        return Some(stale(StaleReason::Identity));
131    }
132    None
133}
134
135/// Drop the stale resolution of `root` from `map`, if any. A link file that
136/// names another vault drops the whole record: one identity has one vault,
137/// so every checkout of it resolves again. An identity change drops only
138/// this checkout from the record of its old identity.
139pub fn forget_stale(map: &mut VaultMap, root: &Path) -> Option<Stale> {
140    let stale = stale_for_root(map, root)?;
141    let (key, _, known) = recorded(map, root)?;
142    let key = key.to_string();
143    match stale.reason {
144        StaleReason::Link { .. } => {
145            map.vaults.remove(&key);
146        }
147        StaleReason::Identity => {
148            if let Some(record) = map.vaults.get_mut(&key) {
149                record.roots.retain(|r| r != &known);
150                if record.roots.is_empty() {
151                    map.vaults.remove(&key);
152                }
153            }
154        }
155    }
156    Some(stale)
157}
158
159/// [`forget_stale`] for every checkout `map` knows.
160pub fn forget_all_stale(map: &mut VaultMap) -> Vec<Stale> {
161    let roots: Vec<String> = map
162        .vaults
163        .values()
164        .flat_map(|record| record.roots.iter().cloned())
165        .collect();
166    roots
167        .iter()
168        .filter_map(|root| forget_stale(map, Path::new(root)))
169        .collect()
170}
171
172/// The vault map at `data_dir` without stale resolutions, as `scope` (the
173/// connected Cloud and account, [`crate::vault::vault_scope`]; `None` when
174/// not connected) sees it; the file is rewritten when one was dropped. What
175/// every pass that sends (sync, task proposals) reads, so none sends into a
176/// vault the checkout left, nor one of another Cloud or account (rc3-81,
177/// bd 39540: a pass during `cloud connect` elsewhere sends nothing).
178pub fn load_current(
179    data_dir: &Path,
180    scope: Option<&str>,
181) -> Result<(VaultMap, Vec<Stale>), CloudError> {
182    let (dropped, map) = super::vault::update_map(data_dir, forget_all_stale)?;
183    for stale in &dropped {
184        tracing::info!(
185            "cloud: dropped a stale vault resolution: {}",
186            stale.describe()
187        );
188    }
189    Ok((super::vault::in_scope(map, scope), dropped))
190}
191
192/// Drop the stale resolution of `root` in the map at `data_dir`.
193pub fn forget_stale_at(data_dir: &Path, root: &Path) -> Result<Option<Stale>, CloudError> {
194    super::vault::update_map(data_dir, |map| forget_stale(map, root)).map(|(stale, _)| stale)
195}
196
197/// The vault the checkout at `root` sends to, from the map of `store` as
198/// the connected Cloud and account see it (rc3-81): `None` when it has none
199/// (or only one of another Cloud or account), refused (`vault_mismatch`)
200/// when its record is stale. The one lookup of every caller that writes to a vault (tasks, bus
201/// posts and leases, docs, the live bus), so a record the link file or the
202/// identity no longer backs is never written to, also before link, connect
203/// or sync dropped it (a `git pull` that changed the link file).
204pub fn vault_for_root(store: &CloudStore, root: &Path) -> Result<Option<VaultRecord>, CloudError> {
205    // A folder the person stopped sharing (`cloud unlink`) has no vault,
206    // also not through its main checkout or another checkout (rc4-6).
207    if crate::unlinked::contains(store.data_dir(), root) {
208        return Ok(None);
209    }
210    vault_in(&super::vault::connected_map(store), root).map(Option::<&VaultRecord>::cloned)
211}
212
213/// The map at `data_dir` without its stale records, the file unchanged, as
214/// `scope` sees it (see [`load_current`]): what the live bus subscribes and
215/// announces from, so it never joins a vault a checkout left, nor one of
216/// another Cloud or account.
217pub fn current_view(data_dir: &Path, scope: Option<&str>) -> VaultMap {
218    let mut map = super::vault::in_scope(VaultMap::load(data_dir), scope);
219    forget_all_stale(&mut map);
220    map
221}
222
223/// [`vault_for_root`] in a loaded `map`.
224pub fn vault_in<'a>(map: &'a VaultMap, root: &Path) -> Result<Option<&'a VaultRecord>, CloudError> {
225    if let Some(stale) = stale_for_root(map, root) {
226        return Err(refuse_stale(&stale));
227    }
228    Ok(map.for_root(&root.to_string_lossy()))
229}
230
231/// Refused (`vault_mismatch`) when `record`, which a caller is about to
232/// sync for the checkout at `root`, is not what the checkout resolves to
233/// now: its link file names another vault, or the map's record of `root`
234/// at `data_dir` is stale, or the map there belongs to another Cloud or
235/// account than `scope` (the session's, [`crate::vault::vault_scope`]) now
236/// (rc3-81, bd 39540). The guard of every vault sync (background pass and
237/// `cloud sync`), whatever map snapshot the caller planned from.
238pub fn refuse_stale_record(
239    data_dir: &Path,
240    scope: &str,
241    record: &VaultRecord,
242    root: &Path,
243) -> Result<(), CloudError> {
244    if let Ok(Some(link)) = read_link(root)
245        && (link.vault.ns != record.ns || link.vault.name != record.name)
246    {
247        return Err(refuse_stale(&Stale {
248            root: root.to_string_lossy().into_owned(),
249            resolved: address(record),
250            reason: StaleReason::Link {
251                linked: format!("{}/{}", link.vault.ns, link.vault.name),
252            },
253        }));
254    }
255    let map = VaultMap::load(data_dir);
256    if !map.belongs_to(scope) {
257        return Err(CloudError::Local(
258            "this machine's vault records belong to another Cloud or account now; nothing was synced"
259                .into(),
260        ));
261    }
262    match stale_for_root(&map, root) {
263        Some(stale) => Err(refuse_stale(&stale)),
264        None => Ok(()),
265    }
266}
267
268/// The refusal for a write into the stale resolution `stale`.
269pub fn refuse_stale(stale: &Stale) -> CloudError {
270    CloudError::Refused(format!(
271        "vault_mismatch: {}. Nothing is sent to {} any more: run `lean-ctx cloud connect` here to resolve the project again",
272        stale.describe(),
273        stale.resolved
274    ))
275}
276
277/// Cloud answered `answered` for the checkout at `root`: refused when its
278/// link file names another vault. Cloud keeps the first binding of an
279/// identity (another Instance of the workspace may have made it), so a
280/// link to another vault cannot move it; syncing anyway would split the
281/// repository silently.
282pub fn refuse_unlinked(root: &Path, answered: &VaultRefV1) -> Result<(), CloudError> {
283    let Some(link) = read_link(root)? else {
284        return Ok(());
285    };
286    if link.vault == *answered {
287        return Ok(());
288    }
289    Err(CloudError::Refused(format!(
290        "vault_mismatch: the Cloud keeps this repository in the vault {}/{} (bound there first, possibly by another Instance of the workspace), but {} names {}/{}. Nothing syncs for it until both agree: run `lean-ctx cloud link {}/{}` here, or move the repository to {}/{} in the Cloud and run `lean-ctx cloud connect` again",
291        answered.ns,
292        answered.name,
293        super::link::LINK_FILE,
294        link.vault.ns,
295        link.vault.name,
296        answered.ns,
297        answered.name,
298        link.vault.ns,
299        link.vault.name,
300    )))
301}
302
303#[cfg(test)]
304mod tests {
305    use super::*;
306
307    fn checkout(base: &Path, name: &str, origin: Option<&str>) -> std::path::PathBuf {
308        let root = base.join(name);
309        std::fs::create_dir_all(root.join(".git")).unwrap();
310        let config = origin.map_or(String::new(), |url| {
311            format!("[remote \"origin\"]\n\turl = {url}\n")
312        });
313        std::fs::write(root.join(".git/config"), config).unwrap();
314        root
315    }
316
317    fn record(map: &mut VaultMap, key: &str, vault: &str, roots: &[&Path]) {
318        let (ns, name) = vault.split_once('/').unwrap();
319        map.vaults.insert(
320            key.into(),
321            VaultRecord {
322                vault_id: format!("id-{name}"),
323                ns: ns.into(),
324                name: name.into(),
325                sealed: false,
326                roots: roots
327                    .iter()
328                    .map(|r| r.to_string_lossy().into_owned())
329                    .collect(),
330            },
331        );
332    }
333
334    fn stable(root: &Path) -> String {
335        stable_identity(&project_identity(root).unwrap())
336    }
337
338    /// The scope of the connected Cloud and account in these tests.
339    const HERE: &str = "https://cloud.example#org=org_a";
340
341    /// rc3-81 bd 39540 M1: a map stamped for another Cloud or account
342    /// (a `cloud connect` elsewhere while a pass runs) gives no sender a
343    /// vault: not the pass that sends (`load_current`), not the lookup of
344    /// tasks, bus and docs (`vault_for_root`), not the live bus
345    /// (`current_view`), not the guard of every vault sync.
346    #[test]
347    fn vault_origin_a_map_of_another_scope_gives_no_sender_a_vault() {
348        let base = tempfile::tempdir().unwrap();
349        let store = CloudStore::at(base.path().join("config"), base.path().join("data"));
350        std::fs::create_dir_all(store.data_dir()).unwrap();
351        let a = checkout(base.path(), "a", Some("https://github.com/acme/pay.git"));
352        let mut map = VaultMap::default();
353        record(&mut map, &stable(&a), "acme/pay", &[&a]);
354        map.origin = Some(crate::vault::vault_scope("https://cloud.example", "org_b"));
355        map.save(store.data_dir()).unwrap();
356        let planned = map.vaults.values().next().unwrap().clone();
357        let enroll = |org: &str| {
358            store
359                .write_config(
360                    crate::state::INSTANCE_FILE,
361                    &crate::state::InstanceRecord {
362                        instance_id: "inst_a".into(),
363                        org_id: org.into(),
364                        org_name: "Acme".into(),
365                        label: "mac".into(),
366                        url: "https://cloud.example".into(),
367                        org_salt_id: "salt".into(),
368                        enrolled_at: "2026-10-24T00:00:00Z".into(),
369                        web_url: None,
370                        org_kind: None,
371                        company_name: None,
372                    },
373                )
374                .unwrap();
375        };
376        enroll("org_a");
377        assert_eq!(crate::vault::connected_scope(&store).as_deref(), Some(HERE));
378        let data = store.data_dir();
379        let (current, _) = load_current(data, Some(HERE)).unwrap();
380        assert!(current.vaults.is_empty(), "the sending pass sees nothing");
381        assert_eq!(vault_for_root(&store, &a).unwrap(), None);
382        assert!(current_view(data, Some(HERE)).vaults.is_empty());
383        let refused = refuse_stale_record(data, HERE, &planned, &a).unwrap_err();
384        assert!(
385            refused.to_string().contains("another Cloud or account"),
386            "{refused}"
387        );
388        assert_eq!(
389            VaultMap::load(data).vaults.len(),
390            1,
391            "kept on disk for its own account"
392        );
393
394        // A switch to another account removes the local Cloud data of the
395        // one before (3.12.8 account scope): the map does not come back
396        // for the account it was stamped for (rc3-81's restore after the
397        // return no longer holds).
398        enroll("org_b");
399        let there = crate::vault::vault_scope("https://cloud.example", "org_b");
400        assert_eq!(crate::vault::connected_scope(&store), Some(there.clone()));
401        assert_eq!(vault_for_root(&store, &a).unwrap(), None);
402        assert!(
403            load_current(data, Some(&there))
404                .unwrap()
405                .0
406                .vaults
407                .is_empty()
408        );
409        assert!(
410            VaultMap::load(data).vaults.is_empty(),
411            "gone after the switch"
412        );
413    }
414
415    /// rc3-81 bd 39540 S-a, bd 39791 S1: a refused link puts back only the
416    /// records of its checkout, and only while the map still belongs to the
417    /// scope it was read for.
418    #[test]
419    fn vault_origin_restore_keeps_a_newer_map_of_another_scope() {
420        let data = tempfile::tempdir().unwrap();
421        let base = tempfile::tempdir().unwrap();
422        let (a, b) = (
423            checkout(base.path(), "a", None),
424            checkout(base.path(), "b", None),
425        );
426        let a_text = a.to_string_lossy().into_owned();
427        let mut snapshot = VaultMap::default();
428        record(&mut snapshot, "s1", "acme/pay", &[&a]);
429        record(&mut snapshot, "s2", "acme/old", &[&b]);
430
431        // Meanwhile: a was moved to another vault, b linked anew, map
432        // stamped. Only a's record comes back; b's newer state stays.
433        let mut changed = VaultMap {
434            origin: Some(HERE.into()),
435            ..Default::default()
436        };
437        record(&mut changed, "s9", "acme/new", &[&a]);
438        record(&mut changed, "s3", "acme/shop", &[&b]);
439        changed.save(data.path()).unwrap();
440        assert!(crate::vault::restore_root(data.path(), &snapshot, &a_text, HERE).unwrap());
441        let map = VaultMap::load(data.path());
442        assert_eq!(map.origin.as_deref(), Some(HERE));
443        assert_eq!(map.for_root(&a_text).map(|r| r.name.as_str()), Some("pay"));
444        assert!(!map.vaults.contains_key("s9"), "a's later record left");
445        assert!(map.vaults.contains_key("s3") && !map.vaults.contains_key("s2"));
446
447        // An enrollment elsewhere switched the map: it stays as it is.
448        let elsewhere = VaultMap {
449            origin: Some(crate::vault::vault_scope("https://cloud.example", "org_b")),
450            ..Default::default()
451        };
452        elsewhere.save(data.path()).unwrap();
453        assert!(!crate::vault::restore_root(data.path(), &snapshot, &a_text, HERE).unwrap());
454        assert_eq!(VaultMap::load(data.path()), elsewhere);
455    }
456
457    /// The guard of `place::sync_vault`: a record planned from an older map
458    /// is refused once the link file names another vault, also when the map
459    /// on disk no longer has it.
460    #[test]
461    fn a_sync_of_a_record_the_link_file_left_is_refused() {
462        let base = tempfile::tempdir().unwrap();
463        let data = base.path().join("data");
464        std::fs::create_dir_all(&data).unwrap();
465        let a = checkout(
466            base.path(),
467            "a",
468            Some("git@github.com:yves/leanctx-cloud.git"),
469        );
470        let mut map = VaultMap::default();
471        record(&mut map, &stable(&a), "yves/cloud", &[&a]);
472        map.save(&data).unwrap();
473        let planned = map.vaults.values().next().unwrap().clone();
474        crate::link::link(&a, "yves/cloud").unwrap();
475        assert!(refuse_stale_record(&data, HERE, &planned, &a).is_ok());
476
477        crate::link::link(&a, "yves/leanctx-cloud").unwrap();
478        let refused = refuse_stale_record(&data, HERE, &planned, &a).unwrap_err();
479        assert!(refused.to_string().contains("vault_mismatch"), "{refused}");
480        VaultMap::default().save(&data).unwrap();
481        assert!(refuse_stale_record(&data, HERE, &planned, &a).is_err());
482    }
483
484    #[test]
485    fn a_link_that_names_another_vault_drops_the_whole_record() {
486        let base = tempfile::tempdir().unwrap();
487        let a = checkout(
488            base.path(),
489            "a",
490            Some("git@github.com:yves/leanctx-cloud.git"),
491        );
492        let b = checkout(
493            base.path(),
494            "b",
495            Some("git@github.com:yves/leanctx-cloud.git"),
496        );
497        let mut map = VaultMap::default();
498        record(&mut map, &stable(&a), "yves/cloud", &[&a, &b]);
499        assert_eq!(
500            stale_for_root(&map, &a),
501            None,
502            "no link file: nothing to compare"
503        );
504
505        super::super::link::link(&a, "yves/leanctx-cloud").unwrap();
506        let stale = stale_for_root(&map, &a).expect("stale");
507        assert_eq!(stale.resolved, "yves/cloud");
508        assert_eq!(stale.linked(), Some("yves/leanctx-cloud"));
509        assert!(
510            stale
511                .describe()
512                .contains("link file names yves/leanctx-cloud")
513        );
514        assert_eq!(forget_stale(&mut map, &a), Some(stale));
515        assert!(map.vaults.is_empty(), "b is the same repository");
516        assert!(map.for_root(&b.to_string_lossy()).is_none());
517    }
518
519    #[test]
520    fn an_identity_change_drops_only_that_checkout() {
521        let base = tempfile::tempdir().unwrap();
522        let a = checkout(base.path(), "a", Some("https://github.com/acme/pay.git"));
523        let mut map = VaultMap::default();
524        record(&mut map, "old-random-identity", "acme/pay", &[&a]);
525        let other = base.path().join("elsewhere");
526        record(&mut map, &stable(&a), "acme/pay", &[&other]);
527        let stale = forget_stale(&mut map, &a).expect("stale");
528        assert_eq!(stale.reason, StaleReason::Identity);
529        assert!(!map.vaults.contains_key("old-random-identity"));
530        assert!(map.vaults.contains_key(&stable(&a)));
531        assert_eq!(forget_stale(&mut map, &a), None);
532    }
533
534    #[test]
535    fn load_current_rewrites_the_map_once() {
536        let base = tempfile::tempdir().unwrap();
537        let data = base.path().join("data");
538        std::fs::create_dir_all(&data).unwrap();
539        let a = checkout(base.path(), "a", Some("https://github.com/acme/pay.git"));
540        let mut map = VaultMap::default();
541        record(&mut map, &stable(&a), "acme/old", &[&a]);
542        map.save(&data).unwrap();
543        super::super::link::link(&a, "acme/pay").unwrap();
544        let (map, dropped) = load_current(&data, None).unwrap();
545        assert_eq!(dropped.len(), 1);
546        assert!(map.vaults.is_empty());
547        assert!(VaultMap::load(&data).vaults.is_empty(), "saved");
548        assert!(load_current(&data, None).unwrap().1.is_empty());
549    }
550
551    #[test]
552    fn cloud_answering_another_vault_than_the_link_is_refused() {
553        let base = tempfile::tempdir().unwrap();
554        let a = checkout(base.path(), "a", Some("https://github.com/acme/pay.git"));
555        let answered = VaultRefV1 {
556            ns: "acme".into(),
557            name: "old".into(),
558        };
559        assert!(
560            refuse_unlinked(&a, &answered).is_ok(),
561            "no link: the Cloud decides"
562        );
563        super::super::link::link(&a, "acme/pay").unwrap();
564        let refused = refuse_unlinked(&a, &answered).unwrap_err().to_string();
565        assert!(refused.contains("vault_mismatch"), "{refused}");
566        assert!(
567            refused.contains("acme/old") && refused.contains("acme/pay"),
568            "{refused}"
569        );
570        let linked = VaultRefV1 {
571            ns: "acme".into(),
572            name: "pay".into(),
573        };
574        assert!(refuse_unlinked(&a, &linked).is_ok());
575    }
576}