diplodocus 0.15.0

Build coherent documentation websites for polyglot software projects.
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
//! Portable diagnostics shared by configuration and documentation processing.

use std::cmp::Ordering;

use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::ir::SourceSpan;

/// Stable diagnostic identifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DiagnosticCode {
    /// An authored Markdown include cannot be expanded.
    #[serde(rename = "invalid-markdown-include")]
    InvalidMarkdownInclude,
    /// A local image exists but fails image format or inert SVG validation.
    #[serde(rename = "invalid-content-image")]
    InvalidContentImage,
    /// Several visible generated pages have the same HTML title.
    #[serde(rename = "duplicate-page-title")]
    DuplicatePageTitle,
    /// An explicitly declared browser component or bundle is invalid.
    #[serde(rename = "invalid-component")]
    InvalidComponent,
    /// An authored local page, asset, or anchor cannot be resolved safely.
    #[serde(rename = "unresolved-document-reference")]
    UnresolvedDocumentReference,
    /// A present package violates a declared relationship constraint.
    #[serde(rename = "incompatible-package-relationship")]
    IncompatiblePackageRelationship,
    /// A present relationship cannot be checked with the available version rules.
    #[serde(rename = "indeterminate-package-relationship")]
    IndeterminatePackageRelationship,
    /// Extraction targets disagree about a package or claim the same item.
    #[serde(rename = "conflicting-extraction")]
    ConflictingExtraction,
    /// No built-in adapter implements an explicitly selected extractor.
    #[serde(rename = "unsupported-extractor")]
    UnsupportedExtractor,
    /// Native Doxygen invocation, configuration, or XML extraction failed.
    #[serde(rename = "doxygen-extraction")]
    DoxygenExtraction,
    /// C++ declarations or documentation exceed the supported adapter subset.
    #[serde(rename = "doxygen-unsupported")]
    DoxygenUnsupported,
    /// Cargo metadata or target selection is invalid.
    #[serde(rename = "rust-metadata")]
    RustMetadata,
    /// Rust source inputs cannot be read within the declared repository.
    #[serde(rename = "rust-source-read")]
    RustSourceRead,
    /// The prepared Rust documentation toolchain is missing or incompatible.
    #[serde(rename = "rust-toolchain")]
    RustToolchain,
    /// Native Rust documentation extraction failed.
    #[serde(rename = "rust-extraction")]
    RustExtraction,
    /// A public Rust declaration exceeds the supported semantic model.
    #[serde(rename = "rust-unsupported-surface")]
    RustUnsupportedSurface,
    /// Rust documentation cannot be represented or linked correctly.
    #[serde(rename = "rust-documentation")]
    RustDocumentation,
    /// Julia metadata is malformed or lacks package identity.
    #[serde(rename = "julia-metadata")]
    JuliaMetadata,
    /// A Julia input cannot be read or decoded safely.
    #[serde(rename = "julia-source-read")]
    JuliaSourceRead,
    /// Maintained Julia source contains syntax errors.
    #[serde(rename = "julia-syntax")]
    JuliaSyntax,
    /// An include is dynamic, cyclic, or otherwise unsupported.
    #[serde(rename = "julia-include")]
    JuliaInclude,
    /// Public Julia declarations exceed the supported static subset.
    #[serde(rename = "julia-unsupported-surface")]
    JuliaUnsupportedSurface,
    /// A public binding has no statically established definition.
    #[serde(rename = "julia-unresolved-definition")]
    JuliaUnresolvedDefinition,
    /// Julia definitions, identities, or lookup names conflict.
    #[serde(rename = "julia-conflicting-surface")]
    JuliaConflictingSurface,
    /// Julia documentation cannot be interpreted without evaluation.
    #[serde(rename = "julia-unsupported-docstring")]
    JuliaUnsupportedDocstring,
    /// Julia Markdown contains unsupported or malformed syntax.
    #[serde(rename = "julia-unsupported-markdown")]
    JuliaUnsupportedMarkdown,
    /// An authored semantic name has no matching item.
    #[serde(rename = "unresolved-item-reference")]
    UnresolvedItemReference,
    /// An authored semantic name identifies several items.
    #[serde(rename = "ambiguous-item-reference")]
    AmbiguousItemReference,
    /// A kernel message cannot be attributed or handled during execution.
    #[serde(rename = "unsupported-kernel-message")]
    UnsupportedKernelMessage,
    /// A lower-priority kernelspec matches the explicitly configured selector.
    #[serde(rename = "shadowed-kernelspec")]
    ShadowedKernelspec,
    /// Configured kernel selection, launch, or readiness failed.
    #[serde(rename = "execution-startup-failed")]
    ExecutionStartupFailed,
    /// Kernel transport, protocol validation, or liveness failed.
    #[serde(rename = "execution-protocol-failed")]
    ExecutionProtocolFailed,
    /// A kernel requested unsupported interactive input.
    #[serde(rename = "execution-input-requested")]
    ExecutionInputRequested,
    /// A cell failed without permission to continue.
    #[serde(rename = "execution-cell-failed")]
    ExecutionCellFailed,
    /// A bounded execution phase timed out.
    #[serde(rename = "execution-timeout")]
    ExecutionTimeout,
    /// The caller canceled page execution.
    #[serde(rename = "execution-cancelled")]
    ExecutionCancelled,
    /// Kernel or asset-staging cleanup failed.
    #[serde(rename = "execution-cleanup-failed")]
    ExecutionCleanupFailed,
    /// An unrecoverable output conversion or validation failure occurred.
    #[serde(rename = "execution-output-failed")]
    ExecutionOutputFailed,
    /// A generated asset escaped its declared boundary.
    #[serde(rename = "generated-asset-outside-boundary")]
    GeneratedAssetOutsideBoundary,
    /// A generated asset could not be found.
    #[serde(rename = "generated-asset-missing")]
    GeneratedAssetMissing,
    /// Execution assets conflict at the same content digest.
    #[serde(rename = "execution-asset-collision")]
    ExecutionAssetCollision,
    /// Cell output has no supported faithful representation.
    #[serde(rename = "unsupported-cell-output")]
    UnsupportedCellOutput,
    /// A supported output payload is malformed and needs a safe alternative.
    #[serde(rename = "invalid-cell-output")]
    InvalidCellOutput,
    /// A kernel HTML candidate violates the active allowlist.
    #[serde(rename = "unsafe-kernel-html")]
    UnsafeKernelHtml,
    /// A kernel SVG candidate violates the active allowlist.
    #[serde(rename = "unsafe-kernel-svg")]
    UnsafeKernelSvg,
    /// Declared execution inputs changed before the attempt could be accepted.
    #[serde(rename = "execution-input-changed")]
    ExecutionInputChanged,
    /// An execution-cache candidate failed complete validation.
    #[serde(rename = "invalid-execution-cache")]
    InvalidExecutionCache,
    /// Optional cache storage failed without invalidating a successful page.
    #[serde(rename = "execution-cache-unavailable")]
    ExecutionCacheUnavailable,
    /// Valid executions produced different results for the same page key.
    #[serde(rename = "non-deterministic-execution")]
    NonDeterministicExecution,
    /// R metadata is malformed or lacks required static values.
    #[serde(rename = "r-metadata")]
    RMetadata,
    /// An R input cannot be read or decoded.
    #[serde(rename = "r-source-read")]
    RSourceRead,
    /// Installed R library discovery or package metadata is unavailable.
    #[serde(rename = "r-library-unavailable")]
    RLibraryUnavailable,
    /// Maintained R source has syntax errors.
    #[serde(rename = "r-syntax")]
    RSyntax,
    /// Namespace syntax or semantics cannot establish a static surface.
    #[serde(rename = "r-unsupported-namespace")]
    RUnsupportedNamespace,
    /// An exported or registered R definition cannot be established.
    #[serde(rename = "r-unresolved-definition")]
    RUnresolvedDefinition,
    /// R declarations, signatures, or documentation have conflicting meanings.
    #[serde(rename = "r-conflicting-surface")]
    RConflictingSurface,
    /// A public R declaration lacks a documented alias.
    #[serde(rename = "r-missing-documented-alias")]
    RMissingDocumentedAlias,
    /// A public R construct exceeds the static semantic subset.
    #[serde(rename = "r-unsupported-surface")]
    RUnsupportedSurface,
    /// Rd parsing failed or recovered malformed syntax.
    #[serde(rename = "r-rd-syntax")]
    RRdSyntax,
    /// Strict Rd views reject a lossy or ambiguous projection.
    #[serde(rename = "r-rd-information-loss")]
    RRdInformationLoss,
    /// Successful Rd nodes have only file-level source attribution.
    #[serde(rename = "r-rd-source-attribution")]
    RRdSourceAttribution,
    /// Rd content cannot be translated or evaluated statically.
    #[serde(rename = "unsupported-rd")]
    UnsupportedRd,
    /// Authored syntax is outside Diplodocus's supported profile.
    #[serde(rename = "unsupported-authored-syntax")]
    UnsupportedAuthoredSyntax,
    /// An authored page selects an invalid or ambiguous layout.
    #[serde(rename = "invalid-page-layout")]
    InvalidPageLayout,
    /// Panache reported malformed embedded YAML.
    #[serde(rename = "invalid-embedded-yaml")]
    InvalidEmbeddedYaml,
    /// Cell-option precedence has more than one winner.
    #[serde(rename = "ambiguous-cell-option")]
    AmbiguousCellOption,
    /// A cell declares an option or fence class outside the QMD subset.
    #[serde(rename = "unsupported-cell-option")]
    UnsupportedCellOption,
    /// A cell option has an invalid type, label, or conflicting declaration.
    #[serde(rename = "invalid-cell-option")]
    InvalidCellOption,
    /// Subcaptions do not match the cell's final selected figures.
    #[serde(rename = "invalid-figure-options")]
    InvalidFigureOptions,
    /// Document metadata requests execution outside collection authority.
    #[serde(rename = "document-execution-not-authorized")]
    DocumentExecutionNotAuthorized,
    /// A QMD document declares an unsupported metadata setting.
    #[serde(rename = "unsupported-qmd-metadata")]
    UnsupportedQmdMetadata,
    /// A QMD metadata declaration has an invalid value type.
    #[serde(rename = "invalid-qmd-metadata")]
    InvalidQmdMetadata,
    /// A configuration file could not be read.
    #[serde(rename = "configuration-read-failed")]
    ConfigurationReadFailed,
    /// Configuration syntax or declarations do not match the input schema.
    #[serde(rename = "invalid-configuration")]
    InvalidConfiguration,
    /// A collection has contradictory or malformed execution settings.
    #[serde(rename = "invalid-execution-configuration")]
    InvalidExecutionConfiguration,
    /// A declared source path has an invalid spelling.
    #[serde(rename = "invalid-source-path")]
    InvalidSourcePath,
    /// A declared source path could not be inspected.
    #[serde(rename = "source-path-io")]
    SourcePathIo,
    /// A source path has the wrong filesystem type.
    #[serde(rename = "source-path-wrong-type")]
    SourcePathWrongType,
    /// A source path escapes its declared boundary.
    #[serde(rename = "source-path-outside-boundary")]
    SourcePathOutsideBoundary,
    /// A repository reference does not select exactly one declaration.
    #[serde(rename = "invalid-repository-reference")]
    InvalidRepositoryReference,
    /// A repository ID is declared more than once in the workspace.
    #[serde(rename = "duplicate-repository-id")]
    DuplicateRepositoryId,
    /// A package ID is declared more than once in the workspace.
    #[serde(rename = "duplicate-package-id")]
    DuplicatePackageId,
    /// An extraction target ID is declared more than once within a package.
    #[serde(rename = "duplicate-target-id")]
    DuplicateTargetId,
    /// A content collection ID is declared more than once in the workspace.
    #[serde(rename = "duplicate-content-id")]
    DuplicateContentId,
    /// A concept ID is declared more than once in the workspace.
    #[serde(rename = "duplicate-concept-id")]
    DuplicateConceptId,
    /// A package URL slug is declared more than once in the site.
    #[serde(rename = "duplicate-package-slug")]
    DuplicatePackageSlug,
    /// A content owner is neither `project` nor a declared package ID.
    #[serde(rename = "unknown-content-owner")]
    UnknownContentOwner,
    /// A concept member references an undeclared workspace package.
    #[serde(rename = "unknown-concept-package")]
    UnknownConceptPackage,
    /// An unqualified relationship endpoint references an undeclared package.
    #[serde(rename = "unknown-relationship-endpoint")]
    UnknownRelationshipEndpoint,
    /// An external relationship endpoint has malformed coordinate syntax.
    #[serde(rename = "invalid-external-package-coordinate")]
    InvalidExternalPackageCoordinate,
    /// Python package metadata is malformed or missing required static fields.
    #[serde(rename = "python-metadata")]
    PythonMetadata,
    /// Required Python package metadata needs backend execution.
    #[serde(rename = "python-dynamic-metadata")]
    PythonDynamicMetadata,
    /// Python source contains malformed syntax.
    #[serde(rename = "python-syntax")]
    PythonSyntax,
    /// Python syntax or version constraints exceed the supported target grammar.
    #[serde(rename = "python-unsupported-version")]
    PythonUnsupportedVersion,
    /// Python source has syntax outside the static extraction subset.
    #[serde(rename = "python-unsupported-syntax")]
    PythonUnsupportedSyntax,
    /// A declared Python input could not be read safely.
    #[serde(rename = "python-source-read")]
    PythonSourceRead,
    /// Multiple inputs define the same Python module surface.
    #[serde(rename = "python-module-collision")]
    PythonModuleCollision,
    /// A Python export list cannot be determined statically.
    #[serde(rename = "python-dynamic-export")]
    PythonDynamicExport,
    /// A public Python import cannot be resolved to a canonical entity.
    #[serde(rename = "python-unresolved-reexport")]
    PythonUnresolvedReexport,
    /// A maintained Python stub conflicts with its implementation.
    #[serde(rename = "python-conflicting-stub")]
    PythonConflictingStub,
    /// A public Python construct has unsupported semantics.
    #[serde(rename = "python-unsupported-surface")]
    PythonUnsupportedSurface,
    /// Python declarations have conflicting canonical identities.
    #[serde(rename = "python-duplicate-identity")]
    PythonDuplicateIdentity,
    /// A Python lookup name refers to multiple canonical entities.
    #[serde(rename = "python-conflicting-alias")]
    PythonConflictingAlias,
    /// A Python declaration lacks supported semantic identity inputs.
    #[serde(rename = "python-invalid-identity")]
    PythonInvalidIdentity,
    /// A Python docstring contains incomplete section syntax.
    #[serde(rename = "python-incomplete-docstring")]
    PythonIncompleteDocstring,
    /// A Python docstring contains unsupported markup or sections.
    #[serde(rename = "python-unsupported-docstring")]
    PythonUnsupportedDocstring,
    /// Decoded Python documentation cannot be mapped exactly to source.
    #[serde(rename = "python-docstring-source-attribution")]
    PythonDocstringSourceAttribution,
}

