Skip to main content

nb_api/
error.rs

1//! Structured error types for `nb-api`.
2//!
3//! This module hosts [`NbError`] and its associated types
4//! ([`ParseErrorKind`], [`IoError`], [`IoErrorKind`]) as defined by
5//! the `add-note-document-model` (P1) specification. All variants
6//! derive `Serialize`/`Deserialize` so errors round-trip cleanly
7//! through JSON-encoded wire protocols (MCP tool responses, etc.).
8//!
9//! [`NbError`] also derives `Display` and implements
10//! [`std::error::Error`], so existing textual error reporting paths
11//! continue to work unchanged.
12//!
13//! # Migration (from `nb-api` 0.2.x to 0.3.0)
14//!
15//! | Old variant | New variant | Migration |
16//! |---|---|---|
17//! | `CommandFailed(String)` | `CommandFailed { command, stderr, exit_code }` | capture fields at call sites; map validation/policy failures to `ValidationError` |
18//! | `NotFound` (unit) | `ExecutableNotFound { path }` | the unit means `nb` binary missing; track path |
19//! | `Io(std::io::Error)` | `Io { path, source: IoError }` | track path in callers; convert via `From`; reverse is lossy |
20//! | `UnsupportedShowTarget { selector, actual_type }` | Same | Unchanged |
21//! | `DuplicateTitleHeading { title, heading }` | Same | Unchanged |
22//!
23//! New variants introduced in 0.3.0: `ParseError`, `InvalidFingerprint`,
24//! `JsonParseError`, `ValidationError`, `ExecutableNotFound`,
25//! `UnsupportedDocumentFormat`.
26//!
27//! ## New `UnsupportedDocumentFormat` variant (R3 revision)
28//!
29//! This is a NEW variant. There is no `nb-api 0.2.x` predecessor.
30//! Consumers upgrading to `nb-api 0.3.0` SHALL add the variant to
31//! their match arms. **Adding a variant to an exhaustive enum
32//! match produces a compile error, not a warning; wildcard
33//! matches continue compiling.** The constant
34//! [`SUPPORTED_DOCUMENT_EXTENSIONS`] (crate-root re-export of the
35//! source-of-truth declared in `parser`) is the basis for the
36//! `supported` payload at construction time.
37
38use std::error::Error as _; // `.source()` on `std::io::Error`
39use std::path::PathBuf;
40
41use serde::{Deserialize, Serialize};
42
43/// Errors raised by `nb-api` operations.
44///
45/// All variants are serializable so they can traverse MCP tool
46/// response envelopes without lossy string flattening. The
47/// [`std::error::Error`] implementation remains for ergonomic
48/// interop with code that uses `?` and standard error reporting.
49///
50/// `std::error::Error` is implemented MANUALLY below rather than
51/// via `thiserror::Error` derive. The derive's autodetect
52/// treats any field named `source` as a `#[source]` chain link
53/// and tries to convert it to `dyn Error`, which fails for
54/// fields of type `String` (e.g., `JsonParseError { source:
55/// String }` per the P1 specification). The manual impl
56/// preserves the field name and only sets a source-chain link
57/// for variants whose source field is itself an `Error`.
58#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
59#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
60#[serde(tag = "type", rename_all = "snake_case")]
61pub enum NbError {
62    /// An `nb` subprocess invocation failed (non-zero exit, or
63    /// spawning failed for a non-NotFound reason).
64    CommandFailed {
65        /// The argument vector (joined) that was executed.
66        command: String,
67        /// Captured stderr (or stdout when stderr was empty).
68        stderr: String,
69        /// Process exit code, if the process started.
70        exit_code: Option<i32>,
71    },
72
73    /// The `nb` executable could not be located on `PATH` (or in
74    /// the resolved location) when a subprocess was spawned.
75    ExecutableNotFound {
76        /// The resolved path the spawn attempt targeted.
77        path: String,
78    },
79
80    /// `nb` reported that the requested selector was not found.
81    NotFound {
82        /// The selector that was not resolved.
83        selector: String,
84    },
85
86    /// An I/O error occurred while accessing a notebook file or
87    /// the on-disk notebook directory. The `source` field captures
88    /// the original `std::io::Error` chain as a serializable
89    /// snapshot (recursive [`IoError`]).
90    Io {
91        /// Path that triggered the I/O error.
92        path: PathBuf,
93        /// Snapshot of the `std::io::Error` chain.
94        source: IoError,
95    },
96
97    /// `nb show` was invoked on a selector whose type is not
98    /// classified as text by `nb` itself (per the
99    /// `add-0-2-0-foundation` public-API spec). Folders, archives,
100    /// audio, video, image, and any other non-textual type reach
101    /// this path. The classification delegates to
102    /// `nb show <selector> --type text` so forward compatibility
103    /// is automatic when `nb` adds new textual types. Probe
104    /// failure (e.g., selector not found) does NOT route here;
105    /// it falls through to the original `CommandFailed` error
106    /// from the content-read path.
107    UnsupportedShowTarget {
108        selector: String,
109        actual_type: String,
110    },
111
112    /// `nb add` was called with a `title` and `content` where the
113    /// first nonblank line of `content` is an exact Markdown ATX H1
114    /// duplicating the title. The validation runs in the caller
115    /// process before any subprocess invocation or notebook side
116    /// effect (including `resolve_notebook`); the rejection
117    /// happens entirely in-process. `heading` carries the exact
118    /// detected source line (including the leading `#` and any
119    /// surrounding whitespace) for actionable diagnostics. See
120    /// `add-0-2-0-foundation` public-API specification.
121    DuplicateTitleHeading { title: String, heading: String },
122
123    /// A structural parse failure.
124    ParseError {
125        kind: ParseErrorKind,
126        location: std::ops::Range<usize>,
127    },
128
129    /// A fingerprint string failed structural validation (wrong
130    /// prefix, wrong length, mixed case, etc.). `reason` carries a
131    /// machine-readable category (e.g., `"empty"`,
132    /// `"unknown_algorithm_prefix"`, `"uppercase_hex"`).
133    InvalidFingerprint { reason: String },
134
135    /// JSON deserialization failed when constructing a typed
136    /// wrapper (e.g., [`crate::fingerprint::Fingerprint::from_json`]).
137    JsonParseError {
138        // Field is named `source` per the P1 specification.
139        source: String,
140    },
141
142    /// A semantic validation error raised by an operation boundary
143    /// (e.g., rejecting input that is structurally valid but
144    /// semantically illegal). `location` is `None` when the
145    /// failure is not byte-anchored.
146    ValidationError {
147        reason: String,
148        location: Option<std::ops::Range<usize>>,
149    },
150
151    /// Format-dispatch refusal (R3 revision).
152    ///
153    /// `parse(bytes, FromPath(path))` returned this error because
154    /// the final filename matched one of the recognized-but-
155    /// unsupported dotted suffixes (e.g., `.org`, `.latex`,
156    /// `.tex`, `.adoc`, `.asciidoc`). Format dispatch precedes
157    /// byte parsing, so no bytes were consumed and no
158    /// parse-error location is meaningful — this is a
159    /// contextual configuration error, not a parse failure.
160    ///
161    /// `extension` carries the lowercase dotted suffix WITHOUT
162    /// the leading dot (e.g., `"org"`, `"latex"`).
163    /// `supported` is the owned canonical list of supported
164    /// extensions, populated at construction time from
165    /// `crate::SUPPORTED_DOCUMENT_EXTENSIONS`. The owned
166    /// `Vec<String>` shape is required for the derived
167    /// `Serialize` / `Deserialize` round-trip contract on
168    /// `NbError`.
169    UnsupportedDocumentFormat {
170        extension: String,
171        supported: Vec<String>,
172    },
173
174    /// Process-shared gate queue wait exceeded. Notebook was not mutated.
175    GateTimeout { gate: String, timeout_ms: u64 },
176
177    /// `Transaction::commit` refused because the notebook worktree/index is dirty.
178    DirtyBaseline { guidance: String },
179
180    /// Plan-op path collision against snapshot or earlier plan ops.
181    PathCollision {
182        path: String,
183        plan_index: Option<u32>,
184    },
185
186    /// Plan targets or would leave durable state on a Git-ignored path in a
187    /// way that cannot be represented in the single checkpoint (existing
188    /// ignored entry mutation), or requires force-staging (reported only when
189    /// force-stage is unavailable). Prefer rejecting existing-ignored mutators.
190    PathIgnored {
191        path: String,
192        guidance: String,
193        plan_index: Option<u32>,
194    },
195
196    /// Validation/apply failure tied to a plan entry.
197    PlanValidation {
198        kind: String,
199        message: String,
200        plan_index: Option<u32>,
201    },
202
203    /// Commit completion is unknown (e.g. transport timeout after checkpoint may have started).
204    IndeterminateCommit {
205        pre_revision: String,
206        post_revision_observed: Option<String>,
207        guidance: String,
208    },
209
210    /// Cleanup after a known failed apply could not verify clean `pre_revision`.
211    RecoveryRequired {
212        pre_revision: String,
213        post_revision_observed: Option<String>,
214        status_observed: Option<String>,
215        preserved_paths: Option<Vec<String>>,
216        guidance: String,
217    },
218
219    /// Body fingerprint precondition failed.
220    FingerprintMismatch {
221        target: crate::types::NoteTarget,
222        guidance: String,
223    },
224
225    /// Line number/anchor precondition failed.
226    AnchorMismatch {
227        target: String,
228        number: u32,
229        guidance: String,
230    },
231
232    /// Substring `expected_count` did not match actual matches.
233    OccurrenceMismatch { expected: u32, actual: u32 },
234
235    /// Overlapping line edits in one batch.
236    OverlappingEdits { indices: Vec<u32> },
237
238    /// Invalid `show_note_lines` window.
239    InvalidLineWindow {
240        offset: u32,
241        limit: u32,
242        total_lines: u32,
243    },
244
245    /// Empty substring pattern refused at enqueue/apply.
246    EmptySubstringPattern,
247
248    /// Contiguous-body-only op invoked on a multi-fragment document.
249    FragmentedBody {
250        fragment_count: u32,
251        guidance: String,
252    },
253
254    /// Structured text surface hit non-UTF-8 bytes in a text-classified file.
255    ///
256    /// Non-textual notes keep using `UnsupportedShowTarget`; this variant
257    /// covers the narrow non-UTF-8-but-text case. Use
258    /// `NbClient::read_note_source_bytes` for raw access.
259    NonUtf8 {
260        selector: String,
261        path: String,
262        kind: String,
263        #[serde(default, skip_serializing_if = "Option::is_none")]
264        mime_hint: Option<String>,
265    },
266
267    /// `.nb-api-index.lock` wait exceeded before any mutation.
268    IndexLockTimeout { path: String, timeout_ms: u64 },
269
270    /// Document structure is not supported for the requested op.
271    UnsupportedStructure { reason: String },
272
273    /// An operation was applied to an entity of the wrong kind:
274    /// deleting a folder as a note, editing text of a non-textual
275    /// file, or changing task state on a non-todo. Replaces
276    /// string-matched `ValidationError` / `UnsupportedStructure`
277    /// reasons with typed kinds. `expected` is the accepted-kinds
278    /// set for the operation, `actual` the single observed kind.
279    WrongKind {
280        expected: crate::KindSet,
281        actual: crate::EntityKind,
282        selector: String,
283        path: String,
284    },
285}
286
287impl std::fmt::Display for NbError {
288    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
289        match self {
290            Self::CommandFailed {
291                command,
292                stderr,
293                exit_code,
294            } => match exit_code {
295                Some(code) => {
296                    write!(
297                        f,
298                        "command {command:?} failed (exit {code}): {stderr}"
299                    )
300                },
301                None => {
302                    write!(
303                        f,
304                        "command {command:?} failed (exit unknown): {stderr}"
305                    )
306                },
307            },
308            Self::ExecutableNotFound { path } => {
309                write!(f, "`nb` executable not found at path {path:?}")
310            },
311            Self::NotFound { selector } => {
312                write!(f, "not found: {selector:?}")
313            },
314            Self::Io { path, source } => {
315                write!(f, "I/O error at {path:?}: {source}")
316            },
317            Self::UnsupportedShowTarget {
318                selector,
319                actual_type,
320            } => write!(
321                f,
322                "selector `{selector}` resolved to non-textual type `{actual_type}`; \
323                 `nb show` does not display non-textual content"
324            ),
325            Self::DuplicateTitleHeading { title, heading } => write!(
326                f,
327                "title `{title}` duplicates the first H1 in content (`{heading}`); \
328                 remove the duplicate heading to avoid double-rendering"
329            ),
330            Self::ParseError { kind, location } => {
331                write!(f, "parse error: {kind:?} at {location:?}")
332            },
333            Self::InvalidFingerprint { reason } => {
334                write!(f, "invalid fingerprint: {reason:?}")
335            },
336            Self::JsonParseError { source } => {
337                write!(f, "JSON parse error: {source:?}")
338            },
339            Self::ValidationError {
340                reason,
341                location: _,
342            } => {
343                write!(f, "validation error: {reason:?}")
344            },
345            Self::UnsupportedDocumentFormat {
346                extension,
347                supported,
348            } => {
349                write!(
350                    f,
351                    "unsupported document format: {extension:?} (supported: {supported:?})"
352                )
353            },
354            Self::GateTimeout { gate, timeout_ms } => {
355                write!(
356                    f,
357                    "gate timeout waiting on {gate} after {timeout_ms}ms"
358                )
359            },
360            Self::DirtyBaseline { guidance } => {
361                write!(f, "dirty baseline: {guidance}")
362            },
363            Self::PathCollision { path, plan_index } => {
364                write!(
365                    f,
366                    "path collision at {path:?} (plan_index={plan_index:?})"
367                )
368            },
369            Self::PathIgnored {
370                path,
371                guidance,
372                plan_index,
373            } => write!(
374                f,
375                "ignored path {path:?} (plan_index={plan_index:?}): {guidance}"
376            ),
377            Self::PlanValidation {
378                kind,
379                message,
380                plan_index,
381            } => write!(
382                f,
383                "plan validation ({kind}) at index {plan_index:?}: {message}"
384            ),
385            Self::IndeterminateCommit {
386                pre_revision,
387                post_revision_observed,
388                guidance,
389            } => write!(
390                f,
391                "indeterminate commit (pre={pre_revision}, post={post_revision_observed:?}): {guidance}"
392            ),
393            Self::RecoveryRequired {
394                pre_revision,
395                guidance,
396                ..
397            } => write!(
398                f,
399                "recovery required (pre_revision={pre_revision}): {guidance}"
400            ),
401            Self::FingerprintMismatch { target, guidance } => {
402                write!(f, "fingerprint mismatch for {target:?}: {guidance}")
403            },
404            Self::AnchorMismatch {
405                target,
406                number,
407                guidance,
408            } => write!(
409                f,
410                "anchor mismatch for {target} line {number}: {guidance}"
411            ),
412            Self::OccurrenceMismatch { expected, actual } => {
413                write!(
414                    f,
415                    "occurrence mismatch: expected={expected} actual={actual}"
416                )
417            },
418            Self::OverlappingEdits { indices } => {
419                write!(f, "overlapping edits at indices {indices:?}")
420            },
421            Self::InvalidLineWindow {
422                offset,
423                limit,
424                total_lines,
425            } => write!(
426                f,
427                "invalid line window offset={offset} limit={limit} total_lines={total_lines}"
428            ),
429            Self::EmptySubstringPattern => {
430                write!(f, "empty substring pattern")
431            },
432            Self::FragmentedBody {
433                fragment_count,
434                guidance,
435            } => write!(
436                f,
437                "fragmented body ({fragment_count} fragments): {guidance}"
438            ),
439            Self::NonUtf8 {
440                selector,
441                path,
442                kind,
443                mime_hint,
444            } => write!(
445                f,
446                "non-UTF-8 text at {selector:?} ({path:?}, kind={kind}, mime={mime_hint:?}); use read_note_source_bytes for raw access"
447            ),
448            Self::IndexLockTimeout { path, timeout_ms } => {
449                write!(f, "index lock timeout on {path} after {timeout_ms}ms")
450            },
451            Self::UnsupportedStructure { reason } => {
452                write!(f, "unsupported structure: {reason}")
453            },
454            Self::WrongKind {
455                expected,
456                actual,
457                selector,
458                path,
459            } => {
460                write!(
461                    f,
462                    "wrong kind for {selector:?} ({path}): expected {expected:?}, observed {actual:?}"
463                )
464            },
465        }
466    }
467}
468
469impl std::error::Error for NbError {
470    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
471        // Only `Io { source: IoError }` carries a true source-chain
472        // link. Every other variant's `source` field (where
473        // present) is a diagnostic String or a non-Error type, so
474        // we explicitly return `None` for them.
475        match self {
476            Self::Io { source, .. } => Some(source),
477            _ => None,
478        }
479    }
480}
481
482/// Narrow refusal contract for the structural parser.
483///
484/// `parse` accepts every input that can be losslessly partitioned
485/// into a [`crate::parser::NoteDocument`], including the frozen
486/// W1 and E1-E11 noncanonical forms. The ONLY refusal cases at
487/// the parse layer are:
488///
489/// - Todo with no non-blank line at all: [`ParseErrorKind::MissingTitle`].
490/// - Bookmark with no non-blank line at all: [`ParseErrorKind::MissingTitle`].
491///
492/// Notes are permissive on empty source. Title-shape errors belong
493/// to a later strict validator (P5+), not to the parser.
494#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
495#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
496pub enum ParseErrorKind {
497    /// The first non-blank line was missing entirely (Todo/Bookmark
498    /// only; Notes are permissive).
499    MissingTitle,
500}
501
502/// Serializable snapshot of a [`std::io::Error`] chain.
503///
504/// `IoError` captures the **chain structure** (as a tree of
505/// snapshots) but does NOT preserve the original `std::io::Error`
506/// identity. The forward conversion [`From<std::io::Error>`] walks
507/// [`std::error::Error::source`] and recurses for each
508/// `std::io::Error` link; nested non-`io::Error` sources are
509/// stringified into [`IoErrorKind::Other`].
510///
511/// The reverse conversion [`From<IoError>`] for `std::io::Error`
512/// is **explicitly lossy** — see [`IoError`]'s `From` impl.
513#[derive(
514    Debug, Clone, Serialize, Deserialize, PartialEq, Eq, thiserror::Error,
515)]
516#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
517#[error("{kind:?}: {message}")]
518pub struct IoError {
519    pub kind: IoErrorKind,
520    pub message: String,
521    pub os_error: Option<i32>,
522    pub source: Option<Box<IoError>>,
523}
524
525/// Discriminator for the `std::io::ErrorKind` taxonomy, lifted into
526/// a serializable form. Marked `#[non_exhaustive]` so future
527/// versions can add new kinds without breaking downstream
528/// `match` arms that include a default branch.
529#[non_exhaustive]
530#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
531#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
532pub enum IoErrorKind {
533    NotFound,
534    PermissionDenied,
535    ConnectionRefused,
536    ConnectionReset,
537    ConnectionAborted,
538    NotConnected,
539    AddrInUse,
540    AddrNotAvailable,
541    BrokenPipe,
542    AlreadyExists,
543    WouldBlock,
544    InvalidInput,
545    InvalidData,
546    TimedOut,
547    WriteZero,
548    Interrupted,
549    UnexpectedEof,
550    OutOfMemory,
551    /// Catch-all for nested sources that are not themselves
552    /// `std::io::Error` (e.g., a third-party crate's error type
553    /// captured as `source`).
554    Other,
555}
556
557impl IoErrorKind {
558    /// Map a `std::io::ErrorKind` into the serializable variant.
559    pub fn from_std(kind: std::io::ErrorKind) -> Self {
560        match kind {
561            std::io::ErrorKind::NotFound => Self::NotFound,
562            std::io::ErrorKind::PermissionDenied => Self::PermissionDenied,
563            std::io::ErrorKind::ConnectionRefused => Self::ConnectionRefused,
564            std::io::ErrorKind::ConnectionReset => Self::ConnectionReset,
565            std::io::ErrorKind::ConnectionAborted => Self::ConnectionAborted,
566            std::io::ErrorKind::NotConnected => Self::NotConnected,
567            std::io::ErrorKind::AddrInUse => Self::AddrInUse,
568            std::io::ErrorKind::AddrNotAvailable => Self::AddrNotAvailable,
569            std::io::ErrorKind::BrokenPipe => Self::BrokenPipe,
570            std::io::ErrorKind::AlreadyExists => Self::AlreadyExists,
571            std::io::ErrorKind::WouldBlock => Self::WouldBlock,
572            std::io::ErrorKind::InvalidInput => Self::InvalidInput,
573            std::io::ErrorKind::InvalidData => Self::InvalidData,
574            std::io::ErrorKind::TimedOut => Self::TimedOut,
575            std::io::ErrorKind::WriteZero => Self::WriteZero,
576            std::io::ErrorKind::Interrupted => Self::Interrupted,
577            std::io::ErrorKind::UnexpectedEof => Self::UnexpectedEof,
578            std::io::ErrorKind::OutOfMemory => Self::OutOfMemory,
579            _ => Self::Other,
580        }
581    }
582}
583
584impl From<std::io::ErrorKind> for IoErrorKind {
585    fn from(kind: std::io::ErrorKind) -> Self {
586        Self::from_std(kind)
587    }
588}
589
590impl From<std::io::Error> for IoError {
591    /// Capture an `io::Error` chain as a tree of serializable
592    /// snapshots.
593    ///
594    /// The implementation recursively walks the
595    /// [`std::error::Error::source`] chain on BORROWED
596    /// `&dyn Error` references. This is critical: `std::io::Error`
597    /// is not `Clone`, so we cannot reconstruct an inner error
598    /// from a borrow without losing its `raw_os_error()` and its
599    /// own source chain. Walking the borrow preserves the chain
600    /// STRUCTURE exactly.
601    ///
602    /// At each level: if the source is itself an `io::Error`,
603    /// recurse on its borrow; otherwise, capture the source as
604    /// an [`IoErrorKind::Other`] snapshot (preserving the
605    /// `Display` text and walking its own source chain for
606    /// nested non-io links).
607    fn from(err: std::io::Error) -> Self {
608        snapshot_io_error(err)
609    }
610}
611
612/// Build an `IoError` snapshot from an `io::Error` value, then
613/// walk its source chain via the borrowed `dyn Error` to
614/// preserve chain structure exactly.
615fn snapshot_io_error(err: std::io::Error) -> IoError {
616    let kind = IoErrorKind::from_std(err.kind());
617    let os_error = err.raw_os_error();
618    let message = err.to_string();
619    let source = walk_source_chain(err.source());
620    IoError {
621        kind,
622        message,
623        os_error,
624        source,
625    }
626}
627
628/// Walk a `&(dyn Error + 'static)` chain, building a list of
629/// `IoError` snapshots. Each link appears EXACTLY ONCE in the
630/// chain (no duplication). Each `std::io::Error` link has its
631/// `raw_os_error()` preserved verbatim via the recursive walk
632/// on the borrowed `dyn Error`.
633///
634/// The chain is built by snapshotting the CURRENT node with its
635/// `source` field set to the recursive walk of the NEXT node.
636/// This avoids the A→B→B duplication that would arise from both
637/// recursing into the source AND iterating/appending the same
638/// source.
639fn walk_source_chain(
640    source: Option<&(dyn std::error::Error + 'static)>,
641) -> Option<Box<IoError>> {
642    let head = source?;
643    Some(Box::new(snapshot_link(head)))
644}
645
646/// Snapshot a single link in the source chain. The link's `source`
647/// field is set to the recursive snapshot of the next link.
648fn snapshot_link(current: &(dyn std::error::Error + 'static)) -> IoError {
649    if let Some(io_err) = current.downcast_ref::<std::io::Error>() {
650        IoError {
651            kind: IoErrorKind::from_std(io_err.kind()),
652            message: io_err.to_string(),
653            os_error: io_err.raw_os_error(),
654            // The recursive walk captures the io_err's own
655            // chain. Each io_err-level appears exactly once.
656            source: walk_source_chain(io_err.source()),
657        }
658    } else {
659        IoError {
660            kind: IoErrorKind::Other,
661            message: current.to_string(),
662            os_error: None,
663            // Recurse on the next link. Because `walk_source_chain`
664            // snapshots its OWN first link and recurses, the
665            // outer iteration does NOT see the next link — no
666            // duplication.
667            source: walk_source_chain(current.source()),
668        }
669    }
670}
671
672impl From<IoError> for std::io::Error {
673    /// Reverse conversion is **explicitly lossy**.
674    ///
675    /// The implementation prefers [`std::io::Error::from_raw_os_error`]
676    /// when [`IoError::os_error`] is `Some`, which LOSES the
677    /// snapshot message and any source chain. Otherwise, it
678    /// constructs a new `io::Error::new(kind, message)`, which
679    /// loses `raw_os_error()`.
680    ///
681    /// The forward conversion ([`From<std::io::Error>`] for
682    /// `IoError`) preserves chain STRUCTURE; this reverse
683    /// conversion does not — the snapshot tree is collapsed to a
684    /// single `std::io::Error`.
685    fn from(snapshot: IoError) -> Self {
686        if let Some(code) = snapshot.os_error {
687            std::io::Error::from_raw_os_error(code)
688        } else {
689            let kind = match snapshot.kind {
690                IoErrorKind::NotFound => std::io::ErrorKind::NotFound,
691                IoErrorKind::PermissionDenied => {
692                    std::io::ErrorKind::PermissionDenied
693                },
694                IoErrorKind::ConnectionRefused => {
695                    std::io::ErrorKind::ConnectionRefused
696                },
697                IoErrorKind::ConnectionReset => {
698                    std::io::ErrorKind::ConnectionReset
699                },
700                IoErrorKind::ConnectionAborted => {
701                    std::io::ErrorKind::ConnectionAborted
702                },
703                IoErrorKind::NotConnected => std::io::ErrorKind::NotConnected,
704                IoErrorKind::AddrInUse => std::io::ErrorKind::AddrInUse,
705                IoErrorKind::AddrNotAvailable => {
706                    std::io::ErrorKind::AddrNotAvailable
707                },
708                IoErrorKind::BrokenPipe => std::io::ErrorKind::BrokenPipe,
709                IoErrorKind::AlreadyExists => {
710                    std::io::ErrorKind::AlreadyExists
711                },
712                IoErrorKind::WouldBlock => std::io::ErrorKind::WouldBlock,
713                IoErrorKind::InvalidInput => std::io::ErrorKind::InvalidInput,
714                IoErrorKind::InvalidData => std::io::ErrorKind::InvalidData,
715                IoErrorKind::TimedOut => std::io::ErrorKind::TimedOut,
716                IoErrorKind::WriteZero => std::io::ErrorKind::WriteZero,
717                IoErrorKind::Interrupted => std::io::ErrorKind::Interrupted,
718                IoErrorKind::UnexpectedEof => {
719                    std::io::ErrorKind::UnexpectedEof
720                },
721                IoErrorKind::OutOfMemory => std::io::ErrorKind::OutOfMemory,
722                IoErrorKind::Other => std::io::ErrorKind::Other,
723            };
724            std::io::Error::new(kind, snapshot.message)
725        }
726    }
727}