marque 0.2.0

Classification marking linter, formatter, and fixer
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
//! Diagnostic rendering for the `marque` CLI.
//!
//! Two formats are supported:
//! - **human**: rustc-style diagnostic — a header line with location and
//!   rule identifier, followed by a source snippet with a `|` gutter, the
//!   offending line(s), and a `^^^` caret line pointing at the span.
//!   ANSI-colored by default.
//! - **json**: NDJSON conforming to `contracts/diagnostic.json`.
//!
//! ANSI is suppressed when any of these is true:
//! - `--no-color` was passed on the command line
//! - `NO_COLOR` env var is set to a non-empty value
//! - `TERM=dumb`
//! - stdout is not a terminal
//!
//! The contract for stream usage:
//! - `check` writes diagnostics to **stdout**.
//! - Operator narration goes to **stderr** (suppressible via `-q`).
//!
//! # Human output shape
//!
//! ```text
//! banner.txt:1:17 error[E001] banner uses abbreviated dissem control "NF"; use "NOFORN"
//!   --> banner.txt:1:17-19
//!    |
//!  1 | TOP SECRET//SI//NF
//!    |                 ^^ replace with "NOFORN"
//!    |
//!    = citation: CAPCO-ISM-v2022-DEC-§3.2
//! ```
//!
//! The line-number gutter width auto-sizes to the largest line number in
//! the diagnostic. For multi-line spans, the caret line extends to the
//! end of the first line of the span; additional lines are not rendered
//! (CAPCO markings are always single-line so this is a corner-case).

use marque_engine::LintResult;
use marque_rules::{AppliedFix, Diagnostic};
use serde::Serialize;
use std::path::Path;

/// Output format selector.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Format {
    Human,
    Json,
}

/// Effective color mode after honoring `--no-color`, `NO_COLOR`, `TERM=dumb`,
/// and TTY detection.
pub fn use_color(no_color_flag: bool) -> bool {
    if no_color_flag {
        return false;
    }
    if std::env::var_os("NO_COLOR").is_some_and(|v| !v.is_empty()) {
        return false;
    }
    if std::env::var("TERM").as_deref() == Ok("dumb") {
        return false;
    }
    use is_terminal::IsTerminal;
    std::io::stdout().is_terminal()
}

/// Pick a default format when the user did not pass `--format`.
/// JSON for non-TTY (pipelines), human for TTY.
pub fn default_format() -> Format {
    use is_terminal::IsTerminal;
    if std::io::stdout().is_terminal() {
        Format::Human
    } else {
        Format::Json
    }
}

