Skip to main content

nb_api/client/
read.rs

1use std::path::{Path, PathBuf};
2
3use crate::argv::search_command_args;
4use crate::error::NbError;
5use crate::fingerprint;
6use crate::gate;
7use crate::lines::{
8    document_lines, note_line_from_body_line, require_contiguous_body,
9    search_lines,
10};
11use crate::output::strip_empty_result_hint;
12use crate::parser::{ParseContext, parse};
13use crate::types::{
14    BodyFragment, NoteTarget, SearchNoteLines, ShowNote, ShowNoteLines,
15};
16use crate::validate::validate_folder_option;
17use crate::{NbClient, SearchMode};
18
19impl NbClient {
20    /// Notebook status from git state, without spawning `nb`:
21    /// porcelain output for the notebook worktree, plus the
22    /// index-only reconciliation note when no note content is
23    /// affected. A missing notebook is terminal `NotFound`, never
24    /// created. (Pre-1.0 break: replaces the verbatim `nb status`
25    /// rendering.)
26    pub async fn show_notebook_status(
27        &self,
28        notebook: Option<&str>,
29    ) -> Result<String, NbError> {
30        let name = self.resolve_notebook_name(notebook)?;
31        let root = self.native_notebook_root(&name).await?;
32        self.with_notebook_gate_native(&root, async {
33            let status = crate::git::notebook_status_porcelain(&root)?;
34            if crate::git::status_is_index_only(&status) {
35                return Ok(format!(
36                    "{status}\n(note: only .index reconciliation is pending; safe to proceed — no note content affected)"
37                ));
38            }
39            Ok(status)
40        })
41        .await
42    }
43
44    /// Lists available notebooks.
45    pub async fn list_notebooks(&self) -> Result<String, NbError> {
46        let _g = gate::acquire_global(self.gate_timeout).await?;
47        // Use --no-color to avoid ANSI escape codes
48        self.exec(&["notebooks", "--no-color"]).await
49    }
50
51    /// Returns the path for a notebook.
52    pub async fn show_notebook_path(
53        &self,
54        notebook: Option<&str>,
55    ) -> Result<PathBuf, NbError> {
56        let notebook = self.resolve_notebook_name(notebook)?;
57        self.ensure_notebook(&notebook).await?;
58        self.with_notebook_gate(
59            &notebook,
60            self.show_notebook_path_unguarded(Some(&notebook)),
61        )
62        .await
63    }
64
65    /// Shows a note as a structured [`ShowNote`] (gate-held).
66    /// Reads resolve via the notebook filesystem plus `.index`
67    /// under one no-ensure gate hold, spawning zero `nb`
68    /// subprocesses. Plain string ids always carry selector
69    /// semantics.
70    pub async fn show_note(
71        &self,
72        id: &str,
73        notebook: Option<&str>,
74    ) -> Result<ShowNote, NbError> {
75        let (notebook, display, input, exact) = self
76            .resolve_read_identity(&NoteTarget::selector(id), notebook)
77            .await?;
78        // No-ensure root BEFORE the gate: the ensuring gate helper
79        // would ensure (and create) a missing notebook.
80        let root = self.native_notebook_root(&notebook).await?;
81        self.with_notebook_gate_native(&root, async {
82            self.show_note_native_inside(
83                &notebook, &display, &input, exact, &root,
84            )
85            .await
86        })
87        .await
88    }
89
90    /// Validate-only qualifier splitting for native reads: notebook
91    /// name, legacy-shaped qualified display, qualifier-stripped
92    /// input, and whether the target needs exact (path) or table
93    /// (selector) resolution. Performs zero I/O and spawns nothing,
94    /// so it runs before the gate; every filesystem touch below
95    /// happens inside one gate hold.
96    async fn resolve_read_identity(
97        &self,
98        target: &NoteTarget,
99        notebook: Option<&str>,
100    ) -> Result<(String, String, String, bool), NbError> {
101        // `input` borrows from `target` (which outlives the call)
102        // while `name` is owned: no borrow conflict.
103        let (name, input, exact): (String, &str, bool) = match target {
104            NoteTarget::Selector { value } => {
105                match crate::validate::parse_qualified_selector(value)? {
106                    Some((embedded, path)) => {
107                        if let Some(field) = notebook {
108                            crate::validate::validate_notebook_name(field)?;
109                            if field != embedded {
110                                return Err(NbError::ValidationError {
111                                    reason: format!(
112                                        "ambiguous selector: id targets notebook `{embedded}`, but notebook field is `{field}`"
113                                    ),
114                                    location: None,
115                                });
116                            }
117                        }
118                        (embedded.to_string(), path, false)
119                    },
120                    None => (
121                        self.resolve_notebook_name(notebook)?,
122                        value.as_str(),
123                        false,
124                    ),
125                }
126            },
127            NoteTarget::Path { value } => {
128                (self.resolve_notebook_name(notebook)?, value.as_str(), true)
129            },
130        };
131        let display = format!("{name}:{input}");
132        Ok((name, display, input.to_string(), exact))
133    }
134
135    /// Map only genuine misses to the display string; I/O failures
136    /// propagate unchanged (never degrade into `NotFound`).
137    fn map_native_miss(display: &str) -> impl Fn(NbError) -> NbError + '_ {
138        move |e| match e {
139            NbError::NotFound { .. } => NbError::NotFound {
140                selector: display.to_string(),
141            },
142            other => other,
143        }
144    }
145
146    /// Native root lookup: `NB_DIR` only, never creates and never
147    /// spawns. A missing notebook is the legacy-shaped qualified
148    /// `NotFound`: reads must not create notebooks as a side effect.
149    /// Genuine filesystem failures (permissions, I/O) propagate as
150    /// `Io` instead of collapsing into `NotFound`.
151    pub(super) async fn native_notebook_root(
152        &self,
153        notebook: &str,
154    ) -> Result<PathBuf, NbError> {
155        match notebook_dir_from_env(notebook, self.require_explicit_nb_dir)? {
156            Some(path) => Ok(path),
157            None => Err(NbError::NotFound {
158                selector: format!("{notebook}:"),
159            }),
160        }
161    }
162
163    /// Classify one id without reading content beyond
164    /// classification: kind, notebook-relative path, shadow-aware
165    /// canonical selector, and numeric id when listed. Plain ids
166    /// carry selector semantics; notebook qualification resolves
167    /// upstream. Side-effect-free: filesystem plus `.index` under
168    /// the gate, zero spawns.
169    pub async fn classify(
170        &self,
171        id: &str,
172        notebook: Option<&str>,
173    ) -> Result<crate::Classify, NbError> {
174        let (notebook, display, input, exact) = self
175            .resolve_read_identity(&NoteTarget::selector(id), notebook)
176            .await?;
177        let root = self.native_notebook_root(&notebook).await?;
178        self.with_notebook_gate_native(&root, async {
179            let rel = if exact {
180                crate::native::resolve_exact(&root, &input)
181            } else {
182                crate::native::resolve_selector(&root, &input)
183            }
184            .map_err(Self::map_native_miss(&display))?;
185            let abs = root.join(&rel);
186            let abs = crate::native::confine_canonical(&root, &abs, &display)?;
187            let class = crate::native::classify_path(&abs, &rel)?;
188            let kind = crate::native::entity_kind_for_rel(&rel, &class);
189            let selector =
190                crate::native::canonical_selector(&notebook, &root, &rel)?;
191            let numeric_id = crate::native::numeric_id_for_rel(&root, &rel)?;
192            Ok(crate::Classify {
193                kind,
194                path: rel,
195                selector,
196                numeric_id,
197            })
198        })
199        .await
200    }
201
202    /// Native inside-gate read: variant-preserving resolution,
203    /// canonical containment, classification, then the native
204    /// read-and-parse tail. The caller resolves `root` (no-ensure,
205    /// no-spawn) before acquiring the no-ensure native gate;
206    /// everything filesystem-touching happens inside that one gate
207    /// hold: no interleaved commits can invalidate the lookup or
208    /// serve stale content.
209    async fn show_note_native_inside(
210        &self,
211        notebook: &str,
212        display: &str,
213        input: &str,
214        exact: bool,
215        root: &Path,
216    ) -> Result<ShowNote, NbError> {
217        let rel = if exact {
218            crate::native::resolve_exact(root, input)
219        } else {
220            crate::native::resolve_selector(root, input)
221        }
222        .map_err(Self::map_native_miss(display))?;
223        let abs = root.join(&rel);
224        let abs = crate::native::confine_canonical(root, &abs, display)?;
225        match crate::native::classify_path(&abs, &rel)? {
226            crate::native::NativeClass::Folder => {
227                return Err(NbError::UnsupportedShowTarget {
228                    selector: display.to_string(),
229                    actual_type: "folder".to_string(),
230                });
231            },
232            crate::native::NativeClass::NonTextual { ext } => {
233                return Err(NbError::UnsupportedShowTarget {
234                    selector: display.to_string(),
235                    actual_type: ext,
236                });
237            },
238            crate::native::NativeClass::Text => {},
239        }
240        self.show_note_from_path(notebook, display, root, &abs)
241            .await
242    }
243
244    /// Read-and-parse tail: canonical rel, source bytes, document
245    /// partition, and structured [`ShowNote`] assembly.
246    /// Diagnostic errors (e.g. `NonUtf8`) carry the requested
247    /// display selector; only a successful payload carries the
248    /// shadow-checked canonical form, with the numeric id from the
249    /// confined fallible lookup.
250    async fn show_note_from_path(
251        &self,
252        notebook: &str,
253        display: &str,
254        root: &Path,
255        path: &Path,
256    ) -> Result<ShowNote, NbError> {
257        let rel = path_relative_to(root, path)?;
258        let source = std::fs::read(path).map_err(|e| NbError::Io {
259            path: path.to_path_buf(),
260            source: e.into(),
261        })?;
262        let canonical =
263            crate::native::canonical_selector(notebook, root, &rel)?;
264        let numeric_id = crate::native::numeric_id_for_rel(root, &rel)?;
265        Self::assemble_show_note(display, &canonical, numeric_id, rel, source)
266    }
267    /// Structured [`ShowNote`] assembly from resolved parts: document
268    /// partition, fragments, titles, and fingerprint. `diagnostic`
269    /// is the requested selector for error payloads; `canonical` is
270    /// the success-payload selector.
271    fn assemble_show_note(
272        diagnostic: &str,
273        canonical: &str,
274        numeric_id: Option<u32>,
275        rel: String,
276        source: Vec<u8>,
277    ) -> Result<ShowNote, NbError> {
278        let doc = match parse(
279            &source,
280            ParseContext::FromPath(PathBuf::from(&rel)),
281        ) {
282            Ok(doc) => doc,
283            // nb may classify additional textual extensions as showable; map
284            // unrecognized formats to a Note partition for structured show.
285            Err(NbError::UnsupportedDocumentFormat { .. }) => parse(
286                &source,
287                ParseContext::Explicit(crate::DocumentKind::Note),
288            )?,
289            Err(err) => return Err(err),
290        };
291        let kind_str = format!("{:?}", doc.kind()).to_lowercase();
292        let non_utf8 = |path: String| NbError::NonUtf8 {
293            selector: diagnostic.to_string(),
294            path,
295            kind: kind_str.clone(),
296            mime_hint: None,
297        };
298        let source_str = std::str::from_utf8(&source)
299            .map_err(|_| non_utf8(rel.clone()))?
300            .to_string();
301        // Fragment offsets into `source`: body_ranges are source-absolute.
302        let ranges = doc.body_ranges();
303        let mut fragments: Vec<BodyFragment> =
304            Vec::with_capacity(ranges.len());
305        for (i, span) in ranges.iter().enumerate() {
306            let bytes = std::str::from_utf8(&source[span.clone()])
307                .map_err(|_| non_utf8(rel.clone()))?
308                .to_string();
309            fragments.push(BodyFragment {
310                index: i as u32,
311                bytes,
312                start_byte: span.start as u32,
313                end_byte: span.end as u32,
314            });
315        }
316        let body_contiguous = fragments.len() <= 1;
317        let body_bytes = doc.body_bytes();
318        let body = std::str::from_utf8(&body_bytes)
319            .map_err(|_| non_utf8(rel.clone()))?
320            .to_string();
321        // Lossy convenience strings; raw title bytes remain authoritative.
322        let tags: Vec<String> = doc
323            .tags()
324            .map(|t| {
325                String::from_utf8_lossy(t)
326                    .trim_start_matches('#')
327                    .to_string()
328            })
329            .collect();
330        let title = doc
331            .title()
332            .map(|bytes| std::str::from_utf8(bytes).map(str::to_string))
333            .transpose()
334            .map_err(|_| non_utf8(rel.clone()))?;
335        let title_text = doc.title().map(|bytes| {
336            let s = String::from_utf8_lossy(bytes);
337            s.trim_end_matches('\n')
338                .trim_start_matches('#')
339                .trim()
340                .to_string()
341        });
342        Ok(ShowNote {
343            selector: canonical.to_string(),
344            path: rel.clone(),
345            kind: doc.kind(),
346            todo_state: doc.todo_state(),
347            title,
348            title_text,
349            tags,
350            body_fragments: fragments,
351            body_contiguous,
352            body,
353            fingerprint: fingerprint::fingerprint(&doc),
354            source: source_str,
355            numeric_id,
356        })
357    }
358
359    /// Raw-bytes escape hatch: full file bytes without UTF-8 validation.
360    ///
361    /// This is the only public read that returns `Vec<u8>`; every other
362    /// structured read is text-only and returns `NonUtf8` on invalid UTF-8.
363    pub async fn read_note_source_bytes(
364        &self,
365        target: NoteTarget,
366        notebook: Option<&str>,
367    ) -> Result<Vec<u8>, NbError> {
368        // Reads resolve via the notebook filesystem plus `.index`
369        // with canonical containment inside one gate hold (escapes
370        // read as `NotFound`, never foreign bytes), zero `nb` spawns.
371        let (notebook, display, input, exact) =
372            self.resolve_read_identity(&target, notebook).await?;
373        // No-ensure root BEFORE the gate: the ensuring gate helper
374        // would ensure (and create) a missing notebook.
375        let root = self.native_notebook_root(&notebook).await?;
376        self.with_notebook_gate_native(&root, async {
377            let rel = if exact {
378                crate::native::resolve_exact(&root, &input)
379            } else {
380                crate::native::resolve_selector(&root, &input)
381            }
382            .map_err(Self::map_native_miss(&display))?;
383            let abs = root.join(&rel);
384            let abs = crate::native::confine_canonical(&root, &abs, &display)?;
385            std::fs::read(&abs).map_err(|e| NbError::Io {
386                path: abs.clone(),
387                source: e.into(),
388            })
389        })
390        .await
391    }
392
393    /// Enumerate body lines for a contiguous-body note.
394    pub async fn show_note_lines(
395        &self,
396        target: NoteTarget,
397        offset: Option<u32>,
398        limit: Option<u32>,
399        notebook: Option<&str>,
400    ) -> Result<ShowNoteLines, NbError> {
401        // Reads resolve via the filesystem plus `.index` with the
402        // native show tail inside one gate hold, zero `nb` spawns.
403        let (notebook, display, input, exact) =
404            self.resolve_read_identity(&target, notebook).await?;
405        // No-ensure root BEFORE the gate: the ensuring gate helper
406        // would ensure (and create) a missing notebook.
407        let root = self.native_notebook_root(&notebook).await?;
408        self.with_notebook_gate_native(&root, async {
409            let shown = self
410                .show_note_native_inside(
411                    &notebook, &display, &input, exact, &root,
412                )
413                .await?;
414            Self::show_lines_window(shown, offset, limit)
415        })
416        .await
417    }
418
419    /// Window one contiguous body into [`ShowNoteLines`].
420    /// Pure projection over an already-read [`ShowNote`].
421    fn show_lines_window(
422        shown: ShowNote,
423        offset: Option<u32>,
424        limit: Option<u32>,
425    ) -> Result<ShowNoteLines, NbError> {
426        let source = shown.source.as_bytes().to_vec();
427        let doc = parse(
428            &source,
429            ParseContext::FromPath(PathBuf::from(&shown.path)),
430        )?;
431        let body = require_contiguous_body(&doc)?;
432        let (eol, has_final_eol, lines) = document_lines(&body);
433        let total_lines = lines.len() as u32;
434        let offset = offset.unwrap_or(1);
435        let limit = limit.unwrap_or(100);
436        if offset == 0 {
437            return Err(NbError::InvalidLineWindow {
438                offset,
439                limit,
440                total_lines,
441            });
442        }
443        if total_lines == 0 {
444            if offset != 1 {
445                return Err(NbError::InvalidLineWindow {
446                    offset,
447                    limit,
448                    total_lines,
449                });
450            }
451            return Ok(ShowNoteLines {
452                selector: shown.selector,
453                path: shown.path,
454                kind: shown.kind,
455                total_lines: 0,
456                offset,
457                limit,
458                next_offset: None,
459                lines: Vec::new(),
460                title: shown.title,
461                tags: shown.tags,
462                body_fingerprint: shown.fingerprint,
463                eol: None,
464                has_final_eol: false,
465                numeric_id: shown.numeric_id,
466            });
467        }
468        if offset > total_lines + 1 {
469            return Err(NbError::InvalidLineWindow {
470                offset,
471                limit,
472                total_lines,
473            });
474        }
475        let start_idx = (offset - 1) as usize;
476        let end_idx = (start_idx + limit as usize).min(lines.len());
477        let window: Vec<_> = lines[start_idx..end_idx]
478            .iter()
479            .map(|l| note_line_from_body_line(l, &body))
480            .collect();
481        let next_offset = if end_idx < lines.len() {
482            Some(offset + window.len() as u32)
483        } else {
484            None
485        };
486        Ok(ShowNoteLines {
487            selector: shown.selector,
488            path: shown.path,
489            kind: shown.kind,
490            total_lines,
491            offset,
492            limit,
493            next_offset,
494            lines: window,
495            title: shown.title,
496            tags: shown.tags,
497            body_fingerprint: shown.fingerprint,
498            eol,
499            has_final_eol,
500            numeric_id: shown.numeric_id,
501        })
502    }
503
504    /// Search body line texts for a pattern (contiguous body only).
505    pub async fn search_note_lines(
506        &self,
507        target: NoteTarget,
508        pattern: &str,
509        notebook: Option<&str>,
510    ) -> Result<SearchNoteLines, NbError> {
511        // Reads resolve via the filesystem plus `.index`; see
512        // `show_note_lines`.
513        let (notebook, display, input, exact) =
514            self.resolve_read_identity(&target, notebook).await?;
515        // No-ensure root BEFORE the gate: the ensuring gate helper
516        // would ensure (and create) a missing notebook.
517        let root = self.native_notebook_root(&notebook).await?;
518        // `pattern` is borrowed across the gate future; copy the
519        // small query string so the future owns its inputs.
520        let pattern = pattern.to_string();
521        self.with_notebook_gate_native(&root, async {
522            let shown = self
523                .show_note_native_inside(
524                    &notebook, &display, &input, exact, &root,
525                )
526                .await?;
527            Self::search_lines_hits(shown, &pattern)
528        })
529        .await
530    }
531
532    /// Search one contiguous body for a pattern.
533    /// Pure projection over an already-read [`ShowNote`].
534    fn search_lines_hits(
535        shown: ShowNote,
536        pattern: &str,
537    ) -> Result<SearchNoteLines, NbError> {
538        let source = shown.source.as_bytes().to_vec();
539        let doc = parse(
540            &source,
541            ParseContext::FromPath(PathBuf::from(&shown.path)),
542        )?;
543        let body = require_contiguous_body(&doc)?;
544        let hits = search_lines(&body, pattern.as_bytes())?;
545        Ok(SearchNoteLines {
546            selector: shown.selector,
547            path: shown.path,
548            kind: shown.kind,
549            hits,
550            body_fingerprint: shown.fingerprint,
551        })
552    }
553
554    /// Lists notes in a notebook or folder.
555    pub async fn list_notes(
556        &self,
557        folder: Option<&str>,
558        tags: &[String],
559        limit: Option<u32>,
560        notebook: Option<&str>,
561    ) -> Result<String, NbError> {
562        let mut args = Vec::new();
563        validate_folder_option(folder)?;
564
565        let notebook = self.resolve_notebook(notebook).await?;
566        let cmd = match folder {
567            Some(f) => format!("{}:{}/", notebook, f),
568            None => format!("{}:", notebook),
569        };
570
571        args.push("list".to_string());
572        args.push(cmd);
573
574        // No color for parsing
575        args.push("--no-color".to_string());
576
577        // Limit
578        if let Some(n) = limit {
579            args.push("-n".to_string());
580            args.push(n.to_string());
581        }
582
583        // Tags filter
584        for tag in tags {
585            args.push("--tags".to_string());
586            let tag_str = if tag.starts_with('#') {
587                tag.clone()
588            } else {
589                format!("#{}", tag)
590            };
591            args.push(tag_str);
592        }
593
594        // Strip the trailing usage/help hint block from empty
595        // results (`0 items.` followed by `Add a note:`,
596        // `Import a file:`, `Help information:`). Detection
597        // keys off the empty-result signal per the
598        // `output-behavior` specification. See `output.rs`
599        // for the helper's contract.
600        self.exec_vec(args)
601            .await
602            .map(|output| strip_empty_result_hint(&output))
603    }
604
605    /// Searches notes.
606    pub async fn search_notes(
607        &self,
608        queries: &[String],
609        mode: SearchMode,
610        tags: &[String],
611        folder: Option<&str>,
612        notebook: Option<&str>,
613    ) -> Result<String, NbError> {
614        validate_folder_option(folder)?;
615        if queries.is_empty() {
616            return Err(NbError::ValidationError {
617                reason: "at least one search query is required".to_string(),
618                location: None,
619            });
620        }
621
622        let notebook = self.resolve_notebook(notebook).await?;
623        let scope = match folder {
624            Some(f) => format!("{}:{}/", notebook, f),
625            None => format!("{}:", notebook),
626        };
627        let args = search_command_args(scope, queries, mode, tags);
628        self.exec_vec(args).await
629    }
630
631    /// Searches notes natively: recursive text-file walk under the
632    /// scope, case-insensitive substring match of the queries
633    /// against title plus body text (`Any`/`All` across queries),
634    /// tag-filtered like the typed list. Returns lexical
635    /// [`crate::ListEntry`] values. Empty queries are
636    /// `ValidationError`. Zero `nb` spawns.
637    pub async fn search_notes_typed(
638        &self,
639        queries: &[String],
640        mode: SearchMode,
641        tags: &[String],
642        folder: Option<&str>,
643        notebook: Option<&str>,
644    ) -> Result<Vec<crate::ListEntry>, NbError> {
645        validate_folder_option(folder)?;
646        if queries.is_empty() {
647            return Err(NbError::ValidationError {
648                reason: "at least one search query is required".to_string(),
649                location: None,
650            });
651        }
652        let notebook = self.resolve_notebook_name(notebook)?;
653        let root = self.native_notebook_root(&notebook).await?;
654        // Leading slashes are NOT trimmed: absolute forms
655        // fail closed as NotFound inside confinement.
656        let scope = folder.unwrap_or_default().to_string();
657        let lowered: Vec<String> =
658            queries.iter().map(|q| q.to_lowercase()).collect();
659        self.with_notebook_gate_native(&root, async {
660            let mut out = Vec::new();
661            for rel in crate::scope::scope_files_recursive(&root, &scope)? {
662                let abs = root.join(&rel);
663                let bytes = std::fs::read(&abs).map_err(|e| NbError::Io {
664                    path: abs.clone(),
665                    source: e.into(),
666                })?;
667                // Textual files only; unparseable content never
668                // matches.
669                if !matches!(
670                    crate::native::classify_path(&abs, &rel)?,
671                    crate::native::NativeClass::Text
672                ) {
673                    continue;
674                }
675                if !Self::tags_match(&bytes, &rel, tags) {
676                    continue;
677                }
678                let doc = match parse(
679                    &bytes,
680                    ParseContext::FromPath(rel.clone().into()),
681                ) {
682                    Ok(doc) => doc,
683                    Err(_) => continue,
684                };
685                let mut haystack = String::new();
686                if let Some(title) = doc.title() {
687                    haystack.push_str(&String::from_utf8_lossy(title));
688                    haystack.push('\n');
689                }
690                haystack.push_str(&String::from_utf8_lossy(&doc.body_bytes()));
691                let haystack = haystack.to_lowercase();
692                let matched = match mode {
693                    SearchMode::Any => {
694                        lowered.iter().any(|q| haystack.contains(q))
695                    },
696                    SearchMode::All => {
697                        lowered.iter().all(|q| haystack.contains(q))
698                    },
699                };
700                if !matched {
701                    continue;
702                }
703                out.push(self.list_entry_for(&notebook, &root, &rel).await?);
704            }
705            Ok(out)
706        })
707        .await
708    }
709
710    /// Assemble one typed list entry for an in-scope relative
711    /// path: shadow-aware canonical selector plus confined
712    /// numeric id. The caller holds the gate and the path comes
713    /// from a symlink-free scope enumeration.
714    pub(super) async fn list_entry_for(
715        &self,
716        notebook: &str,
717        root: &Path,
718        rel: &str,
719    ) -> Result<crate::ListEntry, NbError> {
720        let abs = root.join(rel);
721        let display = format!("{notebook}:{rel}");
722        let abs = crate::native::confine_canonical(root, &abs, &display)?;
723        let class = crate::native::classify_path(&abs, rel)?;
724        let kind = crate::native::entity_kind_for_rel(rel, &class);
725        let selector = crate::native::canonical_selector(notebook, root, rel)?;
726        let numeric_id = crate::native::numeric_id_for_rel(root, rel)?;
727        Ok(crate::ListEntry {
728            selector,
729            path: rel.to_string(),
730            kind,
731            numeric_id,
732        })
733    }
734
735    /// Whether file bytes carry all requested tags. Unparseable
736    /// content never matches a non-empty filter.
737    fn tags_match(bytes: &[u8], rel: &str, tags: &[String]) -> bool {
738        if tags.is_empty() {
739            return true;
740        }
741        let doc = match parse(bytes, ParseContext::FromPath(rel.into())) {
742            Ok(doc) => doc,
743            Err(_) => return false,
744        };
745        let have: Vec<String> = doc
746            .tags()
747            .map(|t| {
748                String::from_utf8_lossy(t)
749                    .trim_start_matches('#')
750                    .to_string()
751            })
752            .collect();
753        tags.iter().all(|wanted| {
754            let want = wanted.trim_start_matches('#');
755            have.iter().any(|got| got == want)
756        })
757    }
758
759    /// Lists notes in a notebook or folder as typed entries:
760    /// one [`crate::ListEntry`] per file directly under the scope
761    /// (non-recursive), excluding dotfiles and symlinks, ordered
762    /// lexically by relative path. Tags filter by parsed document
763    /// tags (all must match); `limit` takes the first N. A missing
764    /// scope is terminal `NotFound`. Zero `nb` spawns.
765    pub async fn list_notes_typed(
766        &self,
767        folder: Option<&str>,
768        tags: &[String],
769        limit: Option<u32>,
770        notebook: Option<&str>,
771    ) -> Result<Vec<crate::ListEntry>, NbError> {
772        validate_folder_option(folder)?;
773        let notebook = self.resolve_notebook_name(notebook)?;
774        let root = self.native_notebook_root(&notebook).await?;
775        // Leading slashes are NOT trimmed: absolute forms
776        // fail closed as NotFound inside confinement.
777        let scope = folder.unwrap_or_default().to_string();
778        self.with_notebook_gate_native(&root, async {
779            let mut out = Vec::new();
780            for rel in crate::scope::scope_files(&root, &scope)? {
781                if let Some(n) = limit
782                    && out.len() >= n as usize
783                {
784                    break;
785                }
786                let abs = root.join(&rel);
787                let bytes = std::fs::read(&abs).map_err(|e| NbError::Io {
788                    path: abs.clone(),
789                    source: e.into(),
790                })?;
791                if !Self::tags_match(&bytes, &rel, tags) {
792                    continue;
793                }
794                out.push(self.list_entry_for(&notebook, &root, &rel).await?);
795            }
796            Ok(out)
797        })
798        .await
799    }
800}
801
802/// Notebook dir from the environment: `<store>/<notebook>`
803/// when present, without creating, ensuring, or spawning. The
804/// store resolves as explicit `NB_DIR`, else the parsed `~/.nbrc`
805/// value, else `~/.nb` (see [`crate::nbrc`]); strict mode skips the
806/// file fallback and fails unset `NB_DIR` as a configuration
807/// error. Genuine filesystem failures propagate; only true absence
808/// maps to `None`.
809pub(super) fn notebook_dir_from_env(
810    notebook: &str,
811    strict: bool,
812) -> Result<Option<PathBuf>, NbError> {
813    let nb_dir = crate::nbrc::resolve_store_dir(strict)?;
814    let path = nb_dir.join(notebook);
815    // `metadata` follows symlinks exactly like the previous
816    // `is_dir` check; only genuine misses map to `None` while
817    // permission and I/O failures propagate instead of collapsing
818    // into `NotFound`.
819    match std::fs::metadata(&path) {
820        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
821        Err(e) => Err(NbError::Io {
822            path: path.clone(),
823            source: e.into(),
824        }),
825        Ok(m) if !m.is_dir() => Ok(None),
826        Ok(_) => match std::fs::metadata(path.join(".git")) {
827            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
828            Err(e) => Err(NbError::Io {
829                path: path.join(".git"),
830                source: e.into(),
831            }),
832            Ok(_) => Ok(Some(path)),
833        },
834    }
835}
836
837pub(super) fn path_relative_to(
838    root: &Path,
839    path: &Path,
840) -> Result<String, NbError> {
841    let root = root.canonicalize().map_err(|e| NbError::Io {
842        path: root.to_path_buf(),
843        source: e.into(),
844    })?;
845    let path = path.canonicalize().map_err(|e| NbError::Io {
846        path: path.to_path_buf(),
847        source: e.into(),
848    })?;
849    let rel =
850        path.strip_prefix(&root)
851            .map_err(|_| NbError::ValidationError {
852                reason: format!(
853                    "path {} is not under notebook root {}",
854                    path.display(),
855                    root.display()
856                ),
857                location: None,
858            })?;
859    // On Windows the canonical form uses `\` separators, which
860    // are normalized here. On Unix a backslash is an ordinary
861    // filename character (e.g. a literal `a\b` file) and must be
862    // preserved verbatim.
863    #[cfg(windows)]
864    {
865        Ok(rel.to_string_lossy().replace('\\', "/"))
866    }
867    #[cfg(not(windows))]
868    {
869        Ok(rel.to_string_lossy().into_owned())
870    }
871}