Skip to main content

lean_ctx_cloud/
local_docs.rs

1// SPDX-License-Identifier: Apache-2.0
2//! A project's docs on this Instance alone ([`lean_ctx_doc::local`]): the
3//! store of a checkout that no vault is linked to. Keyed like knowledge
4//! (`<data dir>/docs/<hash_project_root>`), so the CLI, the MCP tool and
5//! Cloud Desktop find the same pages. Nothing here contacts Cloud.
6//!
7//! A linked checkout keeps reading its vault; [`pages`] and [`mark_shared`]
8//! let the link bring local pages into the vault once.
9
10use std::path::Path;
11
12use lean_ctx_doc::local::{self, Author, Entry, LocalDocs, Revision};
13use lean_ctx_doc::replica::DocSpace;
14// A doc page's field event, not a C0 fact's `maintain::field_set`: named
15// apart so the C0 field guard (review::maintain tests) tells them apart.
16use lean_ctx_doc::write::{EventSpec, field_set as doc_field_set};
17use serde::Serialize;
18use serde_json::{Value, json};
19
20use crate::CloudError;
21
22fn local_err(e: impl std::fmt::Display) -> CloudError {
23    CloudError::Local(e.to_string())
24}
25
26impl From<local::LocalError> for CloudError {
27    fn from(e: local::LocalError) -> Self {
28        local_err(e)
29    }
30}
31
32/// The store of the project at `root`; creates nothing until a write.
33pub fn store(root: &str) -> Result<LocalDocs, CloudError> {
34    if lean_ctx::core::pathutil::is_broad_or_unsafe_root(Path::new(root)) {
35        return Err(CloudError::Config(format!("{root} is not a project")));
36    }
37    let data = lean_ctx::core::data_dir::lean_ctx_data_dir().map_err(CloudError::Local)?;
38    Ok(LocalDocs::at(data.join("docs").join(
39        lean_ctx::core::project_hash::hash_project_root(root),
40    )))
41}
42
43/// Whether `root` is linked to a vault on this machine (its docs are the
44/// vault's). Opens nothing beyond the Cloud config; creates nothing.
45///
46/// The vault map alone decides, as for local tasks: a Cloud state or a
47/// vault map that cannot be read is an error (its reason; callers answer
48/// `unavailable` and refuse), never "unlinked", so a linked checkout's
49/// writes never go local silently. Only a vault map that does not exist
50/// yet means no checkout is linked. Signed out, a linked checkout stays
51/// linked: its doc reads and writes go to the vault and are refused
52/// (`not_connected`) until the machine signs in again; nothing is written
53/// locally for later.
54pub fn is_linked(root: &str) -> Result<bool, String> {
55    let unavailable = |e: &dyn std::fmt::Display| {
56        format!("the LeanCTX Cloud link of this project cannot be read: {e}")
57    };
58    let store = crate::CloudStore::open().map_err(|e| unavailable(&e))?;
59    let path = store
60        .data_dir()
61        .join(lean_ctx::core::vault_map::VAULTS_FILE);
62    let map: crate::vault::VaultMap = match std::fs::read(&path) {
63        Ok(bytes) => serde_json::from_slice(&bytes).map_err(|e| unavailable(&e))?,
64        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
65        Err(e) => return Err(unavailable(&e)),
66    };
67    Ok(map.for_root(root).is_some())
68}
69
70/// RFC 3339 UTC now, whole seconds.
71pub fn now() -> String {
72    lean_ctx_time::UtcDateTime::now().to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true)
73}
74
75/// The journal and the pages as of `upto` (now when `None`), with the
76/// anchors rechecked against the checkout. The recheck is applied to the
77/// view only, never stored: a read writes nothing.
78pub fn read(
79    root: &str,
80    store: &LocalDocs,
81    upto: Option<u64>,
82) -> Result<(Vec<Entry>, DocSpace), CloudError> {
83    let entries = store.entries()?;
84    let space = local::space_of(&entries, upto, &[]);
85    let anchored = space.pages.values().any(|p| {
86        p.page
87            .fields
88            .get("anchors")
89            .and_then(Value::as_array)
90            .is_some_and(|a| !a.is_empty())
91    });
92    if !anchored || upto.is_some() {
93        return Ok((entries, space));
94    }
95    let extra: Vec<EventSpec> = crate::docs::recheck(root, &space);
96    if extra.is_empty() {
97        return Ok((entries, space));
98    }
99    let checked = local::space_of(&entries, None, &extra);
100    Ok((entries, checked))
101}
102
103/// Where a local page went when the checkout was linked.
104#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
105pub struct SharedTo {
106    /// `ns/name`.
107    pub vault: String,
108    pub page_id: String,
109    pub at: String,
110}
111
112/// A local page, for a link that brings pages into the vault.
113#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
114pub struct LocalPage {
115    /// The local page id (`n_…`).
116    pub id: String,
117    pub slug: String,
118    pub title: String,
119    /// The page markdown, `# Title` first, links as `/slug`.
120    pub body: String,
121    pub kind: String,
122    pub status: String,
123    pub updated: Option<String>,
124    pub updated_by: Option<Author>,
125    pub shared: Option<SharedTo>,
126}
127
128/// Where page `p` was brought on a link, if it was.
129pub fn shared_of(p: &lean_ctx_doc::replica::PageView) -> Option<SharedTo> {
130    let s = p.page.fields.get("shared")?;
131    Some(SharedTo {
132        vault: s.get("vault")?.as_str()?.to_owned(),
133        page_id: s.get("page_id")?.as_str()?.to_owned(),
134        at: s.get("at")?.as_str()?.to_owned(),
135    })
136}
137
138/// The live local pages of `root`, by slug.
139pub fn pages(root: &str) -> Result<Vec<LocalPage>, CloudError> {
140    let store = store(root)?;
141    let (entries, space) = read(root, &store, None)?;
142    let last = local::last_revisions(&entries);
143    let slug_of = |id: &str| space.pages.get(id).map(|p| p.slug().to_owned());
144    let mut out: Vec<LocalPage> = space
145        .pages
146        .values()
147        .map(|p| {
148            let rev: Option<&Revision> = last.get(&p.page.id);
149            LocalPage {
150                id: p.page.id.clone(),
151                slug: p.slug().to_owned(),
152                title: p.title().to_owned(),
153                body: lean_ctx_doc::links::to_slugs(&p.markdown(), slug_of),
154                kind: p.page.str("type").unwrap_or("reference").to_owned(),
155                status: p.page.str("status").unwrap_or("draft").to_owned(),
156                updated: rev.map(|r| r.at.clone()),
157                updated_by: rev.map(|r| r.author.clone()),
158                shared: shared_of(p),
159            }
160        })
161        .collect();
162    out.sort_by(|a, b| a.slug.cmp(&b.slug));
163    Ok(out)
164}
165
166/// Records that local page `local_id` now lives in `vault` as
167/// `vault_page_id` (one journaled revision, action `share`), so a second
168/// link run skips it.
169pub fn mark_shared(
170    root: &str,
171    local_id: &str,
172    vault: &str,
173    vault_page_id: &str,
174    author: &Author,
175) -> Result<(), CloudError> {
176    let store = store(root)?;
177    let at = now();
178    store.commit::<CloudError>(author, &at, "share", |space| {
179        let page = space
180            .pages
181            .get(local_id)
182            .ok_or_else(|| CloudError::Config(format!("no local page {local_id}")))?;
183        Ok(vec![doc_field_set(
184            local_id,
185            "shared",
186            json!({ "vault": vault, "page_id": vault_page_id, "at": at }),
187            &page.page.head,
188        )])
189    })?;
190    Ok(())
191}