nb-api 0.4.5

Typed Rust interface to the nb note-taking CLI (subprocess wrapper: escaping, validation, output parsing)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
use std::path::{Path, PathBuf};

use crate::argv::search_command_args;
use crate::error::NbError;
use crate::fingerprint;
use crate::gate;
use crate::lines::{
    document_lines, note_line_from_body_line, require_contiguous_body,
    search_lines,
};
use crate::output::strip_empty_result_hint;
use crate::parser::{ParseContext, parse};
use crate::types::{
    BodyFragment, NoteTarget, SearchNoteLines, ShowNote, ShowNoteLines,
};
use crate::validate::validate_folder_option;
use crate::{NbClient, SearchMode};

impl NbClient {
    /// Notebook status from git state, without spawning `nb`:
    /// porcelain output for the notebook worktree, plus the
    /// index-only reconciliation note when no note content is
    /// affected. A missing notebook is terminal `NotFound`, never
    /// created. (Pre-1.0 break: replaces the verbatim `nb status`
    /// rendering.)
    pub async fn show_notebook_status(
        &self,
        notebook: Option<&str>,
    ) -> Result<String, NbError> {
        let name = self.resolve_notebook_name(notebook)?;
        let root = self.native_notebook_root(&name).await?;
        self.with_notebook_gate_native(&root, async {
            let status = crate::git::notebook_status_porcelain(&root)?;
            if crate::git::status_is_index_only(&status) {
                return Ok(format!(
                    "{status}\n(note: only .index reconciliation is pending; safe to proceed — no note content affected)"
                ));
            }
            Ok(status)
        })
        .await
    }

    /// Lists available notebooks.
    pub async fn list_notebooks(&self) -> Result<String, NbError> {
        let _g = gate::acquire_global(self.gate_timeout).await?;
        // Use --no-color to avoid ANSI escape codes
        self.exec(&["notebooks", "--no-color"]).await
    }

    /// Returns the path for a notebook.
    pub async fn show_notebook_path(
        &self,
        notebook: Option<&str>,
    ) -> Result<PathBuf, NbError> {
        let notebook = self.resolve_notebook_name(notebook)?;
        self.ensure_notebook(&notebook).await?;
        self.with_notebook_gate(
            &notebook,
            self.show_notebook_path_unguarded(Some(&notebook)),
        )
        .await
    }

    /// Shows a note as a structured [`ShowNote`] (gate-held).
    /// Reads resolve via the notebook filesystem plus `.index`
    /// under one no-ensure gate hold, spawning zero `nb`
    /// subprocesses. Plain string ids always carry selector
    /// semantics.
    pub async fn show_note(
        &self,
        id: &str,
        notebook: Option<&str>,
    ) -> Result<ShowNote, NbError> {
        let (notebook, display, input, exact) = self
            .resolve_read_identity(&NoteTarget::selector(id), notebook)
            .await?;
        // No-ensure root BEFORE the gate: the ensuring gate helper
        // would ensure (and create) a missing notebook.
        let root = self.native_notebook_root(&notebook).await?;
        self.with_notebook_gate_native(&root, async {
            self.show_note_native_inside(
                &notebook, &display, &input, exact, &root,
            )
            .await
        })
        .await
    }

    /// Validate-only qualifier splitting for native reads: notebook
    /// name, legacy-shaped qualified display, qualifier-stripped
    /// input, and whether the target needs exact (path) or table
    /// (selector) resolution. Performs zero I/O and spawns nothing,
    /// so it runs before the gate; every filesystem touch below
    /// happens inside one gate hold.
    async fn resolve_read_identity(
        &self,
        target: &NoteTarget,
        notebook: Option<&str>,
    ) -> Result<(String, String, String, bool), NbError> {
        // `input` borrows from `target` (which outlives the call)
        // while `name` is owned: no borrow conflict.
        let (name, input, exact): (String, &str, bool) = match target {
            NoteTarget::Selector { value } => {
                match crate::validate::parse_qualified_selector(value)? {
                    Some((embedded, path)) => {
                        if let Some(field) = notebook {
                            crate::validate::validate_notebook_name(field)?;
                            if field != embedded {
                                return Err(NbError::ValidationError {
                                    reason: format!(
                                        "ambiguous selector: id targets notebook `{embedded}`, but notebook field is `{field}`"
                                    ),
                                    location: None,
                                });
                            }
                        }
                        (embedded.to_string(), path, false)
                    },
                    None => (
                        self.resolve_notebook_name(notebook)?,
                        value.as_str(),
                        false,
                    ),
                }
            },
            NoteTarget::Path { value } => {
                (self.resolve_notebook_name(notebook)?, value.as_str(), true)
            },
        };
        let display = format!("{name}:{input}");
        Ok((name, display, input.to_string(), exact))
    }

