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 =
56        |e: &dyn std::fmt::Display| format!("the Cloud link of this project cannot be read: {e}");
57    let store = crate::CloudStore::open().map_err(|e| unavailable(&e))?;
58    let path = store
59        .data_dir()
60        .join(lean_ctx::core::vault_map::VAULTS_FILE);
61    let map: crate::vault::VaultMap = match std::fs::read(&path) {
62        Ok(bytes) => serde_json::from_slice(&bytes).map_err(|e| unavailable(&e))?,
63        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
64        Err(e) => return Err(unavailable(&e)),
65    };
66    Ok(map.for_root(root).is_some())
67}
68
69/// RFC 3339 UTC now, whole seconds.
70pub fn now() -> String {
71    lean_ctx_time::UtcDateTime::now().to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true)
72}
73
74/// The journal and the pages as of `upto` (now when `None`), with the
75/// anchors rechecked against the checkout. The recheck is applied to the
76/// view only, never stored: a read writes nothing.
77pub fn read(
78    root: &str,
79    store: &LocalDocs,
80    upto: Option<u64>,
81) -> Result<(Vec<Entry>, DocSpace), CloudError> {
82    let entries = store.entries()?;
83    let space = local::space_of(&entries, upto, &[]);
84    let anchored = space.pages.values().any(|p| {
85        p.page
86            .fields
87            .get("anchors")
88            .and_then(Value::as_array)
89            .is_some_and(|a| !a.is_empty())
90    });
91    if !anchored || upto.is_some() {
92        return Ok((entries, space));
93    }
94    let extra: Vec<EventSpec> = crate::docs::recheck(root, &space);
95    if extra.is_empty() {
96        return Ok((entries, space));
97    }
98    let checked = local::space_of(&entries, None, &extra);
99    Ok((entries, checked))
100}
101
102/// Where a local page went when the checkout was linked.
103#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
104pub struct SharedTo {
105    /// `ns/name`.
106    pub vault: String,
107    pub page_id: String,
108    pub at: String,
109}
110
111/// A local page, for a link that brings pages into the vault.
112#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
113pub struct LocalPage {
114    /// The local page id (`n_…`).
115    pub id: String,
116    pub slug: String,
117    pub title: String,
118    /// The page markdown, `# Title` first, links as `/slug`.
119    pub body: String,
120    pub kind: String,
121    pub status: String,
122    pub updated: Option<String>,
123    pub updated_by: Option<Author>,
124    pub shared: Option<SharedTo>,
125}
126
127/// Where page `p` was brought on a link, if it was.
128pub fn shared_of(p: &lean_ctx_doc::replica::PageView) -> Option<SharedTo> {
129    let s = p.page.fields.get("shared")?;
130    Some(SharedTo {
131        vault: s.get("vault")?.as_str()?.to_owned(),
132        page_id: s.get("page_id")?.as_str()?.to_owned(),
133        at: s.get("at")?.as_str()?.to_owned(),
134    })
135}
136
137/// The live local pages of `root`, by slug.
138pub fn pages(root: &str) -> Result<Vec<LocalPage>, CloudError> {
139    let store = store(root)?;
140    let (entries, space) = read(root, &store, None)?;
141    let last = local::last_revisions(&entries);
142    let slug_of = |id: &str| space.pages.get(id).map(|p| p.slug().to_owned());
143    let mut out: Vec<LocalPage> = space
144        .pages
145        .values()
146        .map(|p| {
147            let rev: Option<&Revision> = last.get(&p.page.id);
148            LocalPage {
149                id: p.page.id.clone(),
150                slug: p.slug().to_owned(),
151                title: p.title().to_owned(),
152                body: lean_ctx_doc::links::to_slugs(&p.markdown(), slug_of),
153                kind: p.page.str("type").unwrap_or("reference").to_owned(),
154                status: p.page.str("status").unwrap_or("draft").to_owned(),
155                updated: rev.map(|r| r.at.clone()),
156                updated_by: rev.map(|r| r.author.clone()),
157                shared: shared_of(p),
158            }
159        })
160        .collect();
161    out.sort_by(|a, b| a.slug.cmp(&b.slug));
162    Ok(out)
163}
164
165/// Records that local page `local_id` now lives in `vault` as
166/// `vault_page_id` (one journaled revision, action `share`), so a second
167/// link run skips it.
168pub fn mark_shared(
169    root: &str,
170    local_id: &str,
171    vault: &str,
172    vault_page_id: &str,
173    author: &Author,
174) -> Result<(), CloudError> {
175    let store = store(root)?;
176    let at = now();
177    store.commit::<CloudError>(author, &at, "share", |space| {
178        let page = space
179            .pages
180            .get(local_id)
181            .ok_or_else(|| CloudError::Config(format!("no local page {local_id}")))?;
182        Ok(vec![doc_field_set(
183            local_id,
184            "shared",
185            json!({ "vault": vault, "page_id": vault_page_id, "at": at }),
186            &page.page.head,
187        )])
188    })?;
189    Ok(())
190}