quarto-error-reporting 0.4.0

Structured, source-aware diagnostics with pluggable rendering (ariadne or annotate-snippets) and a pluggable error-code catalog.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
//! JSON-transport shape for [`DiagnosticMessage`] (bd-b9kzg).
//!
//! Lifted from `wasm-quarto-hub-client` so two callers can share
//! one wire format:
//!
//!   * the WASM render bridge (returns `RenderResponse.warnings`
//!     to hub-client and the q2-preview SPA),
//!   * the `q2 preview` server's
//!     [`/api/preview/diagnostics`](https://quarto.org) endpoint
//!     (surfaces server-side `capture_driver` / `deps` /
//!     `re_execute` diagnostics to the SPA).
//!
//! Both sites emit the same JSON shape so the SPA can merge the
//! two feeds without a translation layer. The shape matches
//! Monaco's 1-based `IMarkerData`-style line/column convention.
//!
//! ## Public surface
//!
//! * [`JsonDiagnostic`] — top-level diagnostic.
//! * [`JsonDiagnosticDetail`] — nested detail (1..N per diagnostic).
//! * [`JsonPass1Failure`] — sibling-page parse failure (bd-rqba).
//! * [`diagnostic_to_json`] — `DiagnosticMessage → JsonDiagnostic`,
//!   resolving byte offsets to 1-based line/column via
//!   [`SourceContext`]. `rendered` carries ANSI color and OSC 8
//!   hyperlinks (terminal text).
//! * [`diagnostic_to_json_with_options`] — the same, rendering
//!   `rendered` with caller-chosen [`TextRenderOptions`]; pass
//!   [`TextRenderOptions::plain`] for text free of escape sequences.
//! * [`with_source_file`] — tag a `JsonDiagnostic` with the file
//!   it came from (used by sibling Pass-1 failures, see bd-rqba).

use schemars::JsonSchema;
use serde::Serialize;

use crate::diagnostic::{DetailKind, DiagnosticKind, DiagnosticMessage, TextRenderOptions};
use quarto_source_map::SourceContext;

/// One detail item in a [`JsonDiagnostic`].
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct JsonDiagnosticDetail {
    pub kind: String,
    pub content: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_line: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_column: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_line: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_column: Option<u32>,
}

/// A diagnostic message in transport-friendly JSON form.
///
/// Line and column numbers are 1-based to match Monaco.
///
/// ## `$schema` field (bd-iey8o)
///
/// Each instance carries a `$schema` field pointing at
/// [`JsonDiagnostic::SCHEMA_URL`] so that consumers reading the
/// diagnostic over the wire (CLI stderr, WASM bridge, preview API)
/// can discover the JSON Schema describing this shape without prior
/// knowledge. The field is a static-string field with a default
/// matching the const URL — the only place `JsonDiagnostic` is
/// constructed (`diagnostic_to_json`) sets it, and downstream
/// transforms like `with_source_file` preserve it.
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct JsonDiagnostic {
    /// JSON Schema URI describing this object's shape. Const value
    /// is [`JsonDiagnostic::SCHEMA_URL`]; included on the wire so
    /// consumers can self-discover the contract.
    #[serde(rename = "$schema")]
    #[schemars(rename = "$schema")]
    pub schema: &'static str,
    pub kind: String,
    pub title: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub code: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub problem: Option<String>,
    pub hints: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_line: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_column: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_line: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_column: Option<u32>,
    /// Source-file attribution for project-scoped diagnostics
    /// (bd-rqba). When the project pipeline emits a warning that
    /// originates in *another* file (e.g., a sidebar entry that
    /// references a sibling page), this field carries that
    /// sibling's path so the in-app overlay can label the warning
    /// with its source instead of free-floating text. `None` for
    /// page-local diagnostics whose location already pins them
    /// to the active page's source.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_file: Option<String>,
    pub details: Vec<JsonDiagnosticDetail>,
    /// Pre-rendered source-context snippet (bd-352bh), drawn by the
    /// crate's snippet renderer (ariadne or annotate-snippets).
    /// Populated when the diagnostic carries a `location` and the
    /// converting site has a [`SourceContext`] to draw from
    /// (i.e. always, in [`diagnostic_to_json`]).
    ///
    /// Two modes, chosen by the producer:
    ///
    /// * **Terminal** (the default, [`diagnostic_to_json`]): the same
    ///   text a terminal shows — ANSI color codes and OSC 8 hyperlinks;
    ///   strip them for non-terminal display (e.g. in a browser).
    /// * **Plain** ([`diagnostic_to_json_with_options`] with
    ///   `TextRenderOptions::plain()`): the same layout with no escape
    ///   sequences of any kind, readable as-is by machine consumers.
    ///
    /// Consumers can render this verbatim in a `<pre>` block for the
    /// rich source-context view, or ignore it and fall back to the
    /// structured fields for a compact summary. `None` for unlocated
    /// diagnostics (rare but possible for project-level errors with no
    /// span).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rendered: Option<String>,
    /// Structured provenance for diagnostics rooted in a *virtual* file
    /// (plan 7c): e.g. a notebook cell carries
    /// `{kind: notebook_cell, notebook_path, cell_index (1-based), cell_id,
    /// cell_type}`. The `start_line`/`start_column` fields are relative to
    /// the virtual file's own content, so a consumer needs the origin to
    /// address the position the author sees — (cell, line, column) within
    /// `origin.notebook_path`. `None` when the diagnostic's file is a real
    /// file (or unlocated), in which case the line/column fields already
    /// refer to it directly.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub origin: Option<quarto_source_map::FileOrigin>,
}

