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 disable_git_signing: config.disable_git_signing,
54 allow_top_level_notes: config.allow_top_level_notes,
55 gate_timeout: config.gate_timeout,
56 })
57 }
58
59 pub async fn transaction(
63 &self,
64 notebook: Option<&str>,
65 ) -> Result<Transaction, NbError> {
66 let notebook = self.resolve_notebook_name(notebook)?;
67 let existing = notebook_dir_from_env(¬ebook).unwrap_or_default();
73 if existing.is_none() {
74 self.ensure_notebook(¬ebook).await?;
75 }
76 Ok(Transaction::new(self.clone(), notebook, self.gate_timeout))
77 }
78
79 pub fn gate_timeout(&self) -> std::time::Duration {
81 self.gate_timeout
82 }
83
84 pub(crate) async fn show_notebook_path_unguarded(
91 &self,
92 notebook: Option<&str>,
93 ) -> Result<PathBuf, NbError> {
94 let notebook = self.resolve_notebook_name(notebook)?;
95 let existing: Option<PathBuf> =
98 notebook_dir_from_env(¬ebook).unwrap_or_default();
99 if let Some(path) = existing {
100 return Ok(path);
101 }
102 self.ensure_notebook(¬ebook).await?;
103 let output = self
104 .exec_vec(vec![
105 "notebooks".to_string(),
106 "show".to_string(),
107 notebook.clone(),
108 "--path".to_string(),
109 ])
110 .await?;
111 let path = output.trim();
112 if path.is_empty() {
113 return Err(NbError::CommandFailed {
114 command: format!("nb notebooks show {notebook} --path"),
115 stderr: "nb notebooks path output was empty".to_string(),
116 exit_code: None,
117 });
118 }
119 Ok(PathBuf::from(path))
120 }
121
122 pub(super) async fn with_notebook_gate<F, T>(
123 &self,
124 notebook: &str,
125 f: F,
126 ) -> Result<T, NbError>
127 where
128 F: std::future::Future<Output = Result<T, NbError>>,
129 {
130 let root = self.show_notebook_path_unguarded(Some(notebook)).await?;
131 self.with_notebook_gate_native(&root, f).await
132 }
133
134 pub(super) async fn with_notebook_gate_native<F, T>(
139 &self,
140 root: &Path,
141 f: F,
142 ) -> Result<T, NbError>
143 where
144 F: std::future::Future<Output = Result<T, NbError>>,
145 {
146 let key = gate::git_common_dir_realpath(root)?;
147 let _hold =
148 gate::acquire_notebook(key.clone(), self.gate_timeout, false)
149 .await?;
150 #[cfg(test)]
151 {
152 let notify = native_gate_probe::fired(&key);
159 if let Some(proceed) = notify {
160 let _ = tokio::time::timeout(
161 native_gate_probe::WAIT_TIMEOUT,
162 proceed.notified(),
163 )
164 .await;
165 }
166 }
167 f.await
168 }
169
170 pub(super) fn require_folder_for_new_note(
171 &self,
172 folder: Option<&str>,
173 ) -> Result<(), NbError> {
174 if self.allow_top_level_notes
175 || folder.is_some_and(|value| !value.trim().is_empty())
176 {
177 return Ok(());
178 }
179 Err(NbError::ValidationError {
180 reason: FOLDER_REQUIRED_MESSAGE.to_string(),
181 location: None,
182 })
183 }
184
185 pub(super) async fn resolve_target_selector(
186 &self,
187 id: &str,
188 notebook: Option<&str>,
189 ) -> Result<(String, String), NbError> {
190 if let Some((embedded_notebook, path)) = parse_qualified_selector(id)?
191 {
192 let notebook = match notebook {
193 Some(value) => {
194 validate_notebook_name(value)?;
195 if value != embedded_notebook {
196 return Err(NbError::ValidationError {
197 reason: format!(
198 "ambiguous selector: id targets notebook `{embedded_notebook}`, but notebook field is `{value}`"
199 ),
200 location: None,
201 });
202 }
203 embedded_notebook.to_string()
204 },
205 _ => embedded_notebook.to_string(),
206 };
207 self.ensure_existing_notebook(¬ebook).await?;
208 return Ok((notebook, format!("{}:{}", embedded_notebook, path)));
209 }
210 let notebook = self.resolve_notebook(notebook).await?;
211 Ok((notebook.clone(), format!("{}:{}", notebook, id)))
212 }
213
214 pub(super) fn append_notebook_warning(
215 &self,
216 output: String,
217 notebook: &str,
218 ) -> String {
219 let Some(default_notebook) = self.default_notebook.as_deref() else {
220 return output;
221 };
222 if default_notebook == notebook {
223 return output;
224 }
225 append_warning(
226 output,
227 format!(
228 "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."
229 ),
230 )
231 }
232
233 pub(super) fn resolve_notebook_name(
235 &self,
236 notebook: Option<&str>,
237 ) -> Result<String, NbError> {
238 if let Some(name) = notebook {
239 validate_notebook_name(name)?;
240 return Ok(name.to_string());
241 }
242 if let Some(name) = self.default_notebook.as_deref() {
243 validate_notebook_name(name)?;
244 return Ok(name.to_string());
245 }
246 Err(NbError::ValidationError {
247 reason:
248 "notebook not configured; set --notebook or NB_MCP_NOTEBOOK"
249 .to_string(),
250 location: None,
251 })
252 }
253
254 pub(super) async fn resolve_notebook(
255 &self,
256 notebook: Option<&str>,
257 ) -> Result<String, NbError> {
258 let name = self.resolve_notebook_name(notebook)?;
259 self.ensure_notebook(&name).await?;
260 Ok(name)
261 }
262
263 pub(super) async fn ensure_notebook(
264 &self,
265 notebook: &str,
266 ) -> Result<(), NbError> {
267 match self.check_notebook(notebook).await {
268 Ok(()) => Ok(()),
269 Err(
272 err
273 @ (NbError::ExecutableNotFound { .. } | NbError::Io { .. }),
274 ) => Err(err),
275 Err(NbError::NotFound { .. }) => {
282 if !self.create_notebook {
283 return Err(NbError::ValidationError {
284 reason: format!(
285 "notebook not found; create it with the nb CLI (`nb notebooks add {}`) \
286 or remove --no-create-notebook",
287 notebook
288 ),
289 location: None,
290 });
291 }
292 self.exec_vec(vec![
293 "notebooks".to_string(),
294 "add".to_string(),
295 notebook.to_string(),
296 ])
297 .await?;
298 Ok(())
299 },
300 Err(err) => Err(err),
306 }
307 }
308
309 pub(super) async fn ensure_existing_notebook(
310 &self,
311 notebook: &str,
312 ) -> Result<(), NbError> {
313 match self.check_notebook(notebook).await {
314 Ok(()) => Ok(()),
315 Err(
317 err
318 @ (NbError::ExecutableNotFound { .. } | NbError::Io { .. }),
319 ) => Err(err),
320 Err(err @ NbError::NotFound { .. }) => Err(err),
331 Err(err) => Err(err),
334 }
335 }
336
337 async fn check_notebook(&self, notebook: &str) -> Result<(), NbError> {
338 if notebook_dir_from_env(notebook)?.is_some() {
342 return Ok(());
343 }
344 let show_result = self
345 .exec_vec(vec![
346 "notebooks".to_string(),
347 "show".to_string(),
348 notebook.to_string(),
349 "--path".to_string(),
350 ])
351 .await;
352 match show_result {
353 Ok(output) => {
354 if output.trim().is_empty() {
355 return Err(NbError::CommandFailed {
362 command: format!(
363 "nb notebooks show {notebook} --path"
364 ),
365 stderr: "nb notebooks path output was empty"
366 .to_string(),
367 exit_code: None,
368 });
369 }
370 Ok(())
371 },
372 Err(err) => {
373 match err {
388 NbError::ExecutableNotFound { .. }
389 | NbError::Io { .. } => Err(err),
390 NbError::CommandFailed { ref stderr, .. }
391 if is_notebook_not_found(stderr, notebook) =>
392 {
393 Err(NbError::NotFound {
394 selector: format!("{notebook}:"),
395 })
396 },
397 other => Err(other),
398 }
399 },
400 }
401 }
402
403 pub(super) async fn exec(&self, args: &[&str]) -> Result<String, NbError> {
405 tracing::debug!(?args, "executing nb command");
406 let mut command = Command::new(nb_program());
410 scrub_git_env(&mut command);
422 command
423 .args(args)
424 .stdin(Stdio::null()) .stdout(Stdio::piped())
426 .stderr(Stdio::piped());
427 if self.disable_git_signing {
428 apply_git_signing_env(&mut command);
429 }
430 let joined = format!("nb {}", args.join(" "));
431 let output = command
432 .spawn()
433 .map_err(|e| {
434 if e.kind() == std::io::ErrorKind::NotFound {
435 NbError::ExecutableNotFound {
436 path: "nb".to_string(),
437 }
438 } else {
439 NbError::Io {
440 path: PathBuf::from("nb"),
441 source: e.into(),
442 }
443 }
444 })?
445 .wait_with_output()
446 .await
447 .map_err(|e| NbError::Io {
448 path: PathBuf::from("nb"),
449 source: e.into(),
450 })?;
451
452 if output.status.success() {
453 let stdout = String::from_utf8_lossy(&output.stdout);
454 Ok(strip_ansi(&stdout))
455 } else {
456 let stderr = String::from_utf8_lossy(&output.stderr);
457 let stdout = String::from_utf8_lossy(&output.stdout);
458 let stderr_text = if stderr.is_empty() {
460 strip_ansi(&stdout)
461 } else {
462 strip_ansi(&stderr)
463 };
464 Err(NbError::CommandFailed {
465 command: joined,
466 stderr: stderr_text,
467 exit_code: output.status.code(),
468 })
469 }
470 }
471
472 pub(super) async fn exec_vec(
474 &self,
475 args: Vec<String>,
476 ) -> Result<String, NbError> {
477 let args_ref: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
478 self.exec(&args_ref).await
479 }
480}
481
482#[cfg(test)]
491pub(super) mod native_gate_probe {
492 use std::path::{Path, PathBuf};
493 use std::sync::{Arc, Mutex, MutexGuard};
494 use std::time::Duration;
495
496 use tokio::sync::{Notify, mpsc};
497
498 static PROBE: Mutex<Option<Probe>> = Mutex::new(None);
499
500 struct Probe {
501 entered: mpsc::UnboundedSender<()>,
502 proceed: Arc<Notify>,
503 scope: PathBuf,
506 }
507
508 pub(super) struct Guard {
512 _lock: MutexGuard<'static, ()>,
513 }
514
515 impl Drop for Guard {
516 fn drop(&mut self) {
517 *PROBE.lock().unwrap() = None;
518 }
519 }
520
521 static INSTALL_LOCK: Mutex<()> = Mutex::new(());
522
523 pub(super) fn install(
527 entered: mpsc::UnboundedSender<()>,
528 proceed: Arc<Notify>,
529 scope: PathBuf,
530 ) -> Option<Guard> {
531 let lock = INSTALL_LOCK.try_lock().ok()?;
532 *PROBE.lock().unwrap() = Some(Probe {
533 entered,
534 proceed,
535 scope,
536 });
537 Some(Guard { _lock: lock })
538 }
539
540 pub(super) fn installed() -> bool {
542 PROBE.lock().unwrap().is_some()
543 }
544
545 pub(super) fn fired(scope: &Path) -> Option<Arc<Notify>> {
549 PROBE.lock().unwrap().as_ref().and_then(|probe| {
550 if probe.scope != scope {
551 return None;
552 }
553 let _ = probe.entered.send(());
557 Some(probe.proceed.clone())
558 })
559 }
560
561 pub(super) const WAIT_TIMEOUT: Duration = Duration::from_secs(30);
563}
564
565#[cfg(test)]
574mod native_gate_tests {
575 use std::ffi::OsString;
576 use std::sync::Arc;
577 use std::sync::atomic::{AtomicU64, Ordering};
578
579 use tokio::sync::Notify;
580
581 use super::native_gate_probe;
582 use crate::{Config, NbClient};
583
584 static FIXTURE_SEQ: AtomicU64 = AtomicU64::new(0);
585
586 struct EnvRestore {
587 key: &'static str,
588 prev: Option<OsString>,
589 }
590
591 impl Drop for EnvRestore {
592 fn drop(&mut self) {
593 unsafe {
594 match &self.prev {
595 Some(v) => std::env::set_var(self.key, v),
596 None => std::env::remove_var(self.key),
597 }
598 }
599 }
600 }
601
602 #[tokio::test]
603 async fn native_held_gate_reader_sees_mapping_change() {
604 let seq = FIXTURE_SEQ.fetch_add(1, Ordering::SeqCst);
607 let base = std::env::temp_dir()
608 .join(format!("nb-api-gate-probe-{}-{seq}", std::process::id()));
609 let root = base.join("nbdir").join("nb1");
610 std::fs::create_dir_all(&root).expect("fixture dirs");
611 let git_init = std::process::Command::new("git")
612 .args(["init", "-q"])
613 .current_dir(&root)
614 .status()
615 .expect("git init runs");
616 assert!(git_init.success(), "git init must succeed");
617 std::fs::write(root.join(".index"), "victim.md\nother.md\n")
618 .expect("index");
619 std::fs::write(root.join("victim.md"), "# Victim\nv0\n")
620 .expect("victim");
621 std::fs::write(root.join("other.md"), "# Other\no\n").expect("other");
622
623 let prev = std::env::var_os("NB_DIR");
624 unsafe {
625 std::env::set_var("NB_DIR", base.join("nbdir"));
626 }
627 let _env = EnvRestore {
628 key: "NB_DIR",
629 prev,
630 };
631 let _tmp = TmpRemove { path: base };
632
633 let client = NbClient::new(&Config {
634 notebook: Some("nb1".to_string()),
635 create_notebook: false,
636 allow_top_level_notes: true,
637 disable_git_signing: true,
638 ..Default::default()
639 })
640 .expect("client");
641
642 let (entered_tx, mut entered_rx) =
647 tokio::sync::mpsc::unbounded_channel();
648 let proceed = Arc::new(Notify::new());
649 let scope =
650 crate::gate::git_common_dir_realpath(&root).expect("gate key");
651 let probe =
652 native_gate_probe::install(entered_tx, proceed.clone(), scope)
653 .expect("probe installs once");
654 assert!(
655 native_gate_probe::installed(),
656 "probe visible while installed"
657 );
658 let mut reader = tokio::spawn({
659 let client = client.clone();
660 async move { client.show_note("1", None).await }
661 });
662 if tokio::time::timeout(
666 native_gate_probe::WAIT_TIMEOUT,
667 entered_rx.recv(),
668 )
669 .await
670 .is_err()
671 {
672 reader.abort();
673 panic!("reader never entered the hold");
674 }
675 std::fs::write(root.join(".index"), "other.md\nvictim.md\n")
676 .expect("swap slot 1");
677 proceed.notify_one();
678 let shown = tokio::select! {
679 joined = &mut reader => joined
680 .expect("reader joins")
681 .expect("queued read succeeds"),
682 _ = tokio::time::sleep(native_gate_probe::WAIT_TIMEOUT) => {
683 reader.abort();
684 proceed.notify_one();
685 panic!("queued reader never completed");
686 }
687 };
688 assert_eq!(shown.path, "other.md".to_string(), "{shown:?}");
689 assert_eq!(shown.body, "o\n", "{shown:?}");
690 drop(probe);
693 assert!(
694 !native_gate_probe::installed(),
695 "probe cleared after guard drop"
696 );
697 }
698
699 struct TmpRemove {
700 path: std::path::PathBuf,
701 }
702
703 impl Drop for TmpRemove {
704 fn drop(&mut self) {
705 let _ = std::fs::remove_dir_all(&self.path);
706 }
707 }
708}