Skip to main content

nb_api/
client.rs

1//! [`NbClient`] method implementations.
2
3use std::collections::VecDeque;
4use std::path::{Path, PathBuf};
5use std::process::Stdio;
6use std::sync::LazyLock;
7
8use regex::Regex;
9use tokio::process::Command;
10
11use crate::argv::{
12    child_folder_names, empty_tasks_message, is_empty_tasks_error, normalize_folder,
13    search_command_args, tasks_command_args, tasks_scope,
14};
15use crate::diagnostics::{append_warning, is_notebook_not_found, is_selector_not_found};
16use crate::error::NbError;
17use crate::fingerprint;
18use crate::fingerprint::Fingerprint;
19use crate::gate;
20use crate::git::derive_git_notebook_name;
21use crate::git_env::scrub_git_env;
22use crate::git_signing::apply_git_signing_env;
23use crate::lines::{
24    note_line_from_body_line, require_contiguous_body, search_lines, split_body_lines,
25};
26use crate::nb_program::nb_program;
27use crate::output::strip_empty_result_hint;
28use crate::parser::{ParseContext, parse};
29use crate::transaction::{self, Transaction};
30use crate::types::{
31    BodyFragment, ByteString, CommitOutcome, LineEdit, NoteTarget, Occurrence, SearchNoteLines,
32    ShowNote, ShowNoteLines,
33};
34use crate::validate::{
35    detect_duplicate_title_heading, parse_qualified_selector, validate_destination,
36    validate_folder_option, validate_folder_path, validate_notebook_name,
37};
38use crate::{Config, NbClient, SearchMode, TaskStatus};
39
40/// Regex to match ANSI/ISO 2022 escape sequences.
41///
42/// Covers:
43/// - Fe sequences: `ESC [@-Z\-_]` (single byte after ESC)
44/// - CSI sequences: `ESC [ ... m` (SGR colors, cursor control, etc.)
45/// - nF sequences: `ESC [ -/]* [0-~]` (character set designation like `ESC ( B`)
46static ANSI_REGEX: LazyLock<Regex> =
47    LazyLock::new(|| Regex::new(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|[ -/]*[0-~])").unwrap());
48
49/// Strip ANSI escape sequences from text.
50fn strip_ansi(text: &str) -> String {
51    ANSI_REGEX.replace_all(text, "").into_owned()
52}
53
54/// Result of probing a selector's textual classification via
55/// `nb show <selector> --type text`. Used by
56/// [`NbClient::show_note`](crate::NbClient::show_note) to decide whether
57/// the content-read path is safe.
58enum ShowClassification {
59    /// `nb` classified the type as text. Caller proceeds to
60    /// the content-read path.
61    Textual,
62    /// `nb` classified the type as non-text (folder, archive,
63    /// image, audio, video, etc.). `actual_type` carries the
64    /// `nb`-reported type string (file extension or `folder`).
65    NonTextual { actual_type: String },
66    /// The probe could not classify the selector (selector not
67    /// found, internal error). Caller falls through to the
68    /// original show path so existing missing-selector
69    /// diagnostics are preserved.
70    ProbeFailure,
71}
72
73const FOLDER_REQUIRED_MESSAGE: &str = "This server is configured to require `folder` for new notes. Use the `nb.mkdir` tool to create new folders and the `nb.folders` tool to list existing folders.";
74
75impl NbClient {
76    /// Creates a new nb client.
77    ///
78    /// Uses the notebook from config if set, otherwise falls back to a
79    /// Git-derived notebook name. Does NOT read `NB_MCP_NOTEBOOK` —
80    /// that is an MCP-server-specific env var resolved by the server.
81    pub fn new(config: &Config) -> anyhow::Result<Self> {
82        let default_notebook = config
83            .notebook
84            .as_deref()
85            .map(String::from)
86            .or_else(derive_git_notebook_name);
87        Ok(Self {
88            default_notebook,
89            create_notebook: config.create_notebook,
90            disable_git_signing: config.disable_git_signing,
91            allow_top_level_notes: config.allow_top_level_notes,
92            gate_timeout: config.gate_timeout,
93        })
94    }
95
96    /// Begin a collect-then-commit [`Transaction`] for `notebook`.
97    ///
98    /// Construction performs no durable I/O and does not acquire the gate.
99    pub async fn transaction(&self, notebook: Option<&str>) -> Result<Transaction, NbError> {
100        let notebook = self.resolve_notebook_name(notebook)?;
101        // Prefer filesystem existence under NB_DIR so plan construction does
102        // not invoke `nb` (which can auto-checkpoint a dirty worktree).
103        if notebook_dir_from_env(&notebook).is_none() {
104            self.ensure_notebook(&notebook).await?;
105        }
106        Ok(Transaction::new(self.clone(), notebook, self.gate_timeout))
107    }
108
109    /// Process-shared gate queue timeout configured on this client.
110    pub fn gate_timeout(&self) -> std::time::Duration {
111        self.gate_timeout
112    }
113
114    /// Notebook path without acquiring the notebook gate (caller holds gate or
115    /// is still resolving identity).
116    ///
117    /// Prefers `$NB_DIR/<notebook>` when that directory exists so path
118    /// resolution does not invoke `nb` (which can auto-checkpoint and clear a
119    /// dirty baseline before `Transaction::commit` inspects status).
120    pub(crate) async fn show_notebook_path_unguarded(
121        &self,
122        notebook: Option<&str>,
123    ) -> Result<PathBuf, NbError> {
124        let notebook = self.resolve_notebook_name(notebook)?;
125        if let Some(path) = notebook_dir_from_env(&notebook) {
126            return Ok(path);
127        }
128        self.ensure_notebook(&notebook).await?;
129        let output = self
130            .exec_vec(vec![
131                "notebooks".to_string(),
132                "show".to_string(),
133                notebook.clone(),
134                "--path".to_string(),
135            ])
136            .await?;
137        let path = output.trim();
138        if path.is_empty() {
139            return Err(NbError::CommandFailed {
140                command: format!("nb notebooks show {notebook} --path"),
141                stderr: "nb notebooks path output was empty".to_string(),
142                exit_code: None,
143            });
144        }
145        Ok(PathBuf::from(path))
146    }
147
148    async fn with_notebook_gate<F, T>(&self, notebook: &str, f: F) -> Result<T, NbError>
149    where
150        F: std::future::Future<Output = Result<T, NbError>>,
151    {
152        let root = self.show_notebook_path_unguarded(Some(notebook)).await?;
153        let key = gate::git_common_dir_realpath(&root)?;
154        let _hold = gate::acquire_notebook(key, self.gate_timeout, false).await?;
155        f.await
156    }
157
158    fn require_folder_for_new_note(&self, folder: Option<&str>) -> Result<(), NbError> {
159        if self.allow_top_level_notes || folder.is_some_and(|value| !value.trim().is_empty()) {
160            return Ok(());
161        }
162        Err(NbError::ValidationError {
163            reason: FOLDER_REQUIRED_MESSAGE.to_string(),
164            location: None,
165        })
166    }
167
168    async fn resolve_target_selector(
169        &self,
170        id: &str,
171        notebook: Option<&str>,
172    ) -> Result<(String, String), NbError> {
173        if let Some((embedded_notebook, path)) = parse_qualified_selector(id)? {
174            let notebook = match notebook {
175                Some(value) => {
176                    validate_notebook_name(value)?;
177                    if value != embedded_notebook {
178                        return Err(NbError::ValidationError {
179                            reason: format!(
180                                "ambiguous selector: id targets notebook `{embedded_notebook}`, but notebook field is `{value}`"
181                            ),
182                            location: None,
183                        });
184                    }
185                    embedded_notebook.to_string()
186                }
187                _ => embedded_notebook.to_string(),
188            };
189            self.ensure_existing_notebook(&notebook).await?;
190            return Ok((notebook, format!("{}:{}", embedded_notebook, path)));
191        }
192        let notebook = self.resolve_notebook(notebook).await?;
193        Ok((notebook.clone(), format!("{}:{}", notebook, id)))
194    }
195
196    fn append_notebook_warning(&self, output: String, notebook: &str) -> String {
197        let Some(default_notebook) = self.default_notebook.as_deref() else {
198            return output;
199        };
200        if default_notebook == notebook {
201            return output;
202        }
203        append_warning(
204            output,
205            format!(
206                "Warning: wrote to notebook `{notebook}`, not the project default notebook `{default_notebook}`. If this was unintended, move or delete the note and retry with the correct notebook/folder."
207            ),
208        )
209    }
210
211    /// Resolves the notebook to use for a command.
212    fn resolve_notebook_name(&self, notebook: Option<&str>) -> Result<String, NbError> {
213        if let Some(name) = notebook {
214            validate_notebook_name(name)?;
215            return Ok(name.to_string());
216        }
217        if let Some(name) = self.default_notebook.as_deref() {
218            validate_notebook_name(name)?;
219            return Ok(name.to_string());
220        }
221        Err(NbError::ValidationError {
222            reason: "notebook not configured; set --notebook or NB_MCP_NOTEBOOK".to_string(),
223            location: None,
224        })
225    }
226
227    async fn resolve_notebook(&self, notebook: Option<&str>) -> Result<String, NbError> {
228        let name = self.resolve_notebook_name(notebook)?;
229        self.ensure_notebook(&name).await?;
230        Ok(name)
231    }
232
233    async fn ensure_notebook(&self, notebook: &str) -> Result<(), NbError> {
234        match self.check_notebook(notebook).await {
235            Ok(()) => Ok(()),
236            // Genuine infrastructure failure (no nb binary, IO
237            // error) — surface verbatim; do not try to create.
238            Err(err @ (NbError::ExecutableNotFound { .. } | NbError::Io { .. })) => Err(err),
239            // Typed NotFound from `check_notebook` means the
240            // pinned diagnostic matched the genuine notebook-
241            // absence shape (`Notebook not found: <name>`).
242            // Try to create it; if creation is disabled, surface
243            // a typed validation error; if creation fails,
244            // propagate the new CommandFailed verbatim.
245            Err(NbError::NotFound { .. }) => {
246                if !self.create_notebook {
247                    return Err(NbError::ValidationError {
248                        reason: format!(
249                            "notebook not found; create it with the nb CLI (`nb notebooks add {}`) \
250                             or remove --no-create-notebook",
251                            notebook
252                        ),
253                        location: None,
254                    });
255                }
256                self.exec_vec(vec![
257                    "notebooks".to_string(),
258                    "add".to_string(),
259                    notebook.to_string(),
260                ])
261                .await?;
262                Ok(())
263            }
264            // Any other error from `check_notebook` (permission
265            // denied, transient crash, etc.) propagates verbatim;
266            // we deliberately do not try `notebooks add`, because
267            // a non-NotFound CommandFailed likely indicates a
268            // real failure that creation would not rescue.
269            Err(err) => Err(err),
270        }
271    }
272
273    async fn ensure_existing_notebook(&self, notebook: &str) -> Result<(), NbError> {
274        match self.check_notebook(notebook).await {
275            Ok(()) => Ok(()),
276            // Infrastructure failure — surface verbatim.
277            Err(err @ (NbError::ExecutableNotFound { .. } | NbError::Io { .. })) => Err(err),
278            // Genuine notebook absence: propagate the typed
279            // `NbError::NotFound` produced by `check_notebook`
280            // verbatim. The qualified-selector path
281            // (`<notebook>:<item>`) used by `show_note`,
282            // `add_note`, `edit_note`, etc. surfaces this to the
283            // caller as the typed `NotFound` variant — the
284            // caller can distinguish "notebook gone" from a
285            // generic validation failure. Erasing the typed
286            // `NotFound` into a `ValidationError` would lose
287            // the variant distinction.
288            Err(err @ NbError::NotFound { .. }) => Err(err),
289            // Other CommandFailed errors propagate verbatim
290            // rather than being misclassified as "not found."
291            Err(err) => Err(err),
292        }
293    }
294
295    async fn check_notebook(&self, notebook: &str) -> Result<(), NbError> {
296        let show_result = self
297            .exec_vec(vec![
298                "notebooks".to_string(),
299                "show".to_string(),
300                notebook.to_string(),
301                "--path".to_string(),
302            ])
303            .await;
304        match show_result {
305            Ok(output) => {
306                if output.trim().is_empty() {
307                    // Use the actual argument vector that was passed
308                    // to `exec_vec`, not a reformatted display
309                    // string. This way the `command` field matches
310                    // what was actually executed on the wire, with
311                    // no possibility of drift between the synthetic
312                    // field and the real argv.
313                    return Err(NbError::CommandFailed {
314                        command: format!("nb notebooks show {notebook} --path"),
315                        stderr: "nb notebooks path output was empty".to_string(),
316                        exit_code: None,
317                    });
318                }
319                Ok(())
320            }
321            Err(err) => {
322                // Surface genuine infrastructure failures verbatim
323                // so callers can distinguish "nb is broken" from
324                // "notebook does not exist". Genuine notebook
325                // absence (nb's pinned diagnostic on stderr) maps
326                // to typed `NotFound`. Any other subprocess
327                // failure (e.g., permission denied, a transient
328                // crash, an nb bug surfacing as `NotFound` in
329                // stderr without the literal `Notebook not found:`
330                // prefix) propagates as the original
331                // `CommandFailed` rather than being swallowed
332                // here. The caller (`ensure_notebook` /
333                // `ensure_existing_notebook`) decides whether to
334                // try to create the notebook on `NotFound` or
335                // surface the error verbatim otherwise.
336                match err {
337                    NbError::ExecutableNotFound { .. } | NbError::Io { .. } => Err(err),
338                    NbError::CommandFailed { ref stderr, .. }
339                        if is_notebook_not_found(stderr, notebook) =>
340                    {
341                        Err(NbError::NotFound {
342                            selector: format!("{notebook}:"),
343                        })
344                    }
345                    other => Err(other),
346                }
347            }
348        }
349    }
350
351    /// Executes an nb command and returns stdout.
352    async fn exec(&self, args: &[&str]) -> Result<String, NbError> {
353        tracing::debug!(?args, "executing nb command");
354        // `nb_program` resolves `nb` to a spawnable absolute path on
355        // Windows (PATHEXT-aware: Rust std only finds `.exe` there and
356        // would miss a `nb.cmd` launcher). Unix keeps PATH resolution.
357        let mut command = Command::new(nb_program());
358        // Strip inherited `GIT_*` routing vars before chaining `.args` /
359        // `.env`. Without this, any caller invoking us from inside a
360        // git hook (pre-commit, pre-push, post-checkout) or CI runner
361        // propagates GIT_DIR / GIT_INDEX_FILE / GIT_COMMON_DIR /
362        // GIT_WORK_TREE / GIT_OBJECT_DIRECTORY /
363        // GIT_ALTERNATE_OBJECT_DIRECTORIES into the spawned `nb`,
364        // which is a bash script wrapping git — every git call inside
365        // nb then redirects to the parent repo instead of the
366        // notebook's repo. The blast-by-prefix also covers future
367        // GIT_* redirect vars without requiring a code change.
368        // See `nb-api:issues/3`. Do not remove.
369        scrub_git_env(&mut command);
370        command
371            .args(args)
372            .stdin(Stdio::null()) // Prevent TTY hangs
373            .stdout(Stdio::piped())
374            .stderr(Stdio::piped());
375        if self.disable_git_signing {
376            apply_git_signing_env(&mut command);
377        }
378        let joined = format!("nb {}", args.join(" "));
379        let output = command
380            .spawn()
381            .map_err(|e| {
382                if e.kind() == std::io::ErrorKind::NotFound {
383                    NbError::ExecutableNotFound {
384                        path: "nb".to_string(),
385                    }
386                } else {
387                    NbError::Io {
388                        path: PathBuf::from("nb"),
389                        source: e.into(),
390                    }
391                }
392            })?
393            .wait_with_output()
394            .await
395            .map_err(|e| NbError::Io {
396                path: PathBuf::from("nb"),
397                source: e.into(),
398            })?;
399
400        if output.status.success() {
401            let stdout = String::from_utf8_lossy(&output.stdout);
402            Ok(strip_ansi(&stdout))
403        } else {
404            let stderr = String::from_utf8_lossy(&output.stderr);
405            let stdout = String::from_utf8_lossy(&output.stdout);
406            // nb sometimes writes errors to stdout
407            let stderr_text = if stderr.is_empty() {
408                strip_ansi(&stdout)
409            } else {
410                strip_ansi(&stderr)
411            };
412            Err(NbError::CommandFailed {
413                command: joined,
414                stderr: stderr_text,
415                exit_code: output.status.code(),
416            })
417        }
418    }
419
420    /// Executes an nb command with dynamic arguments.
421    async fn exec_vec(&self, args: Vec<String>) -> Result<String, NbError> {
422        let args_ref: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
423        self.exec(&args_ref).await
424    }
425
426    /// Returns status information about the resolved notebook.
427    pub async fn show_notebook_status(&self, notebook: Option<&str>) -> Result<String, NbError> {
428        let notebook = self.resolve_notebook(notebook).await?;
429        self.exec_vec(vec![format!("{}:", notebook), "status".to_string()])
430            .await
431    }
432
433    /// Lists available notebooks.
434    pub async fn list_notebooks(&self) -> Result<String, NbError> {
435        let _g = gate::acquire_global(self.gate_timeout).await?;
436        // Use --no-color to avoid ANSI escape codes
437        self.exec(&["notebooks", "--no-color"]).await
438    }
439
440    /// Returns the path for a notebook.
441    pub async fn show_notebook_path(&self, notebook: Option<&str>) -> Result<PathBuf, NbError> {
442        let notebook = self.resolve_notebook_name(notebook)?;
443        self.ensure_notebook(&notebook).await?;
444        self.with_notebook_gate(
445            &notebook,
446            self.show_notebook_path_unguarded(Some(&notebook)),
447        )
448        .await
449    }
450
451    /// Creates a new note (one-shot transaction; optional auto-name).
452    pub async fn add_note(
453        &self,
454        title: Option<&str>,
455        content: &str,
456        tags: &[String],
457        folder: Option<&str>,
458        notebook: Option<&str>,
459    ) -> Result<CommitOutcome, NbError> {
460        if let Some(t) = title
461            && let Some(heading) = detect_duplicate_title_heading(t, content)
462        {
463            return Err(NbError::DuplicateTitleHeading {
464                title: t.to_string(),
465                heading,
466            });
467        }
468        self.require_folder_for_new_note(folder)?;
469        validate_folder_option(folder)?;
470        let filename = transaction::auto_filename("md");
471        let path = transaction::join_folder_file(folder, &filename);
472        let mut tx = self.transaction(notebook).await?;
473        tx.add_note(&path, title, content, tags)?;
474        tx.commit().await
475    }
476
477    /// Shows a note as a structured [`ShowNote`] (gate-held).
478    pub async fn show_note(&self, id: &str, notebook: Option<&str>) -> Result<ShowNote, NbError> {
479        let (notebook, selector) = self.resolve_target_selector(id, notebook).await?;
480        self.with_notebook_gate(&notebook, async {
481            self.show_note_inner(&notebook, &selector).await
482        })
483        .await
484    }
485
486    async fn show_note_inner(&self, notebook: &str, selector: &str) -> Result<ShowNote, NbError> {
487        match self.probe_show_classification(selector).await {
488            ShowClassification::NonTextual { actual_type } => {
489                return Err(NbError::UnsupportedShowTarget {
490                    selector: selector.to_string(),
491                    actual_type,
492                });
493            }
494            ShowClassification::Textual | ShowClassification::ProbeFailure => {}
495        }
496        let path = self.resolve_item_path(selector).await?;
497        let root = self.show_notebook_path_unguarded(Some(notebook)).await?;
498        let rel = path_relative_to(&root, &path)?;
499        let source = std::fs::read(&path).map_err(|e| NbError::Io {
500            path: path.clone(),
501            source: e.into(),
502        })?;
503        let doc = match parse(&source, ParseContext::FromPath(PathBuf::from(&rel))) {
504            Ok(doc) => doc,
505            // nb may classify additional textual extensions as showable; map
506            // unrecognized formats to a Note partition for structured show.
507            Err(NbError::UnsupportedDocumentFormat { .. }) => {
508                parse(&source, ParseContext::Explicit(crate::DocumentKind::Note))?
509            }
510            Err(err) => return Err(err),
511        };
512        let fragments: Vec<BodyFragment> = doc
513            .body()
514            .enumerate()
515            .map(|(i, bytes)| BodyFragment {
516                index: i as u32,
517                bytes: ByteString::from_bytes(bytes),
518            })
519            .collect();
520        let body_contiguous = fragments.len() <= 1;
521        let body_bytes = doc.body_bytes();
522        // Lossy convenience strings; raw title bytes remain authoritative.
523        let tags: Vec<String> = doc
524            .tags()
525            .map(|t| {
526                String::from_utf8_lossy(t)
527                    .trim_start_matches('#')
528                    .to_string()
529            })
530            .collect();
531        let title = doc.title().map(ByteString::from_bytes);
532        let title_text = doc.title().map(|bytes| {
533            let s = String::from_utf8_lossy(bytes);
534            s.trim_end_matches('\n')
535                .trim_start_matches('#')
536                .trim()
537                .to_string()
538        });
539        Ok(ShowNote {
540            selector: selector.to_string(),
541            path: rel,
542            kind: doc.kind(),
543            todo_state: doc.todo_state(),
544            title,
545            title_text,
546            tags,
547            body_fragments: fragments,
548            body_contiguous,
549            body: ByteString::from_bytes(body_bytes),
550            fingerprint: fingerprint::fingerprint(&doc),
551            source: ByteString::from_bytes(source),
552        })
553    }
554
555    /// Enumerate body lines for a contiguous-body note.
556    pub async fn show_note_lines(
557        &self,
558        target: NoteTarget,
559        offset: Option<u32>,
560        limit: Option<u32>,
561        notebook: Option<&str>,
562    ) -> Result<ShowNoteLines, NbError> {
563        let (notebook, selector) = self.resolve_note_target(&target, notebook).await?;
564        self.with_notebook_gate(&notebook, async {
565            let shown = self.show_note_inner(&notebook, &selector).await?;
566            let source = shown.source.as_bytes()?;
567            let doc = parse(&source, ParseContext::FromPath(PathBuf::from(&shown.path)))?;
568            let body = require_contiguous_body(&doc)?;
569            let lines = split_body_lines(&body);
570            let total_lines = lines.len() as u32;
571            let offset = offset.unwrap_or(1);
572            let limit = limit.unwrap_or(100);
573            if offset == 0 {
574                return Err(NbError::InvalidLineWindow {
575                    offset,
576                    limit,
577                    total_lines,
578                });
579            }
580            if total_lines == 0 {
581                if offset != 1 {
582                    return Err(NbError::InvalidLineWindow {
583                        offset,
584                        limit,
585                        total_lines,
586                    });
587                }
588                return Ok(ShowNoteLines {
589                    selector: shown.selector,
590                    path: shown.path,
591                    kind: shown.kind,
592                    total_lines: 0,
593                    offset,
594                    limit,
595                    next_offset: None,
596                    lines: Vec::new(),
597                    title: shown.title,
598                    tags: shown.tags,
599                    body_fingerprint: shown.fingerprint,
600                });
601            }
602            if offset > total_lines + 1 {
603                return Err(NbError::InvalidLineWindow {
604                    offset,
605                    limit,
606                    total_lines,
607                });
608            }
609            let start_idx = (offset - 1) as usize;
610            let end_idx = (start_idx + limit as usize).min(lines.len());
611            let window: Vec<_> = lines[start_idx..end_idx]
612                .iter()
613                .map(|l| note_line_from_body_line(l, &body))
614                .collect();
615            let next_offset = if end_idx < lines.len() {
616                Some(offset + window.len() as u32)
617            } else {
618                None
619            };
620            Ok(ShowNoteLines {
621                selector: shown.selector,
622                path: shown.path,
623                kind: shown.kind,
624                total_lines,
625                offset,
626                limit,
627                next_offset,
628                lines: window,
629                title: shown.title,
630                tags: shown.tags,
631                body_fingerprint: shown.fingerprint,
632            })
633        })
634        .await
635    }
636
637    /// Search body line texts for a byte pattern (contiguous body only).
638    pub async fn search_note_lines(
639        &self,
640        target: NoteTarget,
641        pattern: &[u8],
642        notebook: Option<&str>,
643    ) -> Result<SearchNoteLines, NbError> {
644        let (notebook, selector) = self.resolve_note_target(&target, notebook).await?;
645        self.with_notebook_gate(&notebook, async {
646            let shown = self.show_note_inner(&notebook, &selector).await?;
647            let source = shown.source.as_bytes()?;
648            let doc = parse(&source, ParseContext::FromPath(PathBuf::from(&shown.path)))?;
649            let body = require_contiguous_body(&doc)?;
650            let hits = search_lines(&body, pattern)?;
651            Ok(SearchNoteLines {
652                selector: shown.selector,
653                path: shown.path,
654                kind: shown.kind,
655                hits,
656                body_fingerprint: shown.fingerprint,
657            })
658        })
659        .await
660    }
661
662    async fn resolve_item_path(&self, selector: &str) -> Result<PathBuf, NbError> {
663        let output = self
664            .exec_vec(vec![
665                "show".to_string(),
666                selector.to_string(),
667                "--path".to_string(),
668                "--no-color".to_string(),
669            ])
670            .await
671            .map_err(|err| match err {
672                NbError::CommandFailed { stderr, .. }
673                    if is_selector_not_found(&stderr, selector) =>
674                {
675                    NbError::NotFound {
676                        selector: selector.to_string(),
677                    }
678                }
679                other => other,
680            })?;
681        let path = output.trim();
682        if path.is_empty() {
683            return Err(NbError::CommandFailed {
684                command: format!("nb show {selector} --path"),
685                stderr: "empty path".into(),
686                exit_code: None,
687            });
688        }
689        Ok(PathBuf::from(path))
690    }
691
692    async fn resolve_note_target(
693        &self,
694        target: &NoteTarget,
695        notebook: Option<&str>,
696    ) -> Result<(String, String), NbError> {
697        match target {
698            NoteTarget::Selector { value } => self.resolve_target_selector(value, notebook).await,
699            NoteTarget::Path { value } => {
700                let notebook = self.resolve_notebook(notebook).await?;
701                Ok((notebook.clone(), format!("{notebook}:{value}")))
702            }
703        }
704    }
705
706    /// Probe the textual classification of a selector via `nb`'s
707    /// native `--type` mechanism.
708    ///
709    /// Two-step probe: first `nb show <selector> --type text` to
710    /// ask `nb` whether the type is text. If yes, return
711    /// [`ShowClassification::Textual`]. If no, follow up with
712    /// `nb show <selector> --type` to recover the `actual_type`
713    /// for the error diagnostic. If the follow-up also fails
714    /// (selector not found, internal error), return
715    /// [`ShowClassification::ProbeFailure`] so the caller can
716    /// fall through to the original show path.
717    async fn probe_show_classification(&self, selector: &str) -> ShowClassification {
718        let textual = self
719            .exec_vec(vec![
720                "show".to_string(),
721                selector.to_string(),
722                "--type".to_string(),
723                "text".to_string(),
724                "--no-color".to_string(),
725            ])
726            .await;
727        if textual.is_ok() {
728            return ShowClassification::Textual;
729        }
730        match self
731            .exec_vec(vec![
732                "show".to_string(),
733                selector.to_string(),
734                "--type".to_string(),
735                "--no-color".to_string(),
736            ])
737            .await
738        {
739            Ok(stdout) => {
740                let trimmed = stdout.trim();
741                if trimmed.is_empty() {
742                    ShowClassification::ProbeFailure
743                } else {
744                    ShowClassification::NonTextual {
745                        actual_type: trimmed.to_string(),
746                    }
747                }
748            }
749            Err(_) => ShowClassification::ProbeFailure,
750        }
751    }
752
753    /// Lists notes in a notebook or folder.
754    pub async fn list_notes(
755        &self,
756        folder: Option<&str>,
757        tags: &[String],
758        limit: Option<u32>,
759        notebook: Option<&str>,
760    ) -> Result<String, NbError> {
761        let mut args = Vec::new();
762        validate_folder_option(folder)?;
763
764        let notebook = self.resolve_notebook(notebook).await?;
765        let cmd = match folder {
766            Some(f) => format!("{}:{}/", notebook, f),
767            None => format!("{}:", notebook),
768        };
769
770        args.push("list".to_string());
771        args.push(cmd);
772
773        // No color for parsing
774        args.push("--no-color".to_string());
775
776        // Limit
777        if let Some(n) = limit {
778            args.push("-n".to_string());
779            args.push(n.to_string());
780        }
781
782        // Tags filter
783        for tag in tags {
784            args.push("--tags".to_string());
785            let tag_str = if tag.starts_with('#') {
786                tag.clone()
787            } else {
788                format!("#{}", tag)
789            };
790            args.push(tag_str);
791        }
792
793        // Strip the trailing usage/help hint block from empty
794        // results (`0 items.` followed by `Add a note:`,
795        // `Import a file:`, `Help information:`). Detection
796        // keys off the empty-result signal per the
797        // `output-behavior` specification. See `output.rs`
798        // for the helper's contract.
799        self.exec_vec(args)
800            .await
801            .map(|output| strip_empty_result_hint(&output))
802    }
803
804    /// Searches notes.
805    pub async fn search_notes(
806        &self,
807        queries: &[String],
808        mode: SearchMode,
809        tags: &[String],
810        folder: Option<&str>,
811        notebook: Option<&str>,
812    ) -> Result<String, NbError> {
813        validate_folder_option(folder)?;
814        if queries.is_empty() {
815            return Err(NbError::ValidationError {
816                reason: "at least one search query is required".to_string(),
817                location: None,
818            });
819        }
820
821        let notebook = self.resolve_notebook(notebook).await?;
822        let scope = match folder {
823            Some(f) => format!("{}:{}/", notebook, f),
824            None => format!("{}:", notebook),
825        };
826        let args = search_command_args(scope, queries, mode, tags);
827        self.exec_vec(args).await
828    }
829
830    /// Deletes a note (one-shot transaction).
831    pub async fn delete_note(
832        &self,
833        id: &str,
834        notebook: Option<&str>,
835    ) -> Result<CommitOutcome, NbError> {
836        let (nb, selector) = self.resolve_target_selector(id, notebook).await?;
837        let target = self.note_target_for_selector(&nb, &selector).await?;
838        let mut tx = self.transaction(Some(&nb)).await?;
839        tx.delete_note(target)?;
840        tx.commit().await
841    }
842
843    /// Moves or renames a note (one-shot transaction).
844    pub async fn move_note(
845        &self,
846        id: &str,
847        destination: &str,
848        notebook: Option<&str>,
849    ) -> Result<CommitOutcome, NbError> {
850        validate_destination(destination)?;
851        let (nb, selector) = self.resolve_target_selector(id, notebook).await?;
852        let target = self.note_target_for_selector(&nb, &selector).await?;
853        let mut tx = self.transaction(Some(&nb)).await?;
854        tx.move_note(target, destination)?;
855        tx.commit().await
856    }
857
858    async fn note_target_for_selector(
859        &self,
860        notebook: &str,
861        selector: &str,
862    ) -> Result<NoteTarget, NbError> {
863        let root = self.show_notebook_path_unguarded(Some(notebook)).await?;
864        let stripped = selector
865            .rsplit_once(':')
866            .map(|(_, rest)| rest)
867            .unwrap_or(selector);
868        let direct = root.join(stripped);
869        if direct.is_file() {
870            return Ok(NoteTarget::path(stripped));
871        }
872        // Fall back to `nb show --path` for numeric ids / titles.
873        let abs = self.resolve_item_path(selector).await?;
874        let rel = path_relative_to(&root, &abs)?;
875        Ok(NoteTarget::path(rel))
876    }
877
878    /// Creates a todo item (one-shot transaction; optional auto-name).
879    pub async fn add_todo(
880        &self,
881        title: &str,
882        description: Option<&str>,
883        tasks: &[String],
884        tags: &[String],
885        folder: Option<&str>,
886        notebook: Option<&str>,
887    ) -> Result<CommitOutcome, NbError> {
888        self.require_folder_for_new_note(folder)?;
889        validate_folder_option(folder)?;
890        let filename = transaction::auto_filename("todo.md");
891        let path = transaction::join_folder_file(folder, &filename);
892        let mut tx = self.transaction(notebook).await?;
893        tx.add_todo(&path, title, description, tasks, tags)?;
894        tx.commit().await
895    }
896
897    /// Marks a todo as done (one-shot transaction).
898    pub async fn mark_task_done(
899        &self,
900        id: &str,
901        task_number: Option<u32>,
902        notebook: Option<&str>,
903    ) -> Result<CommitOutcome, NbError> {
904        let (nb, selector) = self.resolve_target_selector(id, notebook).await?;
905        let target = self.note_target_for_selector(&nb, &selector).await?;
906        let mut tx = self.transaction(Some(&nb)).await?;
907        tx.mark_task_done(target, task_number)?;
908        tx.commit().await
909    }
910
911    /// Marks a todo as not done (one-shot transaction).
912    pub async fn unmark_task_done(
913        &self,
914        id: &str,
915        task_number: Option<u32>,
916        notebook: Option<&str>,
917    ) -> Result<CommitOutcome, NbError> {
918        let (nb, selector) = self.resolve_target_selector(id, notebook).await?;
919        let target = self.note_target_for_selector(&nb, &selector).await?;
920        let mut tx = self.transaction(Some(&nb)).await?;
921        tx.unmark_task_done(target, task_number)?;
922        tx.commit().await
923    }
924
925    /// Replace contiguous body bytes (one-shot).
926    pub async fn replace_note_body(
927        &self,
928        target: NoteTarget,
929        new_body: impl AsRef<[u8]>,
930        fingerprint: Fingerprint,
931        notebook: Option<&str>,
932    ) -> Result<CommitOutcome, NbError> {
933        let mut tx = self.transaction(notebook).await?;
934        tx.replace_note_body(target, new_body, fingerprint)?;
935        tx.commit().await
936    }
937
938    /// Substring edit on contiguous body (one-shot).
939    #[allow(clippy::too_many_arguments)]
940    pub async fn edit_note_substring(
941        &self,
942        target: NoteTarget,
943        pattern: impl AsRef<[u8]>,
944        replacement: impl AsRef<[u8]>,
945        occurrence: Occurrence,
946        expected_count: u32,
947        fingerprint: Option<Fingerprint>,
948        notebook: Option<&str>,
949    ) -> Result<CommitOutcome, NbError> {
950        let mut tx = self.transaction(notebook).await?;
951        tx.edit_note_substring(
952            target,
953            pattern,
954            replacement,
955            occurrence,
956            expected_count,
957            fingerprint,
958        )?;
959        tx.commit().await
960    }
961
962    /// Line-oriented body edit batch (one-shot).
963    pub async fn edit_note_lines(
964        &self,
965        target: NoteTarget,
966        edits: Vec<LineEdit>,
967        notebook: Option<&str>,
968    ) -> Result<CommitOutcome, NbError> {
969        let mut tx = self.transaction(notebook).await?;
970        tx.edit_note_lines(target, edits)?;
971        tx.commit().await
972    }
973
974    /// Retitle a note without changing path (one-shot).
975    pub async fn retitle_note(
976        &self,
977        target: NoteTarget,
978        title: impl AsRef<[u8]>,
979        notebook: Option<&str>,
980    ) -> Result<CommitOutcome, NbError> {
981        let mut tx = self.transaction(notebook).await?;
982        tx.retitle_note(target, title)?;
983        tx.commit().await
984    }
985
986    /// Add/remove tags (one-shot).
987    pub async fn edit_note_tags(
988        &self,
989        target: NoteTarget,
990        add: &[String],
991        remove: &[String],
992        notebook: Option<&str>,
993    ) -> Result<CommitOutcome, NbError> {
994        let mut tx = self.transaction(notebook).await?;
995        tx.edit_note_tags(target, add, remove)?;
996        tx.commit().await
997    }
998
999    /// Lists checklist items within todos.
1000    ///
1001    /// Invokes the `nb tasks` subcommand. The method enumerates
1002    /// the checklist items within todos (and recursively into
1003    /// subfolders when `recursive = true`), filtered by
1004    /// `status` if provided. The method name matches the
1005    /// underlying `nb` CLI command (`nb tasks`); a future
1006    /// `list_todos` method for the todo **container** listing
1007    /// (invoking `nb todos`) is tracked at
1008    /// `nb-api:todos/api/5` (deferred to `0.3.0+`).
1009    pub async fn list_tasks(
1010        &self,
1011        folder: Option<&str>,
1012        status: Option<TaskStatus>,
1013        recursive: bool,
1014        notebook: Option<&str>,
1015    ) -> Result<String, NbError> {
1016        validate_folder_option(folder)?;
1017        let notebook = self.resolve_notebook(notebook).await?;
1018        let folder = folder.map(normalize_folder);
1019        let scopes = if recursive {
1020            self.tasks_scopes_recursive(&notebook, folder.as_deref())
1021                .await?
1022        } else {
1023            vec![tasks_scope(&notebook, folder.as_deref())]
1024        };
1025
1026        let mut outputs: Vec<String> = Vec::new();
1027        let mut saw_empty = false;
1028        for scope in scopes {
1029            match self.exec_vec(tasks_command_args(scope, status)).await {
1030                Ok(output) => {
1031                    let output = output.trim();
1032                    if !output.is_empty() {
1033                        outputs.push(output.to_string());
1034                    }
1035                }
1036                Err(NbError::CommandFailed { stderr, .. }) if is_empty_tasks_error(&stderr) => {
1037                    saw_empty = true;
1038                }
1039                Err(err) => return Err(err),
1040            }
1041        }
1042        if outputs.is_empty() && saw_empty {
1043            // The `nb` subprocess actually succeeded (exit 0);
1044            // it simply returned no tasks. This is a policy-level
1045            // empty-result, not a command failure. Map to
1046            // ValidationError rather than fabricate a
1047            // CommandFailed with `exit_code: Some(0)` (which
1048            // would be factually misleading).
1049            return Err(NbError::ValidationError {
1050                reason: empty_tasks_message(status),
1051                location: None,
1052            });
1053        }
1054        Ok(outputs.join("\n"))
1055    }
1056
1057    async fn tasks_scopes_recursive(
1058        &self,
1059        notebook: &str,
1060        folder: Option<&str>,
1061    ) -> Result<Vec<String>, NbError> {
1062        let notebook_root = self.show_notebook_path(Some(notebook)).await?;
1063        let start = folder.unwrap_or_default().to_string();
1064        let mut queue = VecDeque::new();
1065        queue.push_back(start.clone());
1066
1067        let mut scopes = vec![tasks_scope(notebook, folder)];
1068        while let Some(current) = queue.pop_front() {
1069            let base = if current.is_empty() {
1070                notebook_root.clone()
1071            } else {
1072                notebook_root.join(&current)
1073            };
1074            let children = child_folder_names(&base)?;
1075            for child in children {
1076                let next = if current.is_empty() {
1077                    child
1078                } else {
1079                    format!("{}/{}", current, child)
1080                };
1081                scopes.push(tasks_scope(notebook, Some(&next)));
1082                queue.push_back(next);
1083            }
1084        }
1085        Ok(scopes)
1086    }
1087
1088    /// Creates a bookmark (one-shot transaction; optional auto-name).
1089    pub async fn add_bookmark(
1090        &self,
1091        url: &str,
1092        title: Option<&str>,
1093        tags: &[String],
1094        comment: Option<&str>,
1095        folder: Option<&str>,
1096        notebook: Option<&str>,
1097    ) -> Result<CommitOutcome, NbError> {
1098        self.require_folder_for_new_note(folder)?;
1099        validate_folder_option(folder)?;
1100        let filename = transaction::auto_filename("bookmark.md");
1101        let path = transaction::join_folder_file(folder, &filename);
1102        let mut tx = self.transaction(notebook).await?;
1103        tx.add_bookmark(&path, url, title, tags, comment)?;
1104        tx.commit().await
1105    }
1106
1107    /// Lists folders in a notebook.
1108    pub async fn list_folders(
1109        &self,
1110        parent: Option<&str>,
1111        notebook: Option<&str>,
1112    ) -> Result<String, NbError> {
1113        let mut args = vec!["list".to_string()];
1114        validate_folder_option(parent)?;
1115
1116        let notebook = self.resolve_notebook(notebook).await?;
1117        let path = match parent {
1118            Some(p) => format!("{}:{}/", notebook, p),
1119            None => format!("{}:", notebook),
1120        };
1121        args.push(path);
1122
1123        // Filter to only show folders
1124        args.push("--type".to_string());
1125        args.push("folder".to_string());
1126        args.push("--no-color".to_string());
1127
1128        // Strip the trailing usage/help hint block from empty
1129        // results (`0 folders.` followed by `Import a file:`,
1130        // `Help information:`). Detection keys off the
1131        // empty-result signal per the `output-behavior`
1132        // specification. See `output.rs` for the helper's
1133        // contract.
1134        self.exec_vec(args)
1135            .await
1136            .map(|output| strip_empty_result_hint(&output))
1137    }
1138
1139    /// Creates a folder (one-shot transaction).
1140    pub async fn add_folder(
1141        &self,
1142        path: &str,
1143        notebook: Option<&str>,
1144    ) -> Result<CommitOutcome, NbError> {
1145        validate_folder_path(path)?;
1146        let mut tx = self.transaction(notebook).await?;
1147        tx.add_folder(path)?;
1148        tx.commit().await
1149    }
1150
1151    /// Imports a file or URL into the notebook as a note.
1152    ///
1153    /// One-shot only under the process-shared notebook gate. Not a
1154    /// [`Transaction`] plan op in 0.3.0.
1155    pub async fn import_note(
1156        &self,
1157        source: &str,
1158        folder: Option<&str>,
1159        filename: Option<&str>,
1160        convert: bool,
1161        notebook: Option<&str>,
1162    ) -> Result<String, NbError> {
1163        let mut args = Vec::new();
1164        self.require_folder_for_new_note(folder)?;
1165        validate_folder_option(folder)?;
1166
1167        let notebook = self.resolve_notebook(notebook).await?;
1168        self.with_notebook_gate(&notebook, async {
1169            let cmd = format!("{}:import", notebook);
1170            args.push(cmd);
1171            args.push(source.to_string());
1172            if convert {
1173                args.push("--convert".to_string());
1174            }
1175            if folder.is_some() || filename.is_some() {
1176                let dest = match (folder, filename) {
1177                    (Some(f), Some(n)) => format!("{}/{}", f, n),
1178                    (Some(f), None) => format!("{}/", f),
1179                    (None, Some(n)) => n.to_string(),
1180                    (None, None) => unreachable!(),
1181                };
1182                args.push(dest);
1183            }
1184            self.exec_vec(args)
1185                .await
1186                .map(|output| self.append_notebook_warning(output, &notebook))
1187        })
1188        .await
1189    }
1190}
1191
1192fn notebook_dir_from_env(notebook: &str) -> Option<PathBuf> {
1193    let nb_dir = std::env::var_os("NB_DIR")?;
1194    let path = PathBuf::from(nb_dir).join(notebook);
1195    if path.is_dir() && path.join(".git").exists() {
1196        Some(path)
1197    } else {
1198        None
1199    }
1200}
1201
1202fn path_relative_to(root: &Path, path: &Path) -> Result<String, NbError> {
1203    let root = root.canonicalize().map_err(|e| NbError::Io {
1204        path: root.to_path_buf(),
1205        source: e.into(),
1206    })?;
1207    let path = path.canonicalize().map_err(|e| NbError::Io {
1208        path: path.to_path_buf(),
1209        source: e.into(),
1210    })?;
1211    let rel = path
1212        .strip_prefix(&root)
1213        .map_err(|_| NbError::ValidationError {
1214            reason: format!(
1215                "path {} is not under notebook root {}",
1216                path.display(),
1217                root.display()
1218            ),
1219            location: None,
1220        })?;
1221    Ok(rel.to_string_lossy().replace('\\', "/"))
1222}