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            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    /// Begin a collect-then-commit [`Transaction`] for `notebook`.
60    ///
61    /// Construction performs no durable I/O and does not acquire the gate.
62    pub async fn transaction(
63        &self,
64        notebook: Option<&str>,
65    ) -> Result<Transaction, NbError> {
66        let notebook = self.resolve_notebook_name(notebook)?;
67        // Prefer filesystem existence under NB_DIR so plan construction does
68        // not invoke `nb` (which can auto-checkpoint a dirty worktree).
69        // Discovery I/O failures fall back to ensure here (legacy
70        // behavior): only the native read path treats them as `Io`.
71        // Only a genuine miss ensures (and possibly creates).
72        let existing = notebook_dir_from_env(&notebook).unwrap_or_default();
73        if existing.is_none() {
74            self.ensure_notebook(&notebook).await?;
75        }
76        Ok(Transaction::new(self.clone(), notebook, self.gate_timeout))
77    }
78
79    /// Process-shared gate queue timeout configured on this client.
80    pub fn gate_timeout(&self) -> std::time::Duration {
81        self.gate_timeout
82    }
83
84    /// Notebook path without acquiring the notebook gate (caller holds gate or
85    /// is still resolving identity).
86    ///
87    /// Prefers `$NB_DIR/<notebook>` when that directory exists so path
88    /// resolution does not invoke `nb` (which can auto-checkpoint and clear a
89    /// dirty baseline before `Transaction::commit` inspects status).
90    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        // Discovery I/O failures fall back to ensure here (legacy
96        // behavior); only the native read path treats them as `Io`.
97        let existing: Option<PathBuf> =
98            notebook_dir_from_env(&notebook).unwrap_or_default();
99        if let Some(path) = existing {
100            return Ok(path);
101        }
102        self.ensure_notebook(&notebook).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    /// Gate hold over an already-resolved notebook root: no
135    /// discovery, no ensure, no spawns. Native reads resolve the root
136    /// with the no-create lookup before acquiring this gate, so a
137    /// missing notebook never materializes as a side effect.
138    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            // Test-only rendezvous: park the holder so a
153            // crate-internal regression test can mutate the mapping
154            // before resolution runs. No production code installs a
155            // probe; absent probe is a no-op. The wait is bounded
156            // (fail-open) so an abandoned test never parks reads
157            // forever.
158            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(&notebook).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    /// Resolves the notebook to use for a command.
234    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            // Genuine infrastructure failure (no nb binary, IO
270            // error) — surface verbatim; do not try to create.
271            Err(
272                err
273                @ (NbError::ExecutableNotFound { .. } | NbError::Io { .. }),
274            ) => Err(err),
275            // Typed NotFound from `check_notebook` means the
276            // pinned diagnostic matched the genuine notebook-
277            // absence shape (`Notebook not found: <name>`).
278            // Try to create it; if creation is disabled, surface
279            // a typed validation error; if creation fails,
280            // propagate the new CommandFailed verbatim.
281            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            // Any other error from `check_notebook` (permission
301            // denied, transient crash, etc.) propagates verbatim;
302            // we deliberately do not try `notebooks add`, because
303            // a non-NotFound CommandFailed likely indicates a
304            // real failure that creation would not rescue.
305            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            // Infrastructure failure — surface verbatim.
316            Err(
317                err
318                @ (NbError::ExecutableNotFound { .. } | NbError::Io { .. }),
319            ) => Err(err),
320            // Genuine notebook absence: propagate the typed
321            // `NbError::NotFound` produced by `check_notebook`
322            // verbatim. The qualified-selector path
323            // (`<notebook>:<item>`) used by `show_note`,
324            // `add_note`, `edit_note`, etc. surfaces this to the
325            // caller as the typed `NotFound` variant — the
326            // caller can distinguish "notebook gone" from a
327            // generic validation failure. Erasing the typed
328            // `NotFound` into a `ValidationError` would lose
329            // the variant distinction.
330            Err(err @ NbError::NotFound { .. }) => Err(err),
331            // Other CommandFailed errors propagate verbatim
332            // rather than being misclassified as "not found."
333            Err(err) => Err(err),
334        }
335    }
336
337    async fn check_notebook(&self, notebook: &str) -> Result<(), NbError> {
338        // Fast path: an existing `$NB_DIR/<notebook>` needs no
339        // subprocess. Discovery I/O failures propagate; only a
340        // genuine miss falls through to the `nb` check below.
341        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                    // Use the actual argument vector that was passed
356                    // to `exec_vec`, not a reformatted display
357                    // string. This way the `command` field matches
358                    // what was actually executed on the wire, with
359                    // no possibility of drift between the synthetic
360                    // field and the real argv.
361                    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                // Surface genuine infrastructure failures verbatim
374                // so callers can distinguish "nb is broken" from
375                // "notebook does not exist". Genuine notebook
376                // absence (nb's pinned diagnostic on stderr) maps
377                // to typed `NotFound`. Any other subprocess
378                // failure (e.g., permission denied, a transient
379                // crash, an nb bug surfacing as `NotFound` in
380                // stderr without the literal `Notebook not found:`
381                // prefix) propagates as the original
382                // `CommandFailed` rather than being swallowed
383                // here. The caller (`ensure_notebook` /
384                // `ensure_existing_notebook`) decides whether to
385                // try to create the notebook on `NotFound` or
386                // surface the error verbatim otherwise.
387                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    /// Executes an nb command and returns stdout.
404    pub(super) async fn exec(&self, args: &[&str]) -> Result<String, NbError> {
405        tracing::debug!(?args, "executing nb command");
406        // `nb_program` resolves `nb` to a spawnable absolute path on
407        // Windows (PATHEXT-aware: Rust std only finds `.exe` there and
408        // would miss a `nb.cmd` launcher). Unix keeps PATH resolution.
409        let mut command = Command::new(nb_program());
410        // Strip inherited `GIT_*` routing vars before chaining `.args` /
411        // `.env`. Without this, any caller invoking us from inside a
412        // git hook (pre-commit, pre-push, post-checkout) or CI runner
413        // propagates GIT_DIR / GIT_INDEX_FILE / GIT_COMMON_DIR /
414        // GIT_WORK_TREE / GIT_OBJECT_DIRECTORY /
415        // GIT_ALTERNATE_OBJECT_DIRECTORIES into the spawned `nb`,
416        // which is a bash script wrapping git — every git call inside
417        // nb then redirects to the parent repo instead of the
418        // notebook's repo. The blast-by-prefix also covers future
419        // GIT_* redirect vars without requiring a code change.
420        // See `nb-api:issues/3`. Do not remove.
421        scrub_git_env(&mut command);
422        command
423            .args(args)
424            .stdin(Stdio::null()) // Prevent TTY hangs
425            .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            // nb sometimes writes errors to stdout
459            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    /// Executes an nb command with dynamic arguments.
473    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/// Test-only rendezvous inside the native gate hold.
483///
484/// Fired after the hold is acquired, before the gated future runs,
485/// so a crate-internal regression test can park a reader mid-hold,
486/// mutate the mapping, then release it — deterministically proving
487/// that resolution happens under the hold. No production code
488/// installs a probe; an absent probe is a no-op. Waiting is bounded
489/// (fail-open): an abandoned rendezvous never parks reads forever.
490#[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        /// Registry key (canonical git common dir) this probe applies
504        /// to; reads under other notebooks never rendezvous.
505        scope: PathBuf,
506    }
507
508    /// RAII uninstall: dropping clears the probe before releasing
509    /// the install lock, so later reads never rendezvous with a
510    /// stale sender.
511    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    /// Install the rendezvous scoped to one gate key; fails when
524    /// another test holds it. Returns a guard that uninstalls on
525    /// drop.
526    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    /// Whether a probe is currently installed (lifecycle assertion).
541    pub(super) fn installed() -> bool {
542        PROBE.lock().unwrap().is_some()
543    }
544
545    /// Signal entry and return the gate to wait on, when a probe is
546    /// installed for this gate key. The wait itself is bounded by
547    /// the caller (fail-open on abandonment).
548    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            // A failed send means the test is gone: still return
554            // the gate so the caller can bound its own wait instead
555            // of parking forever.
556            let _ = probe.entered.send(());
557            Some(probe.proceed.clone())
558        })
559    }
560
561    /// Fail-open bound for a parked rendezvous wait.
562    pub(super) const WAIT_TIMEOUT: Duration = Duration::from_secs(30);
563}
564
565// NOTE: this crate-internal test exists because the queued-reader
566// property (a read parked inside the hold while the index mapping
567// changes) is unreachable deterministically through any public
568// interface: gate acquisition is crate-private, so integration
569// tests can only race the hold statistically (see
570// `native_reads_stay_consistent_under_contention`). Per convention
571// this stays the single inline test exercising a public path;
572// every other native-path case lives in `tests/integration`.
573#[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        // Bare git notebook, no `nb` needed: native reads never
605        // spawn, and gate keys only need `git rev-parse`.
606        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        // Park the reader inside the hold, then swap slot 1 while
643        // it waits: resolution strictly follows the swap. A
644        // pre-gate resolver (lookup before the hold) would resolve
645        // first and read the stale victim file instead.
646        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        // Bounded both ways: an early acquisition or discovery
663        // failure must fail the test, never hang the suite. On
664        // failure the reader is aborted and released.
665        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        // Lifecycle: dropping the guard uninstalls, so later reads
691        // never rendezvous with a stale sender.
692        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}