impl DiagnosticCode {
    /// Stable serialized identifier, also used to order diagnostics.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::DuplicatePageTitle => "duplicate-page-title",
            Self::UnsupportedKernelMessage => "unsupported-kernel-message",
            Self::ShadowedKernelspec => "shadowed-kernelspec",
            Self::ExecutionStartupFailed => "execution-startup-failed",
            Self::ExecutionProtocolFailed => "execution-protocol-failed",
            Self::ExecutionInputRequested => "execution-input-requested",
            Self::ExecutionCellFailed => "execution-cell-failed",
            Self::ExecutionTimeout => "execution-timeout",
            Self::ExecutionCancelled => "execution-cancelled",
            Self::ExecutionCleanupFailed => "execution-cleanup-failed",
            Self::ExecutionOutputFailed => "execution-output-failed",
            Self::ConflictingExtraction => "conflicting-extraction",
            Self::UnresolvedDocumentReference => "unresolved-document-reference",
            Self::InvalidContentImage => "invalid-content-image",
            Self::IncompatiblePackageRelationship => "incompatible-package-relationship",
            Self::IndeterminatePackageRelationship => "indeterminate-package-relationship",
            Self::UnsupportedExtractor => "unsupported-extractor",
            Self::DoxygenExtraction => "doxygen-extraction",
            Self::DoxygenUnsupported => "doxygen-unsupported",
            Self::RustMetadata => "rust-metadata",
            Self::RustSourceRead => "rust-source-read",
            Self::RustToolchain => "rust-toolchain",
            Self::RustExtraction => "rust-extraction",
            Self::RustUnsupportedSurface => "rust-unsupported-surface",
            Self::RustDocumentation => "rust-documentation",
            Self::JuliaMetadata => "julia-metadata",
            Self::JuliaSourceRead => "julia-source-read",
            Self::JuliaSyntax => "julia-syntax",
            Self::JuliaInclude => "julia-include",
            Self::JuliaUnsupportedSurface => "julia-unsupported-surface",
            Self::JuliaUnresolvedDefinition => "julia-unresolved-definition",
            Self::JuliaConflictingSurface => "julia-conflicting-surface",
            Self::JuliaUnsupportedDocstring => "julia-unsupported-docstring",
            Self::JuliaUnsupportedMarkdown => "julia-unsupported-markdown",
            Self::UnresolvedItemReference => "unresolved-item-reference",
            Self::AmbiguousItemReference => "ambiguous-item-reference",
            Self::GeneratedAssetOutsideBoundary => "generated-asset-outside-boundary",
            Self::GeneratedAssetMissing => "generated-asset-missing",
            Self::ExecutionAssetCollision => "execution-asset-collision",
            Self::UnsupportedCellOutput => "unsupported-cell-output",
            Self::InvalidCellOutput => "invalid-cell-output",
            Self::UnsafeKernelHtml => "unsafe-kernel-html",
            Self::UnsafeKernelSvg => "unsafe-kernel-svg",
            Self::ExecutionInputChanged => "execution-input-changed",
            Self::InvalidExecutionCache => "invalid-execution-cache",
            Self::ExecutionCacheUnavailable => "execution-cache-unavailable",
            Self::NonDeterministicExecution => "non-deterministic-execution",
            Self::RMetadata => "r-metadata",
            Self::RSourceRead => "r-source-read",
            Self::RLibraryUnavailable => "r-library-unavailable",
            Self::RSyntax => "r-syntax",
            Self::RUnsupportedNamespace => "r-unsupported-namespace",
            Self::RUnresolvedDefinition => "r-unresolved-definition",
            Self::RConflictingSurface => "r-conflicting-surface",
            Self::RMissingDocumentedAlias => "r-missing-documented-alias",
            Self::RUnsupportedSurface => "r-unsupported-surface",
            Self::RRdSyntax => "r-rd-syntax",
            Self::RRdInformationLoss => "r-rd-information-loss",
            Self::RRdSourceAttribution => "r-rd-source-attribution",
            Self::UnsupportedRd => "unsupported-rd",
            Self::InvalidMarkdownInclude => "invalid-markdown-include",
            Self::InvalidComponent => "invalid-component",
            Self::UnsupportedAuthoredSyntax => "unsupported-authored-syntax",
            Self::InvalidEmbeddedYaml => "invalid-embedded-yaml",
            Self::AmbiguousCellOption => "ambiguous-cell-option",
            Self::UnsupportedCellOption => "unsupported-cell-option",
            Self::InvalidCellOption => "invalid-cell-option",
            Self::InvalidFigureOptions => "invalid-figure-options",
            Self::DocumentExecutionNotAuthorized => "document-execution-not-authorized",
            Self::UnsupportedQmdMetadata => "unsupported-qmd-metadata",
            Self::InvalidQmdMetadata => "invalid-qmd-metadata",
            Self::InvalidPageLayout => "invalid-page-layout",
            Self::ConfigurationReadFailed => "configuration-read-failed",
            Self::InvalidConfiguration => "invalid-configuration",
            Self::InvalidExecutionConfiguration => "invalid-execution-configuration",
            Self::InvalidSourcePath => "invalid-source-path",
            Self::SourcePathIo => "source-path-io",
            Self::SourcePathWrongType => "source-path-wrong-type",
            Self::SourcePathOutsideBoundary => "source-path-outside-boundary",
            Self::InvalidRepositoryReference => "invalid-repository-reference",
            Self::DuplicateRepositoryId => "duplicate-repository-id",
            Self::DuplicatePackageId => "duplicate-package-id",
            Self::DuplicateTargetId => "duplicate-target-id",
            Self::DuplicateContentId => "duplicate-content-id",
            Self::DuplicateConceptId => "duplicate-concept-id",
            Self::DuplicatePackageSlug => "duplicate-package-slug",
            Self::UnknownContentOwner => "unknown-content-owner",
            Self::UnknownConceptPackage => "unknown-concept-package",
            Self::UnknownRelationshipEndpoint => "unknown-relationship-endpoint",
            Self::InvalidExternalPackageCoordinate => "invalid-external-package-coordinate",
            Self::PythonMetadata => "python-metadata",
            Self::PythonDynamicMetadata => "python-dynamic-metadata",
            Self::PythonSyntax => "python-syntax",
            Self::PythonUnsupportedVersion => "python-unsupported-version",
            Self::PythonUnsupportedSyntax => "python-unsupported-syntax",
            Self::PythonSourceRead => "python-source-read",
            Self::PythonModuleCollision => "python-module-collision",
            Self::PythonDynamicExport => "python-dynamic-export",
            Self::PythonUnresolvedReexport => "python-unresolved-reexport",
            Self::PythonConflictingStub => "python-conflicting-stub",
            Self::PythonUnsupportedSurface => "python-unsupported-surface",
            Self::PythonDuplicateIdentity => "python-duplicate-identity",
            Self::PythonConflictingAlias => "python-conflicting-alias",
            Self::PythonInvalidIdentity => "python-invalid-identity",
            Self::PythonIncompleteDocstring => "python-incomplete-docstring",
            Self::PythonUnsupportedDocstring => "python-unsupported-docstring",
            Self::PythonDocstringSourceAttribution => "python-docstring-source-attribution",
        }
    }
}

