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    // Field order is drop order: the file lock ends before the next thread
698    // of this process gets its turn.
699    _file: lean_ctx::core::file_lock::FlockGuard,
700    _turn: lean_ctx::core::file_lock::Turn,
701}
702
703/// Take the lock for the state file `dir/name`, waiting at most
704/// [`STATE_LOCK_WAIT`]; symlinks are refused.
705pub(crate) fn lock_state(dir: &Path, name: &str) -> Result<StateLock, CloudError> {
706    lock_state_within(dir, name, STATE_LOCK_WAIT)
707}
708
709/// [`lock_state`] waiting at most `wait` (zero: only when free right now).
710pub(crate) fn lock_state_within(
711    dir: &Path,
712    name: &str,
713    wait: std::time::Duration,
714) -> Result<StateLock, CloudError> {
715    private_dir(dir)?;
716    let path = dir.join(format!("{name}.lock"));
717    let local = |what: &str| CloudError::Local(format!("{what} {}", path.display()));
718    // Threads of this process queue in arrival order and wait only while the
719    // queue stands still, so eight writers whose Windows replace each take a
720    // few hundred ms do not fail the last one; other processes stay bounded
721    // by the polled file lock below.
722    let turn = lean_ctx::core::file_lock::take_turn(&path, wait).ok_or_else(|| {
723        local(&format!(
724            "lock (no turn within {}ms — giving up)",
725            wait.as_millis()
726        ))
727    })?;
728    let mut options = std::fs::OpenOptions::new();
729    options.read(true).write(true).create(true).truncate(false);
730    #[cfg(unix)]
731    {
732        use std::os::unix::fs::OpenOptionsExt as _;
733        options
734            .mode(0o600)
735            .custom_flags(libc::O_CLOEXEC | libc::O_NOFOLLOW);
736    }
737    let file = options
738        .open(&path)
739        .map_err(|e| local(&format!("open ({e})")))?;
740    let file = lean_ctx::core::file_lock::FlockGuard::exclusive_timeout(file, wait)
741        .map_err(|e| local(&format!("lock ({e})")))?;
742    Ok(StateLock {
743        _file: file,
744        _turn: turn,
745    })
746}
747
748#[cfg(test)]
749mod tests {
750    use super::*;
751
752    /// Personal, Team, Company (Cloud C line): the record says where the
753    /// engine is enrolled; a record from before keeps the plain name.
754    #[test]
755    fn workspace_label_names_personal_team_and_company() {
756        let mut r = InstanceRecord {
757            instance_id: "inst_1".into(),
758            org_id: "org_1".into(),
759            org_name: "Platform".into(),
760            label: "mbp".into(),
761            url: "https://cloud.example".into(),
762            org_salt_id: "s".into(),
763            enrolled_at: "2026-10-26T10:00:00Z".into(),
764            web_url: None,
765            org_kind: None,
766            company_name: None,
767        };
768        assert_eq!(r.workspace_label(), "Platform");
769        r.org_kind = Some("team".into());
770        assert_eq!(r.workspace_label(), "Team Platform");
771        r.company_name = Some("Acme".into());
772        assert_eq!(r.workspace_label(), "Company Acme · Team Platform");
773        r.company_name = None;
774        r.org_kind = Some("personal".into());
775        assert_eq!(r.workspace_label(), "Personal (Platform)");
776        // an old record without the new fields still reads
777        let old: InstanceRecord = serde_json::from_value(serde_json::json!({
778            "instance_id": "i", "org_id": "o", "org_name": "Acme", "label": "l", "url": "u",
779            "org_salt_id": "s", "enrolled_at": "t"
780        }))
781        .unwrap();
782        assert_eq!((old.org_kind, old.company_name), (None, None));
783    }
784
785    #[test]
786    fn private_files_are_atomic_and_owner_only() {
787        let dir = tempfile::tempdir().unwrap();
788        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
789        let token = TokenRecord {
790            access_token: "atl_secret".into(),
791            expires_at: 1,
792        };
793        store.write_config(TOKEN_FILE, &token).unwrap();
794        assert_eq!(
795            store.read_config::<TokenRecord>(TOKEN_FILE).unwrap(),
796            Some(token.clone())
797        );
798        assert!(!format!("{token:?}").contains("atl_secret"));
799        #[cfg(unix)]
800        {
801            use std::os::unix::fs::PermissionsExt as _;
802            let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
803            assert_eq!(mode(store.config_dir()), 0o700);
804            assert_eq!(mode(&store.config_dir().join(TOKEN_FILE)), 0o600);
805        }
806        let leftovers: Vec<_> = std::fs::read_dir(store.config_dir())
807            .unwrap()
808            .filter_map(Result::ok)
809            .filter(|e| e.file_name().to_string_lossy().ends_with(".tmp"))
810            .collect();
811        assert!(leftovers.is_empty());
812    }
813
814    #[test]
815    fn damaged_state_is_moved_aside_and_only_three_copies_stay() {
816        let dir = tempfile::tempdir().unwrap();
817        let path = dir.path().join("state.json");
818        let load = |accept: bool| load_or_quarantine::<Value>(&path, |_| accept);
819        assert_eq!(load(true).unwrap(), None, "missing");
820        std::fs::write(&path, b"{\"ok\": 1}").unwrap();
821        assert_eq!(load(true).unwrap(), Some(serde_json::json!({"ok": 1})));
822        // Refused by the caller (an unknown version): moved, an error.
823        let error = load(false).unwrap_err().to_string();
824        assert!(error.contains("damaged-1"), "{error}");
825        assert!(!path.exists());
826        for n in 0..4 {
827            std::fs::write(&path, format!("broken {n}")).unwrap();
828            assert!(load(true).is_err());
829        }
830        let mut kept: Vec<String> = std::fs::read_dir(dir.path())
831            .unwrap()
832            .filter_map(|e| e.ok()?.file_name().into_string().ok())
833            .collect();
834        kept.sort();
835        assert_eq!(
836            kept,
837            [
838                "state.json.damaged-3",
839                "state.json.damaged-4",
840                "state.json.damaged-5"
841            ]
842        );
843        assert_eq!(
844            std::fs::read(dir.path().join("state.json.damaged-5")).unwrap(),
845            b"broken 3",
846            "the newest copy is the last damaged file"
847        );
848    }
849
850    /// PR #2286 Windows flake: writers of one process that each hold the
851    /// lock a while queue in turn; the last one waits longer than `wait` in
852    /// total but never `wait` without progress, so none gives up.
853    #[test]
854    fn state_lock_waiters_of_one_process_queue_instead_of_timing_out() {
855        let dir = tempfile::tempdir().unwrap();
856        let wait = std::time::Duration::from_millis(400);
857        let hold = std::time::Duration::from_millis(150);
858        let writers: Vec<_> = (0..6)
859            .map(|_| {
860                let dir = dir.path().to_path_buf();
861                std::thread::spawn(move || {
862                    let lock = lock_state_within(&dir, "sent.json", wait);
863                    std::thread::sleep(hold);
864                    lock.is_ok()
865                })
866            })
867            .collect();
868        let got: Vec<bool> = writers.into_iter().map(|w| w.join().unwrap()).collect();
869        assert_eq!(got, [true; 6], "six holds of 150ms exceed one 400ms wait");
870    }
871
872    #[test]
873    fn a_held_state_lock_is_not_taken_twice() {
874        let dir = tempfile::tempdir().unwrap();
875        let held = lock_state(dir.path(), "leases.json").unwrap();
876        assert!(lock_state_within(dir.path(), "leases.json", std::time::Duration::ZERO).is_err());
877        drop(held);
878        assert!(lock_state_within(dir.path(), "leases.json", std::time::Duration::ZERO).is_ok());
879        #[cfg(unix)]
880        {
881            use std::os::unix::fs::PermissionsExt as _;
882            let mode = std::fs::metadata(dir.path().join("leases.json.lock"))
883                .unwrap()
884                .permissions()
885                .mode();
886            assert_eq!(mode & 0o777, 0o600);
887        }
888    }
889
890    #[test]
891    fn forget_keeps_local_data_on_request() {
892        let dir = tempfile::tempdir().unwrap();
893        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
894        store
895            .write_config(TOKEN_FILE, &serde_json::json!({}))
896            .unwrap();
897        store.record_success("lease", "2026-10-20T12:00:00Z");
898        store.forget(true).unwrap();
899        assert!(store.read_config_bytes(TOKEN_FILE).unwrap().is_none());
900        assert_eq!(
901            store.activity().last_seen.as_deref(),
902            Some("2026-10-20T12:00:00Z")
903        );
904        store.forget(false).unwrap();
905        assert!(store.activity().last_seen.is_none());
906    }
907}
908
909/// 3.12.8 cross-account leak: `<data>/cloud` belongs to one server and team.
910#[cfg(test)]
911mod scope_tests {
912    use super::*;
913
914    fn instance(server: &str, org: &str, id: &str) -> InstanceRecord {
915        InstanceRecord {
916            instance_id: id.into(),
917            org_id: org.into(),
918            org_name: org.into(),
919            label: "mbp".into(),
920            url: server.into(),
921            org_salt_id: "s".into(),
922            enrolled_at: "2026-11-23T10:00:00Z".into(),
923            web_url: None,
924            org_kind: None,
925            company_name: None,
926        }
927    }
928
929    /// A's vault map and an unsent draft of A.
930    fn data_of_a(store: &CloudStore) {
931        write_private(store.data_dir(), "projects.json", b"{\"projects\":{}}").unwrap();
932        let drafts = store.data_dir().join("outbox").join("knowledge");
933        std::fs::create_dir_all(&drafts).unwrap();
934        std::fs::write(drafts.join("d1.json"), b"{}").unwrap();
935    }
936
937    fn has_data_of_a(store: &CloudStore) -> bool {
938        store.data_dir().join("projects.json").exists()
939            && store.data_dir().join("outbox/knowledge/d1.json").exists()
940    }
941
942    fn connect(store: &CloudStore, record: &InstanceRecord) {
943        store.write_config(INSTANCE_FILE, record).unwrap();
944    }
945
946    #[test]
947    fn enrolling_another_team_or_server_removes_the_local_data() {
948        let dir = tempfile::tempdir().unwrap();
949        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
950        let a = instance("https://cloud.example", "org_a", "inst_1");
951        store.scope_to_enrollment(&a).unwrap();
952        data_of_a(&store);
953
954        // A reconnect to the same server and team (kept with --keep-local)
955        store
956            .scope_to_enrollment(&instance("https://cloud.example", "org_a", "inst_2"))
957            .unwrap();
958        assert!(has_data_of_a(&store), "same team keeps its drafts");
959        assert_eq!(store.scope().unwrap().instance_id, "inst_2");
960
961        // B: another team on the same server
962        let b = instance("https://cloud.example", "org_b", "inst_3");
963        store.scope_to_enrollment(&b).unwrap();
964        assert!(!has_data_of_a(&store), "nothing of A stays for B");
965        assert_eq!(store.scope(), Some(DataScope::of(&b)));
966
967        // the same team id on another server is another account too
968        data_of_a(&store);
969        store
970            .scope_to_enrollment(&instance("https://staging.example", "org_b", "inst_4"))
971            .unwrap();
972        assert!(!has_data_of_a(&store));
973    }
974
975    #[test]
976    fn data_without_a_stamp_is_removed_at_enrolment() {
977        let dir = tempfile::tempdir().unwrap();
978        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
979        data_of_a(&store); // left by an older version with --keep-local
980        store
981            .scope_to_enrollment(&instance("https://cloud.example", "org_b", "inst_1"))
982            .unwrap();
983        assert!(!has_data_of_a(&store));
984    }
985
986    #[test]
987    fn readers_get_nothing_while_disconnected_or_of_another_account() {
988        let dir = tempfile::tempdir().unwrap();
989        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
990        let a = instance("https://cloud.example", "org_a", "inst_1");
991        store.scope_to_enrollment(&a).unwrap();
992        data_of_a(&store);
993
994        // not connected (disconnect --keep-local): no instance, nothing read
995        assert_eq!(store.instance().unwrap(), None);
996        assert!(has_data_of_a(&store), "kept for a reconnect, not read");
997
998        // connected to the stamped instance: read as before
999        connect(&store, &a);
1000        assert_eq!(store.instance().unwrap(), Some(a.clone()));
1001        assert!(has_data_of_a(&store));
1002
1003        // another instance of the same team only moves the stamp
1004        let a2 = instance("https://cloud.example", "org_a", "inst_2");
1005        connect(&store, &a2);
1006        assert_eq!(store.instance().unwrap(), Some(a2.clone()));
1007        assert!(has_data_of_a(&store));
1008        assert_eq!(store.scope(), Some(DataScope::of(&a2)));
1009
1010        // an instance of another team the enrolment did not scope: A's data
1011        // is removed before anything reads it
1012        let b = instance("https://cloud.example", "org_b", "inst_3");
1013        connect(&store, &b);
1014        assert_eq!(store.instance().unwrap(), Some(b.clone()));
1015        assert!(!has_data_of_a(&store));
1016        assert_eq!(store.scope(), Some(DataScope::of(&b)));
1017    }
1018
1019    #[test]
1020    fn data_from_before_the_stamp_is_adopted_by_the_connected_instance() {
1021        let dir = tempfile::tempdir().unwrap();
1022        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1023        let a = instance("https://cloud.example", "org_a", "inst_1");
1024        data_of_a(&store);
1025        connect(&store, &a);
1026        assert_eq!(store.instance().unwrap(), Some(a.clone()));
1027        assert!(has_data_of_a(&store), "an upgrade keeps the drafts");
1028        assert_eq!(store.scope(), Some(DataScope::of(&a)));
1029    }
1030
1031    /// A checkout of team A with one fact pulled from A and one own fact,
1032    /// found through A's vault map in `store`.
1033    fn knowledge_of_a(store: &CloudStore, root: &str) {
1034        use lean_ctx::core::knowledge::ProjectKnowledge;
1035        use lean_ctx_protocol::cloud::knowledge::{FactV1, ResearchContextDocumentV1};
1036        let doc = ResearchContextDocumentV1 {
1037            facts: vec![FactV1 {
1038                id: "f1".into(),
1039                statement: "Team A pulled claim here.".into(),
1040                kind: "observation".into(),
1041                applies_to: vec![],
1042                sources: vec![],
1043                from_contributions: vec![],
1044                anchors: vec![],
1045            }],
1046            ..ResearchContextDocumentV1::default()
1047        };
1048        super::super::knowledge::learn::sync_into_knowledge(root, "acme", "pay", 1, &doc).unwrap();
1049        let policy = lean_ctx::core::memory_policy::MemoryPolicy::default();
1050        ProjectKnowledge::mutate_locked(root, |k| {
1051            k.remember("arch", "own", "My own claim stays here.", "s", 0.9, &policy);
1052        })
1053        .unwrap();
1054        let mut map = super::super::vault::VaultMap::default();
1055        map.vaults.insert(
1056            "stable".into(),
1057            super::super::vault::VaultRecord {
1058                vault_id: "v1".into(),
1059                ns: "acme".into(),
1060                name: "pay".into(),
1061                sealed: false,
1062                roots: vec![root.to_string()],
1063            },
1064        );
1065        map.save(store.data_dir()).unwrap();
1066    }
1067
1068    /// (pulled fact of A still there, own fact still there)
1069    fn knowledge_left(root: &str) -> (bool, bool) {
1070        let values: Vec<String> = lean_ctx::core::knowledge::ProjectKnowledge::load(root)
1071            .unwrap()
1072            .facts
1073            .iter()
1074            .map(|f| f.value.clone())
1075            .collect();
1076        (
1077            values.iter().any(|v| v.contains("Team A pulled")),
1078            values.iter().any(|v| v.contains("My own claim")),
1079        )
1080    }
1081
1082    /// Disconnect always removes the facts pulled into project knowledge,
1083    /// also with --keep-local; the person's own facts stay.
1084    #[test]
1085    fn forget_removes_pulled_knowledge_also_when_keeping_local_data() {
1086        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1087        let dir = tempfile::tempdir().unwrap();
1088        let repo = tempfile::tempdir().unwrap();
1089        let root = repo.path().to_string_lossy().into_owned();
1090        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1091        let a = instance("https://cloud.example", "org_a", "inst_1");
1092        store.scope_to_enrollment(&a).unwrap();
1093        connect(&store, &a);
1094        knowledge_of_a(&store, &root);
1095
1096        store.forget(true).unwrap();
1097        assert_eq!(knowledge_left(&root), (false, true));
1098        assert!(
1099            store.data_dir().join("projects.json").exists(),
1100            "--keep-local"
1101        );
1102        assert_eq!(store.instance().unwrap(), None);
1103    }
1104
1105    /// 3.12.7 disconnect --keep-local left A's pulled facts behind; enrolling
1106    /// B removes them with A's data, or B's agents would recall them.
1107    #[test]
1108    fn enrolling_another_team_removes_the_knowledge_pulled_from_the_old_one() {
1109        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1110        let dir = tempfile::tempdir().unwrap();
1111        let repo = tempfile::tempdir().unwrap();
1112        let root = repo.path().to_string_lossy().into_owned();
1113        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1114        knowledge_of_a(&store, &root); // unstamped, as 3.12.7 left it
1115
1116        store
1117            .scope_to_enrollment(&instance("https://cloud.example", "org_b", "inst_2"))
1118            .unwrap();
1119        assert_eq!(knowledge_left(&root), (false, true));
1120        assert!(!store.data_dir().join("projects.json").exists());
1121    }
1122
1123    /// The same for a reader that finds data stamped for another team.
1124    #[test]
1125    fn a_reader_removes_the_knowledge_pulled_from_another_team() {
1126        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1127        let dir = tempfile::tempdir().unwrap();
1128        let repo = tempfile::tempdir().unwrap();
1129        let root = repo.path().to_string_lossy().into_owned();
1130        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1131        store
1132            .scope_to_enrollment(&instance("https://cloud.example", "org_a", "inst_1"))
1133            .unwrap();
1134        knowledge_of_a(&store, &root);
1135
1136        connect(
1137            &store,
1138            &instance("https://cloud.example", "org_b", "inst_2"),
1139        );
1140        assert!(store.instance().unwrap().is_some());
1141        assert_eq!(knowledge_left(&root), (false, true));
1142    }
1143
1144    #[test]
1145    fn a_damaged_stamp_counts_as_another_account() {
1146        let dir = tempfile::tempdir().unwrap();
1147        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1148        let a = instance("https://cloud.example", "org_a", "inst_1");
1149        store.scope_to_enrollment(&a).unwrap();
1150        data_of_a(&store);
1151        std::fs::write(store.data_dir().join(SCOPE_FILE), b"{not json").unwrap();
1152        connect(&store, &a);
1153        assert_eq!(store.instance().unwrap(), Some(a.clone()));
1154        assert!(!has_data_of_a(&store));
1155        assert_eq!(store.scope(), Some(DataScope::of(&a)));
1156
1157        // also at enrolment of the same team
1158        data_of_a(&store);
1159        std::fs::write(store.data_dir().join(SCOPE_FILE), b"{not json").unwrap();
1160        store.scope_to_enrollment(&a).unwrap();
1161        assert!(!has_data_of_a(&store));
1162    }
1163
1164    #[test]
1165    fn copies_left_by_an_interrupted_removal_are_swept() {
1166        let dir = tempfile::tempdir().unwrap();
1167        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1168        let left = dir.path().join("data.wiped-4242");
1169        std::fs::create_dir_all(left.join("outbox")).unwrap();
1170        std::fs::write(left.join("outbox/d.json"), b"{}").unwrap();
1171        data_of_a(&store);
1172        store
1173            .scope_to_enrollment(&instance("https://cloud.example", "org_b", "inst_1"))
1174            .unwrap();
1175        assert!(!left.exists());
1176        assert!(!has_data_of_a(&store));
1177    }
1178
1179    /// A checkout removed since (a deleted worktree) does not block the
1180    /// enrolment of another team: its pulled knowledge goes all the same.
1181    #[test]
1182    fn a_removed_checkout_does_not_block_enrolling_another_team() {
1183        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1184        let dir = tempfile::tempdir().unwrap();
1185        let repo = tempfile::tempdir().unwrap();
1186        let root = repo.path().to_string_lossy().into_owned();
1187        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1188        knowledge_of_a(&store, &root);
1189        let store_dir = lean_ctx::core::knowledge::knowledge_dir_of(&root).unwrap();
1190        drop(repo);
1191        assert!(!std::path::Path::new(&root).exists());
1192
1193        store
1194            .scope_to_enrollment(&instance("https://cloud.example", "org_b", "inst_2"))
1195            .unwrap();
1196        let stored = std::fs::read_to_string(store_dir.join("knowledge.json")).unwrap();
1197        assert!(!stored.contains("Team A pulled"), "{stored}");
1198        assert!(stored.contains("My own claim"), "{stored}");
1199    }
1200
1201    /// An MCP request bound to another project still removes the knowledge
1202    /// pulled into every checkout (a removal needs no policy admission).
1203    #[test]
1204    fn a_request_bound_to_another_project_still_removes_pulled_knowledge() {
1205        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1206        let dir = tempfile::tempdir().unwrap();
1207        let repo = tempfile::tempdir().unwrap();
1208        let other = tempfile::tempdir().unwrap();
1209        let root = repo.path().to_string_lossy().into_owned();
1210        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1211        knowledge_of_a(&store, &root);
1212
1213        let (config, data) = (dir.path().join("config"), dir.path().join("data"));
1214        lean_ctx::core::policy::runtime::spawn_for_project(other.path().to_path_buf(), move || {
1215            CloudStore::at(config, data)
1216                .scope_to_enrollment(&instance("https://cloud.example", "org_b", "inst_2"))
1217                .unwrap();
1218        })
1219        .join()
1220        .unwrap();
1221        assert_eq!(knowledge_left(&root), (false, true));
1222    }
1223
1224    /// A damaged store keeps readers out (fail closed), but a disconnect
1225    /// still gets out: it cleans every readable store, ends the enrolment
1226    /// and names the damaged store's file.
1227    #[test]
1228    fn a_damaged_store_never_locks_the_disconnect_out() {
1229        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1230        let dir = tempfile::tempdir().unwrap();
1231        let (healthy, damaged) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
1232        let healthy = healthy.path().to_string_lossy().into_owned();
1233        let damaged_root = damaged.path().to_string_lossy().into_owned();
1234        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1235        store
1236            .scope_to_enrollment(&instance("https://cloud.example", "org_a", "inst_1"))
1237            .unwrap();
1238        knowledge_of_a(&store, &damaged_root);
1239        knowledge_of_a(&store, &healthy);
1240        let mut map = super::super::vault::VaultMap::load(store.data_dir());
1241        for record in map.vaults.values_mut() {
1242            record.roots = vec![healthy.clone(), damaged_root.clone()];
1243        }
1244        map.save(store.data_dir()).unwrap();
1245        let broken = lean_ctx::core::knowledge::knowledge_dir_of(&damaged_root)
1246            .unwrap()
1247            .join("knowledge.json");
1248        std::fs::write(&broken, b"{ damaged").unwrap();
1249
1250        // connected to team B now: A's knowledge cannot all go, nothing is read
1251        let b = instance("https://cloud.example", "org_b", "inst_2");
1252        connect(&store, &b);
1253        assert!(store.instance().is_err());
1254        assert_eq!(store.enrolled_instance().unwrap(), Some(b));
1255
1256        // the disconnect's local side
1257        let error = store.forget(false).unwrap_err().to_string();
1258        assert!(error.contains(&broken.display().to_string()), "{error}");
1259        assert_eq!(knowledge_left(&healthy), (false, true));
1260        assert_eq!(store.enrolled_instance().unwrap(), None);
1261        assert_eq!(store.instance().unwrap(), None);
1262    }
1263
1264    /// The config of a single-dir layout: one of every kind of entry.
1265    const SINGLE_DIR_CONFIG: &[&str] = &[
1266        INSTANCE_KEY_FILE,
1267        KX_KEY_FILE,
1268        LEASE_FILE,
1269        KEYS_FILE,
1270        "keys_v3.json",
1271        "chat_key.json",
1272        "bring-local-0123abcd.json",
1273        "consent.key",
1274        "consent/offer-1.json",
1275        "replica.key",
1276        "scope.json.lock",
1277        "lease.json.damaged-1",
1278        ".keys.json.tmp.4242.0",
1279    ];
1280
1281    fn single_dir_config(cloud: &Path) {
1282        for name in SINGLE_DIR_CONFIG {
1283            let path = cloud.join(name);
1284            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1285            std::fs::write(path, b"{}").unwrap();
1286        }
1287    }
1288
1289    fn missing_config(cloud: &Path) -> Vec<&'static str> {
1290        SINGLE_DIR_CONFIG
1291            .iter()
1292            .copied()
1293            .filter(|name| !cloud.join(name).exists())
1294            .collect()
1295    }
1296
1297    /// rc4-274: a legacy `~/.lean-ctx` or a custom `LEAN_CTX_DATA_DIR` puts
1298    /// `<config>/cloud` and `<data>/cloud` in one directory. Enrolling
1299    /// another account removes only the data there; the config (keys,
1300    /// lease, consent, locks) stays and nothing is left beside it.
1301    #[test]
1302    fn a_single_dir_layout_keeps_the_config_when_the_data_goes() {
1303        let dir = tempfile::tempdir().unwrap();
1304        let cloud = dir.path().join("cloud");
1305        let store = CloudStore::at(&cloud, &cloud);
1306        single_dir_config(&cloud);
1307        data_of_a(&store);
1308        std::fs::write(cloud.join(ACTIVITY_FILE), b"{}").unwrap();
1309
1310        let b = instance("https://cloud.example", "org_b", "inst_2");
1311        store.scope_to_enrollment(&b).unwrap();
1312        assert!(!has_data_of_a(&store), "nothing of A stays for B");
1313        assert!(!cloud.join(ACTIVITY_FILE).exists());
1314        assert_eq!(missing_config(&cloud), Vec::<&str>::new());
1315        assert_eq!(store.scope(), Some(DataScope::of(&b)));
1316        let beside: Vec<_> = std::fs::read_dir(dir.path())
1317            .unwrap()
1318            .map(|e| e.unwrap().file_name())
1319            .collect();
1320        assert_eq!(beside, ["cloud"], "no copy left beside it");
1321
1322        // A reader connected to another team later: the same.
1323        data_of_a(&store);
1324        connect(
1325            &store,
1326            &instance("https://cloud.example", "org_c", "inst_3"),
1327        );
1328        assert!(store.instance().unwrap().is_some());
1329        assert!(!has_data_of_a(&store));
1330        assert_eq!(missing_config(&cloud), Vec::<&str>::new());
1331        assert!(cloud.join(INSTANCE_FILE).exists());
1332    }
1333
1334    /// rc4-274: the config directory reached through a symlink, or lying
1335    /// inside the data directory, is kept as well.
1336    #[cfg(unix)]
1337    #[test]
1338    fn a_config_dir_behind_a_symlink_or_inside_the_data_stays() {
1339        let dir = tempfile::tempdir().unwrap();
1340        let cloud = dir.path().join("cloud");
1341        std::fs::create_dir_all(&cloud).unwrap();
1342        std::os::unix::fs::symlink(&cloud, dir.path().join("linked")).unwrap();
1343        let store = CloudStore::at(dir.path().join("linked"), &cloud);
1344        single_dir_config(&cloud);
1345        data_of_a(&store);
1346        store
1347            .scope_to_enrollment(&instance("https://cloud.example", "org_b", "inst_2"))
1348            .unwrap();
1349        assert!(!has_data_of_a(&store));
1350        assert_eq!(missing_config(&cloud), Vec::<&str>::new());
1351
1352        let data = dir.path().join("data");
1353        let config = data.join("config").join("cloud");
1354        let store = CloudStore::at(&config, &data);
1355        single_dir_config(&config);
1356        data_of_a(&store);
1357        store
1358            .scope_to_enrollment(&instance("https://cloud.example", "org_b", "inst_2"))
1359            .unwrap();
1360        assert!(!has_data_of_a(&store));
1361        assert_eq!(missing_config(&config), Vec::<&str>::new());
1362    }
1363
1364    /// rc4-274: a disconnect without `--keep-local` in a single-dir layout
1365    /// removes the data and the enrolment, but not the rest of the config
1366    /// (as in the XDG split, where `<config>/cloud` is never removed whole).
1367    #[test]
1368    fn a_single_dir_disconnect_removes_the_data_but_not_the_config_dir() {
1369        let dir = tempfile::tempdir().unwrap();
1370        let cloud = dir.path().join("cloud");
1371        let store = CloudStore::at(&cloud, &cloud);
1372        store
1373            .scope_to_enrollment(&instance("https://cloud.example", "org_a", "inst_1"))
1374            .unwrap();
1375        connect(
1376            &store,
1377            &instance("https://cloud.example", "org_a", "inst_1"),
1378        );
1379        data_of_a(&store);
1380        std::fs::write(cloud.join("consent.key"), b"k").unwrap();
1381        store.forget(false).unwrap();
1382        assert!(!has_data_of_a(&store));
1383        assert!(!cloud.join(INSTANCE_FILE).exists());
1384        assert!(!cloud.join(SCOPE_FILE).exists());
1385        assert!(cloud.join("consent.key").exists());
1386    }
1387
1388    /// Every name in the list is one a module writes (a renamed constant
1389    /// cannot leave a stale entry), and data names are not in it.
1390    #[test]
1391    fn config_entries_name_the_config_only() {
1392        for name in CONFIG_ENTRIES {
1393            assert!(is_config_entry(name), "{name}");
1394            assert!(is_config_entry(&format!(".{name}.tmp.1.0")), "{name}");
1395            assert!(is_config_entry(&format!("{name}.damaged-2")), "{name}");
1396        }
1397        for data in [
1398            ACTIVITY_FILE,
1399            SCOPE_FILE,
1400            "projects.json",
1401            "outbox",
1402            "bus",
1403            "replicas",
1404            ".projects.json.tmp.1.0",
1405        ] {
1406            assert!(!is_config_entry(data), "{data}");
1407        }
1408    }
1409}