Skip to main content

lean_ctx_cloud/
state.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Durable Cloud state on this machine.
3//!
4//! `<config_dir>/cloud/` (directory 0700, files 0600, written atomically):
5//! `instance.key`, `kx.key`, `instance.json`, `lease.json` (re-verified on
6//! every load), `keys.json`, `token.json` (never logged).
7//! `<data_dir>/cloud/`: `activity.json` and, with later packages, project
8//! maps, cursors and the outbox.
9
10use std::collections::BTreeMap;
11use std::fmt;
12use std::path::{Path, PathBuf};
13
14use serde::de::DeserializeOwned;
15use serde::{Deserialize, Serialize};
16use serde_json::Value;
17
18use super::CloudError;
19
20pub(crate) const INSTANCE_KEY_FILE: &str = "instance.key";
21pub(crate) const KX_KEY_FILE: &str = "kx.key";
22pub(crate) const INSTANCE_FILE: &str = "instance.json";
23pub(crate) const LEASE_FILE: &str = "lease.json";
24pub(crate) const KEYS_FILE: &str = "keys.json";
25pub(crate) const TOKEN_FILE: &str = "token.json";
26pub(crate) const ACTIVITY_FILE: &str = "activity.json";
27/// The person's sharing answer at connect (`super::connect`).
28pub(crate) const SHARING_FILE: &str = "sharing.json";
29/// When the enrolled Cloud last answered that it has no match route
30/// (`super::mapping`).
31pub(crate) const MATCH_FILE: &str = "vault-match.json";
32/// Who `<data>/cloud` belongs to (3.12.8 account scope, [`DataScope`]).
33pub(crate) const SCOPE_FILE: &str = "scope.json";
34
35/// Every entry of `<config>/cloud` (rc4-274). In a single-dir layout (a
36/// legacy `~/.lean-ctx`, a custom `LEAN_CTX_DATA_DIR`) `<config>/cloud` and
37/// `<data>/cloud` are one directory: removing the data there keeps these,
38/// with their `.damaged-<n>` copies and in-flight temporary files. Every
39/// name written through [`CloudStore::write_config`] must be listed (checked
40/// in debug builds); an entry not listed counts as data and is removed.
41const CONFIG_ENTRIES: &[&str] = &[
42    INSTANCE_KEY_FILE,
43    KX_KEY_FILE,
44    INSTANCE_FILE,
45    LEASE_FILE,
46    KEYS_FILE,
47    TOKEN_FILE,
48    SHARING_FILE,
49    MATCH_FILE,
50    super::keyset_v3::KEYS_V3_FILE,
51    super::root_cert::CERT_FILE,
52    super::revoked::REVOKED_FILE,
53    super::disconnect::PENDING_FILE,
54    super::session_ref::CAPABILITIES_FILE,
55    super::company_bound::FILE,
56    super::bus::relay_v2::PROTOCOL_FILE,
57    super::consent::chat_key::CHAT_KEY_FILE,
58    super::consent::optin_key::OPTIN_KEY_FILE,
59    super::consent::task_key::TASK_KEY_FILE,
60    super::consent::broker::PRESENCE_KEY_FILE,
61    super::consent::broker::ACCOUNT_FILE,
62    super::consent::broker::KEY_FILE,
63    super::consent::broker::DIR,
64    // `replica::crypt::master_key`: the replica master key, when no
65    // keychain holds it.
66    "replica.key",
67];
68
69/// `bring_local` ledgers, one per checkout: `bring-local-<hash>.json`.
70const CONFIG_PREFIX_BRING_LOCAL: &str = "bring-local-";
71
72/// Whether `name`, an entry of `<config>/cloud`, belongs to the config
73/// (rc4-274). Lock files always do: a lock file removed while held no
74/// longer orders anything, and an empty lock of the data costs nothing.
75fn is_config_entry(name: &str) -> bool {
76    if Path::new(name).extension().is_some_and(|ext| ext == "lock") {
77        return true;
78    }
79    let base = name
80        .strip_prefix('.')
81        .and_then(|n| n.split_once(".tmp."))
82        .map_or(name, |(base, _)| base);
83    let base = base.split_once(".damaged-").map_or(base, |(base, _)| base);
84    CONFIG_ENTRIES.contains(&base) || base.starts_with(CONFIG_PREFIX_BRING_LOCAL)
85}
86
87/// The enrolled instance.
88#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
89pub struct InstanceRecord {
90    pub instance_id: String,
91    pub org_id: String,
92    pub org_name: String,
93    pub label: String,
94    /// Origin the instance is enrolled with.
95    pub url: String,
96    pub org_salt_id: String,
97    pub enrolled_at: String,
98    /// Origin of the Cloud web app, when enrollment named one (1.3).
99    #[serde(default, skip_serializing_if = "Option::is_none")]
100    pub web_url: Option<String>,
101    /// `personal` | `team`, when enrollment named it (Cloud C line).
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub org_kind: Option<String>,
104    /// The company the team belongs to, when enrollment named one.
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub company_name: Option<String>,
107}
108
109impl InstanceRecord {
110    /// The scope of the vault map this enrollment reads and writes: its
111    /// Cloud and account (rc3-81, rc4-2, rc4-6).
112    pub fn vault_scope(&self) -> String {
113        lean_ctx::core::vault_map::vault_scope(&self.url, &self.org_id)
114    }
115
116    /// Where the instance is enrolled, as people read it (owner decision
117    /// 26.10.: Personal, Team, Company): `Company Acme · Team Platform`,
118    /// `Team Platform`, `Personal (Ada)`; an older server's record keeps
119    /// the plain name.
120    pub fn workspace_label(&self) -> String {
121        let name = &self.org_name;
122        match (self.company_name.as_deref(), self.org_kind.as_deref()) {
123            (Some(company), _) => format!("Company {company} · Team {name}"),
124            (None, Some("team")) => format!("Team {name}"),
125            (None, Some("personal")) => format!("Personal ({name})"),
126            _ => name.clone(),
127        }
128    }
129}
130
131/// The last verified lease, as received, plus the service clock offset.
132#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
133pub struct LeaseRecord {
134    pub envelope: Value,
135    /// `server_time - local time` when the lease arrived, in seconds.
136    pub offset_seconds: i64,
137    pub received_at: String,
138}
139
140/// A cached access token. `Debug` never shows the token.
141#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
142pub struct TokenRecord {
143    pub access_token: String,
144    /// Unix seconds (service clock).
145    pub expires_at: i64,
146}
147
148impl fmt::Debug for TokenRecord {
149    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150        f.debug_struct("TokenRecord")
151            .field("access_token", &"<redacted>")
152            .field("expires_at", &self.expires_at)
153            .finish()
154    }
155}
156
157/// When Cloud last answered, per channel.
158#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
159pub struct ActivityRecord {
160    pub last_seen: Option<String>,
161    #[serde(default)]
162    pub last_success: BTreeMap<String, String>,
163    pub last_error: Option<String>,
164    /// Why Cloud last refused this workspace as locked (`trial_ended`,
165    /// `plan_ended`); cleared by the next lease Cloud issues.
166    #[serde(default, skip_serializing_if = "Option::is_none")]
167    pub locked: Option<String>,
168    /// Why the last lease renewal failed; kept until a renewal succeeds
169    /// (unlike `last_error`, which the next success of any channel clears).
170    #[serde(default, skip_serializing_if = "Option::is_none")]
171    pub renew_error: Option<String>,
172}
173
174/// Paths of the Cloud state; [`CloudStore::open`] for this machine,
175/// [`CloudStore::at`] for tests and embedders.
176#[derive(Debug, Clone)]
177pub struct CloudStore {
178    config: PathBuf,
179    data: PathBuf,
180}
181
182impl CloudStore {
183    /// `<config_dir>/cloud` and `<data_dir>/cloud` of this installation. Opening
184    /// only resolves the paths: a read-only config directory keeps its mode (the
185    /// Cloud's own directories are made private when something is written there).
186    pub fn open() -> Result<Self, CloudError> {
187        let config = lean_ctx::core::paths::config_dir_read_only().map_err(CloudError::Local)?;
188        let data = lean_ctx::core::paths::data_dir().map_err(CloudError::Local)?;
189        Ok(Self::at(config.join("cloud"), data.join("cloud")))
190    }
191
192    /// State rooted at explicit directories.
193    pub fn at(config_dir: impl Into<PathBuf>, data_dir: impl Into<PathBuf>) -> Self {
194        Self {
195            config: config_dir.into(),
196            data: data_dir.into(),
197        }
198    }
199
200    pub fn config_dir(&self) -> &Path {
201        &self.config
202    }
203
204    pub fn data_dir(&self) -> &Path {
205        &self.data
206    }
207
208    pub(crate) fn read_config_bytes(&self, name: &str) -> Result<Option<Vec<u8>>, CloudError> {
209        read_optional(&self.config.join(name))
210    }
211
212    pub(crate) fn write_config_bytes(&self, name: &str, bytes: &[u8]) -> Result<(), CloudError> {
213        debug_assert!(is_config_entry(name), "{name} is missing in CONFIG_ENTRIES");
214        write_private(&self.config, name, bytes)
215    }
216
217    pub(crate) fn read_config<T: DeserializeOwned>(
218        &self,
219        name: &str,
220    ) -> Result<Option<T>, CloudError> {
221        read_json(&self.config.join(name))
222    }
223
224    pub(crate) fn write_config<T: Serialize>(
225        &self,
226        name: &str,
227        value: &T,
228    ) -> Result<(), CloudError> {
229        debug_assert!(is_config_entry(name), "{name} is missing in CONFIG_ENTRIES");
230        write_private(&self.config, name, &to_json(value)?)
231    }
232
233    pub(crate) fn remove_config(&self, name: &str) -> Result<(), CloudError> {
234        remove_optional(&self.config.join(name))
235    }
236
237    pub fn activity(&self) -> ActivityRecord {
238        read_json(&self.data.join(ACTIVITY_FILE))
239            .ok()
240            .flatten()
241            .unwrap_or_default()
242    }
243
244    /// Record a successful exchange on `channel` at `when` (RFC 3339).
245    pub(crate) fn record_success(&self, channel: &str, when: &str) {
246        let mut activity = self.activity();
247        activity.last_seen = Some(when.to_string());
248        activity
249            .last_success
250            .insert(channel.to_string(), when.to_string());
251        activity.last_error = None;
252        // Activity is informational; failing to record it never fails the exchange.
253        if let Ok(bytes) = to_json(&activity) {
254            let _ = write_private(&self.data, ACTIVITY_FILE, &bytes);
255        }
256    }
257
258    /// Record (`Some`) or clear (`None`) a locked workspace (E9).
259    pub fn record_locked(&self, reason: Option<&str>) {
260        let mut activity = self.activity();
261        if activity.locked.as_deref() == reason {
262            return;
263        }
264        activity.locked = reason.map(str::to_string);
265        if let Ok(bytes) = to_json(&activity) {
266            let _ = write_private(&self.data, ACTIVITY_FILE, &bytes);
267        }
268    }
269
270    /// Record (`Some`) or clear (`None`) why the lease renewal failed.
271    pub(crate) fn record_renew_error(&self, message: Option<&str>) {
272        let mut activity = self.activity();
273        if activity.renew_error.as_deref() == message {
274            return;
275        }
276        activity.renew_error = message.map(str::to_string);
277        if let Ok(bytes) = to_json(&activity) {
278            let _ = write_private(&self.data, ACTIVITY_FILE, &bytes);
279        }
280    }
281
282    pub(crate) fn record_error(&self, message: &str) {
283        let mut activity = self.activity();
284        activity.last_error = Some(message.to_string());
285        if let Ok(bytes) = to_json(&activity) {
286            let _ = write_private(&self.data, ACTIVITY_FILE, &bytes);
287        }
288    }
289
290    /// Whether this engine may record anything for Cloud now: connected (an
291    /// instance record) and not revoked. Two file checks; the recording
292    /// paths call it on every record (K2 review 2, N1).
293    pub(crate) fn may_record(&self) -> bool {
294        self.config.join(INSTANCE_FILE).is_file()
295            && !self.config.join(super::revoked::REVOKED_FILE).is_file()
296    }
297
298    /// The slower half of the recording check (K2 review 3, NEW-3): the
299    /// `[cloud]` switches allow engine metrics and the stored lease has not
300    /// lapsed (read from the local copy; a lease that cannot be read counts
301    /// as lapsed).
302    pub(crate) fn recording_allowed(&self, config: &super::config::CloudConfig) -> bool {
303        config.enabled != Some(false) && config.metrics_upload && self.lease_live()
304    }
305
306    fn lease_live(&self) -> bool {
307        use lean_ctx_protocol::cloud::lease::{CloudLeaseV1, LeaseState};
308        let Ok(Some(record)) = self.read_config::<LeaseRecord>(LEASE_FILE) else {
309            return false;
310        };
311        let Ok(lease) = serde_json::from_value::<CloudLeaseV1>(record.envelope["lease"].clone())
312        else {
313            return false;
314        };
315        let service_now = (lean_ctx_time::UtcDateTime::now()
316            + lean_ctx_time::Duration::seconds(record.offset_seconds))
317        .fixed_offset();
318        matches!(
319            lease.state_at(service_now),
320            Ok(LeaseState::Valid | LeaseState::Grace)
321        )
322    }
323
324    /// Who `<data>/cloud` belongs to, when stamped (3.12.8 account scope).
325    #[cfg(test)]
326    fn scope(&self) -> Option<DataScope> {
327        self.read_scope().ok().flatten()
328    }
329
330    /// The stamp of `<data>/cloud`; `Err` when it cannot be read, which
331    /// counts as another account's.
332    fn read_scope(&self) -> Result<Option<DataScope>, ()> {
333        read_json(&self.data.join(SCOPE_FILE)).map_err(|_| ())
334    }
335
336    fn stamp_scope(&self, instance: &InstanceRecord) -> Result<(), CloudError> {
337        write_private(&self.data, SCOPE_FILE, &to_json(&DataScope::of(instance))?)
338    }
339
340    /// Remove `<data>/cloud` in one step: renamed aside first, so no reader
341    /// sees half of it, then deleted. The replica master key lives in the
342    /// config directory and stays. When the config directory is the data
343    /// directory or lies inside it (a single-dir layout, rc4-274), only the
344    /// data entries are moved aside: the enrolment, its keys and its lease
345    /// stay.
346    fn wipe_data(&self) -> Result<(), CloudError> {
347        if !self.data.exists() {
348            return Ok(());
349        }
350        let name = self
351            .data
352            .file_name()
353            .map_or_else(|| "cloud".into(), |n| n.to_string_lossy().into_owned());
354        let aside = self
355            .data
356            .with_file_name(format!("{name}.wiped-{}", std::process::id()));
357        let _ = std::fs::remove_dir_all(&aside);
358        let move_aside = |e: std::io::Error| {
359            CloudError::Local(format!("move {} aside: {e}", self.data.display()))
360        };
361        match self.config_in_data() {
362            None => std::fs::rename(&self.data, &aside).map_err(move_aside)?,
363            Some(config) => {
364                // The entry of `<data>/cloud` that holds the config directory,
365                // or none when the two are the same directory.
366                let holder = config.components().next().map(|c| c.as_os_str().to_owned());
367                private_dir(&aside)?;
368                for entry in std::fs::read_dir(&self.data).map_err(move_aside)? {
369                    let entry = entry.map_err(move_aside)?;
370                    let entry_name = entry.file_name();
371                    let keep = match &holder {
372                        Some(holder) => *holder == entry_name,
373                        None => is_config_entry(&entry_name.to_string_lossy()),
374                    };
375                    if !keep {
376                        std::fs::rename(entry.path(), aside.join(&entry_name))
377                            .map_err(move_aside)?;
378                    }
379                }
380            }
381        }
382        std::fs::remove_dir_all(&aside)
383            .map_err(|e| CloudError::Local(format!("remove {}: {e}", aside.display())))?;
384        self.sweep_wiped(&name);
385        Ok(())
386    }
387
388    /// Where the config directory lies inside the data directory, relative
389    /// to it (empty: the same directory), or `None` when it lies elsewhere
390    /// (the XDG split). Compared as resolved paths, so a symlinked root is
391    /// seen as well.
392    fn config_in_data(&self) -> Option<PathBuf> {
393        let resolve = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
394        let (config, data) = (resolve(&self.config), resolve(&self.data));
395        config.strip_prefix(&data).ok().map(Path::to_path_buf)
396    }
397
398    /// Copies an earlier removal moved aside but did not finish deleting
399    /// (killed process); best effort.
400    fn sweep_wiped(&self, name: &str) {
401        let Some(parent) = self.data.parent() else {
402            return;
403        };
404        let prefix = format!("{name}.wiped-");
405        let Ok(entries) = std::fs::read_dir(parent) else {
406            return;
407        };
408        for entry in entries.flatten() {
409            let is_copy = entry.file_name().to_string_lossy().starts_with(&prefix);
410            let is_dir = entry.file_type().is_ok_and(|t| t.is_dir());
411            if is_copy && is_dir {
412                let _ = std::fs::remove_dir_all(entry.path());
413            }
414        }
415    }
416
417    /// Remove another account's local Cloud data: first the knowledge
418    /// pulled from it into project knowledge (the vault map that finds the
419    /// checkouts goes with the data), then `<data>/cloud`. Both fail
420    /// closed: nothing is removed half while its knowledge stays findable.
421    fn purge_data(&self) -> Result<(), CloudError> {
422        self.remove_pulled_knowledge().map_err(|failed| {
423            CloudError::Local(format!(
424                "the knowledge pulled from the Cloud could not be removed from {failed}. Until it is, nothing of the Cloud is used on this computer. Try again; if it keeps failing, run `lean-ctx cloud disconnect` in a terminal."
425            ))
426        })?;
427        self.wipe_data()
428    }
429
430    /// The lock that orders scope decisions (wipe and stamp) between
431    /// processes; held in the config directory, which a wipe leaves alone.
432    fn lock_scope(&self) -> Result<StateLock, CloudError> {
433        lock_state(&self.config, SCOPE_FILE)
434    }
435
436    /// Before a new enrolment is stored: the local Cloud data of another
437    /// server or team goes (fail closed, 3.12.8 cross-account leak); data
438    /// of the same server and team stays (a reconnect kept with
439    /// `--keep-local`). Data without a stamp is of an unknown account and
440    /// goes as well.
441    pub(crate) fn scope_to_enrollment(&self, next: &InstanceRecord) -> Result<(), CloudError> {
442        let _lock = self.lock_scope()?;
443        let keep = matches!(
444            self.read_scope(),
445            Ok(Some(s)) if s.server == next.url && s.org_id == next.org_id
446        );
447        if !keep {
448            self.purge_data()?;
449        }
450        self.stamp_scope(next)
451    }
452
453    /// The enrolled instance. `<data>/cloud` is made to belong to it first
454    /// (3.12.8 account scope): every reader of local Cloud data (replicas,
455    /// vault map, drafts, docs, tasks, status) asks here, so data stamped
456    /// for another server or team is removed before anything of it is read.
457    /// Another instance of the same server and team (a reconnect, whose
458    /// enrolment already decided what stays) only moves the stamp, so a
459    /// reader racing an enrolment never removes kept data. Data from before
460    /// the stamp existed is adopted by the connected instance.
461    pub fn instance(&self) -> Result<Option<InstanceRecord>, CloudError> {
462        let Some(instance) = self.read_config::<InstanceRecord>(INSTANCE_FILE)? else {
463            return Ok(None);
464        };
465        let now = DataScope::of(&instance);
466        if matches!(self.read_scope(), Ok(Some(ref scope)) if *scope == now) {
467            return Ok(Some(instance));
468        }
469        // Decided again under the lock: an enrolment or another reader may
470        // have moved the stamp meanwhile. Only the removal fails closed; a
471        // stamp that cannot be written (a read-only data directory) is
472        // written by the next reader.
473        let _lock = self.lock_scope()?;
474        match self.read_scope() {
475            Ok(Some(scope)) if scope == now => {}
476            Ok(Some(scope)) if scope.server == now.server && scope.org_id == now.org_id => {
477                let _ = self.stamp_scope(&instance);
478            }
479            Ok(None) if !self.data.exists() => {}
480            Ok(None) => {
481                let _ = self.stamp_scope(&instance);
482            }
483            Ok(Some(_)) | Err(()) => {
484                self.purge_data()?;
485                let _ = self.stamp_scope(&instance);
486            }
487        }
488        Ok(Some(instance))
489    }
490
491    /// Facts pulled from Cloud into the project knowledge of every checkout
492    /// the vault map knows. Every checkout and every store is tried; the
493    /// ones that failed are returned, each with its folder and store file.
494    fn remove_pulled_knowledge(&self) -> Result<(), String> {
495        let map = super::vault::VaultMap::load(&self.data);
496        let mut roots: Vec<&String> = map.vaults.values().flat_map(|r| &r.roots).collect();
497        roots.sort();
498        roots.dedup();
499        let failed: Vec<String> = roots
500            .into_iter()
501            .filter_map(|root| {
502                super::knowledge::learn::remove_all_pulled(root)
503                    .err()
504                    .map(|e| format!("the folder {root}: {e}"))
505            })
506            .collect();
507        if failed.is_empty() {
508            Ok(())
509        } else {
510            Err(failed.join("; "))
511        }
512    }
513
514    /// The enrolled instance as stored, without the account-scope check of
515    /// [`instance`](Self::instance). Only for a disconnect, which must work
516    /// when that check cannot remove another account's pulled knowledge
517    /// (a damaged store): it ends the enrolment it names.
518    pub fn enrolled_instance(&self) -> Result<Option<InstanceRecord>, CloudError> {
519        self.read_config::<InstanceRecord>(INSTANCE_FILE)
520    }
521
522    /// Remove credentials, lease and keys; with `keep_local` the data
523    /// directory (outbox, replicas, activity) stays, but nothing keeps
524    /// recording for Cloud (metrics, signals, receipts). Knowledge pulled
525    /// into project knowledge always goes (3.12.8 account scope), from every
526    /// store that can be cleaned; a store that cannot (damaged) is named
527    /// after everything else is removed.
528    pub fn forget(&self, keep_local: bool) -> Result<(), CloudError> {
529        let knowledge = self.remove_pulled_knowledge().map_err(|failed| {
530            CloudError::Local(format!(
531                "The Cloud is disconnected on this computer, but the knowledge pulled from it could not be removed from {failed}. Delete that knowledge.json (it holds that folder's local knowledge; a damaged one cannot be read anyway), then connect again."
532            ))
533        });
534        super::receipts::stop_local_recording(&self.data);
535        // rc3-81: the kept vault records name the Cloud and account they
536        // were resolved for before the instance record goes, so a later
537        // connect to another Cloud or account drops them instead of guessing.
538        if keep_local && let Ok(Some(instance)) = self.instance() {
539            super::vault::stamp_left_scope(&self.data, &instance.vault_scope())?;
540        }
541        for name in [
542            TOKEN_FILE,
543            LEASE_FILE,
544            KEYS_FILE,
545            INSTANCE_FILE,
546            KX_KEY_FILE,
547            INSTANCE_KEY_FILE,
548            SHARING_FILE,
549            MATCH_FILE,
550            super::revoked::REVOKED_FILE,
551            super::disconnect::PENDING_FILE,
552        ] {
553            self.remove_config(name)?;
554        }
555        if !keep_local {
556            // Not `remove_dir_all`: in a single-dir layout that would take
557            // the rest of the config with it (rc4-274).
558            self.wipe_data()?;
559        }
560        knowledge
561    }
562}
563
564/// `<data>/cloud/scope.json`: the server, team and instance the local Cloud
565/// data was made for (3.12.8 account scope).
566#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
567struct DataScope {
568    server: String,
569    org_id: String,
570    instance_id: String,
571}
572
573impl DataScope {
574    fn of(instance: &InstanceRecord) -> Self {
575        Self {
576            server: instance.url.clone(),
577            org_id: instance.org_id.clone(),
578            instance_id: instance.instance_id.clone(),
579        }
580    }
581}
582
583fn to_json<T: Serialize>(value: &T) -> Result<Vec<u8>, CloudError> {
584    let mut bytes =
585        serde_json::to_vec_pretty(value).map_err(|e| CloudError::Local(format!("encode: {e}")))?;
586    bytes.push(b'\n');
587    Ok(bytes)
588}
589
590fn read_optional(path: &Path) -> Result<Option<Vec<u8>>, CloudError> {
591    match std::fs::read(path) {
592        Ok(bytes) => Ok(Some(bytes)),
593        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
594        Err(e) => Err(CloudError::Local(format!("read {}: {e}", path.display()))),
595    }
596}
597
598fn read_json<T: DeserializeOwned>(path: &Path) -> Result<Option<T>, CloudError> {
599    let Some(bytes) = read_optional(path)? else {
600        return Ok(None);
601    };
602    serde_json::from_slice(&bytes)
603        .map(Some)
604        .map_err(|e| CloudError::Local(format!("{} is damaged: {e}", path.display())))
605}
606
607fn remove_optional(path: &Path) -> Result<(), CloudError> {
608    match std::fs::remove_file(path) {
609        Ok(()) => Ok(()),
610        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
611        Err(e) => Err(CloudError::Local(format!("remove {}: {e}", path.display()))),
612    }
613}
614
615/// Write `dir/name` so that it is never readable by others and never seen
616/// half-written: a 0700 directory and the shared 0600 atomic writer.
617pub(crate) fn write_private(dir: &Path, name: &str, bytes: &[u8]) -> Result<(), CloudError> {
618    lean_ctx::core::secure_fs::write_private(dir, name, bytes)
619        .map_err(|e| CloudError::Local(e.to_string()))
620}
621
622fn private_dir(dir: &Path) -> Result<(), CloudError> {
623    lean_ctx::core::secure_fs::private_dir(dir).map_err(|e| CloudError::Local(e.to_string()))
624}
625
626/// Copies of a damaged state file kept beside it (`<name>.damaged-<n>`);
627/// older ones are removed (RB8 M14).
628pub(crate) const DAMAGED_KEPT: usize = 3;
629
630/// Load the JSON state file `path` (RB8 M12). Missing: `Ok(None)`. A file
631/// that does not parse, or that `accept` refuses (a version this build does
632/// not know), is moved aside to `<name>.damaged-<n>` and reported as an
633/// error: no caller silently starts again from empty state, each decides
634/// how it fails closed. A file that cannot be read stays where it is.
635pub(crate) fn load_or_quarantine<T: DeserializeOwned>(
636    path: &Path,
637    accept: impl FnOnce(&T) -> bool,
638) -> Result<Option<T>, CloudError> {
639    let Some(bytes) = read_optional(path)? else {
640        return Ok(None);
641    };
642    let why = match serde_json::from_slice::<T>(&bytes) {
643        Ok(value) if accept(&value) => return Ok(Some(value)),
644        Ok(_) => "a version this build does not know".to_string(),
645        Err(e) => e.to_string(),
646    };
647    let moved = quarantine(path)?;
648    Err(CloudError::Local(format!(
649        "{} is damaged ({why}); moved to {}",
650        path.display(),
651        moved.display()
652    )))
653}
654
655/// Move `path` to `<name>.damaged-<n>` (the next free number) and keep only
656/// the newest [`DAMAGED_KEPT`] such copies.
657pub(crate) fn quarantine(path: &Path) -> Result<PathBuf, CloudError> {
658    let local =
659        |e: std::io::Error| CloudError::Local(format!("quarantine {}: {e}", path.display()));
660    let (Some(dir), Some(name)) = (path.parent(), path.file_name().and_then(|n| n.to_str())) else {
661        return Err(CloudError::Local(format!("{} has no name", path.display())));
662    };
663    let prefix = format!("{name}.damaged-");
664    let mut copies: Vec<(u64, PathBuf)> = std::fs::read_dir(dir)
665        .map_err(local)?
666        .filter_map(Result::ok)
667        .filter_map(|e| {
668            let n = e
669                .file_name()
670                .to_str()?
671                .strip_prefix(&prefix)?
672                .parse()
673                .ok()?;
674            Some((n, e.path()))
675        })
676        .collect();
677    copies.sort_unstable();
678    let next = copies.last().map_or(1, |(n, _)| n + 1);
679    let moved = dir.join(format!("{prefix}{next}"));
680    std::fs::rename(path, &moved).map_err(local)?;
681    copies.push((next, moved.clone()));
682    let excess = copies.len().saturating_sub(DAMAGED_KEPT);
683    for (_, old) in copies.drain(..excess) {
684        let _ = std::fs::remove_file(old);
685    }
686    Ok(moved)
687}
688
689/// How long a state lock is waited for before the caller gets an error.
690const STATE_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
691
692/// An exclusive lock on `<dir>/<name>.lock` for one read-modify-write of a
693/// state file shared by processes (RB8 E5: the tool calls and the relay).
694/// Held only around local file work, never across a network request.
695/// Unlocked explicitly when dropped ([`lean_ctx::core::file_lock::FlockGuard`]).
696pub(crate) struct StateLock {
697    _file: lean_ctx::core::file_lock::FlockGuard,
698}
699
700/// Take the lock for the state file `dir/name`, waiting at most
701/// [`STATE_LOCK_WAIT`]; symlinks are refused.
702pub(crate) fn lock_state(dir: &Path, name: &str) -> Result<StateLock, CloudError> {
703    lock_state_within(dir, name, STATE_LOCK_WAIT)
704}
705
706/// [`lock_state`] waiting at most `wait` (zero: only when free right now).
707pub(crate) fn lock_state_within(
708    dir: &Path,
709    name: &str,
710    wait: std::time::Duration,
711) -> Result<StateLock, CloudError> {
712    private_dir(dir)?;
713    let path = dir.join(format!("{name}.lock"));
714    let local = |what: &str| CloudError::Local(format!("{what} {}", path.display()));
715    let mut options = std::fs::OpenOptions::new();
716    options.read(true).write(true).create(true).truncate(false);
717    #[cfg(unix)]
718    {
719        use std::os::unix::fs::OpenOptionsExt as _;
720        options
721            .mode(0o600)
722            .custom_flags(libc::O_CLOEXEC | libc::O_NOFOLLOW);
723    }
724    let file = options
725        .open(&path)
726        .map_err(|e| local(&format!("open ({e})")))?;
727    let file = lean_ctx::core::file_lock::FlockGuard::exclusive_timeout(file, wait)
728        .map_err(|e| local(&format!("lock ({e})")))?;
729    Ok(StateLock { _file: file })
730}
731
732#[cfg(test)]
733mod tests {
734    use super::*;
735
736    /// Personal, Team, Company (Cloud C line): the record says where the
737    /// engine is enrolled; a record from before keeps the plain name.
738    #[test]
739    fn workspace_label_names_personal_team_and_company() {
740        let mut r = InstanceRecord {
741            instance_id: "inst_1".into(),
742            org_id: "org_1".into(),
743            org_name: "Platform".into(),
744            label: "mbp".into(),
745            url: "https://cloud.example".into(),
746            org_salt_id: "s".into(),
747            enrolled_at: "2026-10-26T10:00:00Z".into(),
748            web_url: None,
749            org_kind: None,
750            company_name: None,
751        };
752        assert_eq!(r.workspace_label(), "Platform");
753        r.org_kind = Some("team".into());
754        assert_eq!(r.workspace_label(), "Team Platform");
755        r.company_name = Some("Acme".into());
756        assert_eq!(r.workspace_label(), "Company Acme · Team Platform");
757        r.company_name = None;
758        r.org_kind = Some("personal".into());
759        assert_eq!(r.workspace_label(), "Personal (Platform)");
760        // an old record without the new fields still reads
761        let old: InstanceRecord = serde_json::from_value(serde_json::json!({
762            "instance_id": "i", "org_id": "o", "org_name": "Acme", "label": "l", "url": "u",
763            "org_salt_id": "s", "enrolled_at": "t"
764        }))
765        .unwrap();
766        assert_eq!((old.org_kind, old.company_name), (None, None));
767    }
768
769    #[test]
770    fn private_files_are_atomic_and_owner_only() {
771        let dir = tempfile::tempdir().unwrap();
772        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
773        let token = TokenRecord {
774            access_token: "atl_secret".into(),
775            expires_at: 1,
776        };
777        store.write_config(TOKEN_FILE, &token).unwrap();
778        assert_eq!(
779            store.read_config::<TokenRecord>(TOKEN_FILE).unwrap(),
780            Some(token.clone())
781        );
782        assert!(!format!("{token:?}").contains("atl_secret"));
783        #[cfg(unix)]
784        {
785            use std::os::unix::fs::PermissionsExt as _;
786            let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
787            assert_eq!(mode(store.config_dir()), 0o700);
788            assert_eq!(mode(&store.config_dir().join(TOKEN_FILE)), 0o600);
789        }
790        let leftovers: Vec<_> = std::fs::read_dir(store.config_dir())
791            .unwrap()
792            .filter_map(Result::ok)
793            .filter(|e| e.file_name().to_string_lossy().ends_with(".tmp"))
794            .collect();
795        assert!(leftovers.is_empty());
796    }
797
798    #[test]
799    fn damaged_state_is_moved_aside_and_only_three_copies_stay() {
800        let dir = tempfile::tempdir().unwrap();
801        let path = dir.path().join("state.json");
802        let load = |accept: bool| load_or_quarantine::<Value>(&path, |_| accept);
803        assert_eq!(load(true).unwrap(), None, "missing");
804        std::fs::write(&path, b"{\"ok\": 1}").unwrap();
805        assert_eq!(load(true).unwrap(), Some(serde_json::json!({"ok": 1})));
806        // Refused by the caller (an unknown version): moved, an error.
807        let error = load(false).unwrap_err().to_string();
808        assert!(error.contains("damaged-1"), "{error}");
809        assert!(!path.exists());
810        for n in 0..4 {
811            std::fs::write(&path, format!("broken {n}")).unwrap();
812            assert!(load(true).is_err());
813        }
814        let mut kept: Vec<String> = std::fs::read_dir(dir.path())
815            .unwrap()
816            .filter_map(|e| e.ok()?.file_name().into_string().ok())
817            .collect();
818        kept.sort();
819        assert_eq!(
820            kept,
821            [
822                "state.json.damaged-3",
823                "state.json.damaged-4",
824                "state.json.damaged-5"
825            ]
826        );
827        assert_eq!(
828            std::fs::read(dir.path().join("state.json.damaged-5")).unwrap(),
829            b"broken 3",
830            "the newest copy is the last damaged file"
831        );
832    }
833
834    #[test]
835    fn a_held_state_lock_is_not_taken_twice() {
836        let dir = tempfile::tempdir().unwrap();
837        let held = lock_state(dir.path(), "leases.json").unwrap();
838        assert!(lock_state_within(dir.path(), "leases.json", std::time::Duration::ZERO).is_err());
839        drop(held);
840        assert!(lock_state_within(dir.path(), "leases.json", std::time::Duration::ZERO).is_ok());
841        #[cfg(unix)]
842        {
843            use std::os::unix::fs::PermissionsExt as _;
844            let mode = std::fs::metadata(dir.path().join("leases.json.lock"))
845                .unwrap()
846                .permissions()
847                .mode();
848            assert_eq!(mode & 0o777, 0o600);
849        }
850    }
851
852    #[test]
853    fn forget_keeps_local_data_on_request() {
854        let dir = tempfile::tempdir().unwrap();
855        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
856        store
857            .write_config(TOKEN_FILE, &serde_json::json!({}))
858            .unwrap();
859        store.record_success("lease", "2026-10-20T12:00:00Z");
860        store.forget(true).unwrap();
861        assert!(store.read_config_bytes(TOKEN_FILE).unwrap().is_none());
862        assert_eq!(
863            store.activity().last_seen.as_deref(),
864            Some("2026-10-20T12:00:00Z")
865        );
866        store.forget(false).unwrap();
867        assert!(store.activity().last_seen.is_none());
868    }
869}
870
871/// 3.12.8 cross-account leak: `<data>/cloud` belongs to one server and team.
872#[cfg(test)]
873mod scope_tests {
874    use super::*;
875
876    fn instance(server: &str, org: &str, id: &str) -> InstanceRecord {
877        InstanceRecord {
878            instance_id: id.into(),
879            org_id: org.into(),
880            org_name: org.into(),
881            label: "mbp".into(),
882            url: server.into(),
883            org_salt_id: "s".into(),
884            enrolled_at: "2026-11-23T10:00:00Z".into(),
885            web_url: None,
886            org_kind: None,
887            company_name: None,
888        }
889    }
890
891    /// A's vault map and an unsent draft of A.
892    fn data_of_a(store: &CloudStore) {
893        write_private(store.data_dir(), "projects.json", b"{\"projects\":{}}").unwrap();
894        let drafts = store.data_dir().join("outbox").join("knowledge");
895        std::fs::create_dir_all(&drafts).unwrap();
896        std::fs::write(drafts.join("d1.json"), b"{}").unwrap();
897    }
898
899    fn has_data_of_a(store: &CloudStore) -> bool {
900        store.data_dir().join("projects.json").exists()
901            && store.data_dir().join("outbox/knowledge/d1.json").exists()
902    }
903
904    fn connect(store: &CloudStore, record: &InstanceRecord) {
905        store.write_config(INSTANCE_FILE, record).unwrap();
906    }
907
908    #[test]
909    fn enrolling_another_team_or_server_removes_the_local_data() {
910        let dir = tempfile::tempdir().unwrap();
911        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
912        let a = instance("https://cloud.example", "org_a", "inst_1");
913        store.scope_to_enrollment(&a).unwrap();
914        data_of_a(&store);
915
916        // A reconnect to the same server and team (kept with --keep-local)
917        store
918            .scope_to_enrollment(&instance("https://cloud.example", "org_a", "inst_2"))
919            .unwrap();
920        assert!(has_data_of_a(&store), "same team keeps its drafts");
921        assert_eq!(store.scope().unwrap().instance_id, "inst_2");
922
923        // B: another team on the same server
924        let b = instance("https://cloud.example", "org_b", "inst_3");
925        store.scope_to_enrollment(&b).unwrap();
926        assert!(!has_data_of_a(&store), "nothing of A stays for B");
927        assert_eq!(store.scope(), Some(DataScope::of(&b)));
928
929        // the same team id on another server is another account too
930        data_of_a(&store);
931        store
932            .scope_to_enrollment(&instance("https://staging.example", "org_b", "inst_4"))
933            .unwrap();
934        assert!(!has_data_of_a(&store));
935    }
936
937    #[test]
938    fn data_without_a_stamp_is_removed_at_enrolment() {
939        let dir = tempfile::tempdir().unwrap();
940        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
941        data_of_a(&store); // left by an older version with --keep-local
942        store
943            .scope_to_enrollment(&instance("https://cloud.example", "org_b", "inst_1"))
944            .unwrap();
945        assert!(!has_data_of_a(&store));
946    }
947
948    #[test]
949    fn readers_get_nothing_while_disconnected_or_of_another_account() {
950        let dir = tempfile::tempdir().unwrap();
951        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
952        let a = instance("https://cloud.example", "org_a", "inst_1");
953        store.scope_to_enrollment(&a).unwrap();
954        data_of_a(&store);
955
956        // not connected (disconnect --keep-local): no instance, nothing read
957        assert_eq!(store.instance().unwrap(), None);
958        assert!(has_data_of_a(&store), "kept for a reconnect, not read");
959
960        // connected to the stamped instance: read as before
961        connect(&store, &a);
962        assert_eq!(store.instance().unwrap(), Some(a.clone()));
963        assert!(has_data_of_a(&store));
964
965        // another instance of the same team only moves the stamp
966        let a2 = instance("https://cloud.example", "org_a", "inst_2");
967        connect(&store, &a2);
968        assert_eq!(store.instance().unwrap(), Some(a2.clone()));
969        assert!(has_data_of_a(&store));
970        assert_eq!(store.scope(), Some(DataScope::of(&a2)));
971
972        // an instance of another team the enrolment did not scope: A's data
973        // is removed before anything reads it
974        let b = instance("https://cloud.example", "org_b", "inst_3");
975        connect(&store, &b);
976        assert_eq!(store.instance().unwrap(), Some(b.clone()));
977        assert!(!has_data_of_a(&store));
978        assert_eq!(store.scope(), Some(DataScope::of(&b)));
979    }
980
981    #[test]
982    fn data_from_before_the_stamp_is_adopted_by_the_connected_instance() {
983        let dir = tempfile::tempdir().unwrap();
984        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
985        let a = instance("https://cloud.example", "org_a", "inst_1");
986        data_of_a(&store);
987        connect(&store, &a);
988        assert_eq!(store.instance().unwrap(), Some(a.clone()));
989        assert!(has_data_of_a(&store), "an upgrade keeps the drafts");
990        assert_eq!(store.scope(), Some(DataScope::of(&a)));
991    }
992
993    /// A checkout of team A with one fact pulled from A and one own fact,
994    /// found through A's vault map in `store`.
995    fn knowledge_of_a(store: &CloudStore, root: &str) {
996        use lean_ctx::core::knowledge::ProjectKnowledge;
997        use lean_ctx_protocol::cloud::knowledge::{FactV1, ResearchContextDocumentV1};
998        let doc = ResearchContextDocumentV1 {
999            facts: vec![FactV1 {
1000                id: "f1".into(),
1001                statement: "Team A pulled claim here.".into(),
1002                kind: "observation".into(),
1003                applies_to: vec![],
1004                sources: vec![],
1005                from_contributions: vec![],
1006                anchors: vec![],
1007            }],
1008            ..ResearchContextDocumentV1::default()
1009        };
1010        super::super::knowledge::learn::sync_into_knowledge(root, "acme", "pay", 1, &doc).unwrap();
1011        let policy = lean_ctx::core::memory_policy::MemoryPolicy::default();
1012        ProjectKnowledge::mutate_locked(root, |k| {
1013            k.remember("arch", "own", "My own claim stays here.", "s", 0.9, &policy);
1014        })
1015        .unwrap();
1016        let mut map = super::super::vault::VaultMap::default();
1017        map.vaults.insert(
1018            "stable".into(),
1019            super::super::vault::VaultRecord {
1020                vault_id: "v1".into(),
1021                ns: "acme".into(),
1022                name: "pay".into(),
1023                sealed: false,
1024                roots: vec![root.to_string()],
1025            },
1026        );
1027        map.save(store.data_dir()).unwrap();
1028    }
1029
1030    /// (pulled fact of A still there, own fact still there)
1031    fn knowledge_left(root: &str) -> (bool, bool) {
1032        let values: Vec<String> = lean_ctx::core::knowledge::ProjectKnowledge::load(root)
1033            .unwrap()
1034            .facts
1035            .iter()
1036            .map(|f| f.value.clone())
1037            .collect();
1038        (
1039            values.iter().any(|v| v.contains("Team A pulled")),
1040            values.iter().any(|v| v.contains("My own claim")),
1041        )
1042    }
1043
1044    /// Disconnect always removes the facts pulled into project knowledge,
1045    /// also with --keep-local; the person's own facts stay.
1046    #[test]
1047    fn forget_removes_pulled_knowledge_also_when_keeping_local_data() {
1048        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1049        let dir = tempfile::tempdir().unwrap();
1050        let repo = tempfile::tempdir().unwrap();
1051        let root = repo.path().to_string_lossy().into_owned();
1052        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1053        let a = instance("https://cloud.example", "org_a", "inst_1");
1054        store.scope_to_enrollment(&a).unwrap();
1055        connect(&store, &a);
1056        knowledge_of_a(&store, &root);
1057
1058        store.forget(true).unwrap();
1059        assert_eq!(knowledge_left(&root), (false, true));
1060        assert!(
1061            store.data_dir().join("projects.json").exists(),
1062            "--keep-local"
1063        );
1064        assert_eq!(store.instance().unwrap(), None);
1065    }
1066
1067    /// 3.12.7 disconnect --keep-local left A's pulled facts behind; enrolling
1068    /// B removes them with A's data, or B's agents would recall them.
1069    #[test]
1070    fn enrolling_another_team_removes_the_knowledge_pulled_from_the_old_one() {
1071        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1072        let dir = tempfile::tempdir().unwrap();
1073        let repo = tempfile::tempdir().unwrap();
1074        let root = repo.path().to_string_lossy().into_owned();
1075        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1076        knowledge_of_a(&store, &root); // unstamped, as 3.12.7 left it
1077
1078        store
1079            .scope_to_enrollment(&instance("https://cloud.example", "org_b", "inst_2"))
1080            .unwrap();
1081        assert_eq!(knowledge_left(&root), (false, true));
1082        assert!(!store.data_dir().join("projects.json").exists());
1083    }
1084
1085    /// The same for a reader that finds data stamped for another team.
1086    #[test]
1087    fn a_reader_removes_the_knowledge_pulled_from_another_team() {
1088        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1089        let dir = tempfile::tempdir().unwrap();
1090        let repo = tempfile::tempdir().unwrap();
1091        let root = repo.path().to_string_lossy().into_owned();
1092        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1093        store
1094            .scope_to_enrollment(&instance("https://cloud.example", "org_a", "inst_1"))
1095            .unwrap();
1096        knowledge_of_a(&store, &root);
1097
1098        connect(
1099            &store,
1100            &instance("https://cloud.example", "org_b", "inst_2"),
1101        );
1102        assert!(store.instance().unwrap().is_some());
1103        assert_eq!(knowledge_left(&root), (false, true));
1104    }
1105
1106    #[test]
1107    fn a_damaged_stamp_counts_as_another_account() {
1108        let dir = tempfile::tempdir().unwrap();
1109        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1110        let a = instance("https://cloud.example", "org_a", "inst_1");
1111        store.scope_to_enrollment(&a).unwrap();
1112        data_of_a(&store);
1113        std::fs::write(store.data_dir().join(SCOPE_FILE), b"{not json").unwrap();
1114        connect(&store, &a);
1115        assert_eq!(store.instance().unwrap(), Some(a.clone()));
1116        assert!(!has_data_of_a(&store));
1117        assert_eq!(store.scope(), Some(DataScope::of(&a)));
1118
1119        // also at enrolment of the same team
1120        data_of_a(&store);
1121        std::fs::write(store.data_dir().join(SCOPE_FILE), b"{not json").unwrap();
1122        store.scope_to_enrollment(&a).unwrap();
1123        assert!(!has_data_of_a(&store));
1124    }
1125
1126    #[test]
1127    fn copies_left_by_an_interrupted_removal_are_swept() {
1128        let dir = tempfile::tempdir().unwrap();
1129        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1130        let left = dir.path().join("data.wiped-4242");
1131        std::fs::create_dir_all(left.join("outbox")).unwrap();
1132        std::fs::write(left.join("outbox/d.json"), b"{}").unwrap();
1133        data_of_a(&store);
1134        store
1135            .scope_to_enrollment(&instance("https://cloud.example", "org_b", "inst_1"))
1136            .unwrap();
1137        assert!(!left.exists());
1138        assert!(!has_data_of_a(&store));
1139    }
1140
1141    /// A checkout removed since (a deleted worktree) does not block the
1142    /// enrolment of another team: its pulled knowledge goes all the same.
1143    #[test]
1144    fn a_removed_checkout_does_not_block_enrolling_another_team() {
1145        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1146        let dir = tempfile::tempdir().unwrap();
1147        let repo = tempfile::tempdir().unwrap();
1148        let root = repo.path().to_string_lossy().into_owned();
1149        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1150        knowledge_of_a(&store, &root);
1151        let store_dir = lean_ctx::core::knowledge::knowledge_dir_of(&root).unwrap();
1152        drop(repo);
1153        assert!(!std::path::Path::new(&root).exists());
1154
1155        store
1156            .scope_to_enrollment(&instance("https://cloud.example", "org_b", "inst_2"))
1157            .unwrap();
1158        let stored = std::fs::read_to_string(store_dir.join("knowledge.json")).unwrap();
1159        assert!(!stored.contains("Team A pulled"), "{stored}");
1160        assert!(stored.contains("My own claim"), "{stored}");
1161    }
1162
1163    /// An MCP request bound to another project still removes the knowledge
1164    /// pulled into every checkout (a removal needs no policy admission).
1165    #[test]
1166    fn a_request_bound_to_another_project_still_removes_pulled_knowledge() {
1167        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1168        let dir = tempfile::tempdir().unwrap();
1169        let repo = tempfile::tempdir().unwrap();
1170        let other = tempfile::tempdir().unwrap();
1171        let root = repo.path().to_string_lossy().into_owned();
1172        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1173        knowledge_of_a(&store, &root);
1174
1175        let (config, data) = (dir.path().join("config"), dir.path().join("data"));
1176        lean_ctx::core::policy::runtime::spawn_for_project(other.path().to_path_buf(), move || {
1177            CloudStore::at(config, data)
1178                .scope_to_enrollment(&instance("https://cloud.example", "org_b", "inst_2"))
1179                .unwrap();
1180        })
1181        .join()
1182        .unwrap();
1183        assert_eq!(knowledge_left(&root), (false, true));
1184    }
1185
1186    /// A damaged store keeps readers out (fail closed), but a disconnect
1187    /// still gets out: it cleans every readable store, ends the enrolment
1188    /// and names the damaged store's file.
1189    #[test]
1190    fn a_damaged_store_never_locks_the_disconnect_out() {
1191        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1192        let dir = tempfile::tempdir().unwrap();
1193        let (healthy, damaged) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
1194        let healthy = healthy.path().to_string_lossy().into_owned();
1195        let damaged_root = damaged.path().to_string_lossy().into_owned();
1196        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1197        store
1198            .scope_to_enrollment(&instance("https://cloud.example", "org_a", "inst_1"))
1199            .unwrap();
1200        knowledge_of_a(&store, &damaged_root);
1201        knowledge_of_a(&store, &healthy);
1202        let mut map = super::super::vault::VaultMap::load(store.data_dir());
1203        for record in map.vaults.values_mut() {
1204            record.roots = vec![healthy.clone(), damaged_root.clone()];
1205        }
1206        map.save(store.data_dir()).unwrap();
1207        let broken = lean_ctx::core::knowledge::knowledge_dir_of(&damaged_root)
1208            .unwrap()
1209            .join("knowledge.json");
1210        std::fs::write(&broken, b"{ damaged").unwrap();
1211
1212        // connected to team B now: A's knowledge cannot all go, nothing is read
1213        let b = instance("https://cloud.example", "org_b", "inst_2");
1214        connect(&store, &b);
1215        assert!(store.instance().is_err());
1216        assert_eq!(store.enrolled_instance().unwrap(), Some(b));
1217
1218        // the disconnect's local side
1219        let error = store.forget(false).unwrap_err().to_string();
1220        assert!(error.contains(&broken.display().to_string()), "{error}");
1221        assert_eq!(knowledge_left(&healthy), (false, true));
1222        assert_eq!(store.enrolled_instance().unwrap(), None);
1223        assert_eq!(store.instance().unwrap(), None);
1224    }
1225
1226    /// The config of a single-dir layout: one of every kind of entry.
1227    const SINGLE_DIR_CONFIG: &[&str] = &[
1228        INSTANCE_KEY_FILE,
1229        KX_KEY_FILE,
1230        LEASE_FILE,
1231        KEYS_FILE,
1232        "keys_v3.json",
1233        "chat_key.json",
1234        "bring-local-0123abcd.json",
1235        "consent.key",
1236        "consent/offer-1.json",
1237        "replica.key",
1238        "scope.json.lock",
1239        "lease.json.damaged-1",
1240        ".keys.json.tmp.4242.0",
1241    ];
1242
1243    fn single_dir_config(cloud: &Path) {
1244        for name in SINGLE_DIR_CONFIG {
1245            let path = cloud.join(name);
1246            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1247            std::fs::write(path, b"{}").unwrap();
1248        }
1249    }
1250
1251    fn missing_config(cloud: &Path) -> Vec<&'static str> {
1252        SINGLE_DIR_CONFIG
1253            .iter()
1254            .copied()
1255            .filter(|name| !cloud.join(name).exists())
1256            .collect()
1257    }
1258
1259    /// rc4-274: a legacy `~/.lean-ctx` or a custom `LEAN_CTX_DATA_DIR` puts
1260    /// `<config>/cloud` and `<data>/cloud` in one directory. Enrolling
1261    /// another account removes only the data there; the config (keys,
1262    /// lease, consent, locks) stays and nothing is left beside it.
1263    #[test]
1264    fn a_single_dir_layout_keeps_the_config_when_the_data_goes() {
1265        let dir = tempfile::tempdir().unwrap();
1266        let cloud = dir.path().join("cloud");
1267        let store = CloudStore::at(&cloud, &cloud);
1268        single_dir_config(&cloud);
1269        data_of_a(&store);
1270        std::fs::write(cloud.join(ACTIVITY_FILE), b"{}").unwrap();
1271
1272        let b = instance("https://cloud.example", "org_b", "inst_2");
1273        store.scope_to_enrollment(&b).unwrap();
1274        assert!(!has_data_of_a(&store), "nothing of A stays for B");
1275        assert!(!cloud.join(ACTIVITY_FILE).exists());
1276        assert_eq!(missing_config(&cloud), Vec::<&str>::new());
1277        assert_eq!(store.scope(), Some(DataScope::of(&b)));
1278        let beside: Vec<_> = std::fs::read_dir(dir.path())
1279            .unwrap()
1280            .map(|e| e.unwrap().file_name())
1281            .collect();
1282        assert_eq!(beside, ["cloud"], "no copy left beside it");
1283
1284        // A reader connected to another team later: the same.
1285        data_of_a(&store);
1286        connect(
1287            &store,
1288            &instance("https://cloud.example", "org_c", "inst_3"),
1289        );
1290        assert!(store.instance().unwrap().is_some());
1291        assert!(!has_data_of_a(&store));
1292        assert_eq!(missing_config(&cloud), Vec::<&str>::new());
1293        assert!(cloud.join(INSTANCE_FILE).exists());
1294    }
1295
1296    /// rc4-274: the config directory reached through a symlink, or lying
1297    /// inside the data directory, is kept as well.
1298    #[cfg(unix)]
1299    #[test]
1300    fn a_config_dir_behind_a_symlink_or_inside_the_data_stays() {
1301        let dir = tempfile::tempdir().unwrap();
1302        let cloud = dir.path().join("cloud");
1303        std::fs::create_dir_all(&cloud).unwrap();
1304        std::os::unix::fs::symlink(&cloud, dir.path().join("linked")).unwrap();
1305        let store = CloudStore::at(dir.path().join("linked"), &cloud);
1306        single_dir_config(&cloud);
1307        data_of_a(&store);
1308        store
1309            .scope_to_enrollment(&instance("https://cloud.example", "org_b", "inst_2"))
1310            .unwrap();
1311        assert!(!has_data_of_a(&store));
1312        assert_eq!(missing_config(&cloud), Vec::<&str>::new());
1313
1314        let data = dir.path().join("data");
1315        let config = data.join("config").join("cloud");
1316        let store = CloudStore::at(&config, &data);
1317        single_dir_config(&config);
1318        data_of_a(&store);
1319        store
1320            .scope_to_enrollment(&instance("https://cloud.example", "org_b", "inst_2"))
1321            .unwrap();
1322        assert!(!has_data_of_a(&store));
1323        assert_eq!(missing_config(&config), Vec::<&str>::new());
1324    }
1325
1326    /// rc4-274: a disconnect without `--keep-local` in a single-dir layout
1327    /// removes the data and the enrolment, but not the rest of the config
1328    /// (as in the XDG split, where `<config>/cloud` is never removed whole).
1329    #[test]
1330    fn a_single_dir_disconnect_removes_the_data_but_not_the_config_dir() {
1331        let dir = tempfile::tempdir().unwrap();
1332        let cloud = dir.path().join("cloud");
1333        let store = CloudStore::at(&cloud, &cloud);
1334        store
1335            .scope_to_enrollment(&instance("https://cloud.example", "org_a", "inst_1"))
1336            .unwrap();
1337        connect(
1338            &store,
1339            &instance("https://cloud.example", "org_a", "inst_1"),
1340        );
1341        data_of_a(&store);
1342        std::fs::write(cloud.join("consent.key"), b"k").unwrap();
1343        store.forget(false).unwrap();
1344        assert!(!has_data_of_a(&store));
1345        assert!(!cloud.join(INSTANCE_FILE).exists());
1346        assert!(!cloud.join(SCOPE_FILE).exists());
1347        assert!(cloud.join("consent.key").exists());
1348    }
1349
1350    /// Every name in the list is one a module writes (a renamed constant
1351    /// cannot leave a stale entry), and data names are not in it.
1352    #[test]
1353    fn config_entries_name_the_config_only() {
1354        for name in CONFIG_ENTRIES {
1355            assert!(is_config_entry(name), "{name}");
1356            assert!(is_config_entry(&format!(".{name}.tmp.1.0")), "{name}");
1357            assert!(is_config_entry(&format!("{name}.damaged-2")), "{name}");
1358        }
1359        for data in [
1360            ACTIVITY_FILE,
1361            SCOPE_FILE,
1362            "projects.json",
1363            "outbox",
1364            "bus",
1365            "replicas",
1366            ".projects.json.tmp.1.0",
1367        ] {
1368            assert!(!is_config_entry(data), "{data}");
1369        }
1370    }
1371}