lean-ctx-engine 3.12.12

LeanCTX | OSS library: the open-source runtime for the Context Gateway for AI agents behind the lean-ctx CLI, MCP server and proxy integrations.
Documentation
// SPDX-License-Identifier: Apache-2.0
//! `<data_dir>/cloud/projects.json`: the vaults Cloud resolved for this machine's repositories
//! and the local checkouts seen for each. Written when a checkout is resolved; read wherever a
//! checkout's vault matters (bus, sync, and the per-vault policy floor).

use std::collections::BTreeMap;
use std::path::Path;

use serde::{Deserialize, Serialize};

use lean_ctx_protocol::cloud::vault::VaultV1;

/// The file keeps its pre-VA name, like the field names in it: an older
/// engine (downgrade, or a teammate's machine) still reads it.
pub const VAULTS_FILE: &str = "projects.json";

/// A vault as Cloud resolved it, plus the local checkouts seen for it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VaultRecord {
    /// On disk as `project_id` (pre-VA name) for downgrades and mixed-version teams.
    #[serde(rename = "project_id", alias = "vault_id")]
    pub vault_id: String,
    pub ns: String,
    pub name: String,
    /// Always `false` (sealed vaults are not supported); `projects.json`
    /// carries the field.
    pub sealed: bool,
    #[serde(default)]
    pub roots: Vec<String>,
}

/// `<data_dir>/cloud/projects.json`: stable identity → resolved vault.
///
/// A vault id is only valid on the Cloud and for the account (org) that
/// resolved it (rc3-81; rc4-2/rc4-6 for an account switch on the same
/// Cloud): the active records (`projects`) belong to the scope in `origin`
/// ([`vault_scope`]: `<origin>#org=<org_id>`). A connect to another Cloud
/// or account drops them (3.12.8 account scope: the enrollment removes the
/// local Cloud data of another server or team, and [`VaultMap::use_scope`]
/// applies the same rule to a map that is still there), so a connect
/// elsewhere never shows or syncs them; a connect back resolves anew.
///
/// Who sets `origin`:
/// - enrollment switches the map to the new Cloud and account
///   ([`VaultMap::use_scope`]);
/// - every write while connected stamps the map with the connected Cloud
///   and account and refuses a map of another one ([`VaultMap::claim`]);
/// - a disconnect that keeps the local data stamps the map with the Cloud
///   and account it leaves, before their record is forgotten.
///
/// Readers that know the connected Cloud and account use
/// [`VaultMap::for_scope`], which shows no records of another one (fail
/// closed).
///
/// A stamp without an account (only dev builds of rc3-81 wrote one) matches
/// no account (fail closed) until an enrollment resolves it to the account
/// the machine was enrolled with on that Cloud ([`VaultMap::use_scope`]).
///
/// Downgrade: an older engine reads the file but drops `origin` when it
/// saves it. The file is then unstamped again (the legacy rule of
/// [`VaultMap::use_scope`] applies) until the next write of a newer engine
/// stamps it with the connected scope. The `parked` records that rc3-81
/// builds wrote are ignored when read and dropped at the next save.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct VaultMap {
    /// On disk as `projects` (pre-VA name) for downgrades and mixed-version teams.
    #[serde(default, rename = "projects", alias = "vaults")]
    pub vaults: BTreeMap<String, VaultRecord>,
    /// The scope (Cloud and account, [`vault_scope`]) `vaults` was resolved
    /// in; the Cloud origin alone in a file stamped before accounts were
    /// recorded; `None` in a file written before origins were recorded (see
    /// [`VaultMap::use_scope`]).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub origin: Option<String>,
}

impl VaultMap {
    pub fn load(data_dir: &Path) -> Self {
        std::fs::read(data_dir.join(VAULTS_FILE))
            .ok()
            .and_then(|bytes| serde_json::from_slice(&bytes).ok())
            .unwrap_or_default()
    }

