Skip to main content

omgbase_surface/
read.rs

1//! Reads (`spec/surface/README.md` §2): ref resolution, whole-document reads,
2//! block hydration at a resolution, the outline wire format, and the two
3//! path-ordered list surfaces. Port of `packages/core/src/core/read/*`.
4//! Result keys follow the reference's spelling (`id`, `path`, `raw`, the row
5//! rule of §1.2; `renderedHashMatch`, …) — the fixtures are generated from it.
6
7use std::collections::{BTreeMap, HashMap};
8
9use omgbase_format::hash::hex;
10use omgbase_store::{Store, is_id_ref};
11use rusqlite::{Connection, OptionalExtension, params};
12use serde_json::{Map, Value as Json, json};
13
14use crate::context::glob_to_like;
15use crate::cursor::{decode_path_cursor, encode_cursor};
16use crate::error::Result;
17use crate::paths::{reference_path, storage_path};
18
19/// Max refs honored per `docs_read_many` / `blocks_read_many` call.
20pub const MANY_CAP: usize = 100;
21/// `docs_list` / `docs_tree` default page size.
22pub const LIST_DEFAULT_LIMIT: usize = 200;
23
24/// `ceil(JSON length / 4)`: the token estimate every budget uses.
25#[must_use]
26pub fn token_cost(v: &Json) -> usize {
27    v.to_string().chars().count().div_ceil(4)
28}
29
30// ---- documents --------------------------------------------------------------------------
31
32/// A live document's identity (`findDoc`).
33#[derive(Clone, Debug, PartialEq, Eq)]
34pub struct DocInfo {
35    pub doc_id: String,
36    pub repo_id: String,
37    /// The STORAGE form (`a/b.md`): the library's handle on a document; the
38    /// surface roots what it returns (`spec/surface` §1 "Paths").
39    pub path: String,
40    pub format: String,
41    pub current_rev: Option<String>,
42}
43
44fn doc_row(conn: &Connection, sql: &str, p: &[&dyn rusqlite::ToSql]) -> Result<Option<DocInfo>> {
45    Ok(conn
46        .query_row(sql, p, |r| {
47            Ok(DocInfo {
48                doc_id: r.get(0)?,
49                repo_id: r.get(1)?,
50                path: r.get(2)?,
51                format: r
52                    .get::<_, Option<String>>(3)?
53                    .unwrap_or_else(|| "markdown".to_owned()),
54                current_rev: r.get(4)?,
55            })
56        })
57        .optional()?)
58}
59
60/// A live doc by id.
61pub fn find_doc_by_id(conn: &Connection, doc_id: &str) -> Result<Option<DocInfo>> {
62    doc_row(
63        conn,
64        "SELECT doc_id, repo_id, path, format, current_rev FROM docs WHERE doc_id = ?1 AND deleted_commit IS NULL",
65        &[&doc_id],
66    )
67}
68
69/// A live doc by repo + path, in either form (`spec/surface` §1 "Paths").
70pub fn find_doc_by_path(conn: &Connection, repo_id: &str, path: &str) -> Result<Option<DocInfo>> {
71    doc_row(
72        conn,
73        "SELECT doc_id, repo_id, path, format, current_rev FROM docs WHERE repo_id = ?1 AND path = ?2 AND deleted_commit IS NULL",
74        &[&repo_id, &storage_path(path)],
75    )
76}
77
78/// The id-or-path dispatch every doc-ref surface routes through: a `d_` id
79/// is looked up by id only (never falling through to a path).
80pub fn find_doc_by_ref(conn: &Connection, repo_id: &str, r: &str) -> Result<Option<DocInfo>> {
81    if is_id_ref(r, "d") {
82        return find_doc_by_id(conn, r);
83    }
84    find_doc_by_path(conn, repo_id, r)
85}
86
87/// The prefix of an id-shaped ref (`^[a-z]+_[alphabet]{1,7}$`, so the
88/// fixture minter's `b_0` counts, as the reference's `isValidId` after
89/// `spec/mutate`).
90fn id_prefix(r: &str) -> Option<&str> {
91    let (p, _) = r.split_once('_')?;
92    is_id_ref(r, p).then_some(p)
93}
94
95/// `resolve_ref`'s answer.
96#[derive(Clone, Debug, PartialEq, Eq)]
97pub enum ResolvedRef {
98    Block { doc_id: String, block_id: String },
99    Document { doc_id: String },
100}
101
102impl ResolvedRef {
103    #[must_use]
104    pub fn doc_id(&self) -> &str {
105        match self {
106            ResolvedRef::Block { doc_id, .. } | ResolvedRef::Document { doc_id } => doc_id,
107        }
108    }
109}
110
111fn is_node_id(s: &str) -> bool {
112    s.len() == 14
113        && s.starts_with("n_")
114        && s[2..]
115            .bytes()
116            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
117}
118
119/// §2 `resolve_ref`: an `n_` node id → its live block, else its doc; a `b_`
120/// id → its live block; a `d_` id → the live doc; anything else → the live
121/// doc at that path; `None` when nothing matches.
122pub fn resolve_ref(conn: &Connection, repo_id: &str, r: &str) -> Result<Option<ResolvedRef>> {
123    if is_node_id(r) {
124        let node: Option<(String, Option<String>)> = conn
125            .query_row(
126                "SELECT doc_id, block_id FROM nodes WHERE node_id = ?1",
127                params![r],
128                |row| Ok((row.get(0)?, row.get(1)?)),
129            )
130            .optional()?;
131        let Some((doc_id, block_id)) = node else {
132            return Ok(None);
133        };
134        if let Some(b) = block_id {
135            let live: bool = conn
136                .prepare_cached(
137                    "SELECT 1 FROM blocks WHERE block_id = ?1 AND deleted_commit IS NULL",
138                )?
139                .exists(params![b])?;
140            if live {
141                return Ok(Some(ResolvedRef::Block {
142                    doc_id,
143                    block_id: b,
144                }));
145            }
146        }
147        return Ok(Some(ResolvedRef::Document { doc_id }));
148    }
149    match id_prefix(r) {
150        Some("b") => {
151            let doc: Option<String> = conn
152                .query_row(
153                    "SELECT doc_id FROM blocks WHERE block_id = ?1 AND deleted_commit IS NULL",
154                    params![r],
155                    |row| row.get(0),
156                )
157                .optional()?;
158            Ok(doc.map(|doc_id| ResolvedRef::Block {
159                doc_id,
160                block_id: r.to_owned(),
161            }))
162        }
163        Some("d") => {
164            Ok(find_doc_by_id(conn, r)?.map(|i| ResolvedRef::Document { doc_id: i.doc_id }))
165        }
166        _ => {
167            Ok(find_doc_by_path(conn, repo_id, r)?
168                .map(|i| ResolvedRef::Document { doc_id: i.doc_id }))
169        }
170    }
171}
172
173// ---- block forest -------------------------------------------------------------------------
174
175/// A live block with its children (the containment forest).
176#[derive(Clone, Debug, PartialEq)]
177pub struct BlockNode {
178    pub block_id: String,
179    pub doc_id: String,
180    pub parent_block: Option<String>,
181    pub ordinal: i64,
182    pub depth: i64,
183    pub kind: String,
184    pub attrs: Json,
185    pub text: String,
186    pub raw_hash_hex: String,
187    pub children: Vec<BlockNode>,
188}
189
190/// A document's live blocks as an ordered forest (`ORDER BY parent_block,
191/// order_key`; a row whose parent is not live is a root).
192pub fn load_doc_blocks(conn: &Connection, doc_id: &str) -> Result<Vec<BlockNode>> {
193    struct Row {
194        block_id: String,
195        parent_block: Option<String>,
196        ordinal: i64,
197        depth: i64,
198        kind: String,
199        attrs: String,
200        text: String,
201        raw_hash: Vec<u8>,
202    }
203    let rows: Vec<Row> = {
204        let mut stmt = conn.prepare_cached(
205            "SELECT block_id, parent_block, ordinal, depth, type, attrs, text, raw_hash
206             FROM blocks WHERE doc_id = ?1 AND deleted_commit IS NULL
207             ORDER BY parent_block, order_key",
208        )?;
209        let it = stmt.query_map(params![doc_id], |r| {
210            Ok(Row {
211                block_id: r.get(0)?,
212                parent_block: r.get(1)?,
213                ordinal: r.get(2)?,
214                depth: r.get(3)?,
215                kind: r.get(4)?,
216                attrs: r.get(5)?,
217                text: r.get(6)?,
218                raw_hash: r.get(7)?,
219            })
220        })?;
221        it.collect::<std::result::Result<Vec<_>, _>>()?
222    };
223    let ids: Vec<String> = rows.iter().map(|r| r.block_id.clone()).collect();
224    let index: HashMap<&str, usize> = ids
225        .iter()
226        .enumerate()
227        .map(|(i, id)| (id.as_str(), i))
228        .collect();
229    let mut nodes: Vec<Option<BlockNode>> = rows
230        .iter()
231        .map(|r| {
232            Some(BlockNode {
233                block_id: r.block_id.clone(),
234                doc_id: doc_id.to_owned(),
235                parent_block: r.parent_block.clone(),
236                ordinal: r.ordinal,
237                depth: r.depth,
238                kind: r.kind.clone(),
239                attrs: serde_json::from_str(&r.attrs).unwrap_or(Json::Object(Map::new())),
240                text: r.text.clone(),
241                raw_hash_hex: hex(&r.raw_hash),
242                children: Vec::new(),
243            })
244        })
245        .collect();
246    // Children in row order under their parent; roots in row order.
247    let mut children_of: Vec<Vec<usize>> = vec![Vec::new(); rows.len()];
248    let mut roots: Vec<usize> = Vec::new();
249    for (i, r) in rows.iter().enumerate() {
250        match r.parent_block.as_deref().and_then(|p| index.get(p)) {
251            Some(&p) => children_of[p].push(i),
252            None => roots.push(i),
253        }
254    }
255    fn build(i: usize, nodes: &mut [Option<BlockNode>], children_of: &[Vec<usize>]) -> BlockNode {
256        let kids: Vec<BlockNode> = children_of[i]
257            .iter()
258            .map(|&c| build(c, nodes, children_of))
259            .collect();
260        let mut n = nodes[i].take().expect("each node is built once");
261        n.children = kids;
262        n
263    }
264    Ok(roots
265        .into_iter()
266        .map(|i| build(i, &mut nodes, &children_of))
267        .collect())
268}
269
270fn find_block<'n>(roots: &'n [BlockNode], block_id: &str) -> Option<&'n BlockNode> {
271    for n in roots {
272        if n.block_id == block_id {
273            return Some(n);
274        }
275        if let Some(f) = find_block(&n.children, block_id) {
276            return Some(f);
277        }
278    }
279    None
280}
281
282/// A block's raw bytes by hex hash (`""` when unknown).
283pub fn block_raw(conn: &Connection, raw_hash_hex: &str) -> Result<String> {
284    let bytes: Vec<u8> = (0..raw_hash_hex.len() / 2)
285        .filter_map(|i| u8::from_str_radix(&raw_hash_hex[2 * i..2 * i + 2], 16).ok())
286        .collect();
287    Ok(omgbase_store::read::blob_text(conn, &bytes)?)
288}
289
290// ---- docs_read ---------------------------------------------------------------------------
291
292/// The surface's `properties` (§2, 3.0): the `spec/properties` §5 grouped
293/// shape with the computed group's keys spelled as the attributes that read
294/// them — the store writes the computed rows under `$title`/`$tags`
295/// (`spec/properties` §3.3, unchanged), the surface has no `$` names, so
296/// `properties.computed` is `{ title, tags }`. Authored groups are untouched
297/// (an authored `$x:` key keeps its sigil, as `frontmatter.$x` reads it). The
298/// reference's `surfaceProperties`.
299fn surface_properties(mut grouped: Json) -> Json {
300    if let Some(computed) = grouped.get_mut("computed").and_then(Json::as_object_mut) {
301        let rekeyed: Map<String, Json> = std::mem::take(computed)
302            .into_iter()
303            .map(|(k, v)| (k.strip_prefix('$').map_or(k.clone(), str::to_owned), v))
304            .collect();
305        *computed = rekeyed;
306    }
307    grouped
308}
309
310/// §2 `docs_read`: `{ id, path, rev, properties, raw }` (+ `ids`,
311/// `hashes`, `parents` with ids) — the document's row attributes under the
312/// surface's names (§1.2, 3.0); `None` for a missing doc.
313pub fn docs_read(store: &Store, doc_id: &str, include_ids: bool) -> Result<Option<Json>> {
314    let conn = store.conn();
315    let Some(info) = find_doc_by_id(conn, doc_id)? else {
316        return Ok(None);
317    };
318    let Some(content) = store.reconstruct(doc_id)? else {
319        return Ok(None);
320    };
321    let mut m = Map::new();
322    m.insert("id".to_owned(), json!(info.doc_id));
323    m.insert("path".to_owned(), json!(reference_path(&info.path)));
324    m.insert("rev".to_owned(), json!(info.current_rev));
325    m.insert(
326        "properties".to_owned(),
327        surface_properties(store.properties_grouped(doc_id)?),
328    );
329    m.insert("raw".to_owned(), json!(content));
330    if include_ids {
331        let mut ids = Vec::new();
332        let mut hashes = Map::new();
333        let mut parents = Map::new();
334        fn collect(
335            nodes: &[BlockNode],
336            ids: &mut Vec<Json>,
337            hashes: &mut Map<String, Json>,
338            parents: &mut Map<String, Json>,
339        ) {
340            for n in nodes {
341                ids.push(json!(n.block_id));
342                hashes.insert(n.block_id.clone(), json!(n.raw_hash_hex));
343                parents.insert(n.block_id.clone(), json!(n.parent_block));
344                collect(&n.children, ids, hashes, parents);
345            }
346        }
347        collect(
348            &load_doc_blocks(conn, doc_id)?,
349            &mut ids,
350            &mut hashes,
351            &mut parents,
352        );
353        m.insert("ids".to_owned(), Json::Array(ids));
354        m.insert("hashes".to_owned(), Json::Object(hashes));
355        m.insert("parents".to_owned(), Json::Object(parents));
356    }
357    Ok(Some(Json::Object(m)))
358}
359
360/// §2 `docs_read_many`: `{ items, errors, truncated }`.
361pub fn docs_read_many(
362    store: &Store,
363    repo_id: &str,
364    refs: &[String],
365    include_ids: bool,
366    budget_tokens: Option<usize>,
367) -> Result<Json> {
368    let capped = &refs[..refs.len().min(MANY_CAP)];
369    let mut truncated = refs.len() > MANY_CAP;
370    let mut items = Vec::new();
371    let mut errors = Vec::new();
372    let mut seen: Vec<&str> = Vec::new();
373    let mut tokens = 0usize;
374    for r in capped {
375        if seen.contains(&r.as_str()) {
376            continue;
377        }
378        seen.push(r);
379        let info = find_doc_by_ref(store.conn(), repo_id, r)?;
380        let read = match info {
381            Some(i) => docs_read(store, &i.doc_id, include_ids)?,
382            None => None,
383        };
384        let Some(read) = read else {
385            errors.push(json!({ "ref": r, "error": "doc_not_found" }));
386            continue;
387        };
388        // §2 (1.2): the budget is checked from the second item onward — a
389        // first item that alone exceeds it is still emitted (the
390        // `docs_list`/`docs_tree` floor, one list contract).
391        let cost = token_cost(&read);
392        if !items.is_empty() && budget_tokens.is_some_and(|b| tokens + cost > b) {
393            truncated = true;
394            break;
395        }
396        tokens += cost;
397        items.push(read);
398    }
399    Ok(json!({ "items": items, "errors": errors, "truncated": truncated }))
400}
401
402/// §2 `docs_read { at }` / `docs_read_at` (4.7): the document AS OF a
403/// revision — `spec/store` §6.2 reconstruct, the path as of the revision in
404/// the reference form. No `properties`: the properties table is current-state
405/// only (`spec/properties`), and recomputing the bag from the reconstructed
406/// bytes is not a one-call affair of the format layer (the inline fields come
407/// out of the ingest's node projection) — so the time-travel read carries the
408/// bytes and nothing it would have to guess at (through 4.6 `docs_read_at`
409/// returned the CURRENT bag flagged `propertiesAreCurrent: true`). `None`
410/// when `rev` is not a revision of the (live) document.
411pub fn docs_read_at(store: &Store, doc_id: &str, rev: &str) -> Result<Option<Json>> {
412    let Some(r) = store.read_at_revision(doc_id, rev)? else {
413        return Ok(None);
414    };
415    Ok(Some(json!({
416        "id": doc_id,
417        "path": reference_path(&r.path),
418        "rev": rev,
419        "raw": r.content,
420        "renderedHashMatch": r.rendered_hash_match,
421    })))
422}
423
424// ---- blocks_read ----------------------------------------------------------------------------
425
426/// The resolution ladder.
427#[derive(Clone, Copy, Debug, PartialEq, Eq)]
428pub enum Resolution {
429    Skeleton,
430    Outline,
431    Text,
432    Raw,
433    Full,
434}
435
436impl Resolution {
437    /// The wire spelling; `None` for an unknown word.
438    #[must_use]
439    pub fn parse(s: &str) -> Option<Self> {
440        Some(match s {
441            "skeleton" => Resolution::Skeleton,
442            "outline" => Resolution::Outline,
443            "text" => Resolution::Text,
444            "raw" => Resolution::Raw,
445            "full" => Resolution::Full,
446            _ => return None,
447        })
448    }
449}
450
451/// The first `n` whitespace-separated words, `…` when cut.
452#[must_use]
453pub fn first_words(text: &str, n: usize) -> String {
454    let words: Vec<&str> = text.split_whitespace().collect();
455    if words.len() <= n {
456        words.join(" ")
457    } else {
458        format!("{}…", words[..n].join(" "))
459    }
460}
461
462fn project(
463    conn: &Connection,
464    node: &BlockNode,
465    resolution: Resolution,
466    include_children: bool,
467) -> Result<Json> {
468    // A block row under the surface's names (§1.2, 3.0): `id`, the raw bytes
469    // `raw` and their hash `hash`; the placement is the plain fields
470    // `ordinal`/`depth`/`parent_id` on the row.
471    let mut m = Map::new();
472    m.insert("id".to_owned(), json!(node.block_id));
473    m.insert("type".to_owned(), json!(node.kind));
474    match resolution {
475        Resolution::Skeleton => {
476            let label = if node.kind == "heading" {
477                node.text.clone()
478            } else {
479                node.kind.clone()
480            };
481            m.insert("label".to_owned(), json!(label));
482        }
483        Resolution::Outline => {
484            m.insert("label".to_owned(), json!(first_words(&node.text, 10)));
485        }
486        Resolution::Text => {
487            m.insert("text".to_owned(), json!(node.text));
488        }
489        Resolution::Raw => {
490            m.insert(
491                "raw".to_owned(),
492                json!(block_raw(conn, &node.raw_hash_hex)?),
493            );
494            m.insert("hash".to_owned(), json!(node.raw_hash_hex));
495        }
496        Resolution::Full => {
497            m.insert(
498                "raw".to_owned(),
499                json!(block_raw(conn, &node.raw_hash_hex)?),
500            );
501            m.insert("hash".to_owned(), json!(node.raw_hash_hex));
502            m.insert("text".to_owned(), json!(node.text));
503            m.insert("attrs".to_owned(), node.attrs.clone());
504            m.insert("ordinal".to_owned(), json!(node.ordinal));
505            m.insert("depth".to_owned(), json!(node.depth));
506            m.insert("parent_id".to_owned(), json!(node.parent_block));
507        }
508    }
509    if include_children && !node.children.is_empty() {
510        let kids: Result<Vec<Json>> = node
511            .children
512            .iter()
513            .map(|c| project(conn, c, resolution, true))
514            .collect();
515        m.insert("children".to_owned(), Json::Array(kids?));
516    }
517    Ok(Json::Object(m))
518}
519
520/// §2 `blocks_read`: one block subtree at a resolution; `None` when the block
521/// is not live in `doc_id`.
522pub fn blocks_read(
523    store: &Store,
524    doc_id: &str,
525    block_id: &str,
526    resolution: Resolution,
527) -> Result<Option<Json>> {
528    let roots = load_doc_blocks(store.conn(), doc_id)?;
529    match find_block(&roots, block_id) {
530        Some(n) => Ok(Some(project(store.conn(), n, resolution, true)?)),
531        None => Ok(None),
532    }
533}
534
535/// §2 `blocks_read_many`: `{ nodes, truncated, unresolved }`.
536pub fn blocks_read_many(
537    store: &Store,
538    doc_id: Option<&str>,
539    block_ids: &[String],
540    resolution: Resolution,
541    budget_tokens: Option<usize>,
542) -> Result<Json> {
543    let conn = store.conn();
544    let capped = &block_ids[..block_ids.len().min(MANY_CAP)];
545    let mut owner: HashMap<String, String> = HashMap::new();
546    if !capped.is_empty() {
547        let placeholders: Vec<String> = (1..=capped.len()).map(|i| format!("?{i}")).collect();
548        let sql = format!(
549            "SELECT block_id, doc_id FROM blocks WHERE deleted_commit IS NULL AND block_id IN ({})",
550            placeholders.join(",")
551        );
552        let mut stmt = conn.prepare(&sql)?;
553        let rows = stmt.query_map(rusqlite::params_from_iter(capped.iter()), |r| {
554            Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))
555        })?;
556        for row in rows {
557            let (b, d) = row?;
558            if doc_id.is_none_or(|want| want == d) {
559                owner.insert(b, d);
560            }
561        }
562    }
563    let mut forests: BTreeMap<String, Vec<BlockNode>> = BTreeMap::new();
564    for d in owner.values() {
565        if !forests.contains_key(d) {
566            forests.insert(d.clone(), load_doc_blocks(conn, d)?);
567        }
568    }
569    let mut nodes = Vec::new();
570    let mut unresolved = Vec::new();
571    let mut tokens = 0usize;
572    let mut truncated = block_ids.len() > MANY_CAP;
573    for id in capped {
574        let node = owner
575            .get(id)
576            .and_then(|d| forests.get(d))
577            .and_then(|f| find_block(f, id));
578        let Some(node) = node else {
579            unresolved.push(json!(id));
580            continue;
581        };
582        let projected = project(conn, node, resolution, false)?;
583        // §2 (1.2): at least one resolved node, as `docs_read_many`.
584        let cost = token_cost(&projected);
585        if !nodes.is_empty() && budget_tokens.is_some_and(|b| tokens + cost > b) {
586            truncated = true;
587            break;
588        }
589        tokens += cost;
590        nodes.push(projected);
591    }
592    Ok(json!({ "nodes": nodes, "truncated": truncated, "unresolved": unresolved }))
593}
594
595// ---- docs_outline -----------------------------------------------------------------------
596
597fn type_label(node: &BlockNode) -> String {
598    match node.kind.as_str() {
599        "heading" => format!(
600            "h{}",
601            node.attrs
602                .get("level")
603                .map(|l| match l {
604                    Json::String(s) => s.clone(),
605                    Json::Null => String::new(),
606                    other => other.to_string(),
607                })
608                .unwrap_or_default()
609        ),
610        "paragraph" => "p".to_owned(),
611        "list" => "ul".to_owned(),
612        "list_item" | "task" => "li".to_owned(),
613        "blockquote" => "bq".to_owned(),
614        "code_fence" => "code".to_owned(),
615        "table" => "tbl".to_owned(),
616        "table_row" => "tr".to_owned(),
617        "thematic_break" => "hr".to_owned(),
618        "html_block" => "html".to_owned(),
619        "opaque" => "raw".to_owned(),
620        other => other.to_owned(),
621    }
622}
623
624fn label_for(node: &BlockNode) -> String {
625    match node.kind.as_str() {
626        "list" | "blockquote" | "table" => String::new(),
627        "task" => {
628            let checked = node.attrs.get("checked").is_some_and(|c| {
629                !matches!(c, Json::Null | Json::Bool(false)) && c != &json!(0) && c != &json!("")
630            });
631            let glyph = if checked { "☑" } else { "☐" };
632            format!("{glyph} {}", first_words(&node.text, 10))
633        }
634        _ => first_words(&node.text, 10),
635    }
636}
637
638/// §2 `docs_outline`: `{ text, truncated }`.
639pub fn docs_outline(
640    store: &Store,
641    doc_id: &str,
642    skeleton: bool,
643    depth: Option<i64>,
644    budget_tokens: Option<usize>,
645) -> Result<Json> {
646    let roots = load_doc_blocks(store.conn(), doc_id)?;
647    struct Walk {
648        skeleton: bool,
649        max_depth: Option<i64>,
650        budget: Option<usize>,
651        lines: Vec<String>,
652        tokens: usize,
653        truncated: bool,
654    }
655    impl Walk {
656        fn walk(&mut self, nodes: &[BlockNode], indent: i64) {
657            for node in nodes {
658                if self.truncated {
659                    return;
660                }
661                if self.max_depth.is_some_and(|d| indent > d) {
662                    continue;
663                }
664                let pad = "  ".repeat(usize::try_from(indent).unwrap_or(0));
665                let section_mark = if node.kind == "heading" { "  §" } else { "" };
666                let label = if self.skeleton {
667                    String::new()
668                } else {
669                    label_for(node)
670                };
671                let line = format!(
672                    "{pad}{} {:<4} {label}{section_mark}",
673                    node.block_id,
674                    type_label(node)
675                );
676                let line = line.trim_end().to_owned();
677                let line_tokens = line.chars().count().div_ceil(4);
678                if self.budget.is_some_and(|b| self.tokens + line_tokens > b) {
679                    self.truncated = true;
680                    return;
681                }
682                self.tokens += line_tokens;
683                self.lines.push(line);
684                if !node.children.is_empty() {
685                    self.walk(&node.children, indent + 1);
686                }
687            }
688        }
689    }
690    let mut w = Walk {
691        skeleton,
692        max_depth: depth,
693        budget: budget_tokens,
694        lines: Vec::new(),
695        tokens: 0,
696        truncated: false,
697    };
698    w.walk(&roots, 0);
699    let (lines, truncated) = (w.lines, w.truncated);
700    Ok(json!({ "text": lines.join("\n"), "truncated": truncated }))
701}
702
703// ---- docs_list / docs_tree --------------------------------------------------------------
704
705/// One row of `docs_list` (`path` in the storage form; the wire roots it).
706#[derive(Clone, Debug, PartialEq, Eq)]
707pub struct DocListRow {
708    pub doc_id: String,
709    pub path: String,
710    pub blocks: i64,
711    pub ts: Option<String>,
712}
713
714impl DocListRow {
715    /// The wire row (§2, 3.0): `{ id, path, updated_at, blocks }` — the
716    /// document's row attributes, the path in the reference form (§1 "Paths").
717    fn to_json(&self) -> Json {
718        json!({ "id": self.doc_id, "path": reference_path(&self.path), "updated_at": self.ts, "blocks": self.blocks })
719    }
720}
721
722/// Live docs (path, live block count, last-commit ts) matching `like`, by
723/// path, optionally after `after`, capped at `limit`.
724fn live_doc_rows(
725    conn: &Connection,
726    repo_id: &str,
727    like: &str,
728    after: Option<&str>,
729    limit: Option<usize>,
730) -> Result<Vec<DocListRow>> {
731    let mut sql = String::from(
732        "SELECT d.path, d.doc_id,
733                (SELECT count(*) FROM blocks b WHERE b.doc_id = d.doc_id AND b.deleted_commit IS NULL),
734                (SELECT c.ts FROM revisions r JOIN commits c ON c.commit_id = r.commit_id WHERE r.rev_id = d.current_rev)
735         FROM docs d
736         WHERE d.repo_id = ?1 AND d.deleted_commit IS NULL AND d.path LIKE ?2 ESCAPE '\\'",
737    );
738    let mut p: Vec<rusqlite::types::Value> = vec![
739        rusqlite::types::Value::Text(repo_id.to_owned()),
740        rusqlite::types::Value::Text(like.to_owned()),
741    ];
742    if let Some(a) = after {
743        sql.push_str(" AND d.path > ?3");
744        p.push(rusqlite::types::Value::Text(a.to_owned()));
745    }
746    sql.push_str(" ORDER BY d.path");
747    if let Some(l) = limit {
748        sql.push_str(&format!(" LIMIT ?{}", p.len() + 1));
749        p.push(rusqlite::types::Value::Integer(
750            i64::try_from(l).unwrap_or(i64::MAX),
751        ));
752    }
753    // Four shapes at most (`after` × `limit`): every list/tree call reuses a
754    // compiled statement.
755    let mut stmt = conn.prepare_cached(&sql)?;
756    let rows = stmt.query_map(rusqlite::params_from_iter(p.iter()), |r| {
757        Ok(DocListRow {
758            path: r.get(0)?,
759            doc_id: r.get(1)?,
760            blocks: r.get(2)?,
761            ts: r.get(3)?,
762        })
763    })?;
764    Ok(rows.collect::<std::result::Result<Vec<_>, _>>()?)
765}
766
767/// Page an already path-ordered row set under a limit + token budget (at
768/// least one row), issuing a `[path]` cursor when it stops early; the paths
769/// handed in are the reference form, which the cursor carries.
770fn page_path_ordered(
771    rows: Vec<(String, Json)>,
772    limit: usize,
773    budget_tokens: Option<usize>,
774    more_beyond: bool,
775) -> (Vec<Json>, bool, Option<String>) {
776    let mut items: Vec<Json> = Vec::new();
777    let mut last_path: Option<String> = None;
778    let mut tokens = 0usize;
779    let mut truncated = more_beyond;
780    for (path, row) in rows {
781        if items.len() >= limit {
782            truncated = true;
783            break;
784        }
785        let cost = token_cost(&row);
786        if !items.is_empty() && budget_tokens.is_some_and(|b| tokens + cost > b) {
787            truncated = true;
788            break;
789        }
790        tokens += cost;
791        items.push(row);
792        last_path = Some(path);
793    }
794    let cursor = match (&truncated, last_path) {
795        (true, Some(p)) => Some(encode_cursor(&[&p])),
796        _ => None,
797    };
798    (items, truncated, cursor)
799}
800
801/// §2 `docs_list`: `{ items, truncated, cursor }`.
802pub fn docs_list(
803    store: &Store,
804    repo_id: &str,
805    path_glob: Option<&str>,
806    limit: Option<i64>,
807    cursor: Option<&str>,
808    budget_tokens: Option<usize>,
809) -> Result<Json> {
810    // The glob may be spelled in either form; the column holds the storage form.
811    let like = path_glob.map_or_else(|| "%".to_owned(), |g| glob_to_like(storage_path(g), true));
812    let limit = usize::try_from(limit.unwrap_or(LIST_DEFAULT_LIMIT as i64).max(1)).unwrap_or(1);
813    // The cursor carries the reference form (a 1.x cursor is refused); the
814    // keyset predicate runs on the column.
815    let after = match cursor.filter(|c| !c.is_empty()) {
816        Some(c) => Some(
817            storage_path(&decode_path_cursor(c, "docs_list/docs_tree", 1)?.remove(0)).to_owned(),
818        ),
819        None => None,
820    };
821    let mut rows = live_doc_rows(
822        store.conn(),
823        repo_id,
824        &like,
825        after.as_deref(),
826        Some(limit + 1),
827    )?;
828    let more_beyond = rows.len() > limit;
829    rows.truncate(limit);
830    let (items, truncated, cursor) = page_path_ordered(
831        rows.into_iter()
832            .map(|r| (reference_path(&r.path), r.to_json()))
833            .collect(),
834        limit,
835        budget_tokens,
836        more_beyond,
837    );
838    Ok(json!({ "items": items, "truncated": truncated, "cursor": cursor }))
839}
840
841/// Normalize a tree prefix to its storage form: no leading `/`, and either
842/// empty or ending in `/` (either path form is accepted).
843#[must_use]
844pub fn normalize_tree_prefix(path: Option<&str>) -> String {
845    let trimmed = storage_path(path.unwrap_or("")).trim_end_matches('/');
846    if trimmed.is_empty() {
847        String::new()
848    } else {
849        format!("{trimmed}/")
850    }
851}
852
853/// §2 `docs_tree`: `{ prefix, depth, total, entries, truncated, cursor }`. The
854/// tree is built over the storage form and rooted on the way out, so the
855/// prefix (`/` for the root), the entries and the cursor all speak the
856/// reference form (§1 "Paths").
857pub fn docs_tree(
858    store: &Store,
859    repo_id: &str,
860    path: Option<&str>,
861    depth: Option<i64>,
862    limit: Option<i64>,
863    cursor: Option<&str>,
864    budget_tokens: Option<usize>,
865) -> Result<Json> {
866    let prefix = normalize_tree_prefix(path);
867    let depth = usize::try_from(depth.unwrap_or(1).max(1)).unwrap_or(1);
868    let limit = usize::try_from(limit.unwrap_or(LIST_DEFAULT_LIMIT as i64).max(1)).unwrap_or(1);
869    let like = if prefix.is_empty() {
870        "%".to_owned()
871    } else {
872        format!("{}%", glob_to_like(&prefix, true))
873    };
874    let rows = live_doc_rows(store.conn(), repo_id, &like, None, None)?;
875
876    struct Entry {
877        path: String,
878        /// The document's id for a `doc` entry; a `dir` has none.
879        doc_id: Option<String>,
880        dir: bool,
881        docs: i64,
882        blocks: i64,
883        ts: Option<String>,
884    }
885    let mut by_path: Vec<Entry> = Vec::new();
886    let (mut total_docs, mut total_blocks) = (0i64, 0i64);
887    for row in &rows {
888        total_docs += 1;
889        total_blocks += row.blocks;
890        let rel = &row.path[prefix.len().min(row.path.len())..];
891        let segs: Vec<&str> = rel.split('/').collect();
892        if segs.len() <= depth {
893            by_path.push(Entry {
894                path: row.path.clone(),
895                doc_id: Some(row.doc_id.clone()),
896                dir: false,
897                docs: 1,
898                blocks: row.blocks,
899                ts: row.ts.clone(),
900            });
901            continue;
902        }
903        let dir = format!("{prefix}{}/", segs[..depth].join("/"));
904        match by_path.iter_mut().find(|e| e.path == dir) {
905            Some(cur) => {
906                cur.docs += 1;
907                cur.blocks += row.blocks;
908                if let Some(ts) = &row.ts {
909                    if cur.ts.as_ref().is_none_or(|c| ts > c) {
910                        cur.ts = Some(ts.clone());
911                    }
912                }
913            }
914            None => by_path.push(Entry {
915                path: dir,
916                doc_id: None,
917                dir: true,
918                docs: 1,
919                blocks: row.blocks,
920                ts: row.ts.clone(),
921            }),
922        }
923    }
924    by_path.sort_by(|a, b| a.path.cmp(&b.path));
925    if let Some(c) = cursor.filter(|c| !c.is_empty()) {
926        let after = decode_path_cursor(c, "docs_list/docs_tree", 1)?.remove(0);
927        by_path.retain(|e| reference_path(&e.path) > after);
928    }
929    let entries: Vec<(String, Json)> = by_path
930        .into_iter()
931        .map(|e| {
932            // §2 (3.0): a `doc` entry is `{ id, path, kind, docs, blocks,
933            // updated_at }`, a `dir` the same without the `id`.
934            let path = reference_path(&e.path);
935            let mut m = Map::new();
936            if let Some(id) = &e.doc_id {
937                m.insert("id".to_owned(), json!(id));
938            }
939            m.insert("path".to_owned(), json!(path));
940            m.insert("kind".to_owned(), json!(if e.dir { "dir" } else { "doc" }));
941            m.insert("docs".to_owned(), json!(e.docs));
942            m.insert("blocks".to_owned(), json!(e.blocks));
943            m.insert("updated_at".to_owned(), json!(e.ts));
944            (path, Json::Object(m))
945        })
946        .collect();
947    let (items, truncated, cursor) = page_path_ordered(entries, limit, budget_tokens, false);
948    Ok(json!({
949        "prefix": reference_path(&prefix),
950        "depth": depth,
951        "total": { "docs": total_docs, "blocks": total_blocks },
952        "entries": items,
953        "truncated": truncated,
954        "cursor": cursor,
955    }))
956}
957
958#[cfg(test)]
959mod tests {
960    use super::*;
961
962    #[test]
963    fn words_and_prefixes() {
964        assert_eq!(first_words("a  b\tc", 10), "a b c");
965        assert_eq!(first_words("a b c", 2), "a b…");
966        assert_eq!(normalize_tree_prefix(None), "");
967        assert_eq!(normalize_tree_prefix(Some("/projects//")), "projects/");
968        assert_eq!(normalize_tree_prefix(Some("a/b")), "a/b/");
969        assert!(is_node_id("n_0123456789ab"));
970        assert!(!is_node_id("n_0123456789AB"));
971        assert!(!is_node_id("b_0123456789ab"));
972    }
973
974    #[test]
975    fn token_cost_is_ceil_quarter_of_json_length() {
976        assert_eq!(token_cost(&json!("ab")), 1); // "ab" → 4 chars
977        assert_eq!(token_cost(&json!("abc")), 2); // 5 chars
978    }
979}