/// Render a single diagnostic in rustc-style human format. Caller writes to
/// stdout. Produces 6+ lines per diagnostic: header, location arrow, source
/// snippet with line number and caret, citation footer.
pub fn render_human(
    out: &mut dyn std::io::Write,
    path_label: &str,
    source: &[u8],
    diag: &Diagnostic,
    color: bool,
) -> std::io::Result<()> {
    let (line, col_start) = byte_to_line_col(source, diag.span.start);
    let (end_line, col_end_raw) = byte_to_line_col(source, diag.span.end);
    // For multi-line spans, clamp the caret to the end of the first line.
    // CAPCO markings are single-line so this is a defensive clamp.
    let col_end = if end_line == line {
        col_end_raw
    } else {
        // end of source line: look up the line bytes and use its length + 1
        extract_line(source, line)
            .map(|l| l.len() + 1)
            .unwrap_or(col_start + 1)
    };

    let level = level_str(diag.severity);
    let level_styled = paint(color, AnsiStyle::BoldRed, level);
    let rule_styled = paint(color, AnsiStyle::Bold, &format!("[{}]", diag.rule));

    // ---- Header line ----
    // banner.txt:1:17 error[E001] banner uses abbreviated dissem control "NF"; use "NOFORN"
    writeln!(
        out,
        "{path_label}:{line}:{col_start} {level_styled}{rule_styled} {}",
        diag.message
    )?;

    // ---- Source snippet ----
    //   --> path:line:col_start-col_end
    //    |
    //  N | <source line>
    //    |   ^^^^ hint
    //    |
    //    = citation: ...
    let line_num_str = line.to_string();
    let gutter_width = line_num_str.len();
    let gutter = " ".repeat(gutter_width);
    let arrow = paint(color, AnsiStyle::BoldBlue, "-->");
    let pipe = paint(color, AnsiStyle::BoldBlue, "|");
    let eq = paint(color, AnsiStyle::BoldBlue, "=");

    writeln!(
        out,
        "{gutter} {arrow} {path_label}:{line}:{col_start}-{col_end}"
    )?;

    if let Some(line_bytes) = extract_line(source, line) {
        if let Ok(line_text) = std::str::from_utf8(line_bytes) {
            // Blank gutter line above the source snippet
            writeln!(out, "{gutter} {pipe}")?;
            // Source line with line number gutter
            let line_num_styled = paint(color, AnsiStyle::BoldBlue, &line_num_str);
            writeln!(out, "{line_num_styled} {pipe} {line_text}")?;
            // Caret line: spaces to col_start-1, then carets spanning col_start..col_end
            let caret_pad_width = col_start.saturating_sub(1);
            let caret_width = col_end.saturating_sub(col_start).max(1);
            let caret_pad = " ".repeat(caret_pad_width);
            let carets = "^".repeat(caret_width);
            let carets_styled = paint(color, AnsiStyle::BoldRed, &carets);
            let hint = diag
                .fix
                .as_ref()
                .map(|f| {
                    format!(
                        " replace with {:?} (confidence {:.0}%)",
                        f.replacement.as_ref(),
                        f.confidence * 100.0
                    )
                })
                .unwrap_or_default();
            writeln!(out, "{gutter} {pipe} {caret_pad}{carets_styled}{hint}")?;
            // Blank gutter line below the caret
            writeln!(out, "{gutter} {pipe}")?;
        }
    }

    // Citation footer
    writeln!(out, "{gutter} {eq} citation: {}", diag.citation)?;

    Ok(())
}

/// Extract the bytes of the 1-indexed `line_num` from `source`, excluding
/// the trailing `\n` (and `\r` for CRLF). Returns `None` if the source
/// doesn't have that many lines.
fn extract_line(source: &[u8], line_num: usize) -> Option<&[u8]> {
    let mut current_line = 1;
    let mut line_start = 0;
    for (i, &b) in source.iter().enumerate() {
        if b == b'\n' {
            if current_line == line_num {
                // Strip trailing `\r` for CRLF line endings.
                let end = if i > line_start && source[i - 1] == b'\r' {
                    i - 1
                } else {
                    i
                };
                return Some(&source[line_start..end]);
            }
            current_line += 1;
            line_start = i + 1;
        }
    }
    // EOF without trailing `\n` — the last line is everything from
    // `line_start` to the end.
    if current_line == line_num {
        return Some(&source[line_start..]);
    }
    None
}

fn level_str(severity: marque_rules::Severity) -> &'static str {
    match severity {
        marque_rules::Severity::Error => "error",
        marque_rules::Severity::Warn => "warning",
        marque_rules::Severity::Fix => "fix",
        marque_rules::Severity::Off => "off", // unreachable in practice
    }
}

/// ANSI style selectors for the human renderer. Keeping the set small
/// avoids a dependency on `owo-colors` or similar — the escape codes are
/// inlined in `paint`.
#[derive(Debug, Clone, Copy)]
enum AnsiStyle {
    BoldRed,
    BoldBlue,
    Bold,
}

fn paint(color: bool, style: AnsiStyle, text: &str) -> String {
    if !color {
        return text.to_owned();
    }
    let (prefix, suffix) = match style {
        AnsiStyle::BoldRed => ("\x1b[31;1m", "\x1b[0m"),
        AnsiStyle::BoldBlue => ("\x1b[34;1m", "\x1b[0m"),
        AnsiStyle::Bold => ("\x1b[1m", "\x1b[0m"),
    };
    format!("{prefix}{text}{suffix}")
}