/// A Pass-1 failure (parse error or metadata error) in a project
/// file *other than* the active page (bd-rqba). Active-page
/// failures take the page-render error path; siblings flow through
/// here so the overlay can render them with source attribution
/// without forcing the lenient preview to abort.
///
/// Strict-vs-lenient policy lives at the consumer (Decision D1):
/// `quarto preview` / hub-client surfaces these as warnings and
/// keeps rendering; `quarto render` (CLI) treats any non-empty
/// `pass1_failures` as a non-zero exit (`bd-creo`).
///
/// `$schema` carries [`JsonPass1Failure::SCHEMA_URL`] so consumers
/// can distinguish this shape from a plain `JsonDiagnostic` line on
/// a mixed stderr stream and self-discover its contract.
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct JsonPass1Failure {
    /// JSON Schema URI describing this object's shape. Const value
    /// is [`JsonPass1Failure::SCHEMA_URL`].
    #[serde(rename = "$schema")]
    #[schemars(rename = "$schema")]
    pub schema: &'static str,
    pub source_file: String,
    pub error: String,
    pub diagnostics: Vec<JsonDiagnostic>,
}

impl JsonDiagnostic {
    /// JSON Schema URI for the `JsonDiagnostic` wire shape.
    /// Versioned under `/v1/` so future incompatible changes get a
    /// new URL rather than silently breaking old consumers.
    pub const SCHEMA_URL: &'static str = "https://quarto.org/schemas/v1/json-diagnostic.json";
}

impl JsonPass1Failure {
    /// JSON Schema URI for the `JsonPass1Failure` wire shape.
    pub const SCHEMA_URL: &'static str = "https://quarto.org/schemas/v1/json-pass1-failure.json";

    /// Build a `JsonPass1Failure` for a sibling Pass-1 failure
    /// (parse or metadata error) whose diagnostics have already been
    /// converted to [`JsonDiagnostic`] form. The `$schema` field is
    /// populated from the const.
    pub fn new(source_file: String, error: String, diagnostics: Vec<JsonDiagnostic>) -> Self {
        Self {
            schema: Self::SCHEMA_URL,
            source_file,
            error,
            diagnostics,
        }
    }
}

/// Convert a [`DiagnosticMessage`] to a [`JsonDiagnostic`], using
/// the [`SourceContext`] to map byte offsets to 1-based
/// line/column numbers.
///
/// `rendered` uses [`TextRenderOptions::default`]: ANSI color and OSC 8
/// hyperlinks, i.e. the text a terminal would show. Use
/// [`diagnostic_to_json_with_options`] to choose otherwise.
pub fn diagnostic_to_json(diag: &DiagnosticMessage, ctx: &SourceContext) -> JsonDiagnostic {
    diagnostic_to_json_with_options(diag, ctx, &TextRenderOptions::default())
}

