1use std::path::{Path, PathBuf};
2use std::process::Stdio;
3use std::sync::LazyLock;
4
5use regex::Regex;
6use tokio::process::Command;
7
8use crate::diagnostics::{append_warning, is_notebook_not_found};
9use crate::error::NbError;
10use crate::gate;
11use crate::git::derive_git_notebook_name;
12use crate::git_env::scrub_git_env;
13use crate::git_signing::apply_git_signing_env;
14use crate::nb_program::nb_program;
15use crate::transaction::Transaction;
16use crate::validate::{parse_qualified_selector, validate_notebook_name};
17use crate::{Config, NbClient};
18
19use super::read::notebook_dir_from_env;
20
21static ANSI_REGEX: LazyLock<Regex> = LazyLock::new(|| {
28 Regex::new(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|[ -/]*[0-~])").unwrap()
29});
30
31fn strip_ansi(text: &str) -> String {
33 ANSI_REGEX.replace_all(text, "").into_owned()
34}
35
36const 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.";
37
38impl NbClient {
39 pub fn new(config: &Config) -> anyhow::Result<Self> {
45 let default_notebook = config
46 .notebook
47 .as_deref()
48 .map(String::from)
49 .or_else(derive_git_notebook_name);
50 Ok(Self {
51 default_notebook,
52 create_notebook: config.create_notebook,
53 require_explicit_nb_dir: config.require_explicit_nb_dir,
54 disable_git_signing: config.disable_git_signing,
55 allow_top_level_notes: config.allow_top_level_notes,
56 gate_timeout: config.gate_timeout,
57 })
58 }
59
60 pub async fn transaction(
64 &self,
65 notebook: Option<&str>,
66 ) -> Result<Transaction, NbError> {
67 let notebook = self.resolve_notebook_name(notebook)?;
68 let existing =
74 notebook_dir_from_env(¬ebook, self.require_explicit_nb_dir)
75 .unwrap_or_default();
76 if existing.is_none() {
77 self.ensure_notebook(¬ebook).await?;
78 }
79 Ok(Transaction::new(self.clone(), notebook, self.gate_timeout))
80 }
81
82 pub fn gate_timeout(&self) -> std::time::Duration {
84 self.gate_timeout
85 }
86
87 pub(crate) async fn show_notebook_path_unguarded(
94 &self,
95 notebook: Option<&str>,
96 ) -> Result<PathBuf, NbError> {
97 let notebook = self.resolve_notebook_name(notebook)?;
98 let existing: Option<PathBuf> =
101 notebook_dir_from_env(¬ebook, self.require_explicit_nb_dir)
102 .unwrap_or_default();
103 if let Some(path) = existing {
104 return Ok(path);
105 }
106 self.ensure_notebook(¬ebook).await?;
107 let output = self
108 .exec_vec(vec![
109 "notebooks".to_string(),
110 "show".to_string(),
111 notebook.clone(),
112 "--path".to_string(),
113 ])
114 .await?;
115 let path = output.trim();
116 if path.is_empty() {
117 return Err(NbError::CommandFailed {
118 command: format!("nb notebooks show {notebook} --path"),
119 stderr: "nb notebooks path output was empty".to_string(),
120 exit_code: None,
121 });
122 }
123 Ok(PathBuf::from(path))
124 }
125
126 pub(super) async fn with_notebook_gate<F, T>(
127 &self,
128 notebook: &str,
129 f: F,
130 ) -> Result<T, NbError>
131 where
132 F: std::future::Future<Output = Result<T, NbError>>,
133 {
134 let root = self.show_notebook_path_unguarded(Some(notebook)).await?;
135 self.with_notebook_gate_native(&root, f).await
136 }
137
138 pub(super) async fn with_notebook_gate_native<F, T>(
143 &self,
144 root: &Path,
145 f: F,
146 ) -> Result<T, NbError>
147 where
148 F: std::future::Future<Output = Result<T, NbError>>,
149 {
150 let key = gate::git_common_dir_realpath(root)?;
151 let _hold =
152 gate::acquire_notebook(key.clone(), self.gate_timeout, false)
153 .await?;
154 #[cfg(test)]
155 {
156 let notify = native_gate_probe::fired(&key);
163 if let Some(proceed) = notify {
164 let _ = tokio::time::timeout(
165 native_gate_probe::WAIT_TIMEOUT,
166 proceed.notified(),
167 )
168 .await;
169 }
170 }
171 f.await
172 }
173
174 pub(super) fn require_folder_for_new_note(
175 &self,
176 folder: Option<&str>,
177 ) -> Result<(), NbError> {
178 if self.allow_top_level_notes
179 || folder.is_some_and(|value| !value.trim().is_empty())
180 {
181 return Ok(());
182 }
183 Err(NbError::ValidationError {
184 reason: FOLDER_REQUIRED_MESSAGE.to_string(),
185 location: None,
186 })
187 }
188
189 pub(super) async fn resolve_target_selector(
190 &self,
191 id: &str,
192 notebook: Option<&str>,
193 ) -> Result<(String, String), NbError> {
194 if let Some((embedded_notebook, path)) = parse_qualified_selector(id)?
195 {
196 let notebook = match notebook {
197 Some(value) => {
198 validate_notebook_name(value)?;
199 if value != embedded_notebook {
200 return Err(NbError::ValidationError {
201 reason: format!(
202 "ambiguous selector: id targets notebook `{embedded_notebook}`, but notebook field is `{value}`"
203 ),
204 location: None,
205 });
206 }
207 embedded_notebook.to_string()
208 },
209 _ => embedded_notebook.to_string(),
210 };
211 self.ensure_existing_notebook(¬ebook).await?;
212 return Ok((notebook, format!("{}:{}", embedded_notebook, path)));
213 }
214 let notebook = self.resolve_notebook(notebook).await?;
215 Ok((notebook.clone(), format!("{}:{}", notebook, id)))
216 }
217
218 pub(super) fn append_notebook_warning(
219 &self,
220 output: String,
221 notebook: &str,
222 ) -> String {
223 let Some(default_notebook) = self.default_notebook.as_deref() else {
224 return output;
225 };
226 if default_notebook == notebook {
227 return output;
228 }
229 append_warning(
230 output,
231 format!(
232 "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."
233 ),
234 )
235 }
236
237 pub(super) fn resolve_notebook_name(
239 &self,
240 notebook: Option<&str>,
241 ) -> Result<String, NbError> {
242 if let Some(name) = notebook {
243 validate_notebook_name(name)?;
244 return Ok(name.to_string());
245 }
246 if let Some(name) = self.default_notebook.as_deref() {
247 validate_notebook_name(name)?;
248 return Ok(name.to_string());
249 }
250 Err(NbError::ValidationError {
251 reason:
252 "notebook not configured; set --notebook or NB_MCP_NOTEBOOK"
253 .to_string(),
254 location: None,
255 })
256 }
257
258 pub(super) async fn resolve_notebook(
259 &self,
260 notebook: Option<&str>,
261 ) -> Result<String, NbError> {
262 let name = self.resolve_notebook_name(notebook)?;
263 self.ensure_notebook(&name).await?;
264 Ok(name)
265 }
266
267 pub(super) async fn ensure_notebook(
268 &self,
269 notebook: &str,
270 ) -> Result<(), NbError> {
271 match self.check_notebook(notebook).await {
272 Ok(()) => Ok(()),
273 Err(
276 err
277 @ (NbError::ExecutableNotFound { .. } | NbError::Io { .. }),
278 ) => Err(err),
279 Err(NbError::NotFound { .. }) => {
286 if !self.create_notebook {
287 return Err(NbError::ValidationError {
288 reason: format!(
289 "notebook not found; create it with the nb CLI (`nb notebooks add {}`) \
290 or remove --no-create-notebook",
291 notebook
292 ),
293 location: None,
294 });
295 }
296 self.exec_vec(vec![
297 "notebooks".to_string(),
298 "add".to_string(),
299 notebook.to_string(),
300 ])
301 .await?;
302 Ok(())
303 },
304 Err(err) => Err(err),
310 }
311 }
312
313 pub(super) async fn ensure_existing_notebook(
314 &self,
315 notebook: &str,
316 ) -> Result<(), NbError> {
317 match self.check_notebook(notebook).await {
318 Ok(()) => Ok(()),
319 Err(
321 err
322 @ (NbError::ExecutableNotFound { .. } | NbError::Io { .. }),
323 ) => Err(err),
324 Err(err @ NbError::NotFound { .. }) => Err(err),
335 Err(err) => Err(err),
338 }
339 }
340
341 async fn check_notebook(&self, notebook: &str) -> Result<(), NbError> {
342 if notebook_dir_from_env(notebook, self.require_explicit_nb_dir)?
346 .is_some()
347 {
348 return Ok(());
349 }
350 let show_result = self
351 .exec_vec(vec![
352 "notebooks".to_string(),
353 "show".to_string(),
354 notebook.to_string(),
355 "--path".to_string(),
356 ])
357 .await;
358 match show_result {
359 Ok(output) => {
360 if output.trim().is_empty() {
361 return Err(NbError::CommandFailed {
368 command: format!(
369 "nb notebooks show {notebook} --path"
370 ),
371 stderr: "nb notebooks path output was empty"
372 .to_string(),
373 exit_code: None,
374 });
375 }
376 Ok(())
377 },
378 Err(err) => {
379 match err {
394 NbError::ExecutableNotFound { .. }
395 | NbError::Io { .. } => Err(err),
396 NbError::CommandFailed { ref stderr, .. }
397 if is_notebook_not_found(stderr, notebook) =>
398 {
399 Err(NbError::NotFound {
400 selector: format!("{notebook}:"),
401 })
402 },
403 other => Err(other),
404 }
405 },
406 }
407 }
408
409 pub(super) async fn exec(&self, args: &[&str]) -> Result<String, NbError> {
411 tracing::debug!(?args, "executing nb command");
412 let mut command = Command::new(nb_program());
416 scrub_git_env(&mut command);
428 command.env("TERM", "dumb");
439 command
440 .args(args)
441 .stdin(Stdio::null()) .stdout(Stdio::piped())
443 .stderr(Stdio::piped());
444 if self.disable_git_signing {
445 apply_git_signing_env(&mut command);
446 }
447 let joined = format!("nb {}", args.join(" "));
448 let output = command
449 .spawn()
450 .map_err(|e| {
451 if e.kind() == std::io::ErrorKind::NotFound {
452 NbError::ExecutableNotFound {
453 path: "nb".to_string(),
454 }
455 } else {
456 NbError::Io {
457 path: PathBuf::from("nb"),
458 source: e.into(),
459 }
460 }
461 })?
462 .wait_with_output()
463 .await
464 .map_err(|e| NbError::Io {
465 path: PathBuf::from("nb"),
466 source: e.into(),
467 })?;
468
469 if output.status.success() {
470 let stdout = String::from_utf8_lossy(&output.stdout);
471 Ok(strip_ansi(&stdout))
472 } else {
473 let stderr = String::from_utf8_lossy(&output.stderr);
474 let stdout = String::from_utf8_lossy(&output.stdout);
475 let stderr_text = if stderr.is_empty() {
477 strip_ansi(&stdout)
478 } else {
479 strip_ansi(&stderr)
480 };
481 Err(NbError::CommandFailed {
482 command: joined,
483 stderr: stderr_text,
484 exit_code: output.status.code(),
485 })
486 }
487 }
488
489 pub(super) async fn exec_vec(
491 &self,
492 args: Vec<String>,
493 ) -> Result<String, NbError> {
494 let args_ref: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
495 self.exec(&args_ref).await
496 }
497}
498
499#[cfg(test)]
508pub(super) mod native_gate_probe {
509 use std::path::{Path, PathBuf};
510 use std::sync::{Arc, Mutex, MutexGuard};
511 use std::time::Duration;
512
513 use tokio::sync::{Notify, mpsc};
514
515 static PROBE: Mutex<Option<Probe>> = Mutex::new(None);
516
517 struct Probe {
518 entered: mpsc::UnboundedSender<()>,
519 proceed: Arc<Notify>,
520 scope: PathBuf,
523 }
524
525 pub(super) struct Guard {
529 _lock: MutexGuard<'static, ()>,
530 }
531
532 impl Drop for Guard {
533 fn drop(&mut self) {
534 *PROBE.lock().unwrap() = None;
535 }
536 }
537
538 static INSTALL_LOCK: Mutex<()> = Mutex::new(());
539
540 pub(super) fn install(
544 entered: mpsc::UnboundedSender<()>,
545 proceed: Arc<Notify>,
546 scope: PathBuf,
547 ) -> Option<Guard> {
548 let lock = INSTALL_LOCK.try_lock().ok()?;
549 *PROBE.lock().unwrap() = Some(Probe {
550 entered,
551 proceed,
552 scope,
553 });
554 Some(Guard { _lock: lock })
555 }
556
557 pub(super) fn installed() -> bool {
559 PROBE.lock().unwrap().is_some()
560 }
561
562 pub(super) fn fired(scope: &Path) -> Option<Arc<Notify>> {
566 PROBE.lock().unwrap().as_ref().and_then(|probe| {
567 if probe.scope != scope {
568 return None;
569 }
570 let _ = probe.entered.send(());
574 Some(probe.proceed.clone())
575 })
576 }
577
578 pub(super) const WAIT_TIMEOUT: Duration = Duration::from_secs(30);
580}
581
582#[cfg(test)]
591mod native_gate_tests {
592 use std::ffi::OsString;
593 use std::sync::Arc;
594 use std::sync::atomic::{AtomicU64, Ordering};
595
596 use tokio::sync::Notify;
597
598 use super::native_gate_probe;
599 use crate::{Config, NbClient};
600
601 static FIXTURE_SEQ: AtomicU64 = AtomicU64::new(0);
602
603 struct EnvRestore {
604 key: &'static str,
605 prev: Option<OsString>,
606 }
607
608 impl Drop for EnvRestore {
609 fn drop(&mut self) {
610 unsafe {
611 match &self.prev {
612 Some(v) => std::env::set_var(self.key, v),
613 None => std::env::remove_var(self.key),
614 }
615 }
616 }
617 }
618
619 #[tokio::test]
620 async fn native_held_gate_reader_sees_mapping_change() {
621 let seq = FIXTURE_SEQ.fetch_add(1, Ordering::SeqCst);
624 let base = std::env::temp_dir()
625 .join(format!("nb-api-gate-probe-{}-{seq}", std::process::id()));
626 let root = base.join("nbdir").join("nb1");
627 std::fs::create_dir_all(&root).expect("fixture dirs");
628 let git_init = std::process::Command::new("git")
629 .args(["init", "-q"])
630 .current_dir(&root)
631 .status()
632 .expect("git init runs");
633 assert!(git_init.success(), "git init must succeed");
634 std::fs::write(root.join(".index"), "victim.md\nother.md\n")
635 .expect("index");
636 std::fs::write(root.join("victim.md"), "# Victim\nv0\n")
637 .expect("victim");
638 std::fs::write(root.join("other.md"), "# Other\no\n").expect("other");
639
640 let prev = std::env::var_os("NB_DIR");
641 unsafe {
642 std::env::set_var("NB_DIR", base.join("nbdir"));
643 }
644 let _env = EnvRestore {
645 key: "NB_DIR",
646 prev,
647 };
648 let _tmp = TmpRemove { path: base };
649
650 let client = NbClient::new(&Config {
651 notebook: Some("nb1".to_string()),
652 create_notebook: false,
653 allow_top_level_notes: true,
654 disable_git_signing: true,
655 ..Default::default()
656 })
657 .expect("client");
658
659 let (entered_tx, mut entered_rx) =
664 tokio::sync::mpsc::unbounded_channel();
665 let proceed = Arc::new(Notify::new());
666 let scope =
667 crate::gate::git_common_dir_realpath(&root).expect("gate key");
668 let probe =
669 native_gate_probe::install(entered_tx, proceed.clone(), scope)
670 .expect("probe installs once");
671 assert!(
672 native_gate_probe::installed(),
673 "probe visible while installed"
674 );
675 let mut reader = tokio::spawn({
676 let client = client.clone();
677 async move { client.show_note("1", None).await }
678 });
679 if tokio::time::timeout(
683 native_gate_probe::WAIT_TIMEOUT,
684 entered_rx.recv(),
685 )
686 .await
687 .is_err()
688 {
689 reader.abort();
690 panic!("reader never entered the hold");
691 }
692 std::fs::write(root.join(".index"), "other.md\nvictim.md\n")
693 .expect("swap slot 1");
694 proceed.notify_one();
695 let shown = tokio::select! {
696 joined = &mut reader => joined
697 .expect("reader joins")
698 .expect("queued read succeeds"),
699 _ = tokio::time::sleep(native_gate_probe::WAIT_TIMEOUT) => {
700 reader.abort();
701 proceed.notify_one();
702 panic!("queued reader never completed");
703 }
704 };
705 assert_eq!(shown.path, "other.md".to_string(), "{shown:?}");
706 assert_eq!(shown.body, "o\n", "{shown:?}");
707 drop(probe);
710 assert!(
711 !native_gate_probe::installed(),
712 "probe cleared after guard drop"
713 );
714 }
715
716 struct TmpRemove {
717 path: std::path::PathBuf,
718 }
719
720 impl Drop for TmpRemove {
721 fn drop(&mut self) {
722 let _ = std::fs::remove_dir_all(&self.path);
723 }
724 }
725}