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    /// A store on `data` that is not connected: its map as it is on disk.
314    fn at(data: &Path) -> crate::CloudStore {
315        crate::CloudStore::at(data.join("config"), data.to_path_buf())
316    }
317
318    fn record(map: &mut VaultMap, key: &str, vault: (&str, &str), roots: &[&Path]) {
319        map.vaults.insert(
320            key.into(),
321            VaultRecord {
322                vault_id: format!("vlt_{key}"),
323                ns: vault.0.into(),
324                name: vault.1.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 shared(data: &Path, roots: &[&Path]) {
335        let mut map = VaultMap::default();
336        record(&mut map, "k1", ("acme", "payments"), roots);
337        map.save(data).unwrap();
338    }
339
340    #[test]
341    fn a_shared_folder_is_unlinked_and_its_link_file_removed() {
342        let data = tempfile::tempdir().unwrap();
343        let repo = tempfile::tempdir().unwrap();
344        link(repo.path(), "acme/payments").unwrap();
345        shared(data.path(), &[repo.path()]);
346
347        let outcome = unlink(data.path(), repo.path(), None).unwrap();
348        assert_eq!(outcome.vault.unwrap().vault_id, "vlt_k1");
349        assert_eq!(outcome.link_file, LinkFile::Removed);
350        assert_eq!(outcome.drafts_dropped, 0);
351        assert!(!repo.path().join(LINK_FILE).exists());
352        assert!(
353            repo.path().join(".lean-ctx-id").exists(),
354            "identity is kept"
355        );
356        let map = VaultMap::load(data.path());
357        assert!(map.vaults.is_empty(), "the empty record is dropped");
358        assert!(map.for_root(&repo.path().to_string_lossy()).is_none());
359        assert!(crate::link::read_link(repo.path()).unwrap().is_none());
360        assert!(crate::unlinked::contains(data.path(), repo.path()));
361    }
362
363    #[test]
364    fn a_folder_that_is_not_shared_is_left_as_it_was_by_unlink() {
365        let data = tempfile::tempdir().unwrap();
366        let repo = tempfile::tempdir().unwrap();
367        let other = tempfile::tempdir().unwrap();
368        shared(data.path(), &[other.path()]);
369        let before = std::fs::read(data.path().join("projects.json")).unwrap();
370
371        for _ in 0..2 {
372            let outcome = unlink(data.path(), repo.path(), None).unwrap();
373            assert_eq!(outcome.vault, None);
374            assert_eq!(outcome.link_file, LinkFile::Absent);
375            assert_eq!(outcome.drafts_dropped, 0);
376        }
377        assert_eq!(
378            std::fs::read(data.path().join("projects.json")).unwrap(),
379            before
380        );
381        assert!(!crate::unlinked::contains(data.path(), repo.path()));
382    }
383
384    #[test]
385    fn unlink_of_one_of_two_folders_keeps_the_other_and_the_second_checkout_no_longer_resolves() {
386        let data = tempfile::tempdir().unwrap();
387        let one = tempfile::tempdir().unwrap();
388        let two = tempfile::tempdir().unwrap();
389        shared(data.path(), &[one.path(), two.path()]);
390
391        assert!(
392            unlink(data.path(), one.path(), None)
393                .unwrap()
394                .vault
395                .is_some()
396        );
397        let map = VaultMap::load(data.path());
398        let kept = map.vaults.get("k1").expect("record kept");
399        assert_eq!(kept.roots, vec![two.path().to_string_lossy().into_owned()]);
400        // M1: the record of the same repository still exists, but the
401        // unlinked folder resolves no vault through it.
402        assert!(
403            crate::resolution::vault_for_root(&at(data.path()), one.path())
404                .unwrap()
405                .is_none()
406        );
407        assert!(
408            crate::resolution::vault_for_root(&at(data.path()), two.path())
409                .unwrap()
410                .is_some()
411        );
412    }
413
414    #[test]
415    fn unlink_keeps_a_link_file_for_another_vault_and_the_opt_out_covers_it() {
416        let data = tempfile::tempdir().unwrap();
417        let repo = tempfile::tempdir().unwrap();
418        link(repo.path(), "acme/other").unwrap();
419        shared(data.path(), &[repo.path()]);
420
421        let outcome = unlink(data.path(), repo.path(), None).unwrap();
422        assert_eq!(outcome.link_file, LinkFile::Kept(KeptReason::OtherVault));
423        assert_eq!(outcome.link_file.reason(), Some("other_vault"));
424        assert!(repo.path().join(LINK_FILE).exists());
425        assert!(VaultMap::load(data.path()).vaults.is_empty());
426        // S1: the kept link file does not share the folder again.
427        assert!(crate::unlinked::contains(data.path(), repo.path()));
428        assert!(
429            crate::resolution::vault_for_root(&at(data.path()), repo.path())
430                .unwrap()
431                .is_none()
432        );
433    }
434
435    #[test]
436    fn unlink_keeps_a_link_file_for_the_vault_on_another_server() {
437        let data = tempfile::tempdir().unwrap();
438        let repo = tempfile::tempdir().unwrap();
439        link(repo.path(), "acme/payments@selfhost.example").unwrap();
440        shared(data.path(), &[repo.path()]);
441
442        let outcome = unlink(data.path(), repo.path(), None).unwrap();
443        assert_eq!(outcome.link_file, LinkFile::Kept(KeptReason::OtherVault));
444        assert!(repo.path().join(LINK_FILE).exists());
445    }
446
447    #[test]
448    fn unlink_keeps_a_damaged_link_file() {
449        let data = tempfile::tempdir().unwrap();
450        let repo = tempfile::tempdir().unwrap();
451        std::fs::write(repo.path().join(LINK_FILE), "{not json").unwrap();
452        shared(data.path(), &[repo.path()]);
453
454        let outcome = unlink(data.path(), repo.path(), None).unwrap();
455        assert_eq!(outcome.link_file, LinkFile::Kept(KeptReason::Unreadable));
456        assert_eq!(outcome.link_file.reason(), Some("unreadable"));
457        assert!(repo.path().join(LINK_FILE).exists());
458    }
459
460    #[cfg(unix)]
461    #[test]
462    fn unlink_keeps_a_symlinked_link_file() {
463        let data = tempfile::tempdir().unwrap();
464        let repo = tempfile::tempdir().unwrap();
465        let elsewhere = tempfile::tempdir().unwrap();
466        link(elsewhere.path(), "acme/payments").unwrap();
467        std::os::unix::fs::symlink(
468            elsewhere.path().join(LINK_FILE),
469            repo.path().join(LINK_FILE),
470        )
471        .unwrap();
472        shared(data.path(), &[repo.path()]);
473
474        let outcome = unlink(data.path(), repo.path(), None).unwrap();
475        assert_eq!(outcome.link_file, LinkFile::Kept(KeptReason::Symlink));
476        assert!(elsewhere.path().join(LINK_FILE).exists());
477    }
478
479    #[test]
480    fn unlink_drops_the_queued_drafts_of_the_folder_and_counts_them() {
481        let data = tempfile::tempdir().unwrap();
482        let repo = tempfile::tempdir().unwrap();
483        let other = tempfile::tempdir().unwrap();
484        shared(data.path(), &[repo.path()]);
485        let outbox = Outbox::at(data.path());
486        let now = lean_ctx_time::UtcDateTime::now();
487        for root in [repo.path(), repo.path(), other.path()] {
488            outbox
489                .enqueue(
490                    CHANNEL_KNOWLEDGE,
491                    serde_json::json!({"stable_identity": "k1", "root": root.to_string_lossy()}),
492                    now,
493                )
494                .unwrap();
495        }
496
497        let outcome = unlink(data.path(), repo.path(), None).unwrap();
498        assert_eq!(outcome.drafts_dropped, 2);
499        let left = outbox.list(CHANNEL_KNOWLEDGE);
500        assert_eq!(left.len(), 1);
501        assert_eq!(
502            left[0].payload["root"],
503            other.path().to_string_lossy().as_ref()
504        );
505        // The watermark kept under the vault starts again.
506        let mark = data
507            .path()
508            .join(crate::knowledge::draft::WATERMARK_DIR)
509            .join(format!("vlt_k1.{}", crate::knowledge::draft::WATERMARK_EXT));
510        let mark: serde_json::Value =
511            serde_json::from_slice(&std::fs::read(mark).unwrap()).unwrap();
512        assert!(mark["since"].is_null() && mark["last_draft_at"].is_null());
513    }
514
515    #[test]
516    fn unlink_of_a_worktree_shared_through_its_main_checkout_is_refused() {
517        let base = tempfile::tempdir().unwrap();
518        let (main, wt) = crate::link::worktree_layout(base.path());
519        let data = tempfile::tempdir().unwrap();
520        shared(data.path(), &[&main]);
521
522        assert!(matches!(
523            unlink(data.path(), &wt, None),
524            Err(UnlinkError::SharedFromMain { .. })
525        ));
526        assert_eq!(VaultMap::load(data.path()).vaults.len(), 1);
527    }
528
529    #[test]
530    fn unlink_of_a_worktree_with_its_own_record_stops_the_main_checkout_fallback() {
531        let base = tempfile::tempdir().unwrap();
532        let (main, wt) = crate::link::worktree_layout(base.path());
533        let data = tempfile::tempdir().unwrap();
534        shared(data.path(), &[&main, &wt]);
535
536        assert!(unlink(data.path(), &wt, None).unwrap().vault.is_some());
537        // M1: `for_root` alone would fall back to the main checkout.
538        assert!(
539            VaultMap::load(data.path())
540                .for_root(&wt.to_string_lossy())
541                .is_some()
542        );
543        assert!(
544            crate::resolution::vault_for_root(&at(data.path()), &wt)
545                .unwrap()
546                .is_none()
547        );
548        assert!(
549            crate::resolution::vault_for_root(&at(data.path()), &main)
550                .unwrap()
551                .is_some()
552        );
553    }
554
555    #[test]
556    fn a_link_after_unlink_clears_the_opt_out() {
557        let data = tempfile::tempdir().unwrap();
558        let repo = tempfile::tempdir().unwrap();
559        shared(data.path(), &[repo.path()]);
560        unlink(data.path(), repo.path(), None).unwrap();
561        assert!(crate::unlinked::contains(data.path(), repo.path()));
562
563        assert!(crate::unlinked::remove(data.path(), repo.path()).unwrap());
564        assert!(!crate::unlinked::contains(data.path(), repo.path()));
565    }
566
567    /// bd 39657 S-b: a link file without a record still shares the folder
568    /// on the next sync, so unlink stores the opt-out for it; with no vault
569    /// it could name another one than, it is removed (bd 39936).
570    #[test]
571    fn unlink_of_a_link_file_without_a_record_stores_the_opt_out() {
572        let data = tempfile::tempdir().unwrap();
573        let repo = tempfile::tempdir().unwrap();
574        link(repo.path(), "acme/payments").unwrap();
575
576        let outcome = unlink(data.path(), repo.path(), None).unwrap();
577        assert_eq!(outcome.vault, None);
578        assert_eq!(outcome.link_file, LinkFile::Removed);
579        assert!(!repo.path().join(LINK_FILE).exists());
580        assert!(crate::unlinked::contains(data.path(), repo.path()));
581        assert!(
582            crate::resolution::vault_for_root(&at(data.path()), repo.path())
583                .unwrap()
584                .is_none()
585        );
586    }
587
588    /// bd 40060 SHOULD: without a record, a link file for another Cloud (a
589    /// committed self-hosted link) is kept; the opt-out is stored anyway.
590    #[test]
591    fn unlink_without_a_record_keeps_a_link_file_for_another_cloud() {
592        let data = tempfile::tempdir().unwrap();
593        let repo = tempfile::tempdir().unwrap();
594        link(repo.path(), "acme/payments@cloud.selfhosted.example").unwrap();
595        let before = std::fs::read(repo.path().join(LINK_FILE)).unwrap();
596
597        let outcome = unlink(data.path(), repo.path(), None).unwrap();
598        assert_eq!(outcome.link_file, LinkFile::Kept(KeptReason::OtherVault));
599        assert_eq!(std::fs::read(repo.path().join(LINK_FILE)).unwrap(), before);
600        assert!(crate::unlinked::contains(data.path(), repo.path()));
601    }
602
603    /// bd 39936 MUST: a checkout shared only through its identity (the
604    /// record of another checkout of the same repository, no root entry,
605    /// no link file) stores the opt-out and names that vault.
606    #[test]
607    fn unlink_of_a_checkout_shared_through_its_identity_stores_the_opt_out() {
608        let data = tempfile::tempdir().unwrap();
609        let b = tempfile::tempdir().unwrap();
610        let c = tempfile::tempdir().unwrap();
611        std::fs::write(c.path().join(".lean-ctx-id"), "payments-repo").unwrap();
612        let stable = lean_ctx_protocol::cloud::vault::stable_identity(
613            &crate::vault::project_identity(c.path()).unwrap(),
614        );
615        let mut map = VaultMap::default();
616        record(&mut map, &stable, ("acme", "payments"), &[b.path()]);
617        map.save(data.path()).unwrap();
618        let before = std::fs::read(data.path().join("projects.json")).unwrap();
619
620        for _ in 0..2 {
621            let outcome = unlink(data.path(), c.path(), None).unwrap();
622            let vault = outcome.vault.expect("the identity's vault is named");
623            assert_eq!(
624                (vault.ns.as_str(), vault.name.as_str()),
625                ("acme", "payments")
626            );
627            assert_eq!(outcome.link_file, LinkFile::Absent);
628        }
629        assert!(crate::unlinked::contains(data.path(), c.path()));
630        assert!(!crate::unlinked::contains(data.path(), b.path()));
631        assert_eq!(
632            std::fs::read(data.path().join("projects.json")).unwrap(),
633            before,
634            "the other checkout keeps its record"
635        );
636    }
637
638    /// bd 39936: a link file naming the identity's vault is removed; one
639    /// naming a different vault stays as `other_vault`.
640    #[test]
641    fn unlink_through_the_identity_removes_only_a_link_file_for_that_vault() {
642        let data = tempfile::tempdir().unwrap();
643        let b = tempfile::tempdir().unwrap();
644        let mut map = VaultMap::default();
645        for (name, expected) in [
646            ("acme/payments", LinkFile::Removed),
647            ("acme/other", LinkFile::Kept(KeptReason::OtherVault)),
648        ] {
649            let c = tempfile::tempdir().unwrap();
650            std::fs::write(c.path().join(".lean-ctx-id"), "payments-repo").unwrap();
651            link(c.path(), name).unwrap();
652            let stable = lean_ctx_protocol::cloud::vault::stable_identity(
653                &crate::vault::project_identity(c.path()).unwrap(),
654            );
655            record(&mut map, &stable, ("acme", "payments"), &[b.path()]);
656            map.save(data.path()).unwrap();
657
658            let outcome = unlink(data.path(), c.path(), None).unwrap();
659            assert!(outcome.vault.is_some());
660            assert_eq!(outcome.link_file, expected, "{name}");
661        }
662    }
663
664    /// bd 39657 S-d: a damaged opt-out store fails the unlink and names it.
665    #[test]
666    fn unlink_with_a_damaged_opt_out_store_fails() {
667        let data = tempfile::tempdir().unwrap();
668        let repo = tempfile::tempdir().unwrap();
669        shared(data.path(), &[repo.path()]);
670        std::fs::write(data.path().join(crate::unlinked::FILE), b"[").unwrap();
671
672        let error = unlink(data.path(), repo.path(), None).unwrap_err();
673        assert!(matches!(error, UnlinkError::Failed(_)), "{error}");
674        assert!(error.to_string().contains(crate::unlinked::FILE), "{error}");
675        // Nothing else changed.
676        assert!(
677            VaultMap::load(data.path())
678                .for_root(&repo.path().to_string_lossy())
679                .is_some()
680        );
681    }
682}