    /// Map only genuine misses to the display string; I/O failures
    /// propagate unchanged (never degrade into `NotFound`).
    fn map_native_miss(display: &str) -> impl Fn(NbError) -> NbError + '_ {
        move |e| match e {
            NbError::NotFound { .. } => NbError::NotFound {
                selector: display.to_string(),
            },
            other => other,
        }
    }

    /// Native root lookup: `NB_DIR` only, never creates and never
    /// spawns. A missing notebook is the legacy-shaped qualified
    /// `NotFound`: reads must not create notebooks as a side effect.
    /// Genuine filesystem failures (permissions, I/O) propagate as
    /// `Io` instead of collapsing into `NotFound`.
    pub(super) async fn native_notebook_root(
        &self,
        notebook: &str,
    ) -> Result<PathBuf, NbError> {
        match notebook_dir_from_env(notebook)? {
            Some(path) => Ok(path),
            None => Err(NbError::NotFound {
                selector: format!("{notebook}:"),
            }),
        }
    }

    /// Classify one id without reading content beyond
    /// classification: kind, notebook-relative path, shadow-aware
    /// canonical selector, and numeric id when listed. Plain ids
    /// carry selector semantics; notebook qualification resolves
    /// upstream. Side-effect-free: filesystem plus `.index` under
    /// the gate, zero spawns.
    pub async fn classify(
        &self,
        id: &str,
        notebook: Option<&str>,
    ) -> Result<crate::Classify, NbError> {
        let (notebook, display, input, exact) = self
            .resolve_read_identity(&NoteTarget::selector(id), notebook)
            .await?;
        let root = self.native_notebook_root(&notebook).await?;
        self.with_notebook_gate_native(&root, async {
            let rel = if exact {
                crate::native::resolve_exact(&root, &input)
            } else {
                crate::native::resolve_selector(&root, &input)
            }
            .map_err(Self::map_native_miss(&display))?;
            let abs = root.join(&rel);
            let abs = crate::native::confine_canonical(&root, &abs, &display)?;
            let class = crate::native::classify_path(&abs, &rel)?;
            let kind = crate::native::entity_kind_for_rel(&rel, &class);
            let selector =
                crate::native::canonical_selector(&notebook, &root, &rel)?;
            let numeric_id = crate::native::numeric_id_for_rel(&root, &rel)?;
            Ok(crate::Classify {
                kind,
                path: rel,
                selector,
                numeric_id,
            })
        })
        .await
    }

    /// Native inside-gate read: variant-preserving resolution,
    /// canonical containment, classification, then the native
    /// read-and-parse tail. The caller resolves `root` (no-ensure,
    /// no-spawn) before acquiring the no-ensure native gate;
    /// everything filesystem-touching happens inside that one gate
    /// hold: no interleaved commits can invalidate the lookup or
    /// serve stale content.
    async fn show_note_native_inside(
        &self,
        notebook: &str,
        display: &str,
        input: &str,
        exact: bool,
        root: &Path,
    ) -> Result<ShowNote, NbError> {
        let rel = if exact {
            crate::native::resolve_exact(root, input)
        } else {
            crate::native::resolve_selector(root, input)
        }
        .map_err(Self::map_native_miss(display))?;
        let abs = root.join(&rel);
        let abs = crate::native::confine_canonical(root, &abs, display)?;
        match crate::native::classify_path(&abs, &rel)? {
            crate::native::NativeClass::Folder => {
                return Err(NbError::UnsupportedShowTarget {
                    selector: display.to_string(),
                    actual_type: "folder".to_string(),
                });
            },
            crate::native::NativeClass::NonTextual { ext } => {
                return Err(NbError::UnsupportedShowTarget {
                    selector: display.to_string(),
                    actual_type: ext,
                });
            },
            crate::native::NativeClass::Text => {},
        }
        self.show_note_from_path(notebook, display, root, &abs)
            .await
    }

    /// Read-and-parse tail: canonical rel, source bytes, document
    /// partition, and structured [`ShowNote`] assembly.
    /// Diagnostic errors (e.g. `NonUtf8`) carry the requested
    /// display selector; only a successful payload carries the
    /// shadow-checked canonical form, with the numeric id from the
    /// confined fallible lookup.
    async fn show_note_from_path(
        &self,
        notebook: &str,
        display: &str,
        root: &Path,
        path: &Path,
    ) -> Result<ShowNote, NbError> {
        let rel = path_relative_to(root, path)?;
        let source = std::fs::read(path).map_err(|e| NbError::Io {
            path: path.to_path_buf(),
            source: e.into(),
        })?;
        let canonical =
            crate::native::canonical_selector(notebook, root, &rel)?;
        let numeric_id = crate::native::numeric_id_for_rel(root, &rel)?;
        Self::assemble_show_note(display, &canonical, numeric_id, rel, source)
    }
    /// Structured [`ShowNote`] assembly from resolved parts: document
    /// partition, fragments, titles, and fingerprint. `diagnostic`
    /// is the requested selector for error payloads; `canonical` is
    /// the success-payload selector.
    fn assemble_show_note(
        diagnostic: &str,
        canonical: &str,
        numeric_id: Option<u32>,
        rel: String,
        source: Vec<u8>,
    ) -> Result<ShowNote, NbError> {
        let doc = match parse(
            &source,
            ParseContext::FromPath(PathBuf::from(&rel)),
        ) {
            Ok(doc) => doc,
            // nb may classify additional textual extensions as showable; map
            // unrecognized formats to a Note partition for structured show.
            Err(NbError::UnsupportedDocumentFormat { .. }) => parse(
                &source,
                ParseContext::Explicit(crate::DocumentKind::Note),
            )?,
            Err(err) => return Err(err),
        };
        let kind_str = format!("{:?}", doc.kind()).to_lowercase();
        let non_utf8 = |path: String| NbError::NonUtf8 {
            selector: diagnostic.to_string(),
            path,
            kind: kind_str.clone(),
            mime_hint: None,
        };
        let source_str = std::str::from_utf8(&source)
            .map_err(|_| non_utf8(rel.clone()))?
            .to_string();
        // Fragment offsets into `source`: body_ranges are source-absolute.
        let ranges = doc.body_ranges();
        let mut fragments: Vec<BodyFragment> =
            Vec::with_capacity(ranges.len());
        for (i, span) in ranges.iter().enumerate() {
            let bytes = std::str::from_utf8(&source[span.clone()])
                .map_err(|_| non_utf8(rel.clone()))?
                .to_string();
            fragments.push(BodyFragment {
                index: i as u32,
                bytes,
                start_byte: span.start as u32,
                end_byte: span.end as u32,
            });
        }
        let body_contiguous = fragments.len() <= 1;
        let body_bytes = doc.body_bytes();
        let body = std::str::from_utf8(&body_bytes)
            .map_err(|_| non_utf8(rel.clone()))?
            .to_string();
        // Lossy convenience strings; raw title bytes remain authoritative.
        let tags: Vec<String> = doc
            .tags()
            .map(|t| {
                String::from_utf8_lossy(t)
                    .trim_start_matches('#')
                    .to_string()
            })
            .collect();
        let title = doc
            .title()
            .map(|bytes| std::str::from_utf8(bytes).map(str::to_string))
            .transpose()
            .map_err(|_| non_utf8(rel.clone()))?;
        let title_text = doc.title().map(|bytes| {
            let s = String::from_utf8_lossy(bytes);
            s.trim_end_matches('\n')
                .trim_start_matches('#')
                .trim()
                .to_string()
        });
        Ok(ShowNote {
            selector: canonical.to_string(),
            path: rel.clone(),
            kind: doc.kind(),
            todo_state: doc.todo_state(),
            title,
            title_text,
            tags,
            body_fragments: fragments,
            body_contiguous,
            body,
            fingerprint: fingerprint::fingerprint(&doc),
            source: source_str,
            numeric_id,
        })
    }

    /// Raw-bytes escape hatch: full file bytes without UTF-8 validation.
    ///
    /// This is the only public read that returns `Vec<u8>`; every other
    /// structured read is text-only and returns `NonUtf8` on invalid UTF-8.
    pub async fn read_note_source_bytes(
        &self,
        target: NoteTarget,
        notebook: Option<&str>,
    ) -> Result<Vec<u8>, NbError> {
        // Reads resolve via the notebook filesystem plus `.index`
        // with canonical containment inside one gate hold (escapes
        // read as `NotFound`, never foreign bytes), zero `nb` spawns.
        let (notebook, display, input, exact) =
            self.resolve_read_identity(&target, notebook).await?;
        // No-ensure root BEFORE the gate: the ensuring gate helper
        // would ensure (and create) a missing notebook.
        let root = self.native_notebook_root(&notebook).await?;
        self.with_notebook_gate_native(&root, async {
            let rel = if exact {
                crate::native::resolve_exact(&root, &input)
            } else {
                crate::native::resolve_selector(&root, &input)
            }
            .map_err(Self::map_native_miss(&display))?;
            let abs = root.join(&rel);
            let abs = crate::native::confine_canonical(&root, &abs, &display)?;
            std::fs::read(&abs).map_err(|e| NbError::Io {
                path: abs.clone(),
                source: e.into(),
            })
        })
        .await
    }

    /// Enumerate body lines for a contiguous-body note.
    pub async fn show_note_lines(
        &self,
        target: NoteTarget,
        offset: Option<u32>,
        limit: Option<u32>,
        notebook: Option<&str>,
    ) -> Result<ShowNoteLines, NbError> {
        // Reads resolve via the filesystem plus `.index` with the
        // native show tail inside one gate hold, zero `nb` spawns.
        let (notebook, display, input, exact) =
            self.resolve_read_identity(&target, notebook).await?;
        // No-ensure root BEFORE the gate: the ensuring gate helper
        // would ensure (and create) a missing notebook.
        let root = self.native_notebook_root(&notebook).await?;
        self.with_notebook_gate_native(&root, async {
            let shown = self
                .show_note_native_inside(
                    &notebook, &display, &input, exact, &root,
                )
                .await?;
            Self::show_lines_window(shown, offset, limit)
        })
        .await
    }

    /// Window one contiguous body into [`ShowNoteLines`].
    /// Pure projection over an already-read [`ShowNote`].
    fn show_lines_window(
        shown: ShowNote,
        offset: Option<u32>,
        limit: Option<u32>,
    ) -> Result<ShowNoteLines, NbError> {
        let source = shown.source.as_bytes().to_vec();
        let doc = parse(
            &source,
            ParseContext::FromPath(PathBuf::from(&shown.path)),
        )?;
        let body = require_contiguous_body(&doc)?;
        let (eol, has_final_eol, lines) = document_lines(&body);
        let total_lines = lines.len() as u32;
        let offset = offset.unwrap_or(1);
        let limit = limit.unwrap_or(100);
        if offset == 0 {
            return Err(NbError::InvalidLineWindow {
                offset,
                limit,
                total_lines,
            });
        }
        if total_lines == 0 {
            if offset != 1 {
                return Err(NbError::InvalidLineWindow {
                    offset,
                    limit,
                    total_lines,
                });
            }
            return Ok(ShowNoteLines {
                selector: shown.selector,
                path: shown.path,
                kind: shown.kind,
                total_lines: 0,
                offset,
                limit,
                next_offset: None,
                lines: Vec::new(),
                title: shown.title,
                tags: shown.tags,
                body_fingerprint: shown.fingerprint,
                eol: None,
                has_final_eol: false,
                numeric_id: shown.numeric_id,
            });
        }
        if offset > total_lines + 1 {
            return Err(NbError::InvalidLineWindow {
                offset,
                limit,
                total_lines,
            });
        }
        let start_idx = (offset - 1) as usize;
        let end_idx = (start_idx + limit as usize).min(lines.len());
        let window: Vec<_> = lines[start_idx..end_idx]
            .iter()
            .map(|l| note_line_from_body_line(l, &body))
            .collect();
        let next_offset = if end_idx < lines.len() {
            Some(offset + window.len() as u32)
        } else {
            None
        };
        Ok(ShowNoteLines {
            selector: shown.selector,
            path: shown.path,
            kind: shown.kind,
            total_lines,
            offset,
            limit,
            next_offset,
            lines: window,
            title: shown.title,
            tags: shown.tags,
            body_fingerprint: shown.fingerprint,
            eol,
            has_final_eol,
            numeric_id: shown.numeric_id,
        })
    }

    /// Search body line texts for a pattern (contiguous body only).
    pub async fn search_note_lines(
        &self,
        target: NoteTarget,
        pattern: &str,
        notebook: Option<&str>,
    ) -> Result<SearchNoteLines, NbError> {
        // Reads resolve via the filesystem plus `.index`; see
        // `show_note_lines`.
        let (notebook, display, input, exact) =
            self.resolve_read_identity(&target, notebook).await?;
        // No-ensure root BEFORE the gate: the ensuring gate helper
        // would ensure (and create) a missing notebook.
        let root = self.native_notebook_root(&notebook).await?;
        // `pattern` is borrowed across the gate future; copy the
        // small query string so the future owns its inputs.
        let pattern = pattern.to_string();
        self.with_notebook_gate_native(&root, async {
            let shown = self
                .show_note_native_inside(
                    &notebook, &display, &input, exact, &root,
                )
                .await?;
            Self::search_lines_hits(shown, &pattern)
        })
        .await
    }

    /// Search one contiguous body for a pattern.
    /// Pure projection over an already-read [`ShowNote`].
    fn search_lines_hits(
        shown: ShowNote,
        pattern: &str,
    ) -> Result<SearchNoteLines, NbError> {
        let source = shown.source.as_bytes().to_vec();
        let doc = parse(
            &source,
            ParseContext::FromPath(PathBuf::from(&shown.path)),
        )?;
        let body = require_contiguous_body(&doc)?;
        let hits = search_lines(&body, pattern.as_bytes())?;
        Ok(SearchNoteLines {
            selector: shown.selector,
            path: shown.path,
            kind: shown.kind,
            hits,
            body_fingerprint: shown.fingerprint,
        })
    }

    /// Lists notes in a notebook or folder.
    pub async fn list_notes(
        &self,
        folder: Option<&str>,
        tags: &[String],
        limit: Option<u32>,
        notebook: Option<&str>,
    ) -> Result<String, NbError> {
        let mut args = Vec::new();
        validate_folder_option(folder)?;

        let notebook = self.resolve_notebook(notebook).await?;
        let cmd = match folder {
            Some(f) => format!("{}:{}/", notebook, f),
            None => format!("{}:", notebook),
        };

        args.push("list".to_string());
        args.push(cmd);

        // No color for parsing
        args.push("--no-color".to_string());

        // Limit
        if let Some(n) = limit {
            args.push("-n".to_string());
            args.push(n.to_string());
        }

        // Tags filter
        for tag in tags {
            args.push("--tags".to_string());
            let tag_str = if tag.starts_with('#') {
                tag.clone()
            } else {
                format!("#{}", tag)
            };
            args.push(tag_str);
        }

        // Strip the trailing usage/help hint block from empty
        // results (`0 items.` followed by `Add a note:`,
        // `Import a file:`, `Help information:`). Detection
        // keys off the empty-result signal per the
        // `output-behavior` specification. See `output.rs`
        // for the helper's contract.
        self.exec_vec(args)
            .await
            .map(|output| strip_empty_result_hint(&output))
    }

    /// Searches notes.
    pub async fn search_notes(
        &self,
        queries: &[String],
        mode: SearchMode,
        tags: &[String],
        folder: Option<&str>,
        notebook: Option<&str>,
    ) -> Result<String, NbError> {
        validate_folder_option(folder)?;
        if queries.is_empty() {
            return Err(NbError::ValidationError {
                reason: "at least one search query is required".to_string(),
                location: None,
            });
        }

        let notebook = self.resolve_notebook(notebook).await?;
        let scope = match folder {
            Some(f) => format!("{}:{}/", notebook, f),
            None => format!("{}:", notebook),
        };
        let args = search_command_args(scope, queries, mode, tags);
        self.exec_vec(args).await
    }

    /// Searches notes natively: recursive text-file walk under the
    /// scope, case-insensitive substring match of the queries
    /// against title plus body text (`Any`/`All` across queries),
    /// tag-filtered like the typed list. Returns lexical
    /// [`crate::ListEntry`] values. Empty queries are
    /// `ValidationError`. Zero `nb` spawns.
    pub async fn search_notes_typed(
        &self,
        queries: &[String],
        mode: SearchMode,
        tags: &[String],
        folder: Option<&str>,
        notebook: Option<&str>,
    ) -> Result<Vec<crate::ListEntry>, NbError> {
        validate_folder_option(folder)?;
        if queries.is_empty() {
            return Err(NbError::ValidationError {
                reason: "at least one search query is required".to_string(),
                location: None,
            });
        }
        let notebook = self.resolve_notebook_name(notebook)?;
        let root = self.native_notebook_root(&notebook).await?;
        // Leading slashes are NOT trimmed: absolute forms
        // fail closed as NotFound inside confinement.
        let scope = folder.unwrap_or_default().to_string();
        let lowered: Vec<String> =
            queries.iter().map(|q| q.to_lowercase()).collect();
        self.with_notebook_gate_native(&root, async {
            let mut out = Vec::new();
            for rel in crate::scope::scope_files_recursive(&root, &scope)? {
                let abs = root.join(&rel);
                let bytes = std::fs::read(&abs).map_err(|e| NbError::Io {
                    path: abs.clone(),
                    source: e.into(),
                })?;
                // Textual files only; unparseable content never
                // matches.
                if !matches!(
                    crate::native::classify_path(&abs, &rel)?,
                    crate::native::NativeClass::Text
                ) {
                    continue;
                }
                if !Self::tags_match(&bytes, &rel, tags) {
                    continue;
                }
                let doc = match parse(
                    &bytes,
                    ParseContext::FromPath(rel.clone().into()),
                ) {
                    Ok(doc) => doc,
                    Err(_) => continue,
                };
                let mut haystack = String::new();
                if let Some(title) = doc.title() {
                    haystack.push_str(&String::from_utf8_lossy(title));
                    haystack.push('\n');
                }
                haystack.push_str(&String::from_utf8_lossy(&doc.body_bytes()));
                let haystack = haystack.to_lowercase();
                let matched = match mode {
                    SearchMode::Any => {
                        lowered.iter().any(|q| haystack.contains(q))
                    },
                    SearchMode::All => {
                        lowered.iter().all(|q| haystack.contains(q))
                    },
                };
                if !matched {
                    continue;
                }
                out.push(self.list_entry_for(&notebook, &root, &rel).await?);
            }
            Ok(out)
        })
        .await
    }

    /// Assemble one typed list entry for an in-scope relative
    /// path: shadow-aware canonical selector plus confined
    /// numeric id. The caller holds the gate and the path comes
    /// from a symlink-free scope enumeration.
    pub(super) async fn list_entry_for(
        &self,
        notebook: &str,
        root: &Path,
        rel: &str,
    ) -> Result<crate::ListEntry, NbError> {
        let abs = root.join(rel);
        let display = format!("{notebook}:{rel}");
        let abs = crate::native::confine_canonical(root, &abs, &display)?;
        let class = crate::native::classify_path(&abs, rel)?;
        let kind = crate::native::entity_kind_for_rel(rel, &class);
        let selector = crate::native::canonical_selector(notebook, root, rel)?;
        let numeric_id = crate::native::numeric_id_for_rel(root, rel)?;
        Ok(crate::ListEntry {
            selector,
            path: rel.to_string(),
            kind,
            numeric_id,
        })
    }

    /// Whether file bytes carry all requested tags. Unparseable
    /// content never matches a non-empty filter.
    fn tags_match(bytes: &[u8], rel: &str, tags: &[String]) -> bool {
        if tags.is_empty() {
            return true;
        }
        let doc = match parse(bytes, ParseContext::FromPath(rel.into())) {
            Ok(doc) => doc,
            Err(_) => return false,
        };
        let have: Vec<String> = doc
            .tags()
            .map(|t| {
                String::from_utf8_lossy(t)
                    .trim_start_matches('#')
                    .to_string()
            })
            .collect();
        tags.iter().all(|wanted| {
            let want = wanted.trim_start_matches('#');
            have.iter().any(|got| got == want)
        })
    }

    /// Lists notes in a notebook or folder as typed entries:
    /// one [`crate::ListEntry`] per file directly under the scope
    /// (non-recursive), excluding dotfiles and symlinks, ordered
    /// lexically by relative path. Tags filter by parsed document
    /// tags (all must match); `limit` takes the first N. A missing
    /// scope is terminal `NotFound`. Zero `nb` spawns.
    pub async fn list_notes_typed(
        &self,
        folder: Option<&str>,
        tags: &[String],
        limit: Option<u32>,
        notebook: Option<&str>,
    ) -> Result<Vec<crate::ListEntry>, NbError> {
        validate_folder_option(folder)?;
        let notebook = self.resolve_notebook_name(notebook)?;
        let root = self.native_notebook_root(&notebook).await?;
        // Leading slashes are NOT trimmed: absolute forms
        // fail closed as NotFound inside confinement.
        let scope = folder.unwrap_or_default().to_string();
        self.with_notebook_gate_native(&root, async {
            let mut out = Vec::new();
            for rel in crate::scope::scope_files(&root, &scope)? {
                if let Some(n) = limit
                    && out.len() >= n as usize
                {
                    break;
                }
                let abs = root.join(&rel);
                let bytes = std::fs::read(&abs).map_err(|e| NbError::Io {
                    path: abs.clone(),
                    source: e.into(),
                })?;
                if !Self::tags_match(&bytes, &rel, tags) {
                    continue;
                }
                out.push(self.list_entry_for(&notebook, &root, &rel).await?);
            }
            Ok(out)
        })
        .await
    }
}

