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    document_lines, note_line_from_body_line, require_contiguous_body, search_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, CommitOutcome, LineEdit, NoteTarget, Occurrence, SearchNoteLines, ShowNote,
32    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; nb-mangled filename).
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::filename_for_title(title, "md");
471        self.create_with_retry(notebook, folder, filename, |tx, path| {
472            tx.add_note(&path, title, content, tags)
473        })
474        .await
475    }
476
477    /// One-shot create with `-N` collision retry on the auto filename.
478    ///
479    /// Explicit-path `Transaction` plans keep hard `PathCollision` errors;
480    /// the mangled/titleless one-shot names instead gain `-1`, `-2`, …
481    /// until free (basenames stay unique per folder, which keeps post-write
482    /// `.index` lookup unambiguous).
483    async fn create_with_retry(
484        &self,
485        notebook: Option<&str>,
486        folder: Option<&str>,
487        filename: String,
488        plan: impl Fn(&mut Transaction, String) -> Result<(), NbError>,
489    ) -> Result<CommitOutcome, NbError> {
490        let mut name = filename.clone();
491        for attempt in 0..100u32 {
492            if attempt > 0 {
493                name = transaction::suffixed_filename(&filename, attempt);
494            }
495            let path = transaction::join_folder_file(folder, &name);
496            let mut tx = self.transaction(notebook).await?;
497            plan(&mut tx, path)?;
498            match tx.commit().await {
499                Ok(outcome) => return Ok(outcome),
500                Err(NbError::PathCollision { .. }) => continue,
501                Err(other) => return Err(other),
502            }
503        }
504        Err(NbError::PathCollision {
505            path: transaction::join_folder_file(folder, &filename),
506            plan_index: None,
507        })
508    }
509
510    /// Shows a note as a structured [`ShowNote`] (gate-held).
511    pub async fn show_note(&self, id: &str, notebook: Option<&str>) -> Result<ShowNote, NbError> {
512        let (notebook, selector) = self.resolve_target_selector(id, notebook).await?;
513        self.with_notebook_gate(&notebook, async {
514            self.show_note_inner(&notebook, &selector).await
515        })
516        .await
517    }
518
519    async fn show_note_inner(&self, notebook: &str, selector: &str) -> Result<ShowNote, NbError> {
520        match self.probe_show_classification(selector).await {
521            ShowClassification::NonTextual { actual_type } => {
522                return Err(NbError::UnsupportedShowTarget {
523                    selector: selector.to_string(),
524                    actual_type,
525                });
526            }
527            ShowClassification::Textual | ShowClassification::ProbeFailure => {}
528        }
529        let path = self.resolve_item_path(selector).await?;
530        let root = self.show_notebook_path_unguarded(Some(notebook)).await?;
531        let rel = path_relative_to(&root, &path)?;
532        let source = std::fs::read(&path).map_err(|e| NbError::Io {
533            path: path.clone(),
534            source: e.into(),
535        })?;
536        let doc = match parse(&source, ParseContext::FromPath(PathBuf::from(&rel))) {
537            Ok(doc) => doc,
538            // nb may classify additional textual extensions as showable; map
539            // unrecognized formats to a Note partition for structured show.
540            Err(NbError::UnsupportedDocumentFormat { .. }) => {
541                parse(&source, ParseContext::Explicit(crate::DocumentKind::Note))?
542            }
543            Err(err) => return Err(err),
544        };
545        let kind_str = format!("{:?}", doc.kind()).to_lowercase();
546        let non_utf8 = |path: String| NbError::NonUtf8 {
547            selector: selector.to_string(),
548            path,
549            kind: kind_str.clone(),
550            mime_hint: None,
551        };
552        let source_str = std::str::from_utf8(&source)
553            .map_err(|_| non_utf8(rel.clone()))?
554            .to_string();
555        // Fragment offsets into `source`: body_ranges are source-absolute.
556        let ranges = doc.body_ranges();
557        let mut fragments: Vec<BodyFragment> = Vec::with_capacity(ranges.len());
558        for (i, span) in ranges.iter().enumerate() {
559            let bytes = std::str::from_utf8(&source[span.clone()])
560                .map_err(|_| non_utf8(rel.clone()))?
561                .to_string();
562            fragments.push(BodyFragment {
563                index: i as u32,
564                bytes,
565                start_byte: span.start as u32,
566                end_byte: span.end as u32,
567            });
568        }
569        let body_contiguous = fragments.len() <= 1;
570        let body_bytes = doc.body_bytes();
571        let body = std::str::from_utf8(&body_bytes)
572            .map_err(|_| non_utf8(rel.clone()))?
573            .to_string();
574        // Lossy convenience strings; raw title bytes remain authoritative.
575        let tags: Vec<String> = doc
576            .tags()
577            .map(|t| {
578                String::from_utf8_lossy(t)
579                    .trim_start_matches('#')
580                    .to_string()
581            })
582            .collect();
583        let title = doc
584            .title()
585            .map(|bytes| std::str::from_utf8(bytes).map(str::to_string))
586            .transpose()
587            .map_err(|_| non_utf8(rel.clone()))?;
588        let title_text = doc.title().map(|bytes| {
589            let s = String::from_utf8_lossy(bytes);
590            s.trim_end_matches('\n')
591                .trim_start_matches('#')
592                .trim()
593                .to_string()
594        });
595        Ok(ShowNote {
596            selector: numeric_selector_for_path(notebook, &root, &rel, selector),
597            path: rel.clone(),
598            kind: doc.kind(),
599            todo_state: doc.todo_state(),
600            title,
601            title_text,
602            tags,
603            body_fragments: fragments,
604            body_contiguous,
605            body,
606            fingerprint: fingerprint::fingerprint(&doc),
607            source: source_str,
608            numeric_id: numeric_id_for_path(&root, &rel),
609        })
610    }
611
612    /// Raw-bytes escape hatch: full file bytes without UTF-8 validation.
613    ///
614    /// This is the only public read that returns `Vec<u8>`; every other
615    /// structured read is text-only and returns `NonUtf8` on invalid UTF-8.
616    pub async fn read_note_source_bytes(
617        &self,
618        target: NoteTarget,
619        notebook: Option<&str>,
620    ) -> Result<Vec<u8>, NbError> {
621        let (notebook, selector) = self.resolve_note_target(&target, notebook).await?;
622        self.with_notebook_gate(&notebook, async {
623            let path = self.resolve_item_path(&selector).await?;
624            std::fs::read(&path).map_err(|e| NbError::Io {
625                path: path.clone(),
626                source: e.into(),
627            })
628        })
629        .await
630    }
631
632    /// Enumerate body lines for a contiguous-body note.
633    pub async fn show_note_lines(
634        &self,
635        target: NoteTarget,
636        offset: Option<u32>,
637        limit: Option<u32>,
638        notebook: Option<&str>,
639    ) -> Result<ShowNoteLines, 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().to_vec();
644            let doc = parse(&source, ParseContext::FromPath(PathBuf::from(&shown.path)))?;
645            let body = require_contiguous_body(&doc)?;
646            let (eol, has_final_eol, lines) = document_lines(&body);
647            let total_lines = lines.len() as u32;
648            let offset = offset.unwrap_or(1);
649            let limit = limit.unwrap_or(100);
650            if offset == 0 {
651                return Err(NbError::InvalidLineWindow {
652                    offset,
653                    limit,
654                    total_lines,
655                });
656            }
657            if total_lines == 0 {
658                if offset != 1 {
659                    return Err(NbError::InvalidLineWindow {
660                        offset,
661                        limit,
662                        total_lines,
663                    });
664                }
665                return Ok(ShowNoteLines {
666                    selector: shown.selector,
667                    path: shown.path,
668                    kind: shown.kind,
669                    total_lines: 0,
670                    offset,
671                    limit,
672                    next_offset: None,
673                    lines: Vec::new(),
674                    title: shown.title,
675                    tags: shown.tags,
676                    body_fingerprint: shown.fingerprint,
677                    eol: None,
678                    has_final_eol: false,
679                    numeric_id: shown.numeric_id,
680                });
681            }
682            if offset > total_lines + 1 {
683                return Err(NbError::InvalidLineWindow {
684                    offset,
685                    limit,
686                    total_lines,
687                });
688            }
689            let start_idx = (offset - 1) as usize;
690            let end_idx = (start_idx + limit as usize).min(lines.len());
691            let window: Vec<_> = lines[start_idx..end_idx]
692                .iter()
693                .map(|l| note_line_from_body_line(l, &body))
694                .collect();
695            let next_offset = if end_idx < lines.len() {
696                Some(offset + window.len() as u32)
697            } else {
698                None
699            };
700            Ok(ShowNoteLines {
701                selector: shown.selector,
702                path: shown.path,
703                kind: shown.kind,
704                total_lines,
705                offset,
706                limit,
707                next_offset,
708                lines: window,
709                title: shown.title,
710                tags: shown.tags,
711                body_fingerprint: shown.fingerprint,
712                eol,
713                has_final_eol,
714                numeric_id: shown.numeric_id,
715            })
716        })
717        .await
718    }
719
720    /// Search body line texts for a pattern (contiguous body only).
721    pub async fn search_note_lines(
722        &self,
723        target: NoteTarget,
724        pattern: &str,
725        notebook: Option<&str>,
726    ) -> Result<SearchNoteLines, NbError> {
727        let (notebook, selector) = self.resolve_note_target(&target, notebook).await?;
728        self.with_notebook_gate(&notebook, async {
729            let shown = self.show_note_inner(&notebook, &selector).await?;
730            let source = shown.source.as_bytes().to_vec();
731            let doc = parse(&source, ParseContext::FromPath(PathBuf::from(&shown.path)))?;
732            let body = require_contiguous_body(&doc)?;
733            let hits = search_lines(&body, pattern.as_bytes())?;
734            Ok(SearchNoteLines {
735                selector: shown.selector,
736                path: shown.path,
737                kind: shown.kind,
738                hits,
739                body_fingerprint: shown.fingerprint,
740            })
741        })
742        .await
743    }
744
745    async fn resolve_item_path(&self, selector: &str) -> Result<PathBuf, NbError> {
746        let output = self
747            .exec_vec(vec![
748                "show".to_string(),
749                selector.to_string(),
750                "--path".to_string(),
751                "--no-color".to_string(),
752            ])
753            .await
754            .map_err(|err| match err {
755                NbError::CommandFailed { stderr, .. }
756                    if is_selector_not_found(&stderr, selector) =>
757                {
758                    NbError::NotFound {
759                        selector: selector.to_string(),
760                    }
761                }
762                other => other,
763            })?;
764        let path = output.trim();
765        if path.is_empty() {
766            return Err(NbError::CommandFailed {
767                command: format!("nb show {selector} --path"),
768                stderr: "empty path".into(),
769                exit_code: None,
770            });
771        }
772        Ok(PathBuf::from(path))
773    }
774
775    async fn resolve_note_target(
776        &self,
777        target: &NoteTarget,
778        notebook: Option<&str>,
779    ) -> Result<(String, String), NbError> {
780        match target {
781            NoteTarget::Selector { value } => self.resolve_target_selector(value, notebook).await,
782            NoteTarget::Path { value } => {
783                let notebook = self.resolve_notebook(notebook).await?;
784                Ok((notebook.clone(), format!("{notebook}:{value}")))
785            }
786        }
787    }
788
789    /// Probe the textual classification of a selector via `nb`'s
790    /// native `--type` mechanism.
791    ///
792    /// Two-step probe: first `nb show <selector> --type text` to
793    /// ask `nb` whether the type is text. If yes, return
794    /// [`ShowClassification::Textual`]. If no, follow up with
795    /// `nb show <selector> --type` to recover the `actual_type`
796    /// for the error diagnostic. If the follow-up also fails
797    /// (selector not found, internal error), return
798    /// [`ShowClassification::ProbeFailure`] so the caller can
799    /// fall through to the original show path.
800    async fn probe_show_classification(&self, selector: &str) -> ShowClassification {
801        let textual = self
802            .exec_vec(vec![
803                "show".to_string(),
804                selector.to_string(),
805                "--type".to_string(),
806                "text".to_string(),
807                "--no-color".to_string(),
808            ])
809            .await;
810        if textual.is_ok() {
811            return ShowClassification::Textual;
812        }
813        match self
814            .exec_vec(vec![
815                "show".to_string(),
816                selector.to_string(),
817                "--type".to_string(),
818                "--no-color".to_string(),
819            ])
820            .await
821        {
822            Ok(stdout) => {
823                let trimmed = stdout.trim();
824                if trimmed.is_empty() {
825                    ShowClassification::ProbeFailure
826                } else {
827                    ShowClassification::NonTextual {
828                        actual_type: trimmed.to_string(),
829                    }
830                }
831            }
832            Err(_) => ShowClassification::ProbeFailure,
833        }
834    }
835
836    /// Lists notes in a notebook or folder.
837    pub async fn list_notes(
838        &self,
839        folder: Option<&str>,
840        tags: &[String],
841        limit: Option<u32>,
842        notebook: Option<&str>,
843    ) -> Result<String, NbError> {
844        let mut args = Vec::new();
845        validate_folder_option(folder)?;
846
847        let notebook = self.resolve_notebook(notebook).await?;
848        let cmd = match folder {
849            Some(f) => format!("{}:{}/", notebook, f),
850            None => format!("{}:", notebook),
851        };
852
853        args.push("list".to_string());
854        args.push(cmd);
855
856        // No color for parsing
857        args.push("--no-color".to_string());
858
859        // Limit
860        if let Some(n) = limit {
861            args.push("-n".to_string());
862            args.push(n.to_string());
863        }
864
865        // Tags filter
866        for tag in tags {
867            args.push("--tags".to_string());
868            let tag_str = if tag.starts_with('#') {
869                tag.clone()
870            } else {
871                format!("#{}", tag)
872            };
873            args.push(tag_str);
874        }
875
876        // Strip the trailing usage/help hint block from empty
877        // results (`0 items.` followed by `Add a note:`,
878        // `Import a file:`, `Help information:`). Detection
879        // keys off the empty-result signal per the
880        // `output-behavior` specification. See `output.rs`
881        // for the helper's contract.
882        self.exec_vec(args)
883            .await
884            .map(|output| strip_empty_result_hint(&output))
885    }
886
887    /// Searches notes.
888    pub async fn search_notes(
889        &self,
890        queries: &[String],
891        mode: SearchMode,
892        tags: &[String],
893        folder: Option<&str>,
894        notebook: Option<&str>,
895    ) -> Result<String, NbError> {
896        validate_folder_option(folder)?;
897        if queries.is_empty() {
898            return Err(NbError::ValidationError {
899                reason: "at least one search query is required".to_string(),
900                location: None,
901            });
902        }
903
904        let notebook = self.resolve_notebook(notebook).await?;
905        let scope = match folder {
906            Some(f) => format!("{}:{}/", notebook, f),
907            None => format!("{}:", notebook),
908        };
909        let args = search_command_args(scope, queries, mode, tags);
910        self.exec_vec(args).await
911    }
912
913    /// Deletes a note (one-shot transaction).
914    pub async fn delete_note(
915        &self,
916        id: &str,
917        notebook: Option<&str>,
918    ) -> Result<CommitOutcome, NbError> {
919        let (nb, selector) = self.resolve_target_selector(id, notebook).await?;
920        let target = self.note_target_for_selector(&nb, &selector).await?;
921        let mut tx = self.transaction(Some(&nb)).await?;
922        tx.delete_note(target)?;
923        tx.commit().await
924    }
925
926    /// Moves or renames a note (one-shot transaction).
927    pub async fn move_note(
928        &self,
929        id: &str,
930        destination: &str,
931        notebook: Option<&str>,
932    ) -> Result<CommitOutcome, NbError> {
933        validate_destination(destination)?;
934        let (nb, selector) = self.resolve_target_selector(id, notebook).await?;
935        let target = self.note_target_for_selector(&nb, &selector).await?;
936        let mut tx = self.transaction(Some(&nb)).await?;
937        tx.move_note(target, destination)?;
938        tx.commit().await
939    }
940
941    async fn note_target_for_selector(
942        &self,
943        notebook: &str,
944        selector: &str,
945    ) -> Result<NoteTarget, NbError> {
946        let root = self.show_notebook_path_unguarded(Some(notebook)).await?;
947        let stripped = selector
948            .rsplit_once(':')
949            .map(|(_, rest)| rest)
950            .unwrap_or(selector);
951        let direct = root.join(stripped);
952        if direct.is_file() {
953            return Ok(NoteTarget::path(stripped));
954        }
955        // Fall back to `nb show --path` for numeric ids / titles.
956        let abs = self.resolve_item_path(selector).await?;
957        let rel = path_relative_to(&root, &abs)?;
958        Ok(NoteTarget::path(rel))
959    }
960
961    /// Creates a todo item (one-shot transaction; nb-mangled filename).
962    pub async fn add_todo(
963        &self,
964        title: &str,
965        description: Option<&str>,
966        tasks: &[String],
967        tags: &[String],
968        folder: Option<&str>,
969        notebook: Option<&str>,
970    ) -> Result<CommitOutcome, NbError> {
971        self.require_folder_for_new_note(folder)?;
972        validate_folder_option(folder)?;
973        let filename = transaction::filename_for_title(Some(title), "todo.md");
974        self.create_with_retry(notebook, folder, filename, |tx, path| {
975            tx.add_todo(&path, title, description, tasks, tags)
976        })
977        .await
978    }
979
980    /// Marks a todo as done (one-shot transaction).
981    pub async fn mark_task_done(
982        &self,
983        id: &str,
984        task_number: Option<u32>,
985        notebook: Option<&str>,
986    ) -> Result<CommitOutcome, NbError> {
987        let (nb, selector) = self.resolve_target_selector(id, notebook).await?;
988        let target = self.note_target_for_selector(&nb, &selector).await?;
989        let mut tx = self.transaction(Some(&nb)).await?;
990        tx.mark_task_done(target, task_number)?;
991        tx.commit().await
992    }
993
994    /// Marks a todo as not done (one-shot transaction).
995    pub async fn unmark_task_done(
996        &self,
997        id: &str,
998        task_number: Option<u32>,
999        notebook: Option<&str>,
1000    ) -> Result<CommitOutcome, NbError> {
1001        let (nb, selector) = self.resolve_target_selector(id, notebook).await?;
1002        let target = self.note_target_for_selector(&nb, &selector).await?;
1003        let mut tx = self.transaction(Some(&nb)).await?;
1004        tx.unmark_task_done(target, task_number)?;
1005        tx.commit().await
1006    }
1007
1008    /// Replace contiguous body text (one-shot).
1009    pub async fn replace_note_body(
1010        &self,
1011        target: NoteTarget,
1012        new_body: &str,
1013        fingerprint: Fingerprint,
1014        notebook: Option<&str>,
1015    ) -> Result<CommitOutcome, NbError> {
1016        let mut tx = self.transaction(notebook).await?;
1017        tx.replace_note_body(target, new_body, fingerprint)?;
1018        tx.commit().await
1019    }
1020
1021    /// Substring edit on contiguous body (one-shot).
1022    #[allow(clippy::too_many_arguments)]
1023    pub async fn edit_note_substring(
1024        &self,
1025        target: NoteTarget,
1026        pattern: &str,
1027        replacement: &str,
1028        occurrence: Occurrence,
1029        expected_count: u32,
1030        fingerprint: Option<Fingerprint>,
1031        notebook: Option<&str>,
1032    ) -> Result<CommitOutcome, NbError> {
1033        let mut tx = self.transaction(notebook).await?;
1034        tx.edit_note_substring(
1035            target,
1036            pattern,
1037            replacement,
1038            occurrence,
1039            expected_count,
1040            fingerprint,
1041        )?;
1042        tx.commit().await
1043    }
1044
1045    /// Line-oriented body edit batch (one-shot).
1046    pub async fn edit_note_lines(
1047        &self,
1048        target: NoteTarget,
1049        edits: Vec<LineEdit>,
1050        notebook: Option<&str>,
1051    ) -> Result<CommitOutcome, NbError> {
1052        let mut tx = self.transaction(notebook).await?;
1053        tx.edit_note_lines(target, edits)?;
1054        tx.commit().await
1055    }
1056
1057    /// Retitle a note without changing path (one-shot).
1058    pub async fn retitle_note(
1059        &self,
1060        target: NoteTarget,
1061        title: &str,
1062        notebook: Option<&str>,
1063    ) -> Result<CommitOutcome, NbError> {
1064        let mut tx = self.transaction(notebook).await?;
1065        tx.retitle_note(target, title)?;
1066        tx.commit().await
1067    }
1068
1069    /// Add/remove tags (one-shot).
1070    pub async fn edit_note_tags(
1071        &self,
1072        target: NoteTarget,
1073        add: &[String],
1074        remove: &[String],
1075        notebook: Option<&str>,
1076    ) -> Result<CommitOutcome, NbError> {
1077        let mut tx = self.transaction(notebook).await?;
1078        tx.edit_note_tags(target, add, remove)?;
1079        tx.commit().await
1080    }
1081
1082    /// Lists checklist items within todos.
1083    ///
1084    /// Invokes the `nb tasks` subcommand. The method enumerates
1085    /// the checklist items within todos (and recursively into
1086    /// subfolders when `recursive = true`), filtered by
1087    /// `status` if provided. The method name matches the
1088    /// underlying `nb` CLI command (`nb tasks`); a future
1089    /// `list_todos` method for the todo **container** listing
1090    /// (invoking `nb todos`) is tracked at
1091    /// `nb-api:todos/api/5` (deferred to `0.3.0+`).
1092    pub async fn list_tasks(
1093        &self,
1094        folder: Option<&str>,
1095        status: Option<TaskStatus>,
1096        recursive: bool,
1097        notebook: Option<&str>,
1098    ) -> Result<String, NbError> {
1099        validate_folder_option(folder)?;
1100        let notebook = self.resolve_notebook(notebook).await?;
1101        let folder = folder.map(normalize_folder);
1102        let scopes = if recursive {
1103            self.tasks_scopes_recursive(&notebook, folder.as_deref())
1104                .await?
1105        } else {
1106            vec![tasks_scope(&notebook, folder.as_deref())]
1107        };
1108
1109        let mut outputs: Vec<String> = Vec::new();
1110        let mut saw_empty = false;
1111        for scope in scopes {
1112            match self.exec_vec(tasks_command_args(scope, status)).await {
1113                Ok(output) => {
1114                    let output = output.trim();
1115                    if !output.is_empty() {
1116                        outputs.push(output.to_string());
1117                    }
1118                }
1119                Err(NbError::CommandFailed { stderr, .. }) if is_empty_tasks_error(&stderr) => {
1120                    saw_empty = true;
1121                }
1122                Err(err) => return Err(err),
1123            }
1124        }
1125        if outputs.is_empty() && saw_empty {
1126            // The `nb` subprocess actually succeeded (exit 0);
1127            // it simply returned no tasks. This is a policy-level
1128            // empty-result, not a command failure. Map to
1129            // ValidationError rather than fabricate a
1130            // CommandFailed with `exit_code: Some(0)` (which
1131            // would be factually misleading).
1132            return Err(NbError::ValidationError {
1133                reason: empty_tasks_message(status),
1134                location: None,
1135            });
1136        }
1137        Ok(outputs.join("\n"))
1138    }
1139
1140    async fn tasks_scopes_recursive(
1141        &self,
1142        notebook: &str,
1143        folder: Option<&str>,
1144    ) -> Result<Vec<String>, NbError> {
1145        let notebook_root = self.show_notebook_path(Some(notebook)).await?;
1146        let start = folder.unwrap_or_default().to_string();
1147        let mut queue = VecDeque::new();
1148        queue.push_back(start.clone());
1149
1150        let mut scopes = vec![tasks_scope(notebook, folder)];
1151        while let Some(current) = queue.pop_front() {
1152            let base = if current.is_empty() {
1153                notebook_root.clone()
1154            } else {
1155                notebook_root.join(&current)
1156            };
1157            let children = child_folder_names(&base)?;
1158            for child in children {
1159                let next = if current.is_empty() {
1160                    child
1161                } else {
1162                    format!("{}/{}", current, child)
1163                };
1164                scopes.push(tasks_scope(notebook, Some(&next)));
1165                queue.push_back(next);
1166            }
1167        }
1168        Ok(scopes)
1169    }
1170
1171    /// Creates a bookmark (one-shot transaction; nb-mangled filename).
1172    pub async fn add_bookmark(
1173        &self,
1174        url: &str,
1175        title: Option<&str>,
1176        tags: &[String],
1177        comment: Option<&str>,
1178        folder: Option<&str>,
1179        notebook: Option<&str>,
1180    ) -> Result<CommitOutcome, NbError> {
1181        self.require_folder_for_new_note(folder)?;
1182        validate_folder_option(folder)?;
1183        let filename = transaction::filename_for_title(title, "bookmark.md");
1184        self.create_with_retry(notebook, folder, filename, |tx, path| {
1185            tx.add_bookmark(&path, url, title, tags, comment)
1186        })
1187        .await
1188    }
1189
1190    /// Lists folders in a notebook.
1191    pub async fn list_folders(
1192        &self,
1193        parent: Option<&str>,
1194        notebook: Option<&str>,
1195    ) -> Result<String, NbError> {
1196        let mut args = vec!["list".to_string()];
1197        validate_folder_option(parent)?;
1198
1199        let notebook = self.resolve_notebook(notebook).await?;
1200        let path = match parent {
1201            Some(p) => format!("{}:{}/", notebook, p),
1202            None => format!("{}:", notebook),
1203        };
1204        args.push(path);
1205
1206        // Filter to only show folders
1207        args.push("--type".to_string());
1208        args.push("folder".to_string());
1209        args.push("--no-color".to_string());
1210
1211        // Strip the trailing usage/help hint block from empty
1212        // results (`0 folders.` followed by `Import a file:`,
1213        // `Help information:`). Detection keys off the
1214        // empty-result signal per the `output-behavior`
1215        // specification. See `output.rs` for the helper's
1216        // contract.
1217        self.exec_vec(args)
1218            .await
1219            .map(|output| strip_empty_result_hint(&output))
1220    }
1221
1222    /// Creates a folder (one-shot transaction).
1223    pub async fn add_folder(
1224        &self,
1225        path: &str,
1226        notebook: Option<&str>,
1227    ) -> Result<CommitOutcome, NbError> {
1228        validate_folder_path(path)?;
1229        let mut tx = self.transaction(notebook).await?;
1230        tx.add_folder(path)?;
1231        tx.commit().await
1232    }
1233
1234    /// Imports a file or URL into the notebook as a note.
1235    ///
1236    /// One-shot only under the process-shared notebook gate. Not a
1237    /// [`Transaction`] plan op in 0.3.0.
1238    pub async fn import_note(
1239        &self,
1240        source: &str,
1241        folder: Option<&str>,
1242        filename: Option<&str>,
1243        convert: bool,
1244        notebook: Option<&str>,
1245    ) -> Result<String, NbError> {
1246        let mut args = Vec::new();
1247        self.require_folder_for_new_note(folder)?;
1248        validate_folder_option(folder)?;
1249
1250        let notebook = self.resolve_notebook(notebook).await?;
1251        self.with_notebook_gate(&notebook, async {
1252            let cmd = format!("{}:import", notebook);
1253            args.push(cmd);
1254            args.push(source.to_string());
1255            if convert {
1256                args.push("--convert".to_string());
1257            }
1258            if folder.is_some() || filename.is_some() {
1259                let dest = match (folder, filename) {
1260                    (Some(f), Some(n)) => format!("{}/{}", f, n),
1261                    (Some(f), None) => format!("{}/", f),
1262                    (None, Some(n)) => n.to_string(),
1263                    (None, None) => unreachable!(),
1264                };
1265                args.push(dest);
1266            }
1267            self.exec_vec(args)
1268                .await
1269                .map(|output| self.append_notebook_warning(output, &notebook))
1270        })
1271        .await
1272    }
1273}
1274
1275/// Numeric `.index` id for a notebook-relative path, if the basename is
1276/// listed in its folder `.index` (blank/deleted lines never match).
1277fn numeric_id_for_path(notebook_root: &Path, rel: &str) -> Option<u32> {
1278    let (folder, basename) = match rel.rfind('/') {
1279        Some(i) => (rel[..i].to_string(), rel[i + 1..].to_string()),
1280        None => (String::new(), rel.to_string()),
1281    };
1282    transaction::index_id_in_folder(notebook_root, &folder, &basename)
1283}
1284
1285/// `ShowNote`/`ShowNoteLines` selector: numeric `<folder>/<id>` form when the
1286/// path resolves via `.index`, else the qualified selector that was read.
1287fn numeric_selector_for_path(
1288    notebook: &str,
1289    notebook_root: &Path,
1290    rel: &str,
1291    fallback: &str,
1292) -> String {
1293    match numeric_id_for_path(notebook_root, rel) {
1294        Some(id) => match rel.rfind('/') {
1295            Some(i) => format!("{notebook}:{}/{}", &rel[..i], id),
1296            None => format!("{notebook}:{id}"),
1297        },
1298        None => fallback.to_string(),
1299    }
1300}
1301
1302fn notebook_dir_from_env(notebook: &str) -> Option<PathBuf> {
1303    let nb_dir = std::env::var_os("NB_DIR")?;
1304    let path = PathBuf::from(nb_dir).join(notebook);
1305    if path.is_dir() && path.join(".git").exists() {
1306        Some(path)
1307    } else {
1308        None
1309    }
1310}
1311
1312fn path_relative_to(root: &Path, path: &Path) -> Result<String, NbError> {
1313    let root = root.canonicalize().map_err(|e| NbError::Io {
1314        path: root.to_path_buf(),
1315        source: e.into(),
1316    })?;
1317    let path = path.canonicalize().map_err(|e| NbError::Io {
1318        path: path.to_path_buf(),
1319        source: e.into(),
1320    })?;
1321    let rel = path
1322        .strip_prefix(&root)
1323        .map_err(|_| NbError::ValidationError {
1324            reason: format!(
1325                "path {} is not under notebook root {}",
1326                path.display(),
1327                root.display()
1328            ),
1329            location: None,
1330        })?;
1331    Ok(rel.to_string_lossy().replace('\\', "/"))
1332}