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`: `spec/store` §6.2 plus the current properties.
403pub fn docs_read_at(store: &Store, doc_id: &str, rev: &str) -> Result<Option<Json>> {
404    let Some(r) = store.read_at_revision(doc_id, rev)? else {
405        return Ok(None);
406    };
407    Ok(Some(json!({
408        "id": doc_id,
409        "path": reference_path(&r.path),
410        "rev": rev,
411        "raw": r.content,
412        "renderedHashMatch": r.rendered_hash_match,
413        "properties": surface_properties(store.properties_grouped(doc_id)?),
414        "propertiesAreCurrent": true,
415    })))
416}
417
418// ---- blocks_read ----------------------------------------------------------------------------
419
420/// The resolution ladder.
421#[derive(Clone, Copy, Debug, PartialEq, Eq)]
422pub enum Resolution {
423    Skeleton,
424    Outline,
425    Text,
426    Raw,
427    Full,
428}
429
430impl Resolution {
431    /// The wire spelling; `None` for an unknown word.
432    #[must_use]
433    pub fn parse(s: &str) -> Option<Self> {
434        Some(match s {
435            "skeleton" => Resolution::Skeleton,
436            "outline" => Resolution::Outline,
437            "text" => Resolution::Text,
438            "raw" => Resolution::Raw,
439            "full" => Resolution::Full,
440            _ => return None,
441        })
442    }
443}
444
445/// The first `n` whitespace-separated words, `…` when cut.
446#[must_use]
447pub fn first_words(text: &str, n: usize) -> String {
448    let words: Vec<&str> = text.split_whitespace().collect();
449    if words.len() <= n {
450        words.join(" ")
451    } else {
452        format!("{}…", words[..n].join(" "))
453    }
454}
455
456fn project(
457    conn: &Connection,
458    node: &BlockNode,
459    resolution: Resolution,
460    include_children: bool,
461) -> Result<Json> {
462    // A block row under the surface's names (§1.2, 3.0): `id`, the raw bytes
463    // `raw` and their hash `hash`; the placement is the plain fields
464    // `ordinal`/`depth`/`parent_id` on the row.
465    let mut m = Map::new();
466    m.insert("id".to_owned(), json!(node.block_id));
467    m.insert("type".to_owned(), json!(node.kind));
468    match resolution {
469        Resolution::Skeleton => {
470            let label = if node.kind == "heading" {
471                node.text.clone()
472            } else {
473                node.kind.clone()
474            };
475            m.insert("label".to_owned(), json!(label));
476        }
477        Resolution::Outline => {
478            m.insert("label".to_owned(), json!(first_words(&node.text, 10)));
479        }
480        Resolution::Text => {
481            m.insert("text".to_owned(), json!(node.text));
482        }
483        Resolution::Raw => {
484            m.insert(
485                "raw".to_owned(),
486                json!(block_raw(conn, &node.raw_hash_hex)?),
487            );
488            m.insert("hash".to_owned(), json!(node.raw_hash_hex));
489        }
490        Resolution::Full => {
491            m.insert(
492                "raw".to_owned(),
493                json!(block_raw(conn, &node.raw_hash_hex)?),
494            );
495            m.insert("hash".to_owned(), json!(node.raw_hash_hex));
496            m.insert("text".to_owned(), json!(node.text));
497            m.insert("attrs".to_owned(), node.attrs.clone());
498            m.insert("ordinal".to_owned(), json!(node.ordinal));
499            m.insert("depth".to_owned(), json!(node.depth));
500            m.insert("parent_id".to_owned(), json!(node.parent_block));
501        }
502    }
503    if include_children && !node.children.is_empty() {
504        let kids: Result<Vec<Json>> = node
505            .children
506            .iter()
507            .map(|c| project(conn, c, resolution, true))
508            .collect();
509        m.insert("children".to_owned(), Json::Array(kids?));
510    }
511    Ok(Json::Object(m))
512}
513
514/// §2 `blocks_read`: one block subtree at a resolution; `None` when the block
515/// is not live in `doc_id`.
516pub fn blocks_read(
517    store: &Store,
518    doc_id: &str,
519    block_id: &str,
520    resolution: Resolution,
521) -> Result<Option<Json>> {
522    let roots = load_doc_blocks(store.conn(), doc_id)?;
523    match find_block(&roots, block_id) {
524        Some(n) => Ok(Some(project(store.conn(), n, resolution, true)?)),
525        None => Ok(None),
526    }
527}
528
529/// §2 `blocks_read_many`: `{ nodes, truncated, unresolved }`.
530pub fn blocks_read_many(
531    store: &Store,
532    doc_id: Option<&str>,
533    block_ids: &[String],
534    resolution: Resolution,
535    budget_tokens: Option<usize>,
536) -> Result<Json> {
537    let conn = store.conn();
538    let capped = &block_ids[..block_ids.len().min(MANY_CAP)];
539    let mut owner: HashMap<String, String> = HashMap::new();
540    if !capped.is_empty() {
541        let placeholders: Vec<String> = (1..=capped.len()).map(|i| format!("?{i}")).collect();
542        let sql = format!(
543            "SELECT block_id, doc_id FROM blocks WHERE deleted_commit IS NULL AND block_id IN ({})",
544            placeholders.join(",")
545        );
546        let mut stmt = conn.prepare(&sql)?;
547        let rows = stmt.query_map(rusqlite::params_from_iter(capped.iter()), |r| {
548            Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))
549        })?;
550        for row in rows {
551            let (b, d) = row?;
552            if doc_id.is_none_or(|want| want == d) {
553                owner.insert(b, d);
554            }
555        }
556    }
557    let mut forests: BTreeMap<String, Vec<BlockNode>> = BTreeMap::new();
558    for d in owner.values() {
559        if !forests.contains_key(d) {
560            forests.insert(d.clone(), load_doc_blocks(conn, d)?);
561        }
562    }
563    let mut nodes = Vec::new();
564    let mut unresolved = Vec::new();
565    let mut tokens = 0usize;
566    let mut truncated = block_ids.len() > MANY_CAP;
567    for id in capped {
568        let node = owner
569            .get(id)
570            .and_then(|d| forests.get(d))
571            .and_then(|f| find_block(f, id));
572        let Some(node) = node else {
573            unresolved.push(json!(id));
574            continue;
575        };
576        let projected = project(conn, node, resolution, false)?;
577        // §2 (1.2): at least one resolved node, as `docs_read_many`.
578        let cost = token_cost(&projected);
579        if !nodes.is_empty() && budget_tokens.is_some_and(|b| tokens + cost > b) {
580            truncated = true;
581            break;
582        }
583        tokens += cost;
584        nodes.push(projected);
585    }
586    Ok(json!({ "nodes": nodes, "truncated": truncated, "unresolved": unresolved }))
587}
588
589// ---- docs_outline -----------------------------------------------------------------------
590
591fn type_label(node: &BlockNode) -> String {
592    match node.kind.as_str() {
593        "heading" => format!(
594            "h{}",
595            node.attrs
596                .get("level")
597                .map(|l| match l {
598                    Json::String(s) => s.clone(),
599                    Json::Null => String::new(),
600                    other => other.to_string(),
601                })
602                .unwrap_or_default()
603        ),
604        "paragraph" => "p".to_owned(),
605        "list" => "ul".to_owned(),
606        "list_item" | "task" => "li".to_owned(),
607        "blockquote" => "bq".to_owned(),
608        "code_fence" => "code".to_owned(),
609        "table" => "tbl".to_owned(),
610        "table_row" => "tr".to_owned(),
611        "thematic_break" => "hr".to_owned(),
612        "html_block" => "html".to_owned(),
613        "opaque" => "raw".to_owned(),
614        other => other.to_owned(),
615    }
616}
617
618fn label_for(node: &BlockNode) -> String {
619    match node.kind.as_str() {
620        "list" | "blockquote" | "table" => String::new(),
621        "task" => {
622            let checked = node.attrs.get("checked").is_some_and(|c| {
623                !matches!(c, Json::Null | Json::Bool(false)) && c != &json!(0) && c != &json!("")
624            });
625            let glyph = if checked { "☑" } else { "☐" };
626            format!("{glyph} {}", first_words(&node.text, 10))
627        }
628        _ => first_words(&node.text, 10),
629    }
630}
631
632/// §2 `docs_outline`: `{ text, truncated }`.
633pub fn docs_outline(
634    store: &Store,
635    doc_id: &str,
636    skeleton: bool,
637    depth: Option<i64>,
638    budget_tokens: Option<usize>,
639) -> Result<Json> {
640    let roots = load_doc_blocks(store.conn(), doc_id)?;
641    struct Walk {
642        skeleton: bool,
643        max_depth: Option<i64>,
644        budget: Option<usize>,
645        lines: Vec<String>,
646        tokens: usize,
647        truncated: bool,
648    }
649    impl Walk {
650        fn walk(&mut self, nodes: &[BlockNode], indent: i64) {
651            for node in nodes {
652                if self.truncated {
653                    return;
654                }
655                if self.max_depth.is_some_and(|d| indent > d) {
656                    continue;
657                }
658                let pad = "  ".repeat(usize::try_from(indent).unwrap_or(0));
659                let section_mark = if node.kind == "heading" { "  §" } else { "" };
660                let label = if self.skeleton {
661                    String::new()
662                } else {
663                    label_for(node)
664                };
665                let line = format!(
666                    "{pad}{} {:<4} {label}{section_mark}",
667                    node.block_id,
668                    type_label(node)
669                );
670                let line = line.trim_end().to_owned();
671                let line_tokens = line.chars().count().div_ceil(4);
672                if self.budget.is_some_and(|b| self.tokens + line_tokens > b) {
673                    self.truncated = true;
674                    return;
675                }
676                self.tokens += line_tokens;
677                self.lines.push(line);
678                if !node.children.is_empty() {
679                    self.walk(&node.children, indent + 1);
680                }
681            }
682        }
683    }
684    let mut w = Walk {
685        skeleton,
686        max_depth: depth,
687        budget: budget_tokens,
688        lines: Vec::new(),
689        tokens: 0,
690        truncated: false,
691    };
692    w.walk(&roots, 0);
693    let (lines, truncated) = (w.lines, w.truncated);
694    Ok(json!({ "text": lines.join("\n"), "truncated": truncated }))
695}
696
697// ---- docs_list / docs_tree --------------------------------------------------------------
698
699/// One row of `docs_list` (`path` in the storage form; the wire roots it).
700#[derive(Clone, Debug, PartialEq, Eq)]
701pub struct DocListRow {
702    pub doc_id: String,
703    pub path: String,
704    pub blocks: i64,
705    pub ts: Option<String>,
706}
707
708impl DocListRow {
709    /// The wire row (§2, 3.0): `{ id, path, updated_at, blocks }` — the
710    /// document's row attributes, the path in the reference form (§1 "Paths").
711    fn to_json(&self) -> Json {
712        json!({ "id": self.doc_id, "path": reference_path(&self.path), "updated_at": self.ts, "blocks": self.blocks })
713    }
714}
715
716/// Live docs (path, live block count, last-commit ts) matching `like`, by
717/// path, optionally after `after`, capped at `limit`.
718fn live_doc_rows(
719    conn: &Connection,
720    repo_id: &str,
721    like: &str,
722    after: Option<&str>,
723    limit: Option<usize>,
724) -> Result<Vec<DocListRow>> {
725    let mut sql = String::from(
726        "SELECT d.path, d.doc_id,
727                (SELECT count(*) FROM blocks b WHERE b.doc_id = d.doc_id AND b.deleted_commit IS NULL),
728                (SELECT c.ts FROM revisions r JOIN commits c ON c.commit_id = r.commit_id WHERE r.rev_id = d.current_rev)
729         FROM docs d
730         WHERE d.repo_id = ?1 AND d.deleted_commit IS NULL AND d.path LIKE ?2 ESCAPE '\\'",
731    );
732    let mut p: Vec<rusqlite::types::Value> = vec![
733        rusqlite::types::Value::Text(repo_id.to_owned()),
734        rusqlite::types::Value::Text(like.to_owned()),
735    ];
736    if let Some(a) = after {
737        sql.push_str(" AND d.path > ?3");
738        p.push(rusqlite::types::Value::Text(a.to_owned()));
739    }
740    sql.push_str(" ORDER BY d.path");
741    if let Some(l) = limit {
742        sql.push_str(&format!(" LIMIT ?{}", p.len() + 1));
743        p.push(rusqlite::types::Value::Integer(
744            i64::try_from(l).unwrap_or(i64::MAX),
745        ));
746    }
747    // Four shapes at most (`after` × `limit`): every list/tree call reuses a
748    // compiled statement.
749    let mut stmt = conn.prepare_cached(&sql)?;
750    let rows = stmt.query_map(rusqlite::params_from_iter(p.iter()), |r| {
751        Ok(DocListRow {
752            path: r.get(0)?,
753            doc_id: r.get(1)?,
754            blocks: r.get(2)?,
755            ts: r.get(3)?,
756        })
757    })?;
758    Ok(rows.collect::<std::result::Result<Vec<_>, _>>()?)
759}
760
761/// Page an already path-ordered row set under a limit + token budget (at
762/// least one row), issuing a `[path]` cursor when it stops early; the paths
763/// handed in are the reference form, which the cursor carries.
764fn page_path_ordered(
765    rows: Vec<(String, Json)>,
766    limit: usize,
767    budget_tokens: Option<usize>,
768    more_beyond: bool,
769) -> (Vec<Json>, bool, Option<String>) {
770    let mut items: Vec<Json> = Vec::new();
771    let mut last_path: Option<String> = None;
772    let mut tokens = 0usize;
773    let mut truncated = more_beyond;
774    for (path, row) in rows {
775        if items.len() >= limit {
776            truncated = true;
777            break;
778        }
779        let cost = token_cost(&row);
780        if !items.is_empty() && budget_tokens.is_some_and(|b| tokens + cost > b) {
781            truncated = true;
782            break;
783        }
784        tokens += cost;
785        items.push(row);
786        last_path = Some(path);
787    }
788    let cursor = match (&truncated, last_path) {
789        (true, Some(p)) => Some(encode_cursor(&[&p])),
790        _ => None,
791    };
792    (items, truncated, cursor)
793}
794
795/// §2 `docs_list`: `{ items, truncated, cursor }`.
796pub fn docs_list(
797    store: &Store,
798    repo_id: &str,
799    path_glob: Option<&str>,
800    limit: Option<i64>,
801    cursor: Option<&str>,
802    budget_tokens: Option<usize>,
803) -> Result<Json> {
804    // The glob may be spelled in either form; the column holds the storage form.
805    let like = path_glob.map_or_else(|| "%".to_owned(), |g| glob_to_like(storage_path(g), true));
806    let limit = usize::try_from(limit.unwrap_or(LIST_DEFAULT_LIMIT as i64).max(1)).unwrap_or(1);
807    // The cursor carries the reference form (a 1.x cursor is refused); the
808    // keyset predicate runs on the column.
809    let after = match cursor.filter(|c| !c.is_empty()) {
810        Some(c) => Some(
811            storage_path(&decode_path_cursor(c, "docs_list/docs_tree", 1)?.remove(0)).to_owned(),
812        ),
813        None => None,
814    };
815    let mut rows = live_doc_rows(
816        store.conn(),
817        repo_id,
818        &like,
819        after.as_deref(),
820        Some(limit + 1),
821    )?;
822    let more_beyond = rows.len() > limit;
823    rows.truncate(limit);
824    let (items, truncated, cursor) = page_path_ordered(
825        rows.into_iter()
826            .map(|r| (reference_path(&r.path), r.to_json()))
827            .collect(),
828        limit,
829        budget_tokens,
830        more_beyond,
831    );
832    Ok(json!({ "items": items, "truncated": truncated, "cursor": cursor }))
833}
834
835/// Normalize a tree prefix to its storage form: no leading `/`, and either
836/// empty or ending in `/` (either path form is accepted).
837#[must_use]
838pub fn normalize_tree_prefix(path: Option<&str>) -> String {
839    let trimmed = storage_path(path.unwrap_or("")).trim_end_matches('/');
840    if trimmed.is_empty() {
841        String::new()
842    } else {
843        format!("{trimmed}/")
844    }
845}
846
847/// §2 `docs_tree`: `{ prefix, depth, total, entries, truncated, cursor }`. The
848/// tree is built over the storage form and rooted on the way out, so the
849/// prefix (`/` for the root), the entries and the cursor all speak the
850/// reference form (§1 "Paths").
851pub fn docs_tree(
852    store: &Store,
853    repo_id: &str,
854    path: Option<&str>,
855    depth: Option<i64>,
856    limit: Option<i64>,
857    cursor: Option<&str>,
858    budget_tokens: Option<usize>,
859) -> Result<Json> {
860    let prefix = normalize_tree_prefix(path);
861    let depth = usize::try_from(depth.unwrap_or(1).max(1)).unwrap_or(1);
862    let limit = usize::try_from(limit.unwrap_or(LIST_DEFAULT_LIMIT as i64).max(1)).unwrap_or(1);
863    let like = if prefix.is_empty() {
864        "%".to_owned()
865    } else {
866        format!("{}%", glob_to_like(&prefix, true))
867    };
868    let rows = live_doc_rows(store.conn(), repo_id, &like, None, None)?;
869
870    struct Entry {
871        path: String,
872        /// The document's id for a `doc` entry; a `dir` has none.
873        doc_id: Option<String>,
874        dir: bool,
875        docs: i64,
876        blocks: i64,
877        ts: Option<String>,
878    }
879    let mut by_path: Vec<Entry> = Vec::new();
880    let (mut total_docs, mut total_blocks) = (0i64, 0i64);
881    for row in &rows {
882        total_docs += 1;
883        total_blocks += row.blocks;
884        let rel = &row.path[prefix.len().min(row.path.len())..];
885        let segs: Vec<&str> = rel.split('/').collect();
886        if segs.len() <= depth {
887            by_path.push(Entry {
888                path: row.path.clone(),
889                doc_id: Some(row.doc_id.clone()),
890                dir: false,
891                docs: 1,
892                blocks: row.blocks,
893                ts: row.ts.clone(),
894            });
895            continue;
896        }
897        let dir = format!("{prefix}{}/", segs[..depth].join("/"));
898        match by_path.iter_mut().find(|e| e.path == dir) {
899            Some(cur) => {
900                cur.docs += 1;
901                cur.blocks += row.blocks;
902                if let Some(ts) = &row.ts {
903                    if cur.ts.as_ref().is_none_or(|c| ts > c) {
904                        cur.ts = Some(ts.clone());
905                    }
906                }
907            }
908            None => by_path.push(Entry {
909                path: dir,
910                doc_id: None,
911                dir: true,
912                docs: 1,
913                blocks: row.blocks,
914                ts: row.ts.clone(),
915            }),
916        }
917    }
918    by_path.sort_by(|a, b| a.path.cmp(&b.path));
919    if let Some(c) = cursor.filter(|c| !c.is_empty()) {
920        let after = decode_path_cursor(c, "docs_list/docs_tree", 1)?.remove(0);
921        by_path.retain(|e| reference_path(&e.path) > after);
922    }
923    let entries: Vec<(String, Json)> = by_path
924        .into_iter()
925        .map(|e| {
926            // §2 (3.0): a `doc` entry is `{ id, path, kind, docs, blocks,
927            // updated_at }`, a `dir` the same without the `id`.
928            let path = reference_path(&e.path);
929            let mut m = Map::new();
930            if let Some(id) = &e.doc_id {
931                m.insert("id".to_owned(), json!(id));
932            }
933            m.insert("path".to_owned(), json!(path));
934            m.insert("kind".to_owned(), json!(if e.dir { "dir" } else { "doc" }));
935            m.insert("docs".to_owned(), json!(e.docs));
936            m.insert("blocks".to_owned(), json!(e.blocks));
937            m.insert("updated_at".to_owned(), json!(e.ts));
938            (path, Json::Object(m))
939        })
940        .collect();
941    let (items, truncated, cursor) = page_path_ordered(entries, limit, budget_tokens, false);
942    Ok(json!({
943        "prefix": reference_path(&prefix),
944        "depth": depth,
945        "total": { "docs": total_docs, "blocks": total_blocks },
946        "entries": items,
947        "truncated": truncated,
948        "cursor": cursor,
949    }))
950}
951
952#[cfg(test)]
953mod tests {
954    use super::*;
955
956    #[test]
957    fn words_and_prefixes() {
958        assert_eq!(first_words("a  b\tc", 10), "a b c");
959        assert_eq!(first_words("a b c", 2), "a b…");
960        assert_eq!(normalize_tree_prefix(None), "");
961        assert_eq!(normalize_tree_prefix(Some("/projects//")), "projects/");
962        assert_eq!(normalize_tree_prefix(Some("a/b")), "a/b/");
963        assert!(is_node_id("n_0123456789ab"));
964        assert!(!is_node_id("n_0123456789AB"));
965        assert!(!is_node_id("b_0123456789ab"));
966    }
967
968    #[test]
969    fn token_cost_is_ceil_quarter_of_json_length() {
970        assert_eq!(token_cost(&json!("ab")), 1); // "ab" → 4 chars
971        assert_eq!(token_cost(&json!("abc")), 2); // 5 chars
972    }
973}