Skip to main content

lean_ctx_cloud/
unlink.rs

1// SPDX-License-Identifier: Apache-2.0
2//! `lean-ctx cloud unlink` (rc4-6): stop sharing one project folder with
3//! its vault, on this machine only.
4//!
5//! Local only: Cloud has no route to leave a vault, and none is needed. The
6//! vault and its data stay in Cloud; this machine just no longer binds the
7//! folder to it. Works while disconnected.
8//!
9//! In this order (a failure names what was already done):
10//! 1. the folder is remembered as not shared ([`crate::unlinked`]): nothing
11//!    resolves a vault for it again (another checkout of the repository, its
12//!    main checkout, a kept link file, a session that ends) until
13//!    `cloud link` in the folder;
14//! 2. knowledge drafts queued for that folder are dropped, and the capture
15//!    watermark of the project is reset, so a later share captures their
16//!    facts again;
17//! 3. the folder leaves its record in `projects.json`, and the record goes
18//!    when no folder remains (background sync only syncs recorded vaults);
19//! 4. `.lean-ctx-cloud.json` in the folder is removed, only when it is a
20//!    regular file that names that vault on this Cloud (a link to another
21//!    vault or server, a damaged file or a symlink stays).
22//!
23//! Kept: local knowledge, cache, sessions and `.lean-ctx-id`.
24
25use std::path::Path;
26
27use lean_ctx::core::pathutil::same_project;
28
29use crate::CloudError;
30use crate::link::LINK_FILE;
31use crate::outbox::{CHANNEL_KNOWLEDGE, Outbox};
32use crate::vault::{VaultMap, VaultRecord};
33
34/// Why a link file stayed in the folder.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum KeptReason {
37    /// It names another vault (or the vault on another server).
38    OtherVault,
39    /// It could not be read or parsed (or is no regular file).
40    Unreadable,
41    /// It is a symlink, never followed.
42    Symlink,
43}
44
45impl KeptReason {
46    /// The contract value (`link_file_reason`).
47    pub fn as_str(self) -> &'static str {
48        match self {
49            Self::OtherVault => "other_vault",
50            Self::Unreadable => "unreadable",
51            Self::Symlink => "symlink",
52        }
53    }
54}
55
56/// What became of the folder's `.lean-ctx-cloud.json`.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum LinkFile {
59    Removed,
60    Kept(KeptReason),
61    Absent,
62}
63
64impl LinkFile {
65    /// The contract value (`link_file`).
66    pub fn as_str(self) -> &'static str {
67        match self {
68            Self::Removed => "removed",
69            Self::Kept(_) => "kept",
70            Self::Absent => "absent",
71        }
72    }
73
74    /// The contract value (`link_file_reason`), only for a kept file.
75    pub fn reason(self) -> Option<&'static str> {
76        match self {
77            Self::Kept(reason) => Some(reason.as_str()),
78            _ => None,
79        }
80    }
81}
82
83/// What [`unlink`] did.
84#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct Unlinked {
86    /// The vault the folder no longer shares; `None`: it was not shared and
87    /// nothing changed.
88    pub vault: Option<VaultRecord>,
89    pub link_file: LinkFile,
90    /// Unsent knowledge drafts of the folder that were dropped.
91    pub drafts_dropped: usize,
92}
93
94/// Why [`unlink`] refused.
95#[derive(Debug)]
96pub enum UnlinkError {
97    /// The folder is a linked git worktree shared through its main checkout
98    /// `main`: the binding belongs to that folder.
99    SharedFromMain { main: String },
100    /// A file could not be written or removed.
101    Failed(CloudError),
102}
103
104impl std::fmt::Display for UnlinkError {
105    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106        match self {
107            Self::SharedFromMain { main } => write!(
108                f,
109                "this folder is shared through its main checkout {main}; stop sharing there"
110            ),
111            Self::Failed(error) => write!(f, "{error}"),
112        }
113    }
114}
115
116impl From<CloudError> for UnlinkError {
117    fn from(error: CloudError) -> Self {
118        Self::Failed(error)
119    }
120}
121
122/// Stop sharing the project folder `root` (cloud data dir `data_dir`;
123/// `server`: the self-hosted server of the connected Cloud, `None` for the
124/// hosted one or when not connected). Idempotent: a folder that is not
125/// shared changes nothing (`vault: None`).
126pub fn unlink(data_dir: &Path, root: &Path, server: Option<&str>) -> Result<Unlinked, UnlinkError> {
127    let root_text = root.to_string_lossy();
128    // S3: load → save without a lock; after !662 this moves to
129    // `vault::update_map`, with a race test against `Resolver::resolve`.
130    let mut map = VaultMap::load(data_dir);
131    let own = |record: &VaultRecord| record.roots.iter().any(|r| same_project(r, &root_text));
132    let Some((stable, vault)) = map
133        .vaults
134        .iter()
135        .find(|(_, record)| own(record))
136        .map(|(stable, record)| (stable.clone(), record.clone()))
137    else {
138        if let Some(main) = crate::link::main_worktree_root(root)
139            && map.for_root(&root_text).is_some()
140        {
141            return Err(UnlinkError::SharedFromMain {
142                main: main.to_string_lossy().into_owned(),
143            });
144        }
145        return unlink_unrecorded(data_dir, root, server, &map);
146    };
147    let mut done: Vec<String> = Vec::new();
148    let partial = |done: &[String], error: CloudError| {
149        if done.is_empty() {
150            UnlinkError::Failed(error)
151        } else {
152            UnlinkError::Failed(CloudError::Local(format!(
153                "{error} (already done: {})",
154                done.join(", ")
155            )))
156        }
157    };
158    crate::unlinked::add(data_dir, root).map_err(|e| partial(&done, e))?;
159    done.push("the folder is no longer shared on this machine".into());
160    let drafts_dropped =
161        drop_queued_drafts(data_dir, &root_text, &mut done).map_err(|e| partial(&done, e))?;
162    if drafts_dropped > 0 {
163        // Before the record goes: the watermark is kept under the vault.
164        crate::knowledge::draft::reset_watermark(data_dir, &stable)
165            .map_err(|e| partial(&done, e))?;
166        done.push("capture starts again from the beginning".into());
167    }
168    for record in map.vaults.values_mut() {
169        record.roots.retain(|r| !same_project(r, &root_text));
170    }
171    map.vaults.retain(|_, record| !record.roots.is_empty());
172    map.save(data_dir).map_err(|e| {
173        partial(
174            &done,
175            CloudError::Local(format!("write projects.json: {e}")),
176        )
177    })?;
178    done.push("the vault record was updated".into());
179    let link_file = match link_file_state(root, Some(&vault), server) {
180        LinkFile::Removed => {
181            remove_link_file(root).map_err(|e| partial(&done, e))?;
182            LinkFile::Removed
183        }
184        other => other,
185    };
186    Ok(Unlinked {
187        vault: Some(vault),
188        link_file,
189        drafts_dropped,
190    })
191}
192
193/// [`unlink`] of a folder no record names. It is still shared when its
194/// identity has a record (another checkout of the same repository, bd 39936)
195/// or when a link file would share it on the next sync (bd 39657 S-b): the
196/// opt-out is stored, its queued drafts are dropped, and the answer names
197/// the identity's vault. Without either nothing changes (`vault: None`).
198fn unlink_unrecorded(
199    data_dir: &Path,
200    root: &Path,
201    server: Option<&str>,
202    map: &VaultMap,
203) -> Result<Unlinked, UnlinkError> {
204    let by_identity = crate::vault::project_identity(root)
205        .map(|id| lean_ctx_protocol::cloud::vault::stable_identity(&id))
206        .and_then(|stable| map.vaults.get(&stable).cloned());
207    let link_file = link_file_state(root, by_identity.as_ref(), server);
208    if by_identity.is_none() && link_file == LinkFile::Absent {
209        return Ok(Unlinked {
210            vault: None,
211            link_file,
212            drafts_dropped: 0,
213        });
214    }
215    let mut done: Vec<String> = Vec::new();
216    crate::unlinked::add(data_dir, root)?;
217    done.push("the folder is no longer shared on this machine".into());
218    let partial = |done: &[String], error: CloudError| {
219        UnlinkError::Failed(CloudError::Local(format!(
220            "{error} (already done: {})",
221            done.join(", ")
222        )))
223    };
224    let root_text = root.to_string_lossy();
225    // The record and its capture watermark stay: they belong to the other
226    // checkout of the repository, which keeps sharing.
227    let drafts_dropped =
228        drop_queued_drafts(data_dir, &root_text, &mut done).map_err(|e| partial(&done, e))?;
229    if link_file == LinkFile::Removed {
230        remove_link_file(root).map_err(|e| partial(&done, e))?;
231    }
232    Ok(Unlinked {
233        vault: by_identity,
234        link_file,
235        drafts_dropped,
236    })
237}
238
239/// The state of `root`'s own link file: [`LinkFile::Removed`] means it is a
240/// regular, readable file that may be removed: it names this Cloud and
241/// `vault`, or any vault of this Cloud when there is none (`None`) it
242/// could name another one than (bd 39936: `other_vault` only for a file
243/// naming a different vault; bd 40060: a file for another Cloud is kept).
244fn link_file_state(root: &Path, vault: Option<&VaultRecord>, server: Option<&str>) -> LinkFile {
245    let Ok(meta) = std::fs::symlink_metadata(root.join(LINK_FILE)) else {
246        return LinkFile::Absent;
247    };
248    if meta.file_type().is_symlink() {
249        return LinkFile::Kept(KeptReason::Symlink);
250    }
251    if !meta.is_file() {
252        return LinkFile::Kept(KeptReason::Unreadable);
253    }
254    let Ok(Some(link)) = crate::link::read_link_file_at(root) else {
255        return LinkFile::Kept(KeptReason::Unreadable);
256    };
257    let same_server = match (link.server.as_deref(), server) {
258        (None, None) => true,
259        (Some(a), Some(b)) => a.eq_ignore_ascii_case(b),
260        _ => false,
261    };
262    let names_vault = same_server
263        && vault.is_none_or(|vault| link.vault.ns == vault.ns && link.vault.name == vault.name);
264    if names_vault {
265        LinkFile::Removed
266    } else {
267        LinkFile::Kept(KeptReason::OtherVault)
268    }
269}
270
271fn remove_link_file(root: &Path) -> Result<(), CloudError> {
272    let path = root.join(LINK_FILE);
273    match std::fs::remove_file(&path) {
274        Ok(()) => Ok(()),
275        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
276        Err(e) => Err(CloudError::Local(format!("remove {}: {e}", path.display()))),
277    }
278}
279
280/// Drop the knowledge drafts queued from `root`: sending one resolves its
281/// folder again. Returns how many were dropped.
282fn drop_queued_drafts(
283    data_dir: &Path,
284    root: &str,
285    done: &mut Vec<String>,
286) -> Result<usize, CloudError> {
287    let outbox = Outbox::at(data_dir);
288    let mut dropped = 0;
289    for item in outbox.list(CHANNEL_KNOWLEDGE) {
290        let from_root = item.payload["root"]
291            .as_str()
292            .is_some_and(|queued| same_project(queued, root));
293        if from_root {
294            outbox.remove(&item).inspect_err(|_| {
295                if dropped > 0 {
296                    done.push(format!("{dropped} queued draft(s) dropped"));
297                }
298            })?;
299            dropped += 1;
300        }
301    }
302    if dropped > 0 {
303        done.push(format!("{dropped} queued draft(s) dropped"));
304    }
305    Ok(dropped)
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311    use crate::link::link;
312
313    fn record(map: &mut VaultMap, key: &str, vault: (&str, &str), roots: &[&Path]) {
314        map.vaults.insert(
315            key.into(),
316            VaultRecord {
317                vault_id: format!("vlt_{key}"),
318                ns: vault.0.into(),
319                name: vault.1.into(),
320                sealed: false,
321                roots: roots
322                    .iter()
323                    .map(|r| r.to_string_lossy().into_owned())
324                    .collect(),
325            },
326        );
327    }
328
329    fn shared(data: &Path, roots: &[&Path]) {
330        let mut map = VaultMap::default();
331        record(&mut map, "k1", ("acme", "payments"), roots);
332        map.save(data).unwrap();
333    }
334
335    #[test]
336    fn a_shared_folder_is_unlinked_and_its_link_file_removed() {
337        let data = tempfile::tempdir().unwrap();
338        let repo = tempfile::tempdir().unwrap();
339        link(repo.path(), "acme/payments").unwrap();
340        shared(data.path(), &[repo.path()]);
341
342        let outcome = unlink(data.path(), repo.path(), None).unwrap();
343        assert_eq!(outcome.vault.unwrap().vault_id, "vlt_k1");
344        assert_eq!(outcome.link_file, LinkFile::Removed);
345        assert_eq!(outcome.drafts_dropped, 0);
346        assert!(!repo.path().join(LINK_FILE).exists());
347        assert!(
348            repo.path().join(".lean-ctx-id").exists(),
349            "identity is kept"
350        );
351        let map = VaultMap::load(data.path());
352        assert!(map.vaults.is_empty(), "the empty record is dropped");
353        assert!(map.for_root(&repo.path().to_string_lossy()).is_none());
354        assert!(crate::link::read_link(repo.path()).unwrap().is_none());
355        assert!(crate::unlinked::contains(data.path(), repo.path()));
356    }
357
358    #[test]
359    fn a_folder_that_is_not_shared_is_left_as_it_was_by_unlink() {
360        let data = tempfile::tempdir().unwrap();
361        let repo = tempfile::tempdir().unwrap();
362        let other = tempfile::tempdir().unwrap();
363        shared(data.path(), &[other.path()]);
364        let before = std::fs::read(data.path().join("projects.json")).unwrap();
365
366        for _ in 0..2 {
367            let outcome = unlink(data.path(), repo.path(), None).unwrap();
368            assert_eq!(outcome.vault, None);
369            assert_eq!(outcome.link_file, LinkFile::Absent);
370            assert_eq!(outcome.drafts_dropped, 0);
371        }
372        assert_eq!(
373            std::fs::read(data.path().join("projects.json")).unwrap(),
374            before
375        );
376        assert!(!crate::unlinked::contains(data.path(), repo.path()));
377    }
378
379    #[test]
380    fn unlink_of_one_of_two_folders_keeps_the_other_and_the_second_checkout_no_longer_resolves() {
381        let data = tempfile::tempdir().unwrap();
382        let one = tempfile::tempdir().unwrap();
383        let two = tempfile::tempdir().unwrap();
384        shared(data.path(), &[one.path(), two.path()]);
385
386        assert!(
387            unlink(data.path(), one.path(), None)
388                .unwrap()
389                .vault
390                .is_some()
391        );
392        let map = VaultMap::load(data.path());
393        let kept = map.vaults.get("k1").expect("record kept");
394        assert_eq!(kept.roots, vec![two.path().to_string_lossy().into_owned()]);
395        // M1: the record of the same repository still exists, but the
396        // unlinked folder resolves no vault through it.
397        assert!(
398            crate::resolution::vault_for_root(data.path(), one.path())
399                .unwrap()
400                .is_none()
401        );
402        assert!(
403            crate::resolution::vault_for_root(data.path(), two.path())
404                .unwrap()
405                .is_some()
406        );
407    }
408
409    #[test]
410    fn unlink_keeps_a_link_file_for_another_vault_and_the_opt_out_covers_it() {
411        let data = tempfile::tempdir().unwrap();
412        let repo = tempfile::tempdir().unwrap();
413        link(repo.path(), "acme/other").unwrap();
414        shared(data.path(), &[repo.path()]);
415
416        let outcome = unlink(data.path(), repo.path(), None).unwrap();
417        assert_eq!(outcome.link_file, LinkFile::Kept(KeptReason::OtherVault));
418        assert_eq!(outcome.link_file.reason(), Some("other_vault"));
419        assert!(repo.path().join(LINK_FILE).exists());
420        assert!(VaultMap::load(data.path()).vaults.is_empty());
421        // S1: the kept link file does not share the folder again.
422        assert!(crate::unlinked::contains(data.path(), repo.path()));
423        assert!(
424            crate::resolution::vault_for_root(data.path(), repo.path())
425                .unwrap()
426                .is_none()
427        );
428    }
429
430    #[test]
431    fn unlink_keeps_a_link_file_for_the_vault_on_another_server() {
432        let data = tempfile::tempdir().unwrap();
433        let repo = tempfile::tempdir().unwrap();
434        link(repo.path(), "acme/payments@selfhost.example").unwrap();
435        shared(data.path(), &[repo.path()]);
436
437        let outcome = unlink(data.path(), repo.path(), None).unwrap();
438        assert_eq!(outcome.link_file, LinkFile::Kept(KeptReason::OtherVault));
439        assert!(repo.path().join(LINK_FILE).exists());
440    }
441
442    #[test]
443    fn unlink_keeps_a_damaged_link_file() {
444        let data = tempfile::tempdir().unwrap();
445        let repo = tempfile::tempdir().unwrap();
446        std::fs::write(repo.path().join(LINK_FILE), "{not json").unwrap();
447        shared(data.path(), &[repo.path()]);
448
449        let outcome = unlink(data.path(), repo.path(), None).unwrap();
450        assert_eq!(outcome.link_file, LinkFile::Kept(KeptReason::Unreadable));
451        assert_eq!(outcome.link_file.reason(), Some("unreadable"));
452        assert!(repo.path().join(LINK_FILE).exists());
453    }
454
455    #[cfg(unix)]
456    #[test]
457    fn unlink_keeps_a_symlinked_link_file() {
458        let data = tempfile::tempdir().unwrap();
459        let repo = tempfile::tempdir().unwrap();
460        let elsewhere = tempfile::tempdir().unwrap();
461        link(elsewhere.path(), "acme/payments").unwrap();
462        std::os::unix::fs::symlink(
463            elsewhere.path().join(LINK_FILE),
464            repo.path().join(LINK_FILE),
465        )
466        .unwrap();
467        shared(data.path(), &[repo.path()]);
468
469        let outcome = unlink(data.path(), repo.path(), None).unwrap();
470        assert_eq!(outcome.link_file, LinkFile::Kept(KeptReason::Symlink));
471        assert!(elsewhere.path().join(LINK_FILE).exists());
472    }
473
474    #[test]
475    fn unlink_drops_the_queued_drafts_of_the_folder_and_counts_them() {
476        let data = tempfile::tempdir().unwrap();
477        let repo = tempfile::tempdir().unwrap();
478        let other = tempfile::tempdir().unwrap();
479        shared(data.path(), &[repo.path()]);
480        let outbox = Outbox::at(data.path());
481        let now = lean_ctx_time::UtcDateTime::now();
482        for root in [repo.path(), repo.path(), other.path()] {
483            outbox
484                .enqueue(
485                    CHANNEL_KNOWLEDGE,
486                    serde_json::json!({"stable_identity": "k1", "root": root.to_string_lossy()}),
487                    now,
488                )
489                .unwrap();
490        }
491
492        let outcome = unlink(data.path(), repo.path(), None).unwrap();
493        assert_eq!(outcome.drafts_dropped, 2);
494        let left = outbox.list(CHANNEL_KNOWLEDGE);
495        assert_eq!(left.len(), 1);
496        assert_eq!(
497            left[0].payload["root"],
498            other.path().to_string_lossy().as_ref()
499        );
500        // The watermark kept under the vault starts again.
501        let mark = data
502            .path()
503            .join(crate::knowledge::draft::WATERMARK_DIR)
504            .join(format!("vlt_k1.{}", crate::knowledge::draft::WATERMARK_EXT));
505        let mark: serde_json::Value =
506            serde_json::from_slice(&std::fs::read(mark).unwrap()).unwrap();
507        assert!(mark["since"].is_null() && mark["last_draft_at"].is_null());
508    }
509
510    #[test]
511    fn unlink_of_a_worktree_shared_through_its_main_checkout_is_refused() {
512        let base = tempfile::tempdir().unwrap();
513        let (main, wt) = crate::link::worktree_layout(base.path());
514        let data = tempfile::tempdir().unwrap();
515        shared(data.path(), &[&main]);
516
517        assert!(matches!(
518            unlink(data.path(), &wt, None),
519            Err(UnlinkError::SharedFromMain { .. })
520        ));
521        assert_eq!(VaultMap::load(data.path()).vaults.len(), 1);
522    }
523
524    #[test]
525    fn unlink_of_a_worktree_with_its_own_record_stops_the_main_checkout_fallback() {
526        let base = tempfile::tempdir().unwrap();
527        let (main, wt) = crate::link::worktree_layout(base.path());
528        let data = tempfile::tempdir().unwrap();
529        shared(data.path(), &[&main, &wt]);
530
531        assert!(unlink(data.path(), &wt, None).unwrap().vault.is_some());
532        // M1: `for_root` alone would fall back to the main checkout.
533        assert!(
534            VaultMap::load(data.path())
535                .for_root(&wt.to_string_lossy())
536                .is_some()
537        );
538        assert!(
539            crate::resolution::vault_for_root(data.path(), &wt)
540                .unwrap()
541                .is_none()
542        );
543        assert!(
544            crate::resolution::vault_for_root(data.path(), &main)
545                .unwrap()
546                .is_some()
547        );
548    }
549
550    #[test]
551    fn a_link_after_unlink_clears_the_opt_out() {
552        let data = tempfile::tempdir().unwrap();
553        let repo = tempfile::tempdir().unwrap();
554        shared(data.path(), &[repo.path()]);
555        unlink(data.path(), repo.path(), None).unwrap();
556        assert!(crate::unlinked::contains(data.path(), repo.path()));
557
558        assert!(crate::unlinked::remove(data.path(), repo.path()).unwrap());
559        assert!(!crate::unlinked::contains(data.path(), repo.path()));
560    }
561
562    /// bd 39657 S-b: a link file without a record still shares the folder
563    /// on the next sync, so unlink stores the opt-out for it; with no vault
564    /// it could name another one than, it is removed (bd 39936).
565    #[test]
566    fn unlink_of_a_link_file_without_a_record_stores_the_opt_out() {
567        let data = tempfile::tempdir().unwrap();
568        let repo = tempfile::tempdir().unwrap();
569        link(repo.path(), "acme/payments").unwrap();
570
571        let outcome = unlink(data.path(), repo.path(), None).unwrap();
572        assert_eq!(outcome.vault, None);
573        assert_eq!(outcome.link_file, LinkFile::Removed);
574        assert!(!repo.path().join(LINK_FILE).exists());
575        assert!(crate::unlinked::contains(data.path(), repo.path()));
576        assert!(
577            crate::resolution::vault_for_root(data.path(), repo.path())
578                .unwrap()
579                .is_none()
580        );
581    }
582
583    /// bd 40060 SHOULD: without a record, a link file for another Cloud (a
584    /// committed self-hosted link) is kept; the opt-out is stored anyway.
585    #[test]
586    fn unlink_without_a_record_keeps_a_link_file_for_another_cloud() {
587        let data = tempfile::tempdir().unwrap();
588        let repo = tempfile::tempdir().unwrap();
589        link(repo.path(), "acme/payments@cloud.selfhosted.example").unwrap();
590        let before = std::fs::read(repo.path().join(LINK_FILE)).unwrap();
591
592        let outcome = unlink(data.path(), repo.path(), None).unwrap();
593        assert_eq!(outcome.link_file, LinkFile::Kept(KeptReason::OtherVault));
594        assert_eq!(std::fs::read(repo.path().join(LINK_FILE)).unwrap(), before);
595        assert!(crate::unlinked::contains(data.path(), repo.path()));
596    }
597
598    /// bd 39936 MUST: a checkout shared only through its identity (the
599    /// record of another checkout of the same repository, no root entry,
600    /// no link file) stores the opt-out and names that vault.
601    #[test]
602    fn unlink_of_a_checkout_shared_through_its_identity_stores_the_opt_out() {
603        let data = tempfile::tempdir().unwrap();
604        let b = tempfile::tempdir().unwrap();
605        let c = tempfile::tempdir().unwrap();
606        std::fs::write(c.path().join(".lean-ctx-id"), "payments-repo").unwrap();
607        let stable = lean_ctx_protocol::cloud::vault::stable_identity(
608            &crate::vault::project_identity(c.path()).unwrap(),
609        );
610        let mut map = VaultMap::default();
611        record(&mut map, &stable, ("acme", "payments"), &[b.path()]);
612        map.save(data.path()).unwrap();
613        let before = std::fs::read(data.path().join("projects.json")).unwrap();
614
615        for _ in 0..2 {
616            let outcome = unlink(data.path(), c.path(), None).unwrap();
617            let vault = outcome.vault.expect("the identity's vault is named");
618            assert_eq!(
619                (vault.ns.as_str(), vault.name.as_str()),
620                ("acme", "payments")
621            );
622            assert_eq!(outcome.link_file, LinkFile::Absent);
623        }
624        assert!(crate::unlinked::contains(data.path(), c.path()));
625        assert!(!crate::unlinked::contains(data.path(), b.path()));
626        assert_eq!(
627            std::fs::read(data.path().join("projects.json")).unwrap(),
628            before,
629            "the other checkout keeps its record"
630        );
631    }
632
633    /// bd 39936: a link file naming the identity's vault is removed; one
634    /// naming a different vault stays as `other_vault`.
635    #[test]
636    fn unlink_through_the_identity_removes_only_a_link_file_for_that_vault() {
637        let data = tempfile::tempdir().unwrap();
638        let b = tempfile::tempdir().unwrap();
639        let mut map = VaultMap::default();
640        for (name, expected) in [
641            ("acme/payments", LinkFile::Removed),
642            ("acme/other", LinkFile::Kept(KeptReason::OtherVault)),
643        ] {
644            let c = tempfile::tempdir().unwrap();
645            std::fs::write(c.path().join(".lean-ctx-id"), "payments-repo").unwrap();
646            link(c.path(), name).unwrap();
647            let stable = lean_ctx_protocol::cloud::vault::stable_identity(
648                &crate::vault::project_identity(c.path()).unwrap(),
649            );
650            record(&mut map, &stable, ("acme", "payments"), &[b.path()]);
651            map.save(data.path()).unwrap();
652
653            let outcome = unlink(data.path(), c.path(), None).unwrap();
654            assert!(outcome.vault.is_some());
655            assert_eq!(outcome.link_file, expected, "{name}");
656        }
657    }
658
659    /// bd 39657 S-d: a damaged opt-out store fails the unlink and names it.
660    #[test]
661    fn unlink_with_a_damaged_opt_out_store_fails() {
662        let data = tempfile::tempdir().unwrap();
663        let repo = tempfile::tempdir().unwrap();
664        shared(data.path(), &[repo.path()]);
665        std::fs::write(data.path().join(crate::unlinked::FILE), b"[").unwrap();
666
667        let error = unlink(data.path(), repo.path(), None).unwrap_err();
668        assert!(matches!(error, UnlinkError::Failed(_)), "{error}");
669        assert!(error.to_string().contains(crate::unlinked::FILE), "{error}");
670        // Nothing else changed.
671        assert!(
672            VaultMap::load(data.path())
673                .for_root(&repo.path().to_string_lossy())
674                .is_some()
675        );
676    }
677}