/// Diagnostic severity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Severity {
    /// The input is invalid. Errors sort before warnings.
    Error,
    /// Processing can continue, but the condition is visible.
    Warning,
}

/// A normalized, nonempty relative path using forward-slash separators.
///
/// Construction and deserialization reject absolute paths, colons (including
/// Windows prefixes), backslashes, NUL bytes, and empty, `.` or `..` components.
/// This type performs no filesystem access or symlink validation. Callers supply
/// paths relative to the source's declared root, never canonical machine paths.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct DiagnosticPath(#[serde(deserialize_with = "deserialize_path")] String);

/// A diagnostic path is not a normalized portable relative path.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[error(
    "diagnostic paths must be nonempty normalized relative paths with forward-slash separators"
)]
pub struct InvalidDiagnosticPath;

impl DiagnosticPath {
    /// The normalized relative spelling.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl TryFrom<String> for DiagnosticPath {
    type Error = InvalidDiagnosticPath;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        if value.contains(['\\', '\0', ':'])
            || value
                .split('/')
                .any(|component| matches!(component, "" | "." | ".."))
        {
            return Err(InvalidDiagnosticPath);
        }
        Ok(Self(value))
    }
}

impl TryFrom<&str> for DiagnosticPath {
    type Error = InvalidDiagnosticPath;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::try_from(value.to_owned())
    }
}