/// Notebook dir from the environment: `$NB_DIR/<notebook>` when
/// present, without creating, ensuring, or spawning. Genuine
/// filesystem failures propagate; only true absence maps to `None`.
pub(super) fn notebook_dir_from_env(
    notebook: &str,
) -> Result<Option<PathBuf>, NbError> {
    let Some(nb_dir) = std::env::var_os("NB_DIR") else {
        return Ok(None);
    };
    let path = PathBuf::from(nb_dir).join(notebook);
    // `metadata` follows symlinks exactly like the previous
    // `is_dir` check; only genuine misses map to `None` while
    // permission and I/O failures propagate instead of collapsing
    // into `NotFound`.
    match std::fs::metadata(&path) {
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(NbError::Io {
            path: path.clone(),
            source: e.into(),
        }),
        Ok(m) if !m.is_dir() => Ok(None),
        Ok(_) => match std::fs::metadata(path.join(".git")) {
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
            Err(e) => Err(NbError::Io {
                path: path.join(".git"),
                source: e.into(),
            }),
            Ok(_) => Ok(Some(path)),
        },
    }
}

pub(super) fn path_relative_to(
    root: &Path,
    path: &Path,
) -> Result<String, NbError> {
    let root = root.canonicalize().map_err(|e| NbError::Io {
        path: root.to_path_buf(),
        source: e.into(),
    })?;
    let path = path.canonicalize().map_err(|e| NbError::Io {
        path: path.to_path_buf(),
        source: e.into(),
    })?;
    let rel =
        path.strip_prefix(&root)
            .map_err(|_| NbError::ValidationError {
                reason: format!(
                    "path {} is not under notebook root {}",
                    path.display(),
                    root.display()
                ),
                location: None,
            })?;
    // On Windows the canonical form uses `\` separators, which
    // are normalized here. On Unix a backslash is an ordinary
    // filename character (e.g. a literal `a\b` file) and must be
    // preserved verbatim.
    #[cfg(windows)]
    {
        Ok(rel.to_string_lossy().replace('\\', "/"))
    }
    #[cfg(not(windows))]
    {
        Ok(rel.to_string_lossy().into_owned())
    }
}