    /// The vault of the local checkout `root`: the one recorded for it, else
    /// (a linked git worktree never synced itself) the one of its main
    /// checkout, which is the same repository.
    pub fn for_root(&self, root: &str) -> Option<&VaultRecord> {
        let find = |root: &str| {
            self.vaults.values().find(|record| {
                record
                    .roots
                    .iter()
                    .any(|known| crate::core::pathutil::same_project(known, root))
            })
        };
        find(root).or_else(|| {
            let main = crate::core::git_worktree::main_worktree_root(Path::new(root))?;
            find(&main.to_string_lossy())
        })
    }

    pub fn save(&self, data_dir: &Path) -> std::io::Result<()> {
        let bytes = serde_json::to_vec_pretty(self).map_err(std::io::Error::other)?;
        crate::core::secure_fs::write_private(data_dir, VAULTS_FILE, &bytes)
    }

    /// Record a resolve answer for `stable`, remembering `root`.
    pub fn record(&mut self, stable: &str, vault: &VaultV1, root: &Path) {
        let root = root.to_string_lossy().into_owned();
        let entry = self
            .vaults
            .entry(stable.to_string())
            .or_insert_with(|| VaultRecord {
                vault_id: vault.vault_id.clone(),
                ns: vault.vault.ns.clone(),
                name: vault.vault.name.clone(),
                sealed: false,
                roots: Vec::new(),
            });
        entry.vault_id.clone_from(&vault.vault_id);
        entry.ns.clone_from(&vault.vault.ns);
        entry.name.clone_from(&vault.vault.name);
        entry.sealed = false;
        if !entry.roots.contains(&root) {
            entry.roots.push(root);
        }
    }

    /// Stamp the map with `scope` ([`vault_scope`]), the Cloud and account
    /// this machine is connected to while it writes: an unstamped map gets
    /// it. `false` when the map belongs to another Cloud or account: the
    /// caller records nothing (enrollment is the one switch).
    pub fn claim(&mut self, scope: &str) -> bool {
        match &self.origin {
            None => {
                self.origin = Some(stored_scope(scope));
                true
            }
            Some(own) => same_scope(own, scope),
        }
    }

    /// This map as the Cloud and account at `connected` ([`vault_scope`])
    /// see it: without any records when they were resolved on another Cloud
    /// or for another account (fail closed). A view for reading; never saved.
    #[must_use]
    pub fn for_scope(mut self, connected: &str) -> Self {
        if !self.belongs_to(connected) {
            self.vaults.clear();
        }
        self
    }

    /// [`Self::claim`] for the scope this machine was enrolled with until
    /// now (at a disconnect): a stamp with that Cloud alone (dev builds of
    /// rc3-81) was written for this account and gets it added.
    pub fn claim_enrolled(&mut self, scope: &str) -> bool {
        if let Some(own) = self.origin.as_deref()
            && split_scope(own).1.is_none()
            && same_origin(split_scope(own).0, split_scope(scope).0)
        {
            self.origin = Some(stored_scope(scope));
            return true;
        }
        self.claim(scope)
    }

    /// Whether the active records may be used in `scope` ([`vault_scope`]):
    /// the map is unstamped (written before scopes were recorded; every
    /// enrollment stamps it, so it belongs to the scope this machine is
    /// still connected to) or stamped with exactly that Cloud and account.
    pub fn belongs_to(&self, scope: &str) -> bool {
        self.origin
            .as_deref()
            .is_none_or(|own| same_scope(own, scope))
    }