fn deserialize_path<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<String, D::Error> {
    let path = DiagnosticPath::try_from(String::deserialize(deserializer)?)
        .map_err(serde::de::Error::custom)?;
    Ok(path.0)
}

/// Portable origin of the primary and related spans in a diagnostic.
///
/// Configuration sources sort before repository sources. Configuration paths
/// sort lexically; repository sources sort by repository ID, then path.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum DiagnosticSource {
    /// A file relative to the workspace configuration directory.
    Configuration {
        /// Configuration-relative path, usually `diplodocus.yaml`.
        path: DiagnosticPath,
    },
    /// A file within an explicitly declared repository.
    Repository {
        /// Stable repository ID, independent of its checkout directory.
        repository: String,
        /// Repository-relative source path.
        path: DiagnosticPath,
    },
}

/// Semantic entity related to a diagnostic, independent of rendered URLs.
///
/// Variants sort by the `kind` spelling below, then fields in declaration order.
/// Indices are zero-based declaration positions and sort numerically. These
/// references retain declared identities without checking that they resolve.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum DiagnosticEntity {
    /// A conceptual API group.
    Concept {
        /// Declared concept ID.
        id: String,
    },
    /// The workspace configuration as a whole.
    Configuration,
    /// An indexed configuration field, before a semantic entity is available.
    ConfigurationField {
        /// Schema field path, such as `packages[0].slug`.
        path: String,
    },
    /// An authored content collection.
    Content {
        /// Declared collection ID.
        id: String,
    },
    /// An authored document in a content collection.
    Document {
        /// Declared collection ID.
        collection: String,
        /// Collection-relative document path.
        path: DiagnosticPath,
    },
    /// An extracted item scoped to a package.
    Item {
        /// Declared package ID.
        package: String,
        /// Extractor-assigned item ID.
        id: String,
    },
    /// A package or internal component.
    Package {
        /// Declared package ID.
        id: String,
    },
    /// The workspace project.
    Project,
    /// A relationship declaration, which has no authored ID.
    Relationship {
        /// Index in the workspace's relationship declarations.
        index: usize,
    },
    /// An explicitly declared repository.
    Repository {
        /// Declared repository ID.
        id: String,
    },
    /// An extraction target scoped to its package.
    Target {
        /// Declared package ID.
        package: String,
        /// Declared target ID.
        id: String,
    },
}

