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