/// Like [`diagnostic_to_json`], but renders the `rendered` field with the
/// given [`TextRenderOptions`]. Every other field is independent of
/// `options`.
///
/// Pass [`TextRenderOptions::plain`] for machine consumers (jq pipelines,
/// agents, CI logs): `rendered` then contains no escape sequences of any
/// kind.
///
/// # Example
///
/// ```
/// use quarto_error_reporting::{
///     DiagnosticMessageBuilder, TextRenderOptions, diagnostic_to_json_with_options,
/// };
/// use quarto_source_map::{SourceContext, SourceInfo};
///
/// let mut ctx = SourceContext::new();
/// let file = ctx.add_file("doc.qmd".into(), Some("title: [oops\n".into()));
/// let diag = DiagnosticMessageBuilder::error("Unclosed bracket")
///     .with_location(SourceInfo::original(file, 7, 8))
///     .build();
///
/// let json = diagnostic_to_json_with_options(&diag, &ctx, &TextRenderOptions::plain());
/// let rendered = json.rendered.expect("located diagnostics are pre-rendered");
/// assert!(rendered.contains("Unclosed bracket"));
/// assert!(!rendered.contains('\x1b'));
/// ```
pub fn diagnostic_to_json_with_options(
    diag: &DiagnosticMessage,
    ctx: &SourceContext,
    options: &TextRenderOptions,
) -> JsonDiagnostic {
    // Map the main location. The mapped start is kept for the origin
    // lookup below (the file the diagnostic is rooted in carries the
    // provenance).
    let mapped_start = diag
        .location
        .as_ref()
        .and_then(|loc| loc.map_offset(0, ctx));
    let (start_line, start_column, end_line, end_column) = if let Some(loc) = &diag.location {
        // Map start position (offset 0 relative to this SourceInfo)
        let start = mapped_start.clone();
        // Map end position (offset = length of span)
        let end = loc
            .map_offset(loc.length(), ctx)
            .or_else(|| {
                // Fallback: if end mapping fails, try length-1
                if loc.length() > 0 {
                    loc.map_offset(loc.length() - 1, ctx)
                } else {
                    None
                }
            })
            .or_else(|| start.clone());

        match (start, end) {
            (Some(s), Some(e)) => (
                Some((s.location.row + 1) as u32),    // 1-based line
                Some((s.location.column + 1) as u32), // 1-based column
                Some((e.location.row + 1) as u32),
                Some((e.location.column + 1) as u32),
            ),
            (Some(s), None) => (
                Some((s.location.row + 1) as u32),
                Some((s.location.column + 1) as u32),
                None,
                None,
            ),
            _ => (None, None, None, None),
        }
    } else {
        (None, None, None, None)
    };

    // Convert details
    let details: Vec<JsonDiagnosticDetail> = diag
        .details
        .iter()
        .map(|detail| {
            let (d_start_line, d_start_col, d_end_line, d_end_col) =
                if let Some(loc) = &detail.location {
                    let start = loc.map_offset(0, ctx);
                    let end = loc.map_offset(loc.length(), ctx).or_else(|| start.clone());

                    match (start, end) {
                        (Some(s), Some(e)) => (
                            Some((s.location.row + 1) as u32),
                            Some((s.location.column + 1) as u32),
                            Some((e.location.row + 1) as u32),
                            Some((e.location.column + 1) as u32),
                        ),
                        (Some(s), None) => (
                            Some((s.location.row + 1) as u32),
                            Some((s.location.column + 1) as u32),
                            None,
                            None,
                        ),
                        _ => (None, None, None, None),
                    }
                } else {
                    (None, None, None, None)
                };

            let kind_str = match detail.kind {
                DetailKind::Error => "error",
                DetailKind::Info => "info",
                DetailKind::Note | DetailKind::Faded => "note",
            };

            JsonDiagnosticDetail {
                kind: kind_str.to_string(),
                content: detail.content.as_str().to_string(),
                start_line: d_start_line,
                start_column: d_start_col,
                end_line: d_end_line,
                end_column: d_end_col,
            }
        })
        .collect();

    let kind_str = match diag.kind {
        DiagnosticKind::Error => "error",
        DiagnosticKind::Warning => "warning",
        DiagnosticKind::Info => "info",
        DiagnosticKind::Note => "note",
    };

    let hints: Vec<String> = diag.hints.iter().map(|h| h.as_str().to_string()).collect();

    // Structured origin for virtual-file diagnostics: the file the main
    // location's *start* resolves into carries the provenance. Details are
    // intentionally not origin-tagged — they have no file field at all and
    // their coordinates are already auxiliary.
    let origin = mapped_start
        .as_ref()
        .and_then(|s| ctx.get_file(s.file_id))
        .and_then(|f| f.metadata.origin.clone());

    // bd-352bh: pre-render the source-context snippet for diagnostics
    // that have a location, honoring the caller's `options` (color /
    // hyperlinks). `DiagnosticMessage::to_text_with_options` delegates
    // to the snippet renderer when both the diagnostic's location AND
    // the supplied `SourceContext` are present (see `diagnostic.rs`'s
    // `to_text_with_renderer`); for locationless diagnostics the
    // function would produce a tidyverse text block instead, which
    // duplicates what the structured fields already carry. So we
    // gate on `diag.location.is_some()` to avoid shipping that
    // redundant text on the wire.
    let rendered = if diag.location.is_some() {
        Some(diag.to_text_with_options(Some(ctx), options))
    } else {
        None
    };

    JsonDiagnostic {
        schema: JsonDiagnostic::SCHEMA_URL,
        kind: kind_str.to_string(),
        title: diag.title.clone(),
        code: diag.code.clone(),
        problem: diag.problem.as_ref().map(|p| p.as_str().to_string()),
        hints,
        start_line,
        start_column,
        end_line,
        end_column,
        // Default unattributed; callers that know the source file
        // (e.g., the Pass-1 failure path) tag it explicitly via
        // [`with_source_file`].
        source_file: None,
        details,
        rendered,
        origin,
    }
}