    /// Make the map belong to the Cloud and account at `scope`
    /// ([`vault_scope`]): the active records of another scope are dropped
    /// (3.12.8 account scope; nothing is kept for a connect back). A file
    /// without an origin (written before origins were recorded) counts as
    /// resolved on `legacy_scope`, its account included (fail closed:
    /// another account on the same Cloud is another scope). A file stamped
    /// with a Cloud alone (only dev builds of rc3-81 wrote one) counts as
    /// resolved for the account of `legacy_scope` when that names the same
    /// Cloud, else as a scope of its own that no account matches. Returns
    /// whether anything changed.
    pub fn use_scope(&mut self, scope: &str, legacy_scope: &str) -> bool {
        let current = match self.origin.as_deref() {
            None => stored_scope(legacy_scope),
            Some(own)
                if split_scope(own).1.is_none()
                    && same_origin(split_scope(own).0, split_scope(legacy_scope).0) =>
            {
                stored_scope(legacy_scope)
            }
            Some(own) => stored_scope(own),
        };
        if same_scope(&current, scope) {
            let changed = self.origin.as_deref() != Some(current.as_str());
            self.origin = Some(current);
            return changed;
        }
        self.vaults.clear();
        self.origin = Some(stored_scope(scope));
        true
    }

    /// Forget the local checkout `root`: it leaves the record that lists it
    /// (a record without roots left is dropped). Returns that record, as it
    /// was before.
    pub fn forget_root(&mut self, root: &str) -> Option<VaultRecord> {
        let found = self
            .vaults
            .values()
            .find(|record| {
                record
                    .roots
                    .iter()
                    .any(|known| crate::core::pathutil::same_project(known, root))
            })
            .cloned();
        self.vaults.retain(|_, record| {
            let before = record.roots.len();
            record
                .roots
                .retain(|known| !crate::core::pathutil::same_project(known, root));
            record.roots.len() == before || !record.roots.is_empty()
        });
        found
    }
}

/// Separates the account from the Cloud origin in a scope.
const ORG_MARK: &str = "#org=";

/// The scope a vault id is valid in (rc3-81, rc4-2, rc4-6): the Cloud at
/// `origin` and the account (org) `org_id` on it, as one string so
/// `projects.json` keeps its shape (the `origin` field):
/// `<origin>#org=<org_id>`, the origin normalized like `stored_origin`.
/// An empty `org_id` gives the origin alone.
pub fn vault_scope(origin: &str, org_id: &str) -> String {
    let origin = stored_origin(origin);
    match org_id.trim() {
        "" => origin,
        org => format!("{origin}{ORG_MARK}{org}"),
    }
}

/// `(origin, org)` of a scope; a scope without an account (an origin as
/// older code stamped it) has `None`.
fn split_scope(scope: &str) -> (&str, Option<&str>) {
    match scope.split_once(ORG_MARK) {
        Some((origin, org)) if !org.trim().is_empty() => (origin, Some(org.trim())),
        Some((origin, _)) => (origin, None),
        None => (scope, None),
    }
}

/// `scope` as the map stores it (see [`vault_scope`]).
fn stored_scope(scope: &str) -> String {
    let (origin, org) = split_scope(scope);
    vault_scope(origin, org.unwrap_or(""))
}

/// Whether `a` and `b` are the same scope: the same Cloud (after
/// `stored_origin`) and the same account (fail closed, rc3-81 bd 39791
/// S2: a scope without an account matches only another without one).
fn same_scope(a: &str, b: &str) -> bool {
    let ((a_origin, a_org), (b_origin, b_org)) = (split_scope(a), split_scope(b));
    same_origin(a_origin, b_origin) && a_org == b_org
}

/// `origin` as the map stores it: trimmed, without a trailing slash or the
/// default https port, lower case. Origins come normalized from the
/// connect path; this keeps a hand-edited or older spelling comparable.
fn stored_origin(origin: &str) -> String {
    let origin = origin.trim().trim_end_matches('/').to_ascii_lowercase();
    match origin.strip_suffix(":443") {
        Some(bare) if bare.starts_with("https://") => bare.to_string(),
        _ => origin,
    }
}

/// Whether `a` and `b` name the same Cloud, after `stored_origin`.
fn same_origin(a: &str, b: &str) -> bool {
    lean_ctx_protocol::cloud::same_cloud_origin(&stored_origin(a), &stored_origin(b))
}