Skip to main content

nb_api/
lib.rs

1//! Typed Rust interface to the `nb` note-taking CLI.
2//!
3//! Handles notebook qualification, escaping, and output parsing.
4//! Wraps the `nb` CLI as a subprocess, providing async methods for
5//! all note-taking operations.
6
7mod git;
8mod git_env;
9mod output;
10
11#[cfg(feature = "testing")]
12pub mod testing;
13
14pub use git::{derive_git_notebook_name, git_rev_parse};
15pub use git_env::{leaked_git_names, scrub_git_env, scrub_git_env_std};
16
17use std::{collections::VecDeque, path::PathBuf, process::Stdio, sync::LazyLock};
18
19use regex::Regex;
20use serde::{Deserialize, Serialize};
21use tokio::process::Command;
22
23/// Regex to match ANSI/ISO 2022 escape sequences.
24///
25/// Covers:
26/// - Fe sequences: `ESC [@-Z\-_]` (single byte after ESC)
27/// - CSI sequences: `ESC [ ... m` (SGR colors, cursor control, etc.)
28/// - nF sequences: `ESC [ -/]* [0-~]` (character set designation like `ESC ( B`)
29static ANSI_REGEX: LazyLock<Regex> =
30    LazyLock::new(|| Regex::new(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|[ -/]*[0-~])").unwrap());
31
32/// Strip ANSI escape sequences from text.
33fn strip_ansi(text: &str) -> String {
34    ANSI_REGEX.replace_all(text, "").into_owned()
35}
36
37/// Errors from nb CLI invocation.
38#[derive(Debug, thiserror::Error)]
39pub enum NbError {
40    #[error("nb command failed: {0}")]
41    CommandFailed(String),
42
43    #[error(
44        "nb not found in PATH; install via: brew install xwmx/taps/nb (macOS) or see https://github.com/xwmx/nb#installation"
45    )]
46    NotFound,
47
48    #[error("IO error: {0}")]
49    Io(#[from] std::io::Error),
50
51    /// `nb show` was invoked on a selector whose type is not
52    /// classified as text by `nb` itself (per
53    /// `add-0-2-0-foundation` public-API spec). Folders, archives,
54    /// audio, video, image, and any other non-textual type reach
55    /// this path. The classification delegates to
56    /// `nb show <selector> --type text` so forward compatibility
57    /// is automatic when `nb` adds new textual types. Probe
58    /// failure (e.g., selector not found) does NOT route here;
59    /// it falls through to the original `CommandFailed` error
60    /// from the content-read path.
61    #[error(
62        "selector `{selector}` resolved to non-textual type `{actual_type}`; \
63         `nb show` does not display non-textual content"
64    )]
65    UnsupportedShowTarget {
66        selector: String,
67        actual_type: String,
68    },
69
70    /// `nb add` was called with a `title` and `content` where the
71    /// first nonblank line of `content` is an exact Markdown ATX H1
72    /// duplicating the title. The validation runs in the caller
73    /// process before any subprocess invocation or notebook side
74    /// effect (including `resolve_notebook`); the rejection
75    /// happens entirely in-process. `heading` carries the exact
76    /// detected source line (including the leading `#` and any
77    /// surrounding whitespace) for actionable diagnostics. See
78    /// `add-0-2-0-foundation` public-API specification.
79    #[error(
80        "title `{title}` duplicates the first H1 in content (`{heading}`); \
81         remove the duplicate heading to avoid double-rendering"
82    )]
83    DuplicateTitleHeading { title: String, heading: String },
84}
85
86/// Result of probing a selector's textual classification via
87/// `nb show <selector> --type text`. Used by
88/// [`NbClient::show_note`](crate::NbClient::show_note) to decide whether
89/// the content-read path is safe.
90enum ShowClassification {
91    /// `nb` classified the type as text. Caller proceeds to
92    /// the content-read path.
93    Textual,
94    /// `nb` classified the type as non-text (folder, archive,
95    /// image, audio, video, etc.). `actual_type` carries the
96    /// `nb`-reported type string (file extension or `folder`).
97    NonTextual { actual_type: String },
98    /// The probe could not classify the selector (selector not
99    /// found, internal error). Caller falls through to the
100    /// original show path so existing missing-selector
101    /// diagnostics are preserved.
102    ProbeFailure,
103}
104
105/// Configuration for constructing an [`NbClient`].
106///
107/// Contains only nb-relevant fields. MCP-specific fields
108/// (e.g., `show_paths`) remain in the server's config.
109#[derive(Clone, Debug)]
110pub struct Config {
111    /// Default notebook name (overrides Git-derived fallback).
112    pub notebook: Option<String>,
113    /// Automatically create missing notebooks.
114    pub create_notebook: bool,
115    /// Allow new notes to be created at notebook root.
116    pub allow_top_level_notes: bool,
117    /// Disable Git commit and tag signing for `nb` subprocesses.
118    pub disable_git_signing: bool,
119}
120
121impl Default for Config {
122    fn default() -> Self {
123        Self {
124            notebook: None,
125            create_notebook: true,
126            allow_top_level_notes: false,
127            disable_git_signing: false,
128        }
129    }
130}
131
132/// Client for invoking nb commands.
133#[derive(Clone)]
134pub struct NbClient {
135    /// Default notebook to use if not specified per-command.
136    default_notebook: Option<String>,
137    /// Automatically create missing notebooks.
138    create_notebook: bool,
139    /// Disable Git commit and tag signing for `nb` subprocesses.
140    disable_git_signing: bool,
141    /// Allow new notes to be created at notebook root.
142    allow_top_level_notes: bool,
143}
144
145const 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.";
146
147const NOTEBOOK_FIELD_MESSAGE: &str = "Invalid `notebook`: use a bare notebook name only. Use `folder` for folder paths and `id`/`selector` for note selectors.";
148
149const FOLDER_FIELD_MESSAGE: &str = "Invalid folder path: use `folder` for folder paths only, not notebook-qualified selectors. To choose a notebook, use the separate `notebook` field.";
150
151/// Behavior mode for [`NbClient::edit_note`] content updates.
152///
153/// ## Vocabulary
154///
155/// The variant previously named `Replace` is now `Overwrite` to
156/// remove the vocabulary trap at the root of `nb-api:issues/api/6`:
157/// callers reading `mode: "replace"` reasonably expected a
158/// substring-style replacement (analogous to
159/// [`str::replace`]), but `nb edit --overwrite`
160/// is destructive — it replaces every byte of the note body.
161/// Renaming the variant to `Overwrite` makes the destructive
162/// intent unambiguous at the call site.
163///
164/// The legacy string `"replace"` is accepted as a serde alias for
165/// backward compatibility with payloads produced before this
166/// rename. The alias is **not** advertised in the derived
167/// [`schemars`](https://docs.rs/schemars) JSON Schema — only the
168/// canonical `"overwrite"` is exposed to MCP tool consumers.
169///
170/// ## Mapping
171///
172/// | Variant | Canonical serialization | `nb edit` flag(s) | Effect |
173/// |---------|------------------------|-------------------|--------|
174/// | [`EditMode::Overwrite`] | `"overwrite"` | `--overwrite --content <content>` | Replace **every byte** of the note body with `<content>`. Destructive: any existing content is lost. |
175/// | [`EditMode::Append`] | `"append"` | `--content <content>` | Append `<content>` after the existing note body. |
176/// | [`EditMode::Prepend`] | `"prepend"` | `--prepend --content <content>` | Prepend `<content>` before the existing note body. |
177///
178/// ## Default
179///
180/// `EditMode` derives `Default` with `EditMode::Overwrite` as the
181/// default variant. This is the **`nb-api` default**, chosen for
182/// compatibility with the current API contract and the documented
183/// destructive default on `nb_api`'s edit API. Note that this is
184/// distinct from the `nb` CLI's native no-flag behavior (`nb edit
185/// --content` without `--overwrite` appends; see the mapping
186/// table above). Requiredness on the consumer side (e.g., the
187/// `mode` field on `nb-mcp-server`'s `EditArgs`) is a
188/// **consumer-layer concern**, not enforced here. Downstream
189/// consumers that want to require `mode` explicitly should drop
190/// `#[serde(default)]` from their containing struct.
191#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)]
192#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
193#[serde(rename_all = "lowercase")]
194pub enum EditMode {
195    /// Replace **every byte** of the note body with the provided
196    /// content. Destructive: any existing content is lost. Maps to
197    /// `nb edit --overwrite --content <content>`.
198    ///
199    /// Accepts legacy `"replace"` as a serde alias for backward
200    /// compatibility with payloads produced before the variant
201    /// rename. The alias is not advertised in the derived JSON
202    /// Schema; only `"overwrite"` is exposed to schema consumers.
203    #[default]
204    #[serde(alias = "replace")]
205    Overwrite,
206    /// Append the provided content after the existing note body.
207    /// Maps to `nb edit --content <content>` (the `nb` default
208    /// content-mode behavior).
209    Append,
210    /// Prepend the provided content before the existing note body.
211    /// Maps to `nb edit --prepend --content <content>`.
212    Prepend,
213}
214
215/// Matching mode for `nb search` query terms.
216#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq, Eq)]
217#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
218#[serde(rename_all = "lowercase")]
219pub enum SearchMode {
220    /// Match any query term (`OR` semantics).
221    #[default]
222    Any,
223    /// Require all query terms (`AND` semantics).
224    All,
225}
226
227/// Status filter for `nb tasks`.
228#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
229#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
230#[serde(rename_all = "lowercase")]
231pub enum TaskStatus {
232    /// Return open tasks.
233    Open,
234    /// Return closed tasks.
235    Closed,
236}
237
238impl NbClient {
239    /// Creates a new nb client.
240    ///
241    /// Uses the notebook from config if set, otherwise falls back to a
242    /// Git-derived notebook name. Does NOT read `NB_MCP_NOTEBOOK` —
243    /// that is an MCP-server-specific env var resolved by the server.
244    pub fn new(config: &Config) -> anyhow::Result<Self> {
245        let default_notebook = config
246            .notebook
247            .as_deref()
248            .map(String::from)
249            .or_else(derive_git_notebook_name);
250        Ok(Self {
251            default_notebook,
252            create_notebook: config.create_notebook,
253            disable_git_signing: config.disable_git_signing,
254            allow_top_level_notes: config.allow_top_level_notes,
255        })
256    }
257
258    fn require_folder_for_new_note(&self, folder: Option<&str>) -> Result<(), NbError> {
259        if self.allow_top_level_notes || folder.is_some_and(|value| !value.trim().is_empty()) {
260            return Ok(());
261        }
262        Err(NbError::CommandFailed(FOLDER_REQUIRED_MESSAGE.to_string()))
263    }
264
265    async fn resolve_target_selector(
266        &self,
267        id: &str,
268        notebook: Option<&str>,
269    ) -> Result<(String, String), NbError> {
270        if let Some((embedded_notebook, path)) = parse_qualified_selector(id)? {
271            let notebook = match notebook {
272                Some(value) => {
273                    validate_notebook_name(value)?;
274                    if value != embedded_notebook {
275                        return Err(NbError::CommandFailed(format!(
276                            "ambiguous selector: id targets notebook `{embedded_notebook}`, but notebook field is `{value}`"
277                        )));
278                    }
279                    embedded_notebook.to_string()
280                }
281                _ => embedded_notebook.to_string(),
282            };
283            self.ensure_existing_notebook(&notebook).await?;
284            return Ok((notebook, format!("{}:{}", embedded_notebook, path)));
285        }
286        let notebook = self.resolve_notebook(notebook).await?;
287        Ok((notebook.clone(), format!("{}:{}", notebook, id)))
288    }
289
290    fn append_notebook_warning(&self, output: String, notebook: &str) -> String {
291        let Some(default_notebook) = self.default_notebook.as_deref() else {
292            return output;
293        };
294        if default_notebook == notebook {
295            return output;
296        }
297        append_warning(
298            output,
299            format!(
300                "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."
301            ),
302        )
303    }
304
305    /// Resolves the notebook to use for a command.
306    fn resolve_notebook_name(&self, notebook: Option<&str>) -> Result<String, NbError> {
307        if let Some(name) = notebook {
308            validate_notebook_name(name)?;
309            return Ok(name.to_string());
310        }
311        if let Some(name) = self.default_notebook.as_deref() {
312            validate_notebook_name(name)?;
313            return Ok(name.to_string());
314        }
315        Err(NbError::CommandFailed(
316            "notebook not configured; set --notebook or NB_MCP_NOTEBOOK".to_string(),
317        ))
318    }
319
320    async fn resolve_notebook(&self, notebook: Option<&str>) -> Result<String, NbError> {
321        let name = self.resolve_notebook_name(notebook)?;
322        self.ensure_notebook(&name).await?;
323        Ok(name)
324    }
325
326    async fn ensure_notebook(&self, notebook: &str) -> Result<(), NbError> {
327        match self.check_notebook(notebook).await {
328            Ok(()) => Ok(()),
329            Err(_) => {
330                if !self.create_notebook {
331                    return Err(NbError::CommandFailed(format!(
332                        "notebook not found; create it with the nb CLI (`nb notebooks add {}`) \
333                         or remove --no-create-notebook",
334                        notebook
335                    )));
336                }
337                self.exec_vec(vec![
338                    "notebooks".to_string(),
339                    "add".to_string(),
340                    notebook.to_string(),
341                ])
342                .await?;
343                Ok(())
344            }
345        }
346    }
347
348    async fn ensure_existing_notebook(&self, notebook: &str) -> Result<(), NbError> {
349        self.check_notebook(notebook).await.map_err(|_| {
350            NbError::CommandFailed(format!(
351                "notebook not found: `{notebook}`. Use a copied selector only for an existing notebook."
352            ))
353        })
354    }
355
356    async fn check_notebook(&self, notebook: &str) -> Result<(), NbError> {
357        let show_result = self
358            .exec_vec(vec![
359                "notebooks".to_string(),
360                "show".to_string(),
361                notebook.to_string(),
362                "--path".to_string(),
363            ])
364            .await;
365        match show_result {
366            Ok(output) => {
367                if output.trim().is_empty() {
368                    return Err(NbError::CommandFailed(
369                        "nb notebooks path output was empty".to_string(),
370                    ));
371                }
372                Ok(())
373            }
374            Err(_) => Err(NbError::CommandFailed(format!(
375                "notebook not found: `{notebook}`"
376            ))),
377        }
378    }
379
380    /// Executes an nb command and returns stdout.
381    async fn exec(&self, args: &[&str]) -> Result<String, NbError> {
382        tracing::debug!(?args, "executing nb command");
383        let mut command = Command::new("nb");
384        // Strip inherited `GIT_*` routing vars before chaining `.args` /
385        // `.env`. Without this, any caller invoking us from inside a
386        // git hook (pre-commit, pre-push, post-checkout) or CI runner
387        // propagates GIT_DIR / GIT_INDEX_FILE / GIT_COMMON_DIR /
388        // GIT_WORK_TREE / GIT_OBJECT_DIRECTORY /
389        // GIT_ALTERNATE_OBJECT_DIRECTORIES into the spawned `nb`,
390        // which is a bash script wrapping git — every git call inside
391        // nb then redirects to the parent repo instead of the
392        // notebook's repo. The blast-by-prefix also covers future
393        // GIT_* redirect vars without requiring a code change.
394        // See `nb-api:issues/3`. Do not remove.
395        scrub_git_env(&mut command);
396        command
397            .args(args)
398            .stdin(Stdio::null()) // Prevent TTY hangs
399            .stdout(Stdio::piped())
400            .stderr(Stdio::piped());
401        if self.disable_git_signing {
402            apply_git_signing_env(&mut command);
403        }
404        let output = command
405            .spawn()
406            .map_err(|e| {
407                if e.kind() == std::io::ErrorKind::NotFound {
408                    NbError::NotFound
409                } else {
410                    NbError::Io(e)
411                }
412            })?
413            .wait_with_output()
414            .await?;
415
416        if output.status.success() {
417            let stdout = String::from_utf8_lossy(&output.stdout);
418            Ok(strip_ansi(&stdout))
419        } else {
420            let stderr = String::from_utf8_lossy(&output.stderr);
421            let stdout = String::from_utf8_lossy(&output.stdout);
422            // nb sometimes writes errors to stdout
423            let msg = if stderr.is_empty() {
424                strip_ansi(&stdout)
425            } else {
426                strip_ansi(&stderr)
427            };
428            Err(NbError::CommandFailed(msg))
429        }
430    }
431
432    /// Executes an nb command with dynamic arguments.
433    async fn exec_vec(&self, args: Vec<String>) -> Result<String, NbError> {
434        let args_ref: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
435        self.exec(&args_ref).await
436    }
437
438    /// Returns status information about the resolved notebook.
439    pub async fn show_notebook_status(&self, notebook: Option<&str>) -> Result<String, NbError> {
440        let notebook = self.resolve_notebook(notebook).await?;
441        self.exec_vec(vec![format!("{}:", notebook), "status".to_string()])
442            .await
443    }
444
445    /// Lists available notebooks.
446    pub async fn list_notebooks(&self) -> Result<String, NbError> {
447        // Use --no-color to avoid ANSI escape codes
448        self.exec(&["notebooks", "--no-color"]).await
449    }
450
451    /// Returns the path for a notebook.
452    pub async fn show_notebook_path(&self, notebook: Option<&str>) -> Result<PathBuf, NbError> {
453        let notebook = self.resolve_notebook(notebook).await?;
454        let output = self
455            .exec_vec(vec![
456                "notebooks".to_string(),
457                "show".to_string(),
458                notebook,
459                "--path".to_string(),
460            ])
461            .await?;
462        let path = output.trim();
463        if path.is_empty() {
464            return Err(NbError::CommandFailed(
465                "nb notebooks path output was empty".to_string(),
466            ));
467        }
468        Ok(PathBuf::from(path))
469    }
470
471    /// Creates a new note.
472    pub async fn add_note(
473        &self,
474        title: Option<&str>,
475        content: &str,
476        tags: &[String],
477        folder: Option<&str>,
478        notebook: Option<&str>,
479    ) -> Result<String, NbError> {
480        // Reject duplicate-H1 BEFORE any subprocess invocation or
481        // notebook side effect (including `resolve_notebook`).
482        // The validation is a pure in-process check; no `nb`
483        // side effect can result from the rejection. This is
484        // the general principle: validate input before any
485        // state-mutating call.
486        if let Some(t) = title
487            && let Some(heading) = detect_duplicate_title_heading(t, content)
488        {
489            return Err(NbError::DuplicateTitleHeading {
490                title: t.to_string(),
491                heading,
492            });
493        }
494        let mut args = Vec::new();
495        self.require_folder_for_new_note(folder)?;
496        validate_folder_option(folder)?;
497
498        let notebook = self.resolve_notebook(notebook).await?;
499        let cmd = format!("{}:add", notebook);
500        args.push(cmd);
501
502        // Title (if provided)
503        if let Some(t) = title {
504            args.push("--title".to_string());
505            args.push(t.to_string());
506        }
507
508        // Content via --content flag (avoids shell escaping issues)
509        args.push("--content".to_string());
510        args.push(content.to_string());
511
512        // Tags (nb expects #hashtag format)
513        for tag in tags {
514            args.push("--tags".to_string());
515            let tag_str = if tag.starts_with('#') {
516                tag.clone()
517            } else {
518                format!("#{}", tag)
519            };
520            args.push(tag_str);
521        }
522
523        // Folder
524        if let Some(f) = folder {
525            args.push("--folder".to_string());
526            args.push(f.to_string());
527        }
528
529        self.exec_vec(args)
530            .await
531            .map(|output| self.append_notebook_warning(output, &notebook))
532    }
533
534    /// Shows a note's content.
535    pub async fn show_note(&self, id: &str, notebook: Option<&str>) -> Result<String, NbError> {
536        let (_, selector) = self.resolve_target_selector(id, notebook).await?;
537        // Probe the selector's classification before reading.
538        // `nb show <selector> --type text` reports whether the
539        // type is text (rc 0) or not (rc non-zero). If the type
540        // is not text, a follow-up `nb show <selector> --type`
541        // reports the actual_type for the error diagnostic. When
542        // the probe cannot classify (selector not found, internal
543        // error), fall through to the original show path so
544        // existing missing-selector diagnostics are preserved.
545        // The semantic check delegates "what is text" to `nb`
546        // itself, ensuring forward compatibility as `nb` adds
547        // new textual types.
548        match self.probe_show_classification(&selector).await {
549            ShowClassification::NonTextual { actual_type } => {
550                return Err(NbError::UnsupportedShowTarget {
551                    selector: selector.clone(),
552                    actual_type,
553                });
554            }
555            ShowClassification::Textual | ShowClassification::ProbeFailure => {
556                // Proceed to content read (Textual) or fall
557                // through to original show (ProbeFailure).
558            }
559        }
560        // Pass `--print` so `nb show` writes stored bytes to stdout instead of
561        // piping through the renderer/pager. The renderer path word-wraps at
562        // ~80 columns when stdout is a pipe, silently corrupting any stored
563        // line longer than that (e.g. JSON in change-meta notes, code blocks,
564        // long URLs). `--print` returns the file verbatim. Do not remove.
565        // See `nb-api:issues/2`.
566        self.exec_vec(vec![
567            "show".to_string(),
568            selector,
569            "--print".to_string(),
570            "--no-color".to_string(),
571        ])
572        .await
573    }
574
575    /// Probe the textual classification of a selector via `nb`'s
576    /// native `--type` mechanism.
577    ///
578    /// Two-step probe: first `nb show <selector> --type text` to
579    /// ask `nb` whether the type is text. If yes, return
580    /// [`ShowClassification::Textual`]. If no, follow up with
581    /// `nb show <selector> --type` to recover the `actual_type`
582    /// for the error diagnostic. If the follow-up also fails
583    /// (selector not found, internal error), return
584    /// [`ShowClassification::ProbeFailure`] so the caller can
585    /// fall through to the original show path.
586    async fn probe_show_classification(&self, selector: &str) -> ShowClassification {
587        let textual = self
588            .exec_vec(vec![
589                "show".to_string(),
590                selector.to_string(),
591                "--type".to_string(),
592                "text".to_string(),
593                "--no-color".to_string(),
594            ])
595            .await;
596        if textual.is_ok() {
597            return ShowClassification::Textual;
598        }
599        match self
600            .exec_vec(vec![
601                "show".to_string(),
602                selector.to_string(),
603                "--type".to_string(),
604                "--no-color".to_string(),
605            ])
606            .await
607        {
608            Ok(stdout) => {
609                let trimmed = stdout.trim();
610                if trimmed.is_empty() {
611                    ShowClassification::ProbeFailure
612                } else {
613                    ShowClassification::NonTextual {
614                        actual_type: trimmed.to_string(),
615                    }
616                }
617            }
618            Err(_) => ShowClassification::ProbeFailure,
619        }
620    }
621
622    /// Lists notes in a notebook or folder.
623    pub async fn list_notes(
624        &self,
625        folder: Option<&str>,
626        tags: &[String],
627        limit: Option<u32>,
628        notebook: Option<&str>,
629    ) -> Result<String, NbError> {
630        let mut args = Vec::new();
631        validate_folder_option(folder)?;
632
633        let notebook = self.resolve_notebook(notebook).await?;
634        let cmd = match folder {
635            Some(f) => format!("{}:{}/", notebook, f),
636            None => format!("{}:", notebook),
637        };
638
639        args.push("list".to_string());
640        args.push(cmd);
641
642        // No color for parsing
643        args.push("--no-color".to_string());
644
645        // Limit
646        if let Some(n) = limit {
647            args.push("-n".to_string());
648            args.push(n.to_string());
649        }
650
651        // Tags filter
652        for tag in tags {
653            args.push("--tags".to_string());
654            let tag_str = if tag.starts_with('#') {
655                tag.clone()
656            } else {
657                format!("#{}", tag)
658            };
659            args.push(tag_str);
660        }
661
662        // Strip the trailing usage/help hint block from empty
663        // results (`0 items.` followed by `Add a note:`,
664        // `Import a file:`, `Help information:`). Detection
665        // keys off the empty-result signal per the
666        // `output-behavior` specification. See `output.rs`
667        // for the helper's contract.
668        self.exec_vec(args)
669            .await
670            .map(|output| output::strip_empty_result_hint(&output))
671    }
672
673    /// Searches notes.
674    pub async fn search_notes(
675        &self,
676        queries: &[String],
677        mode: SearchMode,
678        tags: &[String],
679        folder: Option<&str>,
680        notebook: Option<&str>,
681    ) -> Result<String, NbError> {
682        validate_folder_option(folder)?;
683        if queries.is_empty() {
684            return Err(NbError::CommandFailed(
685                "at least one search query is required".to_string(),
686            ));
687        }
688
689        let notebook = self.resolve_notebook(notebook).await?;
690        let scope = match folder {
691            Some(f) => format!("{}:{}/", notebook, f),
692            None => format!("{}:", notebook),
693        };
694        let args = search_command_args(scope, queries, mode, tags);
695        self.exec_vec(args).await
696    }
697
698    /// Edits a note using the provided content mode.
699    ///
700    /// See [`EditMode`] for the vocabulary rationale (the variant
701    /// previously named `Replace` is now `Overwrite` to remove the
702    /// vocabulary trap at the root of `nb-api:issues/api/6`).
703    ///
704    /// Requiredness on the consumer side (e.g., the `mode` field on
705    /// `nb-mcp-server`'s `EditArgs`) is a consumer-layer concern,
706    /// not enforced here.
707    pub async fn edit_note(
708        &self,
709        id: &str,
710        content: &str,
711        mode: EditMode,
712        notebook: Option<&str>,
713    ) -> Result<String, NbError> {
714        let (notebook, selector) = self.resolve_target_selector(id, notebook).await?;
715        let output = self.exec_vec(edit_args(selector, content, mode)).await?;
716        Ok(self.append_notebook_warning(output, &notebook))
717    }
718
719    /// Deletes a note.
720    pub async fn delete_note(&self, id: &str, notebook: Option<&str>) -> Result<String, NbError> {
721        let (notebook, selector) = self.resolve_target_selector(id, notebook).await?;
722        let output = self
723            .exec_vec(vec!["delete".to_string(), selector, "--force".to_string()])
724            .await?;
725        Ok(self.append_notebook_warning(output, &notebook))
726    }
727
728    /// Moves or renames a note.
729    pub async fn move_note(
730        &self,
731        id: &str,
732        destination: &str,
733        notebook: Option<&str>,
734    ) -> Result<String, NbError> {
735        validate_destination(destination)?;
736        let (notebook, selector) = self.resolve_target_selector(id, notebook).await?;
737        let output = self
738            .exec_vec(vec![
739                "move".to_string(),
740                selector,
741                destination.to_string(),
742                "--force".to_string(),
743            ])
744            .await?;
745        Ok(self.append_notebook_warning(output, &notebook))
746    }
747
748    /// Creates a todo item.
749    pub async fn add_todo(
750        &self,
751        title: &str,
752        description: Option<&str>,
753        tasks: &[String],
754        tags: &[String],
755        folder: Option<&str>,
756        notebook: Option<&str>,
757    ) -> Result<String, NbError> {
758        self.require_folder_for_new_note(folder)?;
759        validate_folder_option(folder)?;
760        let notebook = self.resolve_notebook(notebook).await?;
761        let output = self
762            .exec_vec(todo_command_args(
763                &notebook,
764                title,
765                description,
766                tasks,
767                tags,
768                folder,
769            ))
770            .await?;
771        Ok(self.append_notebook_warning(output, &notebook))
772    }
773
774    /// Marks a todo as done.
775    pub async fn mark_task_done(
776        &self,
777        id: &str,
778        task_number: Option<u32>,
779        notebook: Option<&str>,
780    ) -> Result<String, NbError> {
781        let (notebook, selector) = self.resolve_target_selector(id, notebook).await?;
782        let output = self
783            .exec_vec(task_command_args("do", selector, task_number))
784            .await?;
785        Ok(self.append_notebook_warning(output, &notebook))
786    }
787
788    /// Marks a todo as not done.
789    pub async fn unmark_task_done(
790        &self,
791        id: &str,
792        task_number: Option<u32>,
793        notebook: Option<&str>,
794    ) -> Result<String, NbError> {
795        let (notebook, selector) = self.resolve_target_selector(id, notebook).await?;
796        let output = self
797            .exec_vec(task_command_args("undo", selector, task_number))
798            .await?;
799        Ok(self.append_notebook_warning(output, &notebook))
800    }
801
802    /// Lists checklist items within todos.
803    ///
804    /// Invokes the `nb tasks` subcommand. The method enumerates
805    /// the checklist items within todos (and recursively into
806    /// subfolders when `recursive = true`), filtered by
807    /// `status` if provided. The method name matches the
808    /// underlying `nb` CLI command (`nb tasks`); a future
809    /// `list_todos` method for the todo **container** listing
810    /// (invoking `nb todos`) is tracked at
811    /// `nb-api:todos/api/5` (deferred to `0.3.0+`).
812    pub async fn list_tasks(
813        &self,
814        folder: Option<&str>,
815        status: Option<TaskStatus>,
816        recursive: bool,
817        notebook: Option<&str>,
818    ) -> Result<String, NbError> {
819        validate_folder_option(folder)?;
820        let notebook = self.resolve_notebook(notebook).await?;
821        let folder = folder.map(normalize_folder);
822        let scopes = if recursive {
823            self.tasks_scopes_recursive(&notebook, folder.as_deref())
824                .await?
825        } else {
826            vec![tasks_scope(&notebook, folder.as_deref())]
827        };
828
829        let mut outputs: Vec<String> = Vec::new();
830        let mut saw_empty = false;
831        for scope in scopes {
832            match self.exec_vec(tasks_command_args(scope, status)).await {
833                Ok(output) => {
834                    let output = output.trim();
835                    if !output.is_empty() {
836                        outputs.push(output.to_string());
837                    }
838                }
839                Err(NbError::CommandFailed(message)) if is_empty_tasks_error(&message) => {
840                    saw_empty = true;
841                }
842                Err(err) => return Err(err),
843            }
844        }
845        if outputs.is_empty() && saw_empty {
846            return Err(NbError::CommandFailed(empty_tasks_message(status)));
847        }
848        Ok(outputs.join("\n"))
849    }
850
851    async fn tasks_scopes_recursive(
852        &self,
853        notebook: &str,
854        folder: Option<&str>,
855    ) -> Result<Vec<String>, NbError> {
856        let notebook_root = self.show_notebook_path(Some(notebook)).await?;
857        let start = folder.unwrap_or_default().to_string();
858        let mut queue = VecDeque::new();
859        queue.push_back(start.clone());
860
861        let mut scopes = vec![tasks_scope(notebook, folder)];
862        while let Some(current) = queue.pop_front() {
863            let base = if current.is_empty() {
864                notebook_root.clone()
865            } else {
866                notebook_root.join(&current)
867            };
868            let children = child_folder_names(&base)?;
869            for child in children {
870                let next = if current.is_empty() {
871                    child
872                } else {
873                    format!("{}/{}", current, child)
874                };
875                scopes.push(tasks_scope(notebook, Some(&next)));
876                queue.push_back(next);
877            }
878        }
879        Ok(scopes)
880    }
881
882    /// Creates a bookmark.
883    pub async fn add_bookmark(
884        &self,
885        url: &str,
886        title: Option<&str>,
887        tags: &[String],
888        comment: Option<&str>,
889        folder: Option<&str>,
890        notebook: Option<&str>,
891    ) -> Result<String, NbError> {
892        let mut args = Vec::new();
893        self.require_folder_for_new_note(folder)?;
894        validate_folder_option(folder)?;
895
896        // Build the destination path with optional folder
897        let notebook = self.resolve_notebook(notebook).await?;
898        let dest = match folder {
899            Some(f) => format!("{}:{}/", notebook, f),
900            None => format!("{}:", notebook),
901        };
902
903        let cmd = format!("{}bookmark", dest);
904        args.push(cmd);
905        args.push(url.to_string());
906
907        if let Some(t) = title {
908            args.push("--title".to_string());
909            args.push(t.to_string());
910        }
911
912        if let Some(c) = comment {
913            args.push("--comment".to_string());
914            args.push(c.to_string());
915        }
916
917        for tag in tags {
918            args.push("--tags".to_string());
919            let tag_str = if tag.starts_with('#') {
920                tag.clone()
921            } else {
922                format!("#{}", tag)
923            };
924            args.push(tag_str);
925        }
926
927        self.exec_vec(args)
928            .await
929            .map(|output| self.append_notebook_warning(output, &notebook))
930    }
931
932    /// Lists folders in a notebook.
933    pub async fn list_folders(
934        &self,
935        parent: Option<&str>,
936        notebook: Option<&str>,
937    ) -> Result<String, NbError> {
938        let mut args = vec!["list".to_string()];
939        validate_folder_option(parent)?;
940
941        let notebook = self.resolve_notebook(notebook).await?;
942        let path = match parent {
943            Some(p) => format!("{}:{}/", notebook, p),
944            None => format!("{}:", notebook),
945        };
946        args.push(path);
947
948        // Filter to only show folders
949        args.push("--type".to_string());
950        args.push("folder".to_string());
951        args.push("--no-color".to_string());
952
953        // Strip the trailing usage/help hint block from empty
954        // results (`0 folders.` followed by `Import a file:`,
955        // `Help information:`). Detection keys off the
956        // empty-result signal per the `output-behavior`
957        // specification. See `output.rs` for the helper's
958        // contract.
959        self.exec_vec(args)
960            .await
961            .map(|output| output::strip_empty_result_hint(&output))
962    }
963
964    /// Creates a folder.
965    pub async fn add_folder(&self, path: &str, notebook: Option<&str>) -> Result<String, NbError> {
966        validate_folder_path(path)?;
967        let notebook = self.resolve_notebook(notebook).await?;
968        let folder_path = mkdir_selector(&notebook, path);
969        let output = self
970            .exec_vec(vec!["add".to_string(), "folder".to_string(), folder_path])
971            .await?;
972        Ok(self.append_notebook_warning(output, &notebook))
973    }
974
975    /// Imports a file or URL into the notebook as a note.
976    ///
977    /// Invokes `nb import`, which only handles notes (HTML,
978    /// Markdown, plain text, and other source formats that
979    /// `nb` can convert into a note body). The `_note` suffix
980    /// is correct because `nb import` cannot create bookmarks
981    /// or folders — those use `add_bookmark` and `add_folder`
982    /// respectively. The `source` may be a local file path or
983    /// a URL; HTML sources may be converted to Markdown via
984    /// `convert = true`.
985    pub async fn import_note(
986        &self,
987        source: &str,
988        folder: Option<&str>,
989        filename: Option<&str>,
990        convert: bool,
991        notebook: Option<&str>,
992    ) -> Result<String, NbError> {
993        let mut args = Vec::new();
994        self.require_folder_for_new_note(folder)?;
995        validate_folder_option(folder)?;
996
997        let notebook = self.resolve_notebook(notebook).await?;
998        let cmd = format!("{}:import", notebook);
999        args.push(cmd);
1000
1001        // Source path or URL
1002        args.push(source.to_string());
1003
1004        // Convert HTML to Markdown
1005        if convert {
1006            args.push("--convert".to_string());
1007        }
1008
1009        // Destination: notebook:folder/filename or just folder/filename
1010        // nb import expects destination as a positional argument after source
1011        if folder.is_some() || filename.is_some() {
1012            let dest = match (folder, filename) {
1013                (Some(f), Some(n)) => format!("{}/{}", f, n),
1014                (Some(f), None) => format!("{}/", f),
1015                (None, Some(n)) => n.to_string(),
1016                (None, None) => unreachable!(),
1017            };
1018            args.push(dest);
1019        }
1020
1021        self.exec_vec(args)
1022            .await
1023            .map(|output| self.append_notebook_warning(output, &notebook))
1024    }
1025}
1026
1027fn append_warning(mut output: String, warning: String) -> String {
1028    if !output.trim().is_empty() {
1029        if !output.ends_with('\n') {
1030            output.push('\n');
1031        }
1032        output.push('\n');
1033    }
1034    output.push_str(&warning);
1035    output
1036}
1037
1038fn validate_notebook_name(name: &str) -> Result<(), NbError> {
1039    if name.trim().is_empty() || name.contains(':') || name.contains('/') || name.contains('\\') {
1040        return Err(NbError::CommandFailed(NOTEBOOK_FIELD_MESSAGE.to_string()));
1041    }
1042    Ok(())
1043}
1044
1045fn validate_folder_option(folder: Option<&str>) -> Result<(), NbError> {
1046    if let Some(path) = folder {
1047        validate_folder_path(path)?;
1048    }
1049    Ok(())
1050}
1051
1052fn validate_folder_path(path: &str) -> Result<(), NbError> {
1053    if path.trim().is_empty() || path.contains(':') {
1054        return Err(NbError::CommandFailed(FOLDER_FIELD_MESSAGE.to_string()));
1055    }
1056    Ok(())
1057}
1058
1059fn validate_destination(destination: &str) -> Result<(), NbError> {
1060    if destination.trim().is_empty() || destination.contains(':') {
1061        return Err(NbError::CommandFailed(
1062            "Invalid destination: use a folder path or filename only, not a notebook-qualified selector."
1063                .to_string(),
1064        ));
1065    }
1066    Ok(())
1067}
1068
1069fn parse_qualified_selector(selector: &str) -> Result<Option<(&str, &str)>, NbError> {
1070    let Some((notebook, path)) = selector.split_once(':') else {
1071        return Ok(None);
1072    };
1073    validate_notebook_name(notebook)?;
1074    if path.trim().is_empty() || path.contains(':') {
1075        return Err(NbError::CommandFailed(
1076            "Invalid selector: use at most one notebook qualifier, as `<notebook>:<folder>/<id>`."
1077                .to_string(),
1078        ));
1079    }
1080    Ok(Some((notebook, path)))
1081}
1082
1083/// Detect a duplicate-title H1 in `content`.
1084///
1085/// Returns `Some(<exact source line>)` when `content`'s first
1086/// nonblank line is a CommonMark ATX H1 and the trimmed heading
1087/// text equals the trimmed `title`.
1088///
1089/// Per CommonMark, an ATX H1 is:
1090/// - 0 to 3 leading spaces (4 or more is an indented code block);
1091/// - exactly one opening `#` (2+ is H2 or lower);
1092/// - a required space, tab, or end-of-line after the opening hash
1093///   (`#Title` is NOT an H1);
1094/// - the heading text (inline content);
1095/// - an optional closing hash sequence: a run of `#`s preceded
1096///   by a space or tab and followed only by spaces or tabs to
1097///   end of line. Literal trailing hashes with no preceding
1098///   whitespace (e.g., `# C#`) are part of the heading text, NOT
1099///   a closing sequence.
1100///
1101/// Returns `None` when the title is empty/None, the content has
1102/// no nonblank line, or the first nonblank line is not a
1103/// duplicate H1. Used by [`NbClient::add_note`](crate::NbClient::add_note)
1104/// to detect the common agent-side mistake of including the title
1105/// H1 inside the body content.
1106fn detect_duplicate_title_heading(title: &str, content: &str) -> Option<String> {
1107    let trimmed_title = title.trim();
1108    if trimmed_title.is_empty() {
1109        return None;
1110    }
1111    let first_nonblank = content.lines().find(|line| !line.trim().is_empty())?;
1112    let bytes = first_nonblank.as_bytes();
1113
1114    // 0-3 leading spaces. 4 or more is an indented code block.
1115    let leading_spaces = bytes.iter().take_while(|&&b| b == b' ').count();
1116    if leading_spaces >= 4 {
1117        return None;
1118    }
1119    let after_indent = &first_nonblank[leading_spaces..];
1120
1121    // Exactly one opening `#`. `##` and beyond are H2+.
1122    if !after_indent.starts_with('#') {
1123        return None;
1124    }
1125    if after_indent.starts_with("##") {
1126        return None;
1127    }
1128    let after_hash = &after_indent[1..];
1129
1130    // Required space, tab, or EOL after the opening hash. `#Title`
1131    // is NOT an H1 (no delimiter). A bare `#` IS an H1 with empty
1132    // heading text per CommonMark; the title comparison below
1133    // filters out the false-positive case (empty heading text
1134    // never matches a non-empty title).
1135    let after_hash_bytes = after_hash.as_bytes();
1136    let rest = match after_hash_bytes.first() {
1137        Some(b' ') | Some(b'\t') => &after_hash[1..],
1138        None => "",
1139        Some(_) => return None,
1140    };
1141
1142    // Optional closing hash sequence per CommonMark.
1143    let heading_text = strip_atx_closing_hashes(rest);
1144
1145    if heading_text.trim() == trimmed_title {
1146        Some(first_nonblank.to_string())
1147    } else {
1148        None
1149    }
1150}
1151
1152/// Strip an optional CommonMark ATX closing hash sequence from
1153/// the end of a heading body. The closing sequence is a run of
1154/// one or more `#`s preceded by a space or tab and followed only
1155/// by spaces or tabs to end of string. If no valid closing
1156/// sequence is present, returns the input unchanged. Literal
1157/// trailing hashes with no preceding whitespace (e.g., `C#`) are
1158/// NOT a closing sequence and are preserved.
1159///
1160/// A closing sequence can consume the entire post-delimiter
1161/// content (e.g., `# #`, `# ###`); in that case the heading
1162/// text becomes empty per CommonMark and never matches a
1163/// non-empty title.
1164fn strip_atx_closing_hashes(s: &str) -> String {
1165    let bytes = s.as_bytes();
1166    let n = bytes.len();
1167
1168    // Find where trailing whitespace ends.
1169    let mut end = n;
1170    while end > 0 && (bytes[end - 1] == b' ' || bytes[end - 1] == b'\t') {
1171        end -= 1;
1172    }
1173    if end == 0 || bytes[end - 1] != b'#' {
1174        return s.to_string();
1175    }
1176
1177    // Find the start of the trailing-hash sequence.
1178    let mut hash_start = end;
1179    while hash_start > 0 && bytes[hash_start - 1] == b'#' {
1180        hash_start -= 1;
1181    }
1182
1183    // The closing sequence must be preceded by a space or tab
1184    // within the heading body. If the run of `#`s is preceded by
1185    // a non-whitespace char (e.g., `C#`), it is part of the
1186    // heading text, NOT a closing sequence; preserve the input.
1187    //
1188    // If the run is at offset 0 of the post-delimiter body, it
1189    // is preceded by the delimiter space (which is NOT in the
1190    // body); this is a valid closing sequence that consumes the
1191    // entire body. The heading text becomes empty.
1192    if hash_start == 0 {
1193        return s[..0].to_string();
1194    }
1195    let prev = bytes[hash_start - 1];
1196    if prev != b' ' && prev != b'\t' {
1197        return s.to_string();
1198    }
1199
1200    s[..hash_start].to_string()
1201}
1202
1203fn edit_args(selector: String, content: &str, mode: EditMode) -> Vec<String> {
1204    let mut args = vec!["edit".to_string(), selector];
1205    match mode {
1206        EditMode::Overwrite => args.push("--overwrite".to_string()),
1207        EditMode::Append => {}
1208        EditMode::Prepend => args.push("--prepend".to_string()),
1209    }
1210    args.push("--content".to_string());
1211    args.push(content.to_string());
1212    args
1213}
1214
1215fn task_command_args(action: &str, selector: String, task_number: Option<u32>) -> Vec<String> {
1216    let mut args = vec![action.to_string(), selector];
1217    if let Some(number) = task_number {
1218        args.push(number.to_string());
1219    }
1220    args
1221}
1222
1223fn todo_command_args(
1224    notebook: &str,
1225    title: &str,
1226    description: Option<&str>,
1227    tasks: &[String],
1228    tags: &[String],
1229    folder: Option<&str>,
1230) -> Vec<String> {
1231    let mut args = vec![format!("{notebook}:todo"), "add".to_string()];
1232
1233    // Folder path comes as a positional argument before the title.
1234    if let Some(folder) = folder {
1235        args.push(folder_scope(folder));
1236    }
1237
1238    args.push(title.to_string());
1239
1240    if let Some(description) = description {
1241        args.push("--description".to_string());
1242        args.push(description.to_string());
1243    }
1244
1245    for task in tasks {
1246        args.push("--task".to_string());
1247        args.push(task.to_string());
1248    }
1249
1250    for tag in tags {
1251        args.push("--tags".to_string());
1252        args.push(normalize_tag(tag));
1253    }
1254
1255    args
1256}
1257
1258fn folder_scope(folder: &str) -> String {
1259    if folder.ends_with('/') {
1260        folder.to_string()
1261    } else {
1262        format!("{folder}/")
1263    }
1264}
1265
1266fn normalize_tag(tag: &str) -> String {
1267    if tag.starts_with('#') {
1268        tag.to_string()
1269    } else {
1270        format!("#{tag}")
1271    }
1272}
1273
1274fn normalize_folder(folder: &str) -> String {
1275    folder.trim_matches('/').to_string()
1276}
1277
1278fn mkdir_selector(notebook: &str, path: &str) -> String {
1279    let normalized = normalize_folder(path);
1280    format!("{}:{}", notebook, normalized)
1281}
1282
1283fn tasks_scope(notebook: &str, folder: Option<&str>) -> String {
1284    match folder {
1285        Some(path) if !path.is_empty() => format!("{}:{}/", notebook, path),
1286        _ => format!("{}:", notebook),
1287    }
1288}
1289
1290fn tasks_command_args(scope: String, status: Option<TaskStatus>) -> Vec<String> {
1291    let mut args = vec!["tasks".to_string(), scope];
1292    if let Some(filter) = status {
1293        let status = match filter {
1294            TaskStatus::Open => "open",
1295            TaskStatus::Closed => "closed",
1296        };
1297        args.push(status.to_string());
1298    }
1299    args.push("--no-color".to_string());
1300    args
1301}
1302
1303fn search_command_args(
1304    scope: String,
1305    queries: &[String],
1306    mode: SearchMode,
1307    tags: &[String],
1308) -> Vec<String> {
1309    let mut args = vec!["search".to_string(), scope];
1310    let mut terms = queries.iter();
1311    if let Some(first) = terms.next() {
1312        args.push(first.to_string());
1313    }
1314    match mode {
1315        SearchMode::Any => {
1316            for query in terms {
1317                args.push("--or".to_string());
1318                args.push(query.to_string());
1319            }
1320        }
1321        SearchMode::All => {
1322            for query in terms {
1323                args.push(query.to_string());
1324            }
1325        }
1326    }
1327    for tag in tags {
1328        args.push("--tag".to_string());
1329        args.push(normalize_tag(tag));
1330    }
1331    args.push("--no-color".to_string());
1332    args
1333}
1334
1335fn is_empty_tasks_error(message: &str) -> bool {
1336    message.trim_start().starts_with("! 0 ") && message.contains(" tasks.")
1337}
1338
1339fn empty_tasks_message(status: Option<TaskStatus>) -> String {
1340    match status {
1341        Some(TaskStatus::Open) => "! 0 open tasks.".to_string(),
1342        Some(TaskStatus::Closed) => "! 0 closed tasks.".to_string(),
1343        None => "! 0 tasks.".to_string(),
1344    }
1345}
1346
1347fn child_folder_names(path: &std::path::Path) -> Result<Vec<String>, NbError> {
1348    let read_dir = match std::fs::read_dir(path) {
1349        Ok(entries) => entries,
1350        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
1351        Err(err) => return Err(NbError::Io(err)),
1352    };
1353
1354    let mut names = Vec::new();
1355    for entry in read_dir {
1356        let entry = entry?;
1357        let Some(name) = entry.file_name().to_str().map(|value| value.to_string()) else {
1358            continue;
1359        };
1360        if name.starts_with('.') {
1361            continue;
1362        }
1363        let meta = match entry.metadata() {
1364            Ok(meta) => meta,
1365            Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue,
1366            Err(err) => return Err(NbError::Io(err)),
1367        };
1368        if meta.is_dir() {
1369            names.push(name);
1370        }
1371    }
1372    names.sort();
1373    Ok(names)
1374}
1375
1376const GIT_SIGNING_OVERRIDES: [(&str, &str); 2] =
1377    [("commit.gpgsign", "false"), ("tag.gpgsign", "false")];
1378
1379fn git_signing_env_vars(start_index: usize) -> Vec<(String, String)> {
1380    let total = start_index.saturating_add(GIT_SIGNING_OVERRIDES.len());
1381    let mut env_vars = Vec::with_capacity(1 + GIT_SIGNING_OVERRIDES.len() * 2);
1382    env_vars.push(("GIT_CONFIG_COUNT".to_string(), total.to_string()));
1383    for (offset, (key, value)) in GIT_SIGNING_OVERRIDES.iter().enumerate() {
1384        let index = start_index + offset;
1385        env_vars.push((format!("GIT_CONFIG_KEY_{index}"), (*key).to_string()));
1386        env_vars.push((format!("GIT_CONFIG_VALUE_{index}"), (*value).to_string()));
1387    }
1388    env_vars
1389}
1390
1391fn apply_git_signing_env(command: &mut Command) {
1392    // Always start at index 0. `scrub_git_env` has already removed
1393    // every `GIT_CONFIG_*` from the spawn-time `Command` env (the
1394    // blast-by-prefix defense-in-depth pattern, mirrored from
1395    // `nbspec:71f369e`), so the spawn-time `GIT_CONFIG_COUNT` is
1396    // 0. The parent's pre-scrub `GIT_CONFIG_COUNT` does not flow
1397    // through to the child and must not influence the index.
1398    // (Pre-patch behavior read the parent count via
1399    // `std::env::var("GIT_CONFIG_COUNT")`, which produced a gap
1400    // in the emitted indices whenever the parent had set
1401    // `GIT_CONFIG_*` — see the regression test in
1402    // `tests/integration/git_signing_overrides.rs`.)
1403    for (name, value) in git_signing_env_vars(0) {
1404        command.env(name, value);
1405    }
1406}