/// A diagnostic with optional portable entity and source context.
///
/// Sorting uses source, primary span `(start, end)`, stable code spelling,
/// severity (error before warning), related entity, message, and finally related
/// spans lexicographically by `(start, end)`. Missing sources, primary spans,
/// and entities sort after present values. Every field participates, so equal
/// sort keys have identical serialized representations regardless of input order.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Diagnostic {
    /// Stable identifier.
    pub code: DiagnosticCode,
    /// Severity.
    pub severity: Severity,
    /// Human-readable explanation.
    /// Producers must not embed runtime paths or other machine-specific data.
    pub message: String,
    /// Related semantic entity or configuration field when known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub related_entity: Option<DiagnosticEntity>,
    /// Portable source path and its root when known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<DiagnosticSource>,
    /// Source range when available.
    pub span: Option<SourceSpan>,
    /// Additional declarations contributing to this diagnostic, in source order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub related_spans: Vec<SourceSpan>,
}

impl Diagnostic {
    /// Create a diagnostic without inventing unavailable source or entity context.
    pub fn new(code: DiagnosticCode, severity: Severity, message: impl Into<String>) -> Self {
        Self {
            code,
            severity,
            message: message.into(),
            related_entity: None,
            source: None,
            span: None,
            related_spans: Vec::new(),
        }
    }

