Skip to main content

nb_api/client/
read.rs

1use std::path::{Path, PathBuf};
2
3use crate::argv::search_command_args;
4use crate::diagnostics::is_selector_not_found;
5use crate::error::NbError;
6use crate::fingerprint;
7use crate::gate;
8use crate::lines::{
9    document_lines, note_line_from_body_line, require_contiguous_body,
10    search_lines,
11};
12use crate::output::strip_empty_result_hint;
13use crate::parser::{ParseContext, parse};
14use crate::transaction;
15use crate::types::{
16    BodyFragment, NoteTarget, SearchNoteLines, ShowNote, ShowNoteLines,
17};
18use crate::validate::validate_folder_option;
19use crate::{NbClient, SearchMode};
20
21use super::core::ShowClassification;
22
23impl NbClient {
24    /// Returns status information about the resolved notebook.
25    ///
26    /// When the only notebook dirt is harmless `.index`
27    /// reconciliation (see `git::status_is_index_only`), an
28    /// explanatory note is appended; the raw `nb` output is
29    /// otherwise returned verbatim. The dirt classification runs
30    /// BEFORE any `nb` subprocess in this call: `nb` fires
31    /// fire-and-forget background checkpoints that could otherwise
32    /// commit the very dirt being described between the check and
33    /// the read. Root resolution prefers `NB_DIR` and never shells
34    /// out when it is set; if the root cannot be resolved, the
35    /// verbatim output is returned.
36    pub async fn show_notebook_status(
37        &self,
38        notebook: Option<&str>,
39    ) -> Result<String, NbError> {
40        let name = self.resolve_notebook_name(notebook)?;
41        // Classify first: an `nb` invocation below may background a
42        // checkpoint that reconciles the dirt away mid-call.
43        let index_only = notebook_dir_from_env(&name)
44            .map(|root| {
45                crate::git::notebook_status_porcelain(&root)
46                    .map(|s| crate::git::status_is_index_only(&s))
47                    .unwrap_or(false)
48            })
49            .unwrap_or(false);
50        let notebook = self.resolve_notebook(Some(&name)).await?;
51        let output = self
52            .exec_vec(vec![format!("{}:", notebook), "status".to_string()])
53            .await?;
54        if index_only {
55            return Ok(format!(
56                "{output}\n(note: only .index reconciliation is pending; safe to proceed — no note content affected)"
57            ));
58        }
59        Ok(output)
60    }
61
62    /// Lists available notebooks.
63    pub async fn list_notebooks(&self) -> Result<String, NbError> {
64        let _g = gate::acquire_global(self.gate_timeout).await?;
65        // Use --no-color to avoid ANSI escape codes
66        self.exec(&["notebooks", "--no-color"]).await
67    }
68
69    /// Returns the path for a notebook.
70    pub async fn show_notebook_path(
71        &self,
72        notebook: Option<&str>,
73    ) -> Result<PathBuf, NbError> {
74        let notebook = self.resolve_notebook_name(notebook)?;
75        self.ensure_notebook(&notebook).await?;
76        self.with_notebook_gate(
77            &notebook,
78            self.show_notebook_path_unguarded(Some(&notebook)),
79        )
80        .await
81    }
82
83    /// Shows a note as a structured [`ShowNote`] (gate-held).
84    pub async fn show_note(
85        &self,
86        id: &str,
87        notebook: Option<&str>,
88    ) -> Result<ShowNote, NbError> {
89        let (notebook, selector) =
90            self.resolve_target_selector(id, notebook).await?;
91        self.with_notebook_gate(&notebook, async {
92            self.show_note_inner(&notebook, &selector).await
93        })
94        .await
95    }
96
97    async fn show_note_inner(
98        &self,
99        notebook: &str,
100        selector: &str,
101    ) -> Result<ShowNote, NbError> {
102        // Fast path: existing directories resolve directly without
103        // spawning `nb` (which misdispatches subcommand-colliding
104        // names like `todos`, `notebooks`, `list`; see
105        // nb-mcp-server:todos/mcp/62). Bypass also skips the probe's
106        // reconciling CLI reads. Falls back to the probe + `nb show
107        // --path` path for numeric ids/titles when the filesystem
108        // entry is absent.
109        if let Some(rel) = selector
110            .rsplit_once(':')
111            .map(|(_, rest)| rest)
112            .filter(|rest| !rest.is_empty())
113            && let Ok(root) =
114                self.show_notebook_path_unguarded(Some(notebook)).await
115            && root.join(rel).is_dir()
116        {
117            return Err(NbError::UnsupportedShowTarget {
118                selector: selector.to_string(),
119                actual_type: "folder".to_string(),
120            });
121        }
122        match self.probe_show_classification(selector).await {
123            ShowClassification::NonTextual { actual_type } => {
124                return Err(NbError::UnsupportedShowTarget {
125                    selector: selector.to_string(),
126                    actual_type,
127                });
128            },
129            ShowClassification::Textual | ShowClassification::ProbeFailure => {
130            },
131        }
132        let path = self.resolve_item_path(selector).await?;
133        if path.is_dir() {
134            return Err(NbError::UnsupportedShowTarget {
135                selector: selector.to_string(),
136                actual_type: "folder".to_string(),
137            });
138        }
139        let root = self.show_notebook_path_unguarded(Some(notebook)).await?;
140        let rel = path_relative_to(&root, &path)?;
141        let source = std::fs::read(&path).map_err(|e| NbError::Io {
142            path: path.clone(),
143            source: e.into(),
144        })?;
145        let doc = match parse(
146            &source,
147            ParseContext::FromPath(PathBuf::from(&rel)),
148        ) {
149            Ok(doc) => doc,
150            // nb may classify additional textual extensions as showable; map
151            // unrecognized formats to a Note partition for structured show.
152            Err(NbError::UnsupportedDocumentFormat { .. }) => parse(
153                &source,
154                ParseContext::Explicit(crate::DocumentKind::Note),
155            )?,
156            Err(err) => return Err(err),
157        };
158        let kind_str = format!("{:?}", doc.kind()).to_lowercase();
159        let non_utf8 = |path: String| NbError::NonUtf8 {
160            selector: selector.to_string(),
161            path,
162            kind: kind_str.clone(),
163            mime_hint: None,
164        };
165        let source_str = std::str::from_utf8(&source)
166            .map_err(|_| non_utf8(rel.clone()))?
167            .to_string();
168        // Fragment offsets into `source`: body_ranges are source-absolute.
169        let ranges = doc.body_ranges();
170        let mut fragments: Vec<BodyFragment> =
171            Vec::with_capacity(ranges.len());
172        for (i, span) in ranges.iter().enumerate() {
173            let bytes = std::str::from_utf8(&source[span.clone()])
174                .map_err(|_| non_utf8(rel.clone()))?
175                .to_string();
176            fragments.push(BodyFragment {
177                index: i as u32,
178                bytes,
179                start_byte: span.start as u32,
180                end_byte: span.end as u32,
181            });
182        }
183        let body_contiguous = fragments.len() <= 1;
184        let body_bytes = doc.body_bytes();
185        let body = std::str::from_utf8(&body_bytes)
186            .map_err(|_| non_utf8(rel.clone()))?
187            .to_string();
188        // Lossy convenience strings; raw title bytes remain authoritative.
189        let tags: Vec<String> = doc
190            .tags()
191            .map(|t| {
192                String::from_utf8_lossy(t)
193                    .trim_start_matches('#')
194                    .to_string()
195            })
196            .collect();
197        let title = doc
198            .title()
199            .map(|bytes| std::str::from_utf8(bytes).map(str::to_string))
200            .transpose()
201            .map_err(|_| non_utf8(rel.clone()))?;
202        let title_text = doc.title().map(|bytes| {
203            let s = String::from_utf8_lossy(bytes);
204            s.trim_end_matches('\n')
205                .trim_start_matches('#')
206                .trim()
207                .to_string()
208        });
209        Ok(ShowNote {
210            selector: numeric_selector_for_path(
211                notebook, &root, &rel, selector,
212            ),
213            path: rel.clone(),
214            kind: doc.kind(),
215            todo_state: doc.todo_state(),
216            title,
217            title_text,
218            tags,
219            body_fragments: fragments,
220            body_contiguous,
221            body,
222            fingerprint: fingerprint::fingerprint(&doc),
223            source: source_str,
224            numeric_id: numeric_id_for_path(&root, &rel),
225        })
226    }
227
228    /// Raw-bytes escape hatch: full file bytes without UTF-8 validation.
229    ///
230    /// This is the only public read that returns `Vec<u8>`; every other
231    /// structured read is text-only and returns `NonUtf8` on invalid UTF-8.
232    pub async fn read_note_source_bytes(
233        &self,
234        target: NoteTarget,
235        notebook: Option<&str>,
236    ) -> Result<Vec<u8>, NbError> {
237        let (notebook, selector) =
238            self.resolve_note_target(&target, notebook).await?;
239        self.with_notebook_gate(&notebook, async {
240            let path = self.resolve_item_path(&selector).await?;
241            std::fs::read(&path).map_err(|e| NbError::Io {
242                path: path.clone(),
243                source: e.into(),
244            })
245        })
246        .await
247    }
248
249    /// Enumerate body lines for a contiguous-body note.
250    pub async fn show_note_lines(
251        &self,
252        target: NoteTarget,
253        offset: Option<u32>,
254        limit: Option<u32>,
255        notebook: Option<&str>,
256    ) -> Result<ShowNoteLines, NbError> {
257        let (notebook, selector) =
258            self.resolve_note_target(&target, notebook).await?;
259        self.with_notebook_gate(&notebook, async {
260            let shown = self.show_note_inner(&notebook, &selector).await?;
261            let source = shown.source.as_bytes().to_vec();
262            let doc = parse(
263                &source,
264                ParseContext::FromPath(PathBuf::from(&shown.path)),
265            )?;
266            let body = require_contiguous_body(&doc)?;
267            let (eol, has_final_eol, lines) = document_lines(&body);
268            let total_lines = lines.len() as u32;
269            let offset = offset.unwrap_or(1);
270            let limit = limit.unwrap_or(100);
271            if offset == 0 {
272                return Err(NbError::InvalidLineWindow {
273                    offset,
274                    limit,
275                    total_lines,
276                });
277            }
278            if total_lines == 0 {
279                if offset != 1 {
280                    return Err(NbError::InvalidLineWindow {
281                        offset,
282                        limit,
283                        total_lines,
284                    });
285                }
286                return Ok(ShowNoteLines {
287                    selector: shown.selector,
288                    path: shown.path,
289                    kind: shown.kind,
290                    total_lines: 0,
291                    offset,
292                    limit,
293                    next_offset: None,
294                    lines: Vec::new(),
295                    title: shown.title,
296                    tags: shown.tags,
297                    body_fingerprint: shown.fingerprint,
298                    eol: None,
299                    has_final_eol: false,
300                    numeric_id: shown.numeric_id,
301                });
302            }
303            if offset > total_lines + 1 {
304                return Err(NbError::InvalidLineWindow {
305                    offset,
306                    limit,
307                    total_lines,
308                });
309            }
310            let start_idx = (offset - 1) as usize;
311            let end_idx = (start_idx + limit as usize).min(lines.len());
312            let window: Vec<_> = lines[start_idx..end_idx]
313                .iter()
314                .map(|l| note_line_from_body_line(l, &body))
315                .collect();
316            let next_offset = if end_idx < lines.len() {
317                Some(offset + window.len() as u32)
318            } else {
319                None
320            };
321            Ok(ShowNoteLines {
322                selector: shown.selector,
323                path: shown.path,
324                kind: shown.kind,
325                total_lines,
326                offset,
327                limit,
328                next_offset,
329                lines: window,
330                title: shown.title,
331                tags: shown.tags,
332                body_fingerprint: shown.fingerprint,
333                eol,
334                has_final_eol,
335                numeric_id: shown.numeric_id,
336            })
337        })
338        .await
339    }
340
341    /// Search body line texts for a pattern (contiguous body only).
342    pub async fn search_note_lines(
343        &self,
344        target: NoteTarget,
345        pattern: &str,
346        notebook: Option<&str>,
347    ) -> Result<SearchNoteLines, NbError> {
348        let (notebook, selector) =
349            self.resolve_note_target(&target, notebook).await?;
350        self.with_notebook_gate(&notebook, async {
351            let shown = self.show_note_inner(&notebook, &selector).await?;
352            let source = shown.source.as_bytes().to_vec();
353            let doc = parse(
354                &source,
355                ParseContext::FromPath(PathBuf::from(&shown.path)),
356            )?;
357            let body = require_contiguous_body(&doc)?;
358            let hits = search_lines(&body, pattern.as_bytes())?;
359            Ok(SearchNoteLines {
360                selector: shown.selector,
361                path: shown.path,
362                kind: shown.kind,
363                hits,
364                body_fingerprint: shown.fingerprint,
365            })
366        })
367        .await
368    }
369
370    pub(super) async fn resolve_item_path(
371        &self,
372        selector: &str,
373    ) -> Result<PathBuf, NbError> {
374        // Fast path: existing filesystem entries (files AND
375        // directories) resolve directly without spawning `nb`, which
376        // misdispatches selectors whose trailing component collides
377        // with subcommand vocabulary (`todos` -> tasks listing,
378        // `notebooks` -> notebook root, `list` -> folder listing;
379        // nb-mcp-server:todos/mcp/62). Falls back to `nb show --path`
380        // for numeric ids/titles that have no direct filesystem form.
381        if let Ok(Some((notebook, rel))) =
382            crate::validate::parse_qualified_selector(selector)
383            && !rel.is_empty()
384            && let Ok(root) =
385                self.show_notebook_path_unguarded(Some(notebook)).await
386        {
387            let direct = root.join(rel);
388            if direct.is_file() || direct.is_dir() {
389                return Ok(direct);
390            }
391        }
392        let output = self
393            .exec_vec(vec![
394                "show".to_string(),
395                selector.to_string(),
396                "--path".to_string(),
397                "--no-color".to_string(),
398            ])
399            .await
400            .map_err(|err| match err {
401                NbError::CommandFailed { stderr, .. }
402                    if is_selector_not_found(&stderr, selector) =>
403                {
404                    NbError::NotFound {
405                        selector: selector.to_string(),
406                    }
407                },
408                other => other,
409            })?;
410        let path = output.trim();
411        if path.is_empty() {
412            return Err(NbError::CommandFailed {
413                command: format!("nb show {selector} --path"),
414                stderr: "empty path".into(),
415                exit_code: None,
416            });
417        }
418        Ok(PathBuf::from(path))
419    }
420
421    async fn resolve_note_target(
422        &self,
423        target: &NoteTarget,
424        notebook: Option<&str>,
425    ) -> Result<(String, String), NbError> {
426        match target {
427            NoteTarget::Selector { value } => {
428                self.resolve_target_selector(value, notebook).await
429            },
430            NoteTarget::Path { value } => {
431                let notebook = self.resolve_notebook(notebook).await?;
432                Ok((notebook.clone(), format!("{notebook}:{value}")))
433            },
434        }
435    }
436
437    /// Probe the textual classification of a selector via `nb`'s
438    /// native `--type` mechanism.
439    ///
440    /// Two-step probe: first `nb show <selector> --type text` to
441    /// ask `nb` whether the type is text. If yes, return
442    /// [`ShowClassification::Textual`]. If no, follow up with
443    /// `nb show <selector> --type` to recover the `actual_type`
444    /// for the error diagnostic. If the follow-up also fails
445    /// (selector not found, internal error), return
446    /// [`ShowClassification::ProbeFailure`] so the caller can
447    /// fall through to the original show path.
448    async fn probe_show_classification(
449        &self,
450        selector: &str,
451    ) -> ShowClassification {
452        let textual = self
453            .exec_vec(vec![
454                "show".to_string(),
455                selector.to_string(),
456                "--type".to_string(),
457                "text".to_string(),
458                "--no-color".to_string(),
459            ])
460            .await;
461        if textual.is_ok() {
462            return ShowClassification::Textual;
463        }
464        match self
465            .exec_vec(vec![
466                "show".to_string(),
467                selector.to_string(),
468                "--type".to_string(),
469                "--no-color".to_string(),
470            ])
471            .await
472        {
473            Ok(stdout) => {
474                let trimmed = stdout.trim();
475                if trimmed.is_empty() {
476                    ShowClassification::ProbeFailure
477                } else {
478                    ShowClassification::NonTextual {
479                        actual_type: trimmed.to_string(),
480                    }
481                }
482            },
483            Err(_) => ShowClassification::ProbeFailure,
484        }
485    }
486
487    /// Lists notes in a notebook or folder.
488    pub async fn list_notes(
489        &self,
490        folder: Option<&str>,
491        tags: &[String],
492        limit: Option<u32>,
493        notebook: Option<&str>,
494    ) -> Result<String, NbError> {
495        let mut args = Vec::new();
496        validate_folder_option(folder)?;
497
498        let notebook = self.resolve_notebook(notebook).await?;
499        let cmd = match folder {
500            Some(f) => format!("{}:{}/", notebook, f),
501            None => format!("{}:", notebook),
502        };
503
504        args.push("list".to_string());
505        args.push(cmd);
506
507        // No color for parsing
508        args.push("--no-color".to_string());
509
510        // Limit
511        if let Some(n) = limit {
512            args.push("-n".to_string());
513            args.push(n.to_string());
514        }
515
516        // Tags filter
517        for tag in tags {
518            args.push("--tags".to_string());
519            let tag_str = if tag.starts_with('#') {
520                tag.clone()
521            } else {
522                format!("#{}", tag)
523            };
524            args.push(tag_str);
525        }
526
527        // Strip the trailing usage/help hint block from empty
528        // results (`0 items.` followed by `Add a note:`,
529        // `Import a file:`, `Help information:`). Detection
530        // keys off the empty-result signal per the
531        // `output-behavior` specification. See `output.rs`
532        // for the helper's contract.
533        self.exec_vec(args)
534            .await
535            .map(|output| strip_empty_result_hint(&output))
536    }
537
538    /// Searches notes.
539    pub async fn search_notes(
540        &self,
541        queries: &[String],
542        mode: SearchMode,
543        tags: &[String],
544        folder: Option<&str>,
545        notebook: Option<&str>,
546    ) -> Result<String, NbError> {
547        validate_folder_option(folder)?;
548        if queries.is_empty() {
549            return Err(NbError::ValidationError {
550                reason: "at least one search query is required".to_string(),
551                location: None,
552            });
553        }
554
555        let notebook = self.resolve_notebook(notebook).await?;
556        let scope = match folder {
557            Some(f) => format!("{}:{}/", notebook, f),
558            None => format!("{}:", notebook),
559        };
560        let args = search_command_args(scope, queries, mode, tags);
561        self.exec_vec(args).await
562    }
563}
564
565/// Numeric `.index` id for a notebook-relative path, if the basename is
566/// listed in its folder `.index` (blank/deleted lines never match).
567fn numeric_id_for_path(notebook_root: &Path, rel: &str) -> Option<u32> {
568    let (folder, basename) = match rel.rfind('/') {
569        Some(i) => (rel[..i].to_string(), rel[i + 1..].to_string()),
570        None => (String::new(), rel.to_string()),
571    };
572    transaction::index_id_in_folder(notebook_root, &folder, &basename)
573}
574
575/// `ShowNote`/`ShowNoteLines` selector: numeric `<folder>/<id>` form when the
576/// path resolves via `.index`, else the qualified selector that was read.
577fn numeric_selector_for_path(
578    notebook: &str,
579    notebook_root: &Path,
580    rel: &str,
581    fallback: &str,
582) -> String {
583    match numeric_id_for_path(notebook_root, rel) {
584        Some(id) => match rel.rfind('/') {
585            Some(i) => format!("{notebook}:{}/{}", &rel[..i], id),
586            None => format!("{notebook}:{id}"),
587        },
588        None => fallback.to_string(),
589    }
590}
591
592pub(super) fn notebook_dir_from_env(notebook: &str) -> Option<PathBuf> {
593    let nb_dir = std::env::var_os("NB_DIR")?;
594    let path = PathBuf::from(nb_dir).join(notebook);
595    if path.is_dir() && path.join(".git").exists() {
596        Some(path)
597    } else {
598        None
599    }
600}
601
602pub(super) fn path_relative_to(
603    root: &Path,
604    path: &Path,
605) -> Result<String, NbError> {
606    let root = root.canonicalize().map_err(|e| NbError::Io {
607        path: root.to_path_buf(),
608        source: e.into(),
609    })?;
610    let path = path.canonicalize().map_err(|e| NbError::Io {
611        path: path.to_path_buf(),
612        source: e.into(),
613    })?;
614    let rel =
615        path.strip_prefix(&root)
616            .map_err(|_| NbError::ValidationError {
617                reason: format!(
618                    "path {} is not under notebook root {}",
619                    path.display(),
620                    root.display()
621                ),
622                location: None,
623            })?;
624    Ok(rel.to_string_lossy().replace('\\', "/"))
625}