/// Tag a [`JsonDiagnostic`] with its source file (bd-rqba). Used
/// when surfacing project-scoped warnings that originate in a
/// file other than the active page.
pub fn with_source_file(mut diag: JsonDiagnostic, source_file: String) -> JsonDiagnostic {
    diag.source_file = Some(source_file);
    diag
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::DiagnosticMessage;

    #[test]
    fn warning_with_no_location_serializes_without_position_fields() {
        let diag = DiagnosticMessage::warning("Test warning").with_code("Q-1-1");
        let ctx = SourceContext::new();
        let json = diagnostic_to_json(&diag, &ctx);
        assert_eq!(json.kind, "warning");
        assert_eq!(json.title, "Test warning");
        assert_eq!(json.code.as_deref(), Some("Q-1-1"));
        assert!(json.start_line.is_none());
        assert!(json.start_column.is_none());
    }

    #[test]
    fn error_kind_serializes_as_lowercase() {
        let diag = DiagnosticMessage::error("Boom");
        let ctx = SourceContext::new();
        assert_eq!(diagnostic_to_json(&diag, &ctx).kind, "error");
    }

    #[test]
    fn info_and_note_kinds_serialize() {
        let ctx = SourceContext::new();
        assert_eq!(
            diagnostic_to_json(&DiagnosticMessage::info("i"), &ctx).kind,
            "info"
        );
        assert_eq!(
            diagnostic_to_json(&DiagnosticMessage::new(DiagnosticKind::Note, "n"), &ctx).kind,
            "note"
        );
    }

    #[test]
    fn with_source_file_tags_the_diagnostic() {
        let json = diagnostic_to_json(
            &DiagnosticMessage::warning("Bad sibling"),
            &SourceContext::new(),
        );
        let tagged = with_source_file(json, "other.qmd".to_string());
        assert_eq!(tagged.source_file.as_deref(), Some("other.qmd"));
    }

    /// bd-iey8o: every emitted `JsonDiagnostic` carries a `$schema`
    /// field with the const URL, and it survives `with_source_file`.
    #[test]
    fn diagnostic_carries_schema_url() {
        let json = diagnostic_to_json(
            &DiagnosticMessage::warning("with schema"),
            &SourceContext::new(),
        );
        assert_eq!(json.schema, JsonDiagnostic::SCHEMA_URL);

        let tagged = with_source_file(json, "a.qmd".to_string());
        assert_eq!(tagged.schema, JsonDiagnostic::SCHEMA_URL);
    }

    /// bd-iey8o: `JsonDiagnostic::SCHEMA_URL` is the value seen on
    /// the wire under the `$schema` key (note the `$` prefix from
    /// the serde rename).
    #[test]
    fn diagnostic_serializes_schema_field_as_dollar_schema() {
        let json = diagnostic_to_json(
            &DiagnosticMessage::warning("wire form"),
            &SourceContext::new(),
        );
        let s = serde_json::to_value(&json).unwrap();
        assert_eq!(
            s.get("$schema").and_then(|v| v.as_str()),
            Some(JsonDiagnostic::SCHEMA_URL)
        );
        assert!(
            s.get("schema").is_none(),
            "the serde rename should suppress the un-renamed `schema` key"
        );
    }

    /// bd-iey8o: `JsonPass1Failure::new` populates `$schema` from
    /// the const, and the wire form uses the `$` prefix.
    #[test]
    fn pass1_failure_carries_schema_url() {
        let f = JsonPass1Failure::new("other.qmd".to_string(), "boom".to_string(), vec![]);
        assert_eq!(f.schema, JsonPass1Failure::SCHEMA_URL);
        let s = serde_json::to_value(&f).unwrap();
        assert_eq!(
            s.get("$schema").and_then(|v| v.as_str()),
            Some(JsonPass1Failure::SCHEMA_URL)
        );
    }

    // ─── bd-352bh: ariadne `rendered` field ──────────────────────

    /// Build a `(DiagnosticMessage, SourceContext)` pair where the
    /// diagnostic has a location pointing into a registered file
    /// — enough for ariadne to draw a source-context box.
    fn synth_located_diag() -> (DiagnosticMessage, SourceContext) {
        use quarto_source_map::{
            SourceInfo,
            types::{Location, Range},
        };
        let mut ctx = SourceContext::new();
        let file_id = ctx.add_file(
            "fixture.qmd".to_string(),
            Some("# Title\n\nA paragraph that has _unclosed emphasis.\n".to_string()),
        );
        // Point at the underscore on row 2. Exact span isn't
        // important for the rendered-vs-not assertions.
        let info = SourceInfo::from_range(
            file_id,
            Range {
                start: Location {
                    offset: 28,
                    row: 2,
                    column: 19,
                },
                end: Location {
                    offset: 29,
                    row: 2,
                    column: 20,
                },
            },
        );
        let mut diag =
            DiagnosticMessage::warning("Unclosed Underscore Emphasis").with_code("Q-2-5");
        diag.location = Some(info);
        (diag, ctx)
    }

    #[test]
    fn rendered_is_some_when_location_present() {
        let (diag, ctx) = synth_located_diag();
        let json = diagnostic_to_json(&diag, &ctx);
        let rendered = json
            .rendered
            .as_deref()
            .expect("rendered should be populated when the diagnostic has a location");
        // Ariadne's source-context box always opens with the
        // U+256D "BOX DRAWINGS LIGHT ARC DOWN AND RIGHT" character.
        // Pinning that single byte sequence is robust to font /
        // padding tweaks while still proving "ariadne ran."
        assert!(
            rendered.contains('\u{256D}'),
            "rendered text should contain ariadne's box-drawing chars; got: {rendered:?}",
        );
        // The diagnostic's title and code should also appear.
        assert!(rendered.contains("Unclosed Underscore Emphasis"));
        assert!(rendered.contains("Q-2-5"));
    }

    #[test]
    fn rendered_is_none_when_location_absent() {
        let diag = DiagnosticMessage::warning("Floating warning").with_code("Q-9-9");
        let ctx = SourceContext::new();
        let json = diagnostic_to_json(&diag, &ctx);
        assert!(
            json.rendered.is_none(),
            "rendered should be None for a diagnostic without a location; got: {:?}",
            json.rendered,
        );
    }

    #[test]
    fn rendered_skipped_in_json_when_none() {
        // The serde attribute `skip_serializing_if = "Option::is_none"`
        // keeps the wire shape clean for diagnostics that don't have
        // a location — the field shouldn't appear in the JSON at all.
        let diag = DiagnosticMessage::warning("Floating warning");
        let ctx = SourceContext::new();
        let json = diagnostic_to_json(&diag, &ctx);
        let serialized = serde_json::to_string(&json).unwrap();
        assert!(
            !serialized.contains("\"rendered\""),
            "JSON should omit `rendered` when None; got: {serialized}",
        );
    }

    // ─── plan 7c: structured `origin` for virtual files ──────────

    /// A located diagnostic rooted in a notebook-cell virtual file
    /// carrying `FileMetadata::origin`.
    fn cell_located_diag() -> (DiagnosticMessage, SourceContext) {
        use quarto_source_map::{
            FileOrigin, SourceInfo,
            types::{Location, Range},
        };
        let mut ctx = SourceContext::new();
        let file_id = ctx.add_file(
            "notebook.ipynb[cell 3, code]".to_string(),
            Some("print('boom')\n".to_string()),
        );
        ctx.get_file_mut(file_id).unwrap().metadata.origin = Some(FileOrigin::NotebookCell {
            notebook_path: "notebook.ipynb".to_string(),
            cell_index: 3,
            cell_id: Some("cell-xyz".to_string()),
            cell_type: "code".to_string(),
        });
        let info = SourceInfo::from_range(
            file_id,
            Range {
                start: Location {
                    offset: 7,
                    row: 0,
                    column: 7,
                },
                end: Location {
                    offset: 11,
                    row: 0,
                    column: 11,
                },
            },
        );
        let mut diag = DiagnosticMessage::error("NameError").with_code("Q-IPYNB-1");
        diag.location = Some(info);
        (diag, ctx)
    }

    #[test]
    fn origin_is_some_for_cell_rooted_diagnostics() {
        let (diag, ctx) = cell_located_diag();
        let json = diagnostic_to_json(&diag, &ctx);
        assert_eq!(
            json.origin,
            Some(quarto_source_map::FileOrigin::NotebookCell {
                notebook_path: "notebook.ipynb".to_string(),
                cell_index: 3,
                cell_id: Some("cell-xyz".to_string()),
                cell_type: "code".to_string(),
            })
        );
    }

    #[test]
    fn origin_serializes_with_all_fields() {
        let (diag, ctx) = cell_located_diag();
        let json = diagnostic_to_json(&diag, &ctx);
        let v = serde_json::to_value(&json).unwrap();
        let origin = v.get("origin").expect("origin must serialize");
        assert_eq!(origin["kind"], "notebook_cell");
        assert_eq!(origin["notebook_path"], "notebook.ipynb");
        assert_eq!(origin["cell_index"], 3);
        assert_eq!(origin["cell_id"], "cell-xyz");
        assert_eq!(origin["cell_type"], "code");
    }

    #[test]
    fn origin_is_absent_for_plain_file_diagnostics() {
        let (diag, ctx) = synth_located_diag();
        let json = diagnostic_to_json(&diag, &ctx);
        assert!(json.origin.is_none());
        let serialized = serde_json::to_string(&json).unwrap();
        assert!(
            !serialized.contains("\"origin\""),
            "None origin must be omitted from the wire shape: {serialized}",
        );
    }

    // ==================== Plain `rendered` (qe-hal9cc7b) ====================

    /// A diagnostic in a real on-disk file, which the ariadne renderer
    /// hyperlinks under default options. The `TempDir` keeps it alive.
    fn real_file_diag() -> (DiagnosticMessage, SourceContext, tempfile::TempDir) {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("real.qmd");
        std::fs::write(&path, "title: [oops\n").unwrap();
        let mut ctx = SourceContext::new();
        let file_id = ctx.add_file(path.display().to_string(), None);
        let mut diag = DiagnosticMessage::error("Unclosed bracket").with_code("Q-9-9");
        diag.location = Some(quarto_source_map::SourceInfo::original(file_id, 7, 8));
        (diag, ctx, dir)
    }

    #[test]
    fn plain_rendered_contains_no_escape_bytes() {
        let (real_diag, real_ctx, _dir) = real_file_diag();
        let fixtures = [
            ("in_memory", synth_located_diag()),
            ("notebook_cell", cell_located_diag()),
            ("real_file", (real_diag, real_ctx)),
        ];
        for (name, (diag, ctx)) in &fixtures {
            let plain = diagnostic_to_json_with_options(diag, ctx, &TextRenderOptions::plain());
            // Check the raw `String` for the escape byte: in serialized
            // JSON an escape appears as the six characters `\u001b`, which
            // a byte search would not find.
            let rendered = plain.rendered.as_deref().expect("located → rendered");
            assert!(
                !rendered.contains('\u{1b}'),
                "{name}: plain `rendered` must contain no escape byte; got {rendered:?}"
            );
            assert!(rendered.contains(&diag.title), "{name}: {rendered:?}");
            // And the wire form carries no escaped escape either.
            let wire = serde_json::to_string(&plain).unwrap();
            assert!(
                !wire.contains("\\u001b"),
                "{name}: plain JSON must carry no escaped ESC; got {wire}"
            );

            // The default still renders for a terminal (when a snippet
            // renderer is compiled in; without one, `rendered` is the
            // escape-free structured text either way).
            #[cfg(any(feature = "ariadne", feature = "annotate-snippets"))]
            {
                let default = diagnostic_to_json(diag, ctx);
                assert!(
                    default.rendered.as_deref().unwrap().contains("\u{1b}["),
                    "{name}: default `rendered` keeps ANSI color"
                );
            }
        }
    }

    /// The ariadne default hyperlinks a real file; plain must not.
    #[cfg(feature = "ariadne")]
    #[test]
    fn plain_rendered_drops_hyperlinks_that_default_emits() {
        let (diag, ctx, _dir) = real_file_diag();
        let default = diagnostic_to_json(&diag, &ctx);
        assert!(
            default.rendered.as_deref().unwrap().contains("\u{1b}]8;"),
            "default `rendered` keeps OSC 8 for a real file"
        );
        let plain = diagnostic_to_json_with_options(&diag, &ctx, &TextRenderOptions::plain());
        assert!(!plain.rendered.as_deref().unwrap().contains('\u{1b}'));
    }

    /// Render options affect `rendered` only; every other field is
    /// identical between the default and plain conversions.
    #[test]
    fn render_options_affect_only_rendered() {
        let (real_diag, real_ctx, _dir) = real_file_diag();
        let fixtures = [
            synth_located_diag(),
            cell_located_diag(),
            (real_diag, real_ctx),
        ];
        for (diag, ctx) in &fixtures {
            let without_rendered = |json: JsonDiagnostic| {
                let mut value = serde_json::to_value(json).unwrap();
                value.as_object_mut().unwrap().remove("rendered");
                value
            };
            assert_eq!(
                without_rendered(diagnostic_to_json(diag, ctx)),
                without_rendered(diagnostic_to_json_with_options(
                    diag,
                    ctx,
                    &TextRenderOptions::plain()
                )),
            );
        }
    }

    /// `diagnostic_to_json` is exactly the default-options conversion.
    #[test]
    fn diagnostic_to_json_uses_default_options() {
        let (diag, ctx, _dir) = real_file_diag();
        assert_eq!(
            serde_json::to_value(diagnostic_to_json(&diag, &ctx)).unwrap(),
            serde_json::to_value(diagnostic_to_json_with_options(
                &diag,
                &ctx,
                &TextRenderOptions::default()
            ))
            .unwrap(),
        );
    }
}