/// JSON projection of a Diagnostic conforming to `contracts/diagnostic.json`.
/// Marked `additionalProperties: false` in the schema, so this struct must
/// not include extra fields.
#[derive(Debug, Serialize)]
pub struct DiagnosticJson<'a> {
    pub rule: &'a str,
    pub severity: &'a str,
    pub span: SpanJson,
    pub message: &'a str,
    pub citation: &'a str,
    pub fix: Option<FixJson<'a>>,
}

#[derive(Debug, Serialize)]
pub struct SpanJson {
    pub start: usize,
    pub end: usize,
}

#[derive(Debug, Serialize)]
pub struct FixJson<'a> {
    pub source: &'static str,
    pub replacement: &'a str,
    pub confidence: f32,
    pub migration_ref: Option<&'a str>,
}

pub fn diagnostic_to_json(d: &Diagnostic) -> DiagnosticJson<'_> {
    DiagnosticJson {
        rule: d.rule.as_str(),
        severity: d.severity.as_str(),
        span: SpanJson {
            start: d.span.start,
            end: d.span.end,
        },
        message: d.message.as_ref(),
        citation: d.citation,
        fix: d.fix.as_ref().map(|f| FixJson {
            source: match f.source {
                marque_rules::FixSource::BuiltinRule => "BuiltinRule",
                marque_rules::FixSource::CorrectionsMap => "CorrectionsMap",
                marque_rules::FixSource::MigrationTable => "MigrationTable",
            },
            replacement: f.replacement.as_ref(),
            confidence: f.confidence,
            migration_ref: f.migration_ref,
        }),
    }
}

/// Write the full lint result as NDJSON (one record per line) to stdout.
pub fn render_ndjson(out: &mut dyn std::io::Write, result: &LintResult) -> std::io::Result<()> {
    for d in &result.diagnostics {
        let json = serde_json::to_string(&diagnostic_to_json(d)).map_err(std::io::Error::other)?;
        out.write_all(json.as_bytes())?;
        out.write_all(b"\n")?;
    }
    Ok(())
}