    /// Attach the portable source shared by the primary and related spans.
    pub fn with_source(mut self, source: DiagnosticSource) -> Self {
        self.source = Some(source);
        self
    }

    /// Attach a semantic entity or configuration field.
    pub fn with_entity(mut self, entity: DiagnosticEntity) -> Self {
        self.related_entity = Some(entity);
        self
    }
}

impl Ord for Diagnostic {
    fn cmp(&self, other: &Self) -> Ordering {
        optional_last(&self.source, &other.source)
            .then_with(|| optional_last(&self.span.map(span_key), &other.span.map(span_key)))
            .then_with(|| self.code.as_str().cmp(other.code.as_str()))
            .then_with(|| self.severity.cmp(&other.severity))
            .then_with(|| optional_last(&self.related_entity, &other.related_entity))
            .then_with(|| self.message.cmp(&other.message))
            .then_with(|| {
                self.related_spans
                    .iter()
                    .copied()
                    .map(span_key)
                    .cmp(other.related_spans.iter().copied().map(span_key))
            })
    }
}

impl PartialOrd for Diagnostic {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

fn span_key(span: SourceSpan) -> (usize, usize) {
    (span.start, span.end)
}

fn optional_last<T: Ord>(left: &Option<T>, right: &Option<T>) -> Ordering {
    match (left, right) {
        (Some(left), Some(right)) => left.cmp(right),
        (Some(_), None) => Ordering::Less,
        (None, Some(_)) => Ordering::Greater,
        (None, None) => Ordering::Equal,
    }
}