Skip to main content

nb_api/client/
core.rs

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
21/// Regex to match ANSI/ISO 2022 escape sequences.
22///
23/// Covers:
24/// - Fe sequences: `ESC [@-Z\-_]` (single byte after ESC)
25/// - CSI sequences: `ESC [ ... m` (SGR colors, cursor control, etc.)
26/// - nF sequences: `ESC [ -/]* [0-~]` (character set designation like `ESC ( B`)
27static ANSI_REGEX: LazyLock<Regex> = LazyLock::new(|| {
28    Regex::new(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|[ -/]*[0-~])").unwrap()
29});
30
31/// Strip ANSI escape sequences from text.
32fn 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    /// Creates a new nb client.
40    ///
41    /// Uses the notebook from config if set, otherwise falls back to a
42    /// Git-derived notebook name. Does NOT read `NB_MCP_NOTEBOOK` —
43    /// that is an MCP-server-specific env var resolved by the server.
44    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    /// Begin a collect-then-commit [`Transaction`] for `notebook`.
61    ///
62    /// Construction performs no durable I/O and does not acquire the gate.
63    pub async fn transaction(
64        &self,
65        notebook: Option<&str>,
66    ) -> Result<Transaction, NbError> {
67        let notebook = self.resolve_notebook_name(notebook)?;
68        // Prefer filesystem existence under NB_DIR so plan construction does
69        // not invoke `nb` (which can auto-checkpoint a dirty worktree).
70        // Discovery I/O failures fall back to ensure here (legacy
71        // behavior): only the native read path treats them as `Io`.
72        // Only a genuine miss ensures (and possibly creates).
73        let existing =
74            notebook_dir_from_env(&notebook, self.require_explicit_nb_dir)
75                .unwrap_or_default();
76        if existing.is_none() {
77            self.ensure_notebook(&notebook).await?;
78        }
79        Ok(Transaction::new(self.clone(), notebook, self.gate_timeout))
80    }
81
82    /// Process-shared gate queue timeout configured on this client.
83    pub fn gate_timeout(&self) -> std::time::Duration {
84        self.gate_timeout
85    }
86
87    /// Notebook path without acquiring the notebook gate (caller holds gate or
88    /// is still resolving identity).
89    ///
90    /// Prefers `$NB_DIR/<notebook>` when that directory exists so path
91    /// resolution does not invoke `nb` (which can auto-checkpoint and clear a
92    /// dirty baseline before `Transaction::commit` inspects status).
93    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        // Discovery I/O failures fall back to ensure here (legacy
99        // behavior); only the native read path treats them as `Io`.
100        let existing: Option<PathBuf> =
101            notebook_dir_from_env(&notebook, self.require_explicit_nb_dir)
102                .unwrap_or_default();
103        if let Some(path) = existing {
104            return Ok(path);
105        }
106        self.ensure_notebook(&notebook).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    /// Gate hold over an already-resolved notebook root: no
139    /// discovery, no ensure, no spawns. Native reads resolve the root
140    /// with the no-create lookup before acquiring this gate, so a
141    /// missing notebook never materializes as a side effect.
142    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            // Test-only rendezvous: park the holder so a
157            // crate-internal regression test can mutate the mapping
158            // before resolution runs. No production code installs a
159            // probe; absent probe is a no-op. The wait is bounded
160            // (fail-open) so an abandoned test never parks reads
161            // forever.
162            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(&notebook).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    /// Resolves the notebook to use for a command.
238    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            // Genuine infrastructure failure (no nb binary, IO
274            // error) — surface verbatim; do not try to create.
275            Err(
276                err
277                @ (NbError::ExecutableNotFound { .. } | NbError::Io { .. }),
278            ) => Err(err),
279            // Typed NotFound from `check_notebook` means the
280            // pinned diagnostic matched the genuine notebook-
281            // absence shape (`Notebook not found: <name>`).
282            // Try to create it; if creation is disabled, surface
283            // a typed validation error; if creation fails,
284            // propagate the new CommandFailed verbatim.
285            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            // Any other error from `check_notebook` (permission
305            // denied, transient crash, etc.) propagates verbatim;
306            // we deliberately do not try `notebooks add`, because
307            // a non-NotFound CommandFailed likely indicates a
308            // real failure that creation would not rescue.
309            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            // Infrastructure failure — surface verbatim.
320            Err(
321                err
322                @ (NbError::ExecutableNotFound { .. } | NbError::Io { .. }),
323            ) => Err(err),
324            // Genuine notebook absence: propagate the typed
325            // `NbError::NotFound` produced by `check_notebook`
326            // verbatim. The qualified-selector path
327            // (`<notebook>:<item>`) used by `show_note`,
328            // `add_note`, `edit_note`, etc. surfaces this to the
329            // caller as the typed `NotFound` variant — the
330            // caller can distinguish "notebook gone" from a
331            // generic validation failure. Erasing the typed
332            // `NotFound` into a `ValidationError` would lose
333            // the variant distinction.
334            Err(err @ NbError::NotFound { .. }) => Err(err),
335            // Other CommandFailed errors propagate verbatim
336            // rather than being misclassified as "not found."
337            Err(err) => Err(err),
338        }
339    }
340
341    async fn check_notebook(&self, notebook: &str) -> Result<(), NbError> {
342        // Fast path: an existing `$NB_DIR/<notebook>` needs no
343        // subprocess. Discovery I/O failures propagate; only a
344        // genuine miss falls through to the `nb` check below.
345        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                    // Use the actual argument vector that was passed
362                    // to `exec_vec`, not a reformatted display
363                    // string. This way the `command` field matches
364                    // what was actually executed on the wire, with
365                    // no possibility of drift between the synthetic
366                    // field and the real argv.
367                    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                // Surface genuine infrastructure failures verbatim
380                // so callers can distinguish "nb is broken" from
381                // "notebook does not exist". Genuine notebook
382                // absence (nb's pinned diagnostic on stderr) maps
383                // to typed `NotFound`. Any other subprocess
384                // failure (e.g., permission denied, a transient
385                // crash, an nb bug surfacing as `NotFound` in
386                // stderr without the literal `Notebook not found:`
387                // prefix) propagates as the original
388                // `CommandFailed` rather than being swallowed
389                // here. The caller (`ensure_notebook` /
390                // `ensure_existing_notebook`) decides whether to
391                // try to create the notebook on `NotFound` or
392                // surface the error verbatim otherwise.
393                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    /// Executes an nb command and returns stdout.
410    pub(super) async fn exec(&self, args: &[&str]) -> Result<String, NbError> {
411        tracing::debug!(?args, "executing nb command");
412        // `nb_program` resolves `nb` to a spawnable absolute path on
413        // Windows (PATHEXT-aware: Rust std only finds `.exe` there and
414        // would miss a `nb.cmd` launcher). Unix keeps PATH resolution.
415        let mut command = Command::new(nb_program());
416        // Strip inherited `GIT_*` routing vars before chaining `.args` /
417        // `.env`. Without this, any caller invoking us from inside a
418        // git hook (pre-commit, pre-push, post-checkout) or CI runner
419        // propagates GIT_DIR / GIT_INDEX_FILE / GIT_COMMON_DIR /
420        // GIT_WORK_TREE / GIT_OBJECT_DIRECTORY /
421        // GIT_ALTERNATE_OBJECT_DIRECTORIES into the spawned `nb`,
422        // which is a bash script wrapping git — every git call inside
423        // nb then redirects to the parent repo instead of the
424        // notebook's repo. The blast-by-prefix also covers future
425        // GIT_* redirect vars without requiring a code change.
426        // See `nb-api:issues/3`. Do not remove.
427        scrub_git_env(&mut command);
428        // Canonicalize the child terminal: real `nb` 7.24.0 emits
429        // SGR sequences plus an `ESC ( B` residue on some code
430        // paths when `TERM` advertises color (e.g.
431        // `TERM=xterm-256color`), despite trailing `--no-color`
432        // flags, and it does not honor `NO_COLOR`. `TERM` unset
433        // and `TERM=dumb` both yield plain output; `dumb` is set
434        // (rather than removed) because it stays a valid terminfo
435        // entry for children that require `TERM` to exist. The
436        // `--no-color` flags and the ANSI stripper stay as defense
437        // in depth. See `nb-mcp-server:todos/mcp/64`.
438        command.env("TERM", "dumb");
439        command
440            .args(args)
441            .stdin(Stdio::null()) // Prevent TTY hangs
442            .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            // nb sometimes writes errors to stdout
476            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    /// Executes an nb command with dynamic arguments.
490    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/// Test-only rendezvous inside the native gate hold.
500///
501/// Fired after the hold is acquired, before the gated future runs,
502/// so a crate-internal regression test can park a reader mid-hold,
503/// mutate the mapping, then release it — deterministically proving
504/// that resolution happens under the hold. No production code
505/// installs a probe; an absent probe is a no-op. Waiting is bounded
506/// (fail-open): an abandoned rendezvous never parks reads forever.
507#[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        /// Registry key (canonical git common dir) this probe applies
521        /// to; reads under other notebooks never rendezvous.
522        scope: PathBuf,
523    }
524
525    /// RAII uninstall: dropping clears the probe before releasing
526    /// the install lock, so later reads never rendezvous with a
527    /// stale sender.
528    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    /// Install the rendezvous scoped to one gate key; fails when
541    /// another test holds it. Returns a guard that uninstalls on
542    /// drop.
543    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    /// Whether a probe is currently installed (lifecycle assertion).
558    pub(super) fn installed() -> bool {
559        PROBE.lock().unwrap().is_some()
560    }
561
562    /// Signal entry and return the gate to wait on, when a probe is
563    /// installed for this gate key. The wait itself is bounded by
564    /// the caller (fail-open on abandonment).
565    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            // A failed send means the test is gone: still return
571            // the gate so the caller can bound its own wait instead
572            // of parking forever.
573            let _ = probe.entered.send(());
574            Some(probe.proceed.clone())
575        })
576    }
577
578    /// Fail-open bound for a parked rendezvous wait.
579    pub(super) const WAIT_TIMEOUT: Duration = Duration::from_secs(30);
580}
581
582// NOTE: this crate-internal test exists because the queued-reader
583// property (a read parked inside the hold while the index mapping
584// changes) is unreachable deterministically through any public
585// interface: gate acquisition is crate-private, so integration
586// tests can only race the hold statistically (see
587// `native_reads_stay_consistent_under_contention`). Per convention
588// this stays the single inline test exercising a public path;
589// every other native-path case lives in `tests/integration`.
590#[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        // Bare git notebook, no `nb` needed: native reads never
622        // spawn, and gate keys only need `git rev-parse`.
623        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        // Park the reader inside the hold, then swap slot 1 while
660        // it waits: resolution strictly follows the swap. A
661        // pre-gate resolver (lookup before the hold) would resolve
662        // first and read the stale victim file instead.
663        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        // Bounded both ways: an early acquisition or discovery
680        // failure must fail the test, never hang the suite. On
681        // failure the reader is aborted and released.
682        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        // Lifecycle: dropping the guard uninstalls, so later reads
708        // never rendezvous with a stale sender.
709        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}