Skip to main content

lean_ctx_server/tools/
ctx_doc.rs

1// SPDX-License-Identifier: Apache-2.0
2//! `ctx_doc`: the project's documentation in its Cloud vault (C0 2.2 docs).
3//!
4//! Reads come from the local replica, so they work offline and cost no
5//! request. Writes are queued as signed events in the replica and sent in
6//! the background ([`lean_ctx_cloud::background`]); a write never waits
7//! for Cloud. Links are `/slug#heading` for agents and `cloud:<id>` on the
8//! wire ([`lean_ctx_doc::links`]).
9
10use lean_ctx_doc::links;
11use lean_ctx_doc::model::{Page, PageStatus};
12use lean_ctx_doc::replica::{DocSpace, PageView};
13use lean_ctx_doc::sections;
14use lean_ctx_doc::state::DocState;
15use lean_ctx_doc::write;
16use lean_ctx_doc::write::field_set as doc_field_set;
17
18use lean_ctx_cloud::CloudError;
19use lean_ctx_cloud::docs;
20use lean_ctx_cloud::knowledge::screening::Screen;
21use lean_ctx_cloud::local_docs;
22use lean_ctx_doc::local::{self, Author};
23
24/// The arguments of one call.
25#[derive(Debug, Default)]
26pub struct Args<'a> {
27    pub action: &'a str,
28    pub slug: Option<&'a str>,
29    pub section: Option<&'a str>,
30    pub query: Option<&'a str>,
31    pub content: Option<&'a str>,
32    pub find: Option<&'a str>,
33    pub replace: Option<&'a str>,
34    pub kind: Option<&'a str>,
35    pub status: Option<&'a str>,
36    pub outline: bool,
37    /// write: the code the page derives from (`file:`, `dir:`, `glob:`, `shape:`).
38    pub anchors: &'a [String],
39    /// move: the new slug.
40    pub to: Option<&'a str>,
41    /// show/list (local docs): the pages as of this revision.
42    pub rev: Option<u64>,
43    /// The author of a local revision (default: an unnamed agent).
44    pub author: Option<Author>,
45}
46
47const USAGE: &str = "ctx_doc actions: list [slug=prefix] | show slug [section=heading-slug] [outline=true] | \
48search query | status | write slug content (whole page, `# Title` first) [type] [status=draft|canonical] | \
49edit slug find replace | note slug content | confirm slug (re-pin after checking the page) | \
50local docs (no vault linked) also: history slug | show slug rev=N | move slug to=new-slug | delete slug";
51
52const LOCAL_ONLY: [&str; 3] = ["history", "move", "delete"];
53
54/// Runs one call for the checkout at `root`.
55pub fn handle(root: &str, args: &Args<'_>) -> String {
56    let earlier = lean_ctx_cloud::background::earlier("ctx_doc");
57    match run(root, args) {
58        Ok(out) => earlier.present(out),
59        Err(e) => format!("ctx_doc: {e}"),
60    }
61}
62
63fn run(root: &str, args: &Args<'_>) -> Result<String, CloudError> {
64    // A link that cannot be read refuses: a linked checkout never writes local.
65    if !local_docs::is_linked(root).map_err(CloudError::Local)? {
66        return run_local(root, args);
67    }
68    if LOCAL_ONLY.contains(&args.action) || args.rev.is_some() {
69        return Err(CloudError::Config(format!(
70            "action={} and rev apply to local docs; this checkout's docs are in its vault",
71            args.action
72        )));
73    }
74    match args.action {
75        "list" | "show" | "search" | "status" => {
76            docs::with_vault(root, |v| Ok(read(&docs::space(v.target.replica)?, args)))
77        }
78        "write" | "edit" | "note" | "confirm" => {
79            docs::require_docs_protocol(&lean_ctx_cloud::CloudStore::open()?)?;
80            let queued = docs::with_vault(root, |v| {
81                let space = docs::space(v.target.replica)?;
82                let pinned = pins(root, &space, args)?;
83                let specs = plan_write(&space, args, &pinned)?;
84                let n = specs.len();
85                if n == 0 {
86                    return Ok(format!("{}: nothing changed", v.label));
87                }
88                let now = lean_ctx_time::UtcDateTime::now()
89                    .timestamp_millis()
90                    .unsigned_abs();
91                let mut screen = Screen::for_installation();
92                docs::queue_specs(&v.target, specs, &mut screen, now)?;
93                Ok(format!(
94                    "{}: queued {n} event(s); they are sent in the background",
95                    v.label
96                ))
97            })?;
98            let root = root.to_owned();
99            lean_ctx_cloud::background::submit_once(
100                "ctx_doc",
101                &format!("push:{root}"),
102                move || {
103                    Some(match docs::push_queued(&root) {
104                        Ok(line) => line,
105                        Err(e) if e.is_transient() => format!(
106                            "docs: not sent yet ({e}); the next `lean-ctx cloud sync` sends them"
107                        ),
108                        Err(e) => format!("docs: push failed ({e})"),
109                    })
110                },
111            );
112            Ok(queued)
113        }
114        _ => Err(CloudError::Config(USAGE.into())),
115    }
116}
117
118/// The docs of a checkout no vault is linked to: the project's local store
119/// on this Instance ([`local_docs`]). A write is one revision, saved at once.
120fn run_local(root: &str, args: &Args<'_>) -> Result<String, CloudError> {
121    let store = local_docs::store(root)?;
122    match args.action {
123        "list" | "show" | "search" | "status" => {
124            let (_, space) = local_docs::read(root, &store, args.rev)?;
125            Ok(read(&space, args))
126        }
127        "history" => history_text(&store.entries()?, args.slug),
128        "write" | "edit" | "note" | "confirm" | "move" | "delete" => {
129            let done = commit_local(root, args)?;
130            Ok(match done.rev {
131                None => "local docs: nothing changed".to_owned(),
132                Some(rev) => format!(
133                    "local docs: saved revision {rev} ({} event(s)); no vault is linked, so the page stays on this Instance",
134                    done.events
135                ),
136            })
137        }
138        _ => Err(CloudError::Config(USAGE.into())),
139    }
140}
141
142/// One local write action (`write`, `edit`, `note`, `confirm`, `move`,
143/// `delete`) as one revision of `root`'s local store, planned under its lock.
144pub fn commit_local(root: &str, args: &Args<'_>) -> Result<local::Committed, CloudError> {
145    if !WRITES.contains(&args.action) {
146        return Err(CloudError::Config(USAGE.into()));
147    }
148    if args.rev.is_some() {
149        return Err(CloudError::Config("rev is for reads".into()));
150    }
151    let author = args
152        .author
153        .clone()
154        .unwrap_or_else(|| Author::agent("agent"));
155    local_docs::store(root)?.commit::<CloudError>(
156        &author,
157        &local_docs::now(),
158        args.action,
159        |space| {
160            let pinned = pins(root, space, args)?;
161            plan_write(space, args, &pinned)
162        },
163    )
164}
165
166const WRITES: [&str; 6] = ["write", "edit", "note", "confirm", "move", "delete"];
167
168/// The revisions of the local page `slug` (also a moved or deleted one).
169fn history_text(entries: &[local::Entry], slug: Option<&str>) -> Result<String, CloudError> {
170    let slug = slug.ok_or_else(|| CloudError::Config("slug is required".into()))?;
171    let id = local::page_id_of(entries, slug)
172        .ok_or_else(|| CloudError::Config(format!("no page {slug}; try action=list")))?;
173    let revs = local::history(entries, &id);
174    let mut out = format!("/{slug}: {} revision(s)\n", revs.len());
175    for r in revs {
176        out.push_str(&format!(
177            "rev {} {} {} {} {}\n",
178            r.rev, r.at, r.author.kind, r.author.label, r.action
179        ));
180    }
181    Ok(out)
182}
183
184fn state_word(p: &PageView) -> &'static str {
185    match p.state.state {
186        DocState::Fresh => "fresh",
187        DocState::Noted => "noted",
188        DocState::Stale => "stale",
189    }
190}
191
192fn slug_of(space: &DocSpace) -> impl Fn(&str) -> Option<String> + '_ {
193    |id: &str| space.pages.get(id).map(|p| p.slug().to_owned())
194}
195
196/// The read actions, from the replica's view alone.
197pub fn read(space: &DocSpace, args: &Args<'_>) -> String {
198    match args.action {
199        "list" => list(space, args.slug.unwrap_or("")),
200        "status" => status(space),
201        "search" => search(space, args.query.unwrap_or("")),
202        _ => match args.slug.and_then(|s| space.page_by_slug(s)) {
203            Some(p) => show(space, p, args.section, args.outline),
204            None => format!(
205                "no page {}; try action=list",
206                args.slug.unwrap_or("(slug missing)")
207            ),
208        },
209    }
210}
211
212fn list(space: &DocSpace, prefix: &str) -> String {
213    let mut pages: Vec<&PageView> = space
214        .pages
215        .values()
216        .filter(|p| p.slug().starts_with(prefix))
217        .collect();
218    pages.sort_by(|a, b| a.slug().cmp(b.slug()));
219    if pages.is_empty() {
220        return "no pages".into();
221    }
222    let mut out = format!("{} page(s)\n", pages.len());
223    for p in pages {
224        let notes = p.notes.iter().filter(|n| n.open).count();
225        out.push_str(&format!("/{} — {} [{}", p.slug(), p.title(), state_word(p)));
226        if notes > 0 {
227            out.push_str(&format!(", {notes} note(s)"));
228        }
229        out.push_str("]\n");
230    }
231    out
232}
233
234fn status(space: &DocSpace) -> String {
235    let mut behind: Vec<&PageView> = space
236        .pages
237        .values()
238        .filter(|p| p.state.state != DocState::Fresh)
239        .collect();
240    behind.sort_by(|a, b| a.slug().cmp(b.slug()));
241    if behind.is_empty() {
242        return format!("{} page(s), all fresh", space.pages.len());
243    }
244    let mut out = format!(
245        "{} of {} page(s) behind their code\n",
246        behind.len(),
247        space.pages.len()
248    );
249    for p in behind {
250        out.push_str(&format!("/{} [{}]", p.slug(), state_word(p)));
251        if !p.state.uncovered.is_empty() {
252            out.push_str(&format!(" moved: {}", p.state.uncovered.join(", ")));
253        }
254        out.push('\n');
255    }
256    out
257}
258
259fn show(space: &DocSpace, p: &PageView, section: Option<&str>, outline: bool) -> String {
260    let md = links::to_slugs(&p.markdown(), slug_of(space));
261    let mut out = format!("/{} [{}]\n", p.slug(), state_word(p));
262    if !p.state.uncovered.is_empty() {
263        out.push_str(&format!(
264            "stale: {} moved since the page was written\n",
265            p.state.uncovered.join(", ")
266        ));
267    }
268    for n in p.notes.iter().filter(|n| n.open) {
269        out.push_str(&format!("note: {}\n", n.body));
270    }
271    if outline {
272        for h in links::headings(&md) {
273            out.push_str(&format!(
274                "{} {}  (#{})\n",
275                "#".repeat(h.level),
276                h.text,
277                h.slug
278            ));
279        }
280        return out;
281    }
282    match section {
283        Some(want) => match links::section_of(&md, want) {
284            Some(text) => out.push_str(text),
285            None => out.push_str(&format!("no section #{want}; try outline=true\n")),
286        },
287        None => out.push_str(&md),
288    }
289    out
290}
291
292fn search(space: &DocSpace, query: &str) -> String {
293    let words: Vec<String> = query.split_whitespace().map(str::to_lowercase).collect();
294    if words.is_empty() {
295        return "search needs a query".into();
296    }
297    let mut hits: Vec<(usize, &PageView)> = space
298        .pages
299        .values()
300        .filter_map(|p| {
301            let text = format!("{}\n{}", p.title(), p.markdown()).to_lowercase();
302            let score: usize = words.iter().map(|w| text.matches(w.as_str()).count()).sum();
303            (words.iter().all(|w| text.contains(w.as_str())) && score > 0).then_some((score, p))
304        })
305        .collect();
306    hits.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.slug().cmp(b.1.slug())));
307    if hits.is_empty() {
308        return format!("no page mentions {query}");
309    }
310    let mut out = String::new();
311    for (score, p) in hits.into_iter().take(20) {
312        out.push_str(&format!("/{} — {} ({score})\n", p.slug(), p.title()));
313    }
314    out
315}
316
317pub use lean_ctx_doc::model::valid_slug;
318
319/// The anchors a write pins: the `anchors` argument for `write`, the page's
320/// own anchors re-pinned for `confirm`; none otherwise.
321fn pins(
322    root: &str,
323    space: &DocSpace,
324    args: &Args<'_>,
325) -> Result<Vec<lean_ctx_doc::Anchor>, CloudError> {
326    let wanted: Vec<lean_ctx_doc::Anchor> = match args.action {
327        "write" if !args.anchors.is_empty() => Vec::new(),
328        "confirm" => match args.slug.and_then(|s| space.page_by_slug(s)) {
329            Some(p) => docs::page_anchors(p),
330            None => return Ok(Vec::new()),
331        },
332        _ => return Ok(Vec::new()),
333    };
334    let files = docs::tracked_files(root)
335        .ok_or_else(|| CloudError::Config("anchors need a git checkout".into()))?;
336    if args.action == "write" {
337        return args
338            .anchors
339            .iter()
340            .map(|r| docs::pin(root, &files, r))
341            .collect();
342    }
343    // confirm: the same refs and roles at today's digests; a gone target
344    // cannot be confirmed (edit the page's anchors instead).
345    wanted
346        .into_iter()
347        .map(|mut a| {
348            a.digest = docs::digest_now(root, &files, &a).ok_or_else(|| {
349                CloudError::Config(format!(
350                    "{} is gone: write the page with its new anchors",
351                    a.reference()
352                ))
353            })?;
354            a.commit = docs::head_commit(root);
355            Ok(a)
356        })
357        .collect()
358}
359
360/// The events of a write action against the current `space`; `pinned` are
361/// the anchors `pins` resolved against the checkout.
362pub fn plan_write(
363    space: &DocSpace,
364    args: &Args<'_>,
365    pinned: &[lean_ctx_doc::Anchor],
366) -> Result<Vec<write::EventSpec>, CloudError> {
367    let refuse = |m: &str| CloudError::Config(m.to_owned());
368    let slug = args.slug.ok_or_else(|| refuse("slug is required"))?;
369    let id_of = |s: &str| space.by_slug.get(s).cloned();
370    let mut new_id = docs::new_id;
371    let verified_at = lean_ctx_time::UtcDateTime::now()
372        .timestamp_millis()
373        .unsigned_abs();
374    match args.action {
375        "move" => {
376            let page = space
377                .page_by_slug(slug)
378                .ok_or_else(|| refuse("no such page"))?;
379            let to = args.to.ok_or_else(|| refuse("move needs to=<new slug>"))?;
380            if !valid_slug(to) {
381                return Err(refuse(
382                    "slug must be lowercase words joined by - and /, at most 8 segments",
383                ));
384            }
385            if to == slug {
386                return Ok(Vec::new());
387            }
388            if space.by_slug.contains_key(to) {
389                return Err(refuse(&format!("/{to} is taken")));
390            }
391            // A doc page's field event (lean-ctx-doc), not a C0 fact's
392            // `maintain::field_set` that the C0 field guard checks.
393            Ok(vec![doc_field_set(
394                &page.page.id,
395                "slug",
396                serde_json::Value::from(to),
397                &page.page.head,
398            )])
399        }
400        "delete" => {
401            let page = space
402                .page_by_slug(slug)
403                .ok_or_else(|| refuse("no such page"))?;
404            Ok(vec![write::retract(&page.page.id, "page deleted")])
405        }
406        "confirm" => {
407            let page = space
408                .page_by_slug(slug)
409                .ok_or_else(|| refuse("no such page"))?;
410            if pinned.is_empty() {
411                return Err(refuse("the page has no anchors to confirm"));
412            }
413            Ok(write::confirm(page, pinned, verified_at))
414        }
415        "note" => {
416            let page = space
417                .page_by_slug(slug)
418                .ok_or_else(|| refuse("no such page"))?;
419            let body = args.content.ok_or_else(|| refuse("content is required"))?;
420            Ok(write::add_note(&page.page.id, body, &[], &mut new_id))
421        }
422        "edit" => {
423            let page = space
424                .page_by_slug(slug)
425                .ok_or_else(|| refuse("no such page"))?;
426            let (find, replace) = match (args.find, args.replace) {
427                (Some(f), Some(r)) if !f.is_empty() => (f, r),
428                _ => return Err(refuse("edit needs find and replace")),
429            };
430            let current = links::to_slugs(&page.markdown(), slug_of(space));
431            match current.matches(find).count() {
432                1 => {}
433                0 => {
434                    return Err(refuse(
435                        "find matches nothing: the page moved on, re-read it",
436                    ));
437                }
438                n => {
439                    return Err(refuse(&format!(
440                        "find matches {n} times: extend it until it is unique"
441                    )));
442                }
443            }
444            revise(
445                space,
446                page,
447                &current.replacen(find, replace, 1),
448                &mut new_id,
449            )
450        }
451        _ => {
452            let content = args.content.ok_or_else(|| refuse("content is required"))?;
453            if let Some(page) = space.page_by_slug(slug) {
454                let mut specs = revise(space, page, content, &mut new_id)?;
455                if !pinned.is_empty() {
456                    specs.extend(write::confirm(page, pinned, verified_at));
457                }
458                return Ok(specs);
459            }
460            if !valid_slug(slug) {
461                return Err(refuse(
462                    "slug must be lowercase words joined by - and /, at most 8 segments",
463                ));
464            }
465            let (stored, _dangling) = links::to_storage(content, id_of);
466            let (title, sections) = sections::split(&stored);
467            if title.is_empty() {
468                return Err(refuse("a new page starts with its `# Title` line"));
469            }
470            let status = match args.status {
471                Some("canonical") => PageStatus::Canonical,
472                _ => PageStatus::Draft,
473            };
474            let page = Page {
475                slug: slug.to_owned(),
476                title,
477                kind: args.kind.unwrap_or("reference").to_owned(),
478                status,
479                sections,
480                anchors: pinned.to_vec(),
481                notes: Vec::new(),
482            };
483            let (specs, _) = write::create_page(&page, &link_targets(&stored), &mut new_id);
484            Ok(specs)
485        }
486    }
487}
488
489fn link_targets(stored: &str) -> Vec<String> {
490    let mut out: Vec<String> = links::targets(stored)
491        .into_iter()
492        .filter_map(|t| match links::classify(t) {
493            links::Target::Node { id, .. } => Some(id.to_owned()),
494            _ => None,
495        })
496        .collect();
497    out.sort();
498    out.dedup();
499    out
500}
501
502fn revise(
503    space: &DocSpace,
504    page: &PageView,
505    markdown: &str,
506    new_id: write::NewId<'_>,
507) -> Result<Vec<write::EventSpec>, CloudError> {
508    let (stored, _) = links::to_storage(markdown, |s| space.by_slug.get(s).cloned());
509    let now = space.links.get(&page.page.id).cloned().unwrap_or_default();
510    Ok(write::revise_page(
511        page,
512        &stored,
513        &now,
514        &link_targets(&stored),
515        new_id,
516    ))
517}
518
519#[cfg(test)]
520#[path = "ctx_doc_tests.rs"]
521mod tests;