/// Write the full lint result in human format.
pub fn render_human_result(
    out: &mut dyn std::io::Write,
    path_label: &str,
    source: &[u8],
    result: &LintResult,
    color: bool,
) -> std::io::Result<()> {
    for d in &result.diagnostics {
        render_human(out, path_label, source, d, color)?;
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Audit record NDJSON — contracts/audit-record.json (schema "marque-mvp-1")
// ---------------------------------------------------------------------------

/// JSON projection of an `AppliedFix` conforming to `contracts/audit-record.json`.
///
/// Every field from the schema is present. `schema` is always `"marque-mvp-1"`.
/// Emitted to stderr as NDJSON (one record per line). FR-005a requires atomic
/// emission: serialize to buffer, then single `write_all`.
#[derive(Debug, Serialize)]
pub struct AuditRecordJson {
    pub schema: &'static str,
    pub rule: String,
    pub source: &'static str,
    pub span: SpanJson,
    pub original: String,
    pub replacement: String,
    pub confidence: f32,
    pub migration_ref: Option<String>,
    pub timestamp: String,
    pub classifier_id: Option<String>,
    pub dry_run: bool,
    pub input: Option<String>,
}

const AUDIT_SCHEMA_VERSION: &str = "marque-mvp-1";

fn fix_source_str(source: marque_rules::FixSource) -> &'static str {
    match source {
        marque_rules::FixSource::BuiltinRule => "BuiltinRule",
        marque_rules::FixSource::CorrectionsMap => "CorrectionsMap",
        marque_rules::FixSource::MigrationTable => "MigrationTable",
    }
}

/// Convert an `AppliedFix` to the JSON audit record shape.
pub fn applied_fix_to_audit_json(fix: &AppliedFix) -> AuditRecordJson {
    AuditRecordJson {
        schema: AUDIT_SCHEMA_VERSION,
        rule: fix.proposal.rule.as_str().to_owned(),
        source: fix_source_str(fix.proposal.source),
        span: SpanJson {
            start: fix.proposal.span.start,
            end: fix.proposal.span.end,
        },
        original: fix.proposal.original.to_string(),
        replacement: fix.proposal.replacement.to_string(),
        confidence: fix.proposal.confidence,
        migration_ref: fix.proposal.migration_ref.map(|s| s.to_owned()),
        timestamp: humantime::format_rfc3339(fix.timestamp).to_string(),
        classifier_id: fix.classifier_id.as_ref().map(|s| s.to_string()),
        dry_run: fix.dry_run,
        input: fix.input.as_ref().map(|s| s.to_string()),
    }
}

/// Emit a single audit record as NDJSON to `stderr`.
///
/// FR-005a: each record is serialized to an in-memory buffer and flushed
/// with a single `write_all` ending in `\n`. A partially-serialized record
/// is never flushed. On serialization failure, emits an error frame and
/// returns `Err`.
pub fn render_audit_record(
    stderr: &mut dyn std::io::Write,
    fix: &AppliedFix,
) -> std::io::Result<()> {
    let json = applied_fix_to_audit_json(fix);
    match serde_json::to_vec(&json) {
        Ok(mut buf) => {
            buf.push(b'\n');
            stderr.write_all(&buf)
        }
        Err(e) => {
            render_audit_error_frame(stderr, fix.proposal.rule.as_str(), &e.to_string())?;
            Err(std::io::Error::other(format!(
                "audit record serialization failed for rule {}: {e}",
                fix.proposal.rule
            )))
        }
    }
}

/// Emit an error frame on the audit stream when serialization fails.
///
/// FR-005a fallback: every line on the audit stream must be a complete JSON
/// object. The error frame is the last resort when the normal serializer has
/// already failed, so it JSON-escapes its inputs via `serde_json::to_string`
/// to guarantee well-formed output even if the error message contains quotes
/// or backslashes.
///
/// Shape: `{"schema":"marque-mvp-1","error":"<code>","rule":"<id>"}`
pub fn render_audit_error_frame(
    stderr: &mut dyn std::io::Write,
    rule_id: &str,
    error_code: &str,
) -> std::io::Result<()> {
    // JSON-escape both values so special characters in error messages
    // cannot produce malformed JSON on the audit stream.
    let escaped_error =
        serde_json::to_string(error_code).unwrap_or_else(|_| "\"serialization_error\"".to_owned());
    let escaped_rule = serde_json::to_string(rule_id).unwrap_or_else(|_| "\"unknown\"".to_owned());
    let frame = format!(
        "{{\"schema\":\"{AUDIT_SCHEMA_VERSION}\",\"error\":{escaped_error},\"rule\":{escaped_rule}}}\n"
    );
    stderr.write_all(frame.as_bytes())
}

/// Convert a byte offset into 1-based (line, column).
fn byte_to_line_col(source: &[u8], offset: usize) -> (usize, usize) {
    let mut line = 1usize;
    let mut col = 1usize;
    for &b in &source[..offset.min(source.len())] {
        if b == b'\n' {
            line += 1;
            col = 1;
        } else {
            col += 1;
        }
    }
    (line, col)
}

/// Path-label helper. Uses `-` for stdin sentinels.
pub fn label_for(path: Option<&Path>) -> String {
    match path {
        Some(p) => p.display().to_string(),
        None => "-".to_owned(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use marque_ism::Span;
    use marque_rules::{FixProposal, FixSource, RuleId, Severity};

    fn make_diagnostic(
        rule: &'static str,
        span: Span,
        message: &str,
        fix: Option<FixProposal>,
    ) -> Diagnostic {
        Diagnostic::new(
            RuleId::new(rule),
            Severity::Fix,
            span,
            message,
            "CAPCO-ISM-v2022-DEC-§3.2",
            fix,
        )
    }

    #[test]
    fn extract_line_returns_first_line() {
        let src = b"first\nsecond\nthird";
        assert_eq!(extract_line(src, 1), Some(&b"first"[..]));
    }

    #[test]
    fn extract_line_returns_middle_line() {
        let src = b"first\nsecond\nthird";
        assert_eq!(extract_line(src, 2), Some(&b"second"[..]));
    }

    #[test]
    fn extract_line_returns_last_line_without_trailing_newline() {
        let src = b"first\nsecond";
        assert_eq!(extract_line(src, 2), Some(&b"second"[..]));
    }

    #[test]
    fn extract_line_strips_crlf() {
        let src = b"first\r\nsecond\r\n";
        assert_eq!(extract_line(src, 1), Some(&b"first"[..]));
        assert_eq!(extract_line(src, 2), Some(&b"second"[..]));
    }

    #[test]
    fn extract_line_returns_none_when_out_of_range() {
        let src = b"first\nsecond";
        assert_eq!(extract_line(src, 5), None);
    }

    #[test]
    fn render_human_produces_rustc_style_shape_with_caret() {
        // Single-line source with a span pointing at "NF" in banner form.
        let src = b"TOP SECRET//SI//NF\n";
        let span = Span::new(16, 18);
        let fix = FixProposal::new(
            RuleId::new("E001"),
            FixSource::BuiltinRule,
            span,
            "NF".to_owned(),
            "NOFORN".to_owned(),
            1.0,
            Some("CAPCO-2023-§3.2"),
        );
        let diag = make_diagnostic(
            "E001",
            span,
            "banner uses abbreviated dissem control \"NF\"; use \"NOFORN\"",
            Some(fix),
        );

        let mut out = Vec::new();
        render_human(&mut out, "banner.txt", src, &diag, false).unwrap();
        let rendered = String::from_utf8(out).unwrap();

        // Header line: path:line:col with level + rule + message
        assert!(rendered.contains("banner.txt:1:17 fix[E001]"));
        assert!(rendered.contains("banner uses abbreviated dissem control"));
        // Location arrow
        assert!(rendered.contains("--> banner.txt:1:17-19"));
        // Source snippet with line number gutter
        assert!(rendered.contains("1 | TOP SECRET//SI//NF"));
        // Caret line: 16 spaces of padding + "^^" carets
        // (span starts at col 17, so 16 chars of padding from col 1)
        assert!(
            rendered.contains("                ^^"),
            "expected caret at col 17; got:\n{rendered}"
        );
        // Hint includes the replacement
        assert!(rendered.contains("replace with \"NOFORN\""));
        assert!(rendered.contains("(confidence 100%)"));
        // Citation footer
        assert!(rendered.contains("= citation: CAPCO-ISM-v2022-DEC-§3.2"));
    }

    #[test]
    fn render_human_without_color_has_no_ansi_escapes() {
        let src = b"TOP SECRET//SI//NF\n";
        let span = Span::new(16, 18);
        let diag = make_diagnostic("E001", span, "test", None);

        let mut out = Vec::new();
        render_human(&mut out, "x.txt", src, &diag, false).unwrap();
        let rendered = String::from_utf8(out).unwrap();
        assert!(
            !rendered.contains('\x1b'),
            "color=false must not emit ANSI escapes, got:\n{rendered:?}"
        );
    }

    #[test]
    fn render_human_with_color_emits_ansi_escapes() {
        let src = b"TOP SECRET//SI//NF\n";
        let span = Span::new(16, 18);
        let diag = make_diagnostic("E001", span, "test", None);

        let mut out = Vec::new();
        render_human(&mut out, "x.txt", src, &diag, true).unwrap();
        let rendered = String::from_utf8(out).unwrap();
        assert!(
            rendered.contains('\x1b'),
            "color=true must emit ANSI escapes, got:\n{rendered:?}"
        );
    }

    #[test]
    fn render_human_diagnostic_without_fix_omits_hint() {
        // E008-style: no fix proposal, caret only
        let src = b"SECRET//XYZZY//NOFORN\n";
        let span = Span::new(8, 13);
        let diag = Diagnostic::new(
            RuleId::new("E008"),
            Severity::Error,
            span,
            "unrecognized token",
            "CAPCO-ISM-v2022-DEC-§3.1",
            None,
        );

        let mut out = Vec::new();
        render_human(&mut out, "x.txt", src, &diag, false).unwrap();
        let rendered = String::from_utf8(out).unwrap();
        assert!(rendered.contains("^^^^^"));
        assert!(!rendered.contains("replace with"));
    }

    // --- Audit record tests ---

    #[test]
    fn render_audit_error_frame_produces_valid_json() {
        let mut buf = Vec::new();
        render_audit_error_frame(&mut buf, "E001", "some error").unwrap();
        let s = String::from_utf8(buf).unwrap();
        assert!(s.ends_with('\n'), "must end with newline");
        let v: serde_json::Value = serde_json::from_str(s.trim()).unwrap();
        assert_eq!(v["schema"], "marque-mvp-1");
        assert_eq!(v["error"], "some error");
        assert_eq!(v["rule"], "E001");
    }

    #[test]
    fn render_audit_error_frame_escapes_special_characters() {
        let mut buf = Vec::new();
        // Error message with quotes and backslashes that would break raw interpolation.
        render_audit_error_frame(&mut buf, "E001", "key \"foo\\bar\"").unwrap();
        let s = String::from_utf8(buf).unwrap();
        // Must parse as valid JSON despite special characters in the error.
        let v: serde_json::Value =
            serde_json::from_str(s.trim()).expect("error frame must be valid JSON");
        assert_eq!(v["error"], "key \"foo\\bar\"");
        assert_eq!(v["schema"], "marque-mvp-1");
    }

    #[test]
    fn render_audit_record_produces_valid_ndjson() {
        use marque_rules::AppliedFix;
        use std::sync::Arc;
        use std::time::{Duration, UNIX_EPOCH};

        let fix = FixProposal::new(
            RuleId::new("E001"),
            FixSource::BuiltinRule,
            Span::new(8, 10),
            "NF",
            "NOFORN",
            1.0,
            Some("CAPCO-2023-§3.2"),
        );
        // Intentional test-only exception to the engine-only __engine_promote
        // contract: the renderer test needs a concrete AppliedFix to verify
        // NDJSON serialization without spinning up a full Engine.
        let applied = AppliedFix::__engine_promote(
            fix,
            UNIX_EPOCH + Duration::from_secs(1_700_000_000),
            Some(Arc::from("classifier-42")),
            false,
            Some(Arc::from("test.txt")),
        );

        let mut buf = Vec::new();
        render_audit_record(&mut buf, &applied).unwrap();
        let s = String::from_utf8(buf).unwrap();
        assert!(s.ends_with('\n'));

        let v: serde_json::Value = serde_json::from_str(s.trim()).unwrap();
        assert_eq!(v["schema"], "marque-mvp-1");
        assert_eq!(v["rule"], "E001");
        assert_eq!(v["source"], "BuiltinRule");
        assert_eq!(v["span"]["start"], 8);
        assert_eq!(v["span"]["end"], 10);
        assert_eq!(v["original"], "NF");
        assert_eq!(v["replacement"], "NOFORN");
        assert_eq!(v["confidence"], 1.0);
        assert_eq!(v["migration_ref"], "CAPCO-2023-§3.2");
        assert_eq!(v["classifier_id"], "classifier-42");
        assert_eq!(v["dry_run"], false);
        assert_eq!(v["input"], "test.txt");
        // timestamp must be a valid RFC3339 string
        assert!(v["timestamp"].as_str().unwrap().contains('T'));
    }
}