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
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
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use super::{references, relationships};
use crate::assembly::{AssemblyError, ExecutedWorkspace, WorkspaceSources};
use crate::diagnostics::{
    Diagnostic, DiagnosticCode, DiagnosticEntity, DiagnosticPath, DiagnosticSource, Severity,
};
use crate::execution::assets::{validate_authored_image_bytes, validate_image_bytes};
use crate::ir::*;
use crate::provenance::fingerprint_bytes;

mod repository_links;
mod walk;
pub(crate) use repository_links::repository_target_url;
pub(crate) use walk::{anchors as document_anchors, references as document_references};

pub(crate) fn external_url_allowed(kind: ReferenceKind, spelling: &str, generated: bool) -> bool {
    let Ok(decoded) = percent_encoding::percent_decode_str(spelling).decode_utf8() else {
        return false;
    };
    if spelling
        .chars()
        .chain(decoded.chars())
        .any(|c| c.is_control() || c == '\\')
    {
        return false;
    }
    let Ok(url) = url::Url::parse(spelling) else {
        return false;
    };
    if !url.username().is_empty() || url.password().is_some() {
        return false;
    }
    match kind {
        ReferenceKind::Link => matches!(url.scheme(), "https" | "http" | "mailto"),
        ReferenceKind::Image => {
            !generated && matches!(url.scheme(), "https" | "http") && url.host_str().is_some()
        }
        ReferenceKind::Semantic => false,
    }
}

pub(crate) fn semantic_target<'a>(
    document: &SourcedDocument,
    kind: ReferenceKind,
    spelling: &'a str,
) -> Option<&'a str> {
    if kind == ReferenceKind::Semantic {
        return Some(spelling);
    }
    if kind == ReferenceKind::Link
        && matches!(&document.source_format, DocumentFormat::Extracted { name } if matches!(name.as_str(), "julia-markdown" | "rd" | "numpy-docstring" | "python-docstring" | "rustdoc-markdown" | "doxygen-xml"))
    {
        return spelling.strip_prefix("@ref ");
    }
    None
}

/// A document's semantic owner, independent of its rendered URL.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)]
pub enum DocumentIdentity {
    /// An authored or assembled page.
    Page {
        /// Workspace page ID.
        page: String,
    },
    /// Documentation attached to an API item.
    Item {
        /// Package-scoped item identity.
        item: ItemReference,
    },
    /// Documentation attached to an explicit concept.
    Concept {
        /// Workspace concept ID.
        concept: String,
    },
}

/// Portable destination of a resolved authored reference.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)]
pub enum ReferenceTarget {
    /// Canonical API item, including callable-family identity.
    Item {
        /// Package-scoped identity.
        item: ItemReference,
    },
    /// Another declared page or an anchor in it.
    Page {
        /// Semantic page ID.
        page: String,
        /// Decoded authored anchor.
        fragment: Option<String>,
    },
    /// An anchor within the containing document.
    Anchor {
        /// Decoded authored anchor.
        fragment: String,
    },
    /// Bytes retained in the snapshot, without a checkout dependency.
    Asset {
        /// Content-addressed portable asset.
        asset: AssetReference,
        /// Optional decoded fragment, such as a PDF page.
        fragment: Option<String>,
    },
    /// An existing undeclared target in the discovered document's repository.
    Repository {
        /// Repository containing the canonical target.
        repository: String,
        /// Canonical repository-relative file or directory.
        path: DiagnosticPath,
        /// Whether the target is a directory rather than a regular file.
        directory: bool,
        /// Decoded fragment delegated to the repository host.
        fragment: Option<String>,
    },
    /// An external hyperlink or authored image, never fetched by Diplodocus.
    External {
        /// Original URL accepted by the URL parser.
        url: String,
    },
}

/// Reference syntax determines how a generator presents its target.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ReferenceKind {
    /// Code-only semantic reference.
    Semantic,
    /// Ordinary or automatic hyperlink.
    Link,
    /// Inline image.
    Image,
}

/// One reference in document traversal order, including generated Markdown.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ResolvedReference {
    /// Authored syntax category.
    pub kind: ReferenceKind,
    /// Literal target retained in the document tree.
    pub spelling: String,
    /// Portable destination.
    pub target: ReferenceTarget,
}

/// Resolved metadata for a document, kept separate from its unchanged syntax.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ResolvedDocument {
    /// Semantic document owner.
    pub document: DocumentIdentity,
    /// Selected collection-relative filename, independent of canonical source aliases.
    pub collection_path: Option<DiagnosticPath>,
    /// Expanded Markdown ranges mapped to original files and include directives.
    /// Empty for documents without an include source map, including older snapshots.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub source_ranges: Vec<IncludeSourceRange>,
    /// Authored identifiers only; generated headings never add anchors.
    pub anchors: BTreeSet<String>,
    /// References in depth-first document order.
    pub references: Vec<ResolvedReference>,
}

/// Exact local bytes available for a later snapshot transaction.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContentAsset {
    /// Digest of the exact stored bytes.
    pub fingerprint: Fingerprint,
    /// Validated image type, or `application/octet-stream` for a download.
    pub media_type: String,
    /// Owned bytes; generation need never open a checkout.
    pub bytes: Vec<u8>,
}

/// Reference and asset observations; this is not an HTML rendering trust token.
#[derive(Debug)]
pub struct ResolvedWorkspace {
    records: Vec<ResolvedDocument>,
    pub(crate) components: BTreeMap<String, crate::components::ComponentBundle>,
    pub(crate) public_assets: BTreeMap<String, String>,
    logo: Option<AssetReference>,
    open_graph: Option<AssetReference>,
    assets: BTreeMap<String, ContentAsset>,
    diagnostics: BTreeSet<Diagnostic>,
    inputs: BTreeMap<PathBuf, AssetObservation>,
    repository_targets: BTreeMap<PathBuf, RepositoryTargetObservation>,
}

#[derive(Debug)]
struct RepositoryTargetObservation {
    path: PathBuf,
    boundary: PathBuf,
    directory: bool,
}

#[derive(Debug, PartialEq, Eq)]
struct AssetObservation {
    path: PathBuf,
    boundary: PathBuf,
    fingerprint: Fingerprint,
}
impl ResolvedWorkspace {
    /// Portable records in semantic document order.
    pub fn records(&self) -> &[ResolvedDocument] {
        &self.records
    }
    /// Deduplicated bytes keyed by SHA-256 digest.
    pub fn assets(&self) -> &BTreeMap<String, ContentAsset> {
        &self.assets
    }
    /// Validated navbar image retained with the other portable asset bytes.
    pub fn logo(&self) -> Option<&AssetReference> {
        self.logo.as_ref()
    }
    /// Validated social preview image retained with the other portable assets.
    pub fn open_graph(&self) -> Option<&AssetReference> {
        self.open_graph.as_ref()
    }
    /// All source and resolution warnings in deterministic order.
    pub fn diagnostics(&self) -> &BTreeSet<Diagnostic> {
        &self.diagnostics
    }
    /// Local assets and repository targets checked by this resolution.
    pub fn input_paths(&self) -> impl Iterator<Item = &Path> {
        self.inputs
            .keys()
            .chain(self.repository_targets.keys())
            .map(PathBuf::as_path)
    }
    /// Recheck asset bytes and repository target containment and type.
    pub fn revalidate(&self) -> Result<(), AssemblyError> {
        for (selected, observation) in &self.inputs {
            let AssetObservation {
                path,
                boundary,
                fingerprint,
            } = observation;
            if fs::canonicalize(selected)? != *path {
                return Err(AssemblyError::InputsChanged);
            }
            let resolved = crate::paths::resolve_input_file(
                boundary,
                "asset",
                path.strip_prefix(boundary)
                    .map_err(|_| AssemblyError::InputsChanged)?,
                boundary,
            )?;
            if resolved != *path || fingerprint_bytes(&fs::read(path)?) != *fingerprint {
                return Err(AssemblyError::InputsChanged);
            }
        }
        for (selected, observation) in &self.repository_targets {
            let resolved = crate::paths::resolve_repository_target(
                selected
                    .strip_prefix(&observation.boundary)
                    .map_err(|_| AssemblyError::InputsChanged)?,
                &observation.boundary,
            )?;
            if resolved != observation.path || resolved.is_dir() != observation.directory {
                return Err(AssemblyError::InputsChanged);
            }
        }
        Ok(())
    }
}

/// Resolution errors, retaining all deterministic source diagnostics.
#[derive(Debug, thiserror::Error)]
pub enum ResolutionError {
    /// Input observations changed or became unavailable.
    #[error(transparent)]
    Inputs(#[from] AssemblyError),
    /// At least one reference or relationship is invalid.
    #[error("workspace reference validation failed")]
    Diagnostics(Vec<Diagnostic>),
}
impl ResolutionError {
    /// Portable diagnostics, when the failure came from reference validation.
    pub fn diagnostics(&self) -> &[Diagnostic] {
        match self {
            Self::Diagnostics(diagnostics) => diagnostics,
            _ => &[],
        }
    }
}

/// Resolve static documents and collect checked-in assets without creating files.
///
/// This operation never discovers a kernel, runs authored code, reads an
/// execution cache, or publishes output. It checks only outputs already present.
pub fn resolve_workspace(sources: &WorkspaceSources) -> Result<ResolvedWorkspace, ResolutionError> {
    resolve(sources, sources.native_assets.clone(), false)
}

pub(crate) fn resolve_bundle(
    sources: &WorkspaceSources,
) -> Result<ResolvedWorkspace, ResolutionError> {
    resolve(sources, sources.native_assets.clone(), true)
}

/// Resolve executed documents and copy their verified final staged asset bytes.
///
/// The caller retains the execution owner until this operation and subsequent
/// publication finish. Serialized output remains untrusted on future loading.
pub fn resolve_executed_workspace(
    executed: &ExecutedWorkspace,
) -> Result<ResolvedWorkspace, ResolutionError> {
    let mut generated = executed.sources().native_assets.clone();
    for result in executed.executed_pages().values() {
        for staged in result.staged_assets() {
            let asset = result
                .validated()
                .referenced_assets()
                .find(|asset| asset.reference == staged.reference)
                .ok_or(AssemblyError::InputsChanged)?;
            let bytes = fs::read(&staged.path).map_err(AssemblyError::from)?;
            if fingerprint_bytes(&bytes) != asset.reference.fingerprint
                || bytes.len() as u64 != asset.byte_size
                || validate_image_bytes(&asset.media_type, &bytes).is_err()
            {
                return Err(AssemblyError::InputsChanged.into());
            }
            generated.insert(
                asset.reference.path.clone(),
                ContentAsset {
                    fingerprint: asset.reference.fingerprint.clone(),
                    media_type: asset.media_type.clone(),
                    bytes,
                },
            );
        }
    }
    resolve(executed.sources(), generated, false)
}

struct DocumentContext<'a> {
    identity: DocumentIdentity,
    owner: Option<&'a str>,
    document: &'a SourcedDocument,
    path: Option<PathBuf>,
    entity: DiagnosticEntity,
}

fn resolve(
    sources: &WorkspaceSources,
    generated: BTreeMap<DiagnosticPath, ContentAsset>,
    bundle_export: bool,
) -> Result<ResolvedWorkspace, ResolutionError> {
    sources.revalidate()?;
    let workspace = sources.workspace();
    let mut documents = Vec::new();
    let mut pages: BTreeMap<PathBuf, Vec<String>> = BTreeMap::new();
    let path_for = |source: &SourceLocation| {
        sources
            .paths()
            .repositories
            .iter()
            .find(|r| r.id == source.repository)
            .map(|r| r.path.join(source.path.as_str()))
    };
    for (id, page) in &workspace.pages {
        let path = page.document.source_location.as_ref().and_then(path_for);
        if let Some(path) = &path {
            pages.entry(path.clone()).or_default().push(id.clone());
        }
        for provenance in &page.document.provenance {
            if !matches!(provenance.activity, ProvenanceActivity::Declaration) {
                continue;
            }
            if let Some(DiagnosticSource::Repository {
                repository,
                path: source_path,
            }) = &provenance.source
            {
                let source = SourceLocation {
                    repository: repository.clone(),
                    path: source_path.clone(),
                    span: None,
                };
                if let Some(alias) = path_for(&source) {
                    let aliases = pages.entry(alias).or_default();
                    if !aliases.contains(id) {
                        aliases.push(id.clone());
                    }
                }
            }
        }
        let prepared = sources.prepared_pages().get(id);
        let entity =
            if let (PageKind::Authored { collection }, Some(prepared)) = (&page.kind, prepared) {
                DiagnosticEntity::Document {
                    collection: collection.clone(),
                    path: prepared.relative.clone(),
                }
            } else if let ContentOwner::Package { package } = &page.owner {
                DiagnosticEntity::Package {
                    id: package.clone(),
                }
            } else {
                DiagnosticEntity::Project
            };
        documents.push(DocumentContext {
            identity: DocumentIdentity::Page { page: id.clone() },
            owner: match &page.owner {
                ContentOwner::Project => None,
                ContentOwner::Package { package } => Some(package),
            },
            document: &page.document,
            path,
            entity,
        });
    }
    for (package, record) in &workspace.packages {
        for (item, record) in &record.items {
            if let Some(document) = &record.documentation {
                documents.push(DocumentContext {
                    identity: DocumentIdentity::Item {
                        item: ItemReference {
                            package: package.clone(),
                            item: item.clone(),
                        },
                    },
                    owner: Some(package),
                    document,
                    path: document.source_location.as_ref().and_then(path_for),
                    entity: DiagnosticEntity::Item {
                        package: package.clone(),
                        id: item.clone(),
                    },
                });
            }
        }
    }
    for (concept, record) in &workspace.concepts {
        if let Some(document) = &record.documentation {
            documents.push(DocumentContext {
                identity: DocumentIdentity::Concept {
                    concept: concept.clone(),
                },
                owner: None,
                document,
                path: document.source_location.as_ref().and_then(path_for),
                entity: DiagnosticEntity::Concept {
                    id: concept.clone(),
                },
            });
        }
    }
    documents.sort_by(|a, b| a.identity.cmp(&b.identity));
    let anchors: BTreeMap<_, _> = documents
        .iter()
        .map(|d| {
            (
                d.identity.clone(),
                walk::anchors(&d.document.document.blocks),
            )
        })
        .collect();
    let mut resolution = Resolver {
        sources,
        pages,
        anchors,
        generated,
        result: ResolvedWorkspace {
            records: vec![],
            components: BTreeMap::new(),
            public_assets: BTreeMap::new(),
            logo: None,
            open_graph: None,
            assets: BTreeMap::new(),
            diagnostics: workspace.diagnostics.clone(),
            inputs: BTreeMap::new(),
            repository_targets: BTreeMap::new(),
        },
    };
    resolution
        .result
        .diagnostics
        .extend(relationships::validate(workspace));
    let presentation = &sources.configuration().presentation;
    for (field, declaration, raster_only) in [
        (
            "presentation.logo.path",
            presentation
                .logo
                .as_ref()
                .map(|image| (&image.repository, &image.path)),
            false,
        ),
        (
            "presentation.open-graph.path",
            presentation
                .open_graph
                .as_ref()
                .map(|image| (&image.repository, &image.path)),
            true,
        ),
    ] {
        let Some((repository, image_path)) = declaration else {
            continue;
        };
        let root = &sources
            .paths()
            .repositories
            .iter()
            .find(|r| r.id == *repository)
            .expect("validated presentation image repository")
            .path;
        let path =
            crate::paths::resolve_input_file(root, field, Path::new(image_path.as_str()), root)
                .map_err(AssemblyError::from)?;
        let asset = resolution
            .collect_asset(
                root.join(image_path.as_str()),
                path,
                root,
                ReferenceKind::Image,
            )
            .and_then(|asset| {
                let media_type = &resolution.result.assets[&asset.fingerprint.value].media_type;
                if raster_only && !matches!(media_type.as_str(), "image/png" | "image/jpeg") {
                    Err(DiagnosticCode::UnresolvedDocumentReference)
                } else {
                    Ok(asset)
                }
            });
        match asset {
            Ok(asset) => {
                if raster_only {
                    resolution.result.open_graph = Some(asset);
                } else {
                    resolution.result.logo = Some(asset);
                }
            }
            Err(code) => {
                resolution.result.diagnostics.insert(
                    Diagnostic::new(
                        code,
                        Severity::Error,
                        if raster_only {
                            "presentation.open-graph.path must name a valid PNG or JPEG image."
                        } else {
                            "presentation.logo.path must name a valid SVG, PNG, or JPEG image."
                        },
                    )
                    .with_entity(DiagnosticEntity::ConfigurationField { path: field.into() }),
                );
            }
        }
    }
    for declaration in &presentation.assets {
        let root = &sources
            .paths()
            .repositories
            .iter()
            .find(|r| r.id == declaration.repository)
            .expect("validated public asset repository")
            .path;
        let selected = root.join(declaration.path.as_str());
        let path = crate::paths::resolve_input_file(
            root,
            "presentation.assets.path",
            Path::new(declaration.path.as_str()),
            root,
        )
        .map_err(AssemblyError::from)?;
        let bytes = fs::read(&path).map_err(AssemblyError::from)?;
        let fingerprint = fingerprint_bytes(&bytes);
        resolution.result.public_assets.insert(
            declaration.publish.as_str().into(),
            fingerprint.value.clone(),
        );
        resolution
            .result
            .assets
            .entry(fingerprint.value.clone())
            .or_insert(ContentAsset {
                fingerprint: fingerprint.clone(),
                media_type: "application/octet-stream".into(),
                bytes,
            });
        let observation = AssetObservation {
            path,
            boundary: root.clone(),
            fingerprint,
        };
        if let Some(previous) = resolution.result.inputs.get_mut(&selected) {
            if previous.path != observation.path || previous.fingerprint != observation.fingerprint
            {
                return Err(AssemblyError::InputsChanged.into());
            }
            // Shared branding and public files must retain the narrower read boundary.
            if observation.boundary.starts_with(&previous.boundary) {
                *previous = observation;
            }
        } else {
            resolution.result.inputs.insert(selected, observation);
        }
    }
    for asset in &sources.bundles.assets {
        insert_asset(&mut resolution.result.assets, asset.clone())
            .map_err(|_| AssemblyError::InputsChanged)?;
    }
    let component_names = sources
        .configuration()
        .components
        .iter()
        .map(|component| component.id.as_str())
        .collect();
    for context in documents {
        if let Err(error) =
            crate::components::validate_blocks(&context.document.document.blocks, &component_names)
        {
            let mut diagnostic = (*error).with_entity(context.entity.clone());
            diagnostic.source = context.document.source_location.as_ref().map(|source| {
                DiagnosticSource::Repository {
                    repository: source.repository.clone(),
                    path: source.path.clone(),
                }
            });
            if let DocumentIdentity::Page { page } = &context.identity
                && let Some(prepared) = sources.prepared_pages().get(page)
            {
                crate::assembly::remap_include_diagnostic(&mut diagnostic, &prepared.source_ranges);
            }
            resolution.result.diagnostics.insert(diagnostic);
        }
        let mut imported = sources
            .bundles
            .documents
            .get(&context.identity)
            .map(|record| record.references.iter());
        let mut references = Vec::new();
        walk::references(
            &context.document.document.blocks,
            None,
            &mut |kind, spelling, span, generated| {
                if semantic_target(context.document, kind, spelling).is_none() {
                    if let Some(imported) = &mut imported {
                        references.push(
                            imported
                                .next()
                                .expect("validated bundle references")
                                .clone(),
                        );
                        return;
                    }
                } else if bundle_export {
                    return;
                }
                match resolution.reference(&context, kind, spelling, generated) {
                    Ok(target) => references.push(ResolvedReference {
                        kind,
                        spelling: spelling.into(),
                        target,
                    }),
                    Err(code) => {
                        let mut diagnostic = Diagnostic::new(
                        code,
                        Severity::Error,
                        if code == DiagnosticCode::InvalidContentImage {
                            format!(
                                "Image asset `{spelling}` failed validation. PNG and JPEG must decode completely; SVG must satisfy the inert image policy, which excludes DTDs, styles, definitions, references, and clipping paths. Convert static Matplotlib SVGs to PNG before linking them; see the SVG conversion recipe in the authoring guide."
                            )
                        } else {
                            format!(
                                "Cannot resolve {kind:?} target `{spelling}` unambiguously and safely."
                            )
                        },
                    )
                    .with_entity(context.entity.clone());
                        diagnostic.span = context
                            .document
                            .provenance
                            .iter()
                            .find_map(|record| match record.activity {
                                ProvenanceActivity::DecodedDocumentation { decoded_span }
                                    if decoded_span == span =>
                                {
                                    record.span
                                }
                                _ => None,
                            })
                            .or(Some(span));
                        diagnostic.source = context.document.source_location.as_ref().map(|s| {
                            DiagnosticSource::Repository {
                                repository: s.repository.clone(),
                                path: s.path.clone(),
                            }
                        });
                        if !generated
                            && let DocumentIdentity::Page { page } = &context.identity
                            && let Some(prepared) = sources.prepared_pages().get(page)
                        {
                            crate::assembly::remap_include_diagnostic(
                                &mut diagnostic,
                                &prepared.source_ranges,
                            );
                        }
                        resolution.result.diagnostics.insert(diagnostic);
                    }
                }
            },
        );
        resolution.result.records.push(ResolvedDocument {
            source_ranges: match &context.identity {
                DocumentIdentity::Page { page } => sources
                    .prepared_pages()
                    .get(page)
                    .map(|p| p.source_ranges.clone())
                    .unwrap_or_default(),
                _ => Vec::new(),
            },
            collection_path: match &context.identity {
                DocumentIdentity::Page { page } => sources
                    .prepared_pages()
                    .get(page)
                    .map(|p| p.relative.clone()),
                _ => None,
            },
            anchors: resolution
                .anchors
                .get(&context.identity)
                .cloned()
                .unwrap_or_default(),
            document: context.identity,
            references,
        });
    }
    // Rich alternatives can own assets without an inline Markdown reference.
    for asset in resolution.generated.values() {
        insert_asset(&mut resolution.result.assets, asset.clone())
            .map_err(|_| AssemblyError::InputsChanged)?;
    }
    if resolution
        .result
        .diagnostics
        .iter()
        .any(|d| d.severity == Severity::Error)
    {
        return Err(ResolutionError::Diagnostics(
            resolution.result.diagnostics.into_iter().collect(),
        ));
    }
    let (components, assets, inputs) = crate::components::collect(sources)
        .map_err(|diagnostic| ResolutionError::Diagnostics(vec![*diagnostic]))?;
    resolution.result.components = components;
    for (digest, asset) in assets {
        resolution.result.assets.entry(digest).or_insert(asset);
    }
    for (path, boundary) in inputs {
        let fingerprint = fingerprint_bytes(&fs::read(&path).map_err(AssemblyError::from)?);
        resolution.result.inputs.insert(
            path.clone(),
            AssetObservation {
                path,
                boundary,
                fingerprint,
            },
        );
    }
    sources.revalidate()?;
    resolution.result.revalidate()?;
    Ok(resolution.result)
}

struct Resolver<'a> {
    sources: &'a WorkspaceSources,
    pages: BTreeMap<PathBuf, Vec<String>>,
    anchors: BTreeMap<DocumentIdentity, BTreeSet<String>>,
    generated: BTreeMap<DiagnosticPath, ContentAsset>,
    result: ResolvedWorkspace,
}

impl Resolver<'_> {
    fn reference(
        &mut self,
        context: &DocumentContext<'_>,
        kind: ReferenceKind,
        spelling: &str,
        generated: bool,
    ) -> Result<ReferenceTarget, DiagnosticCode> {
        let invalid = DiagnosticCode::UnresolvedDocumentReference;
        if kind == ReferenceKind::Link
            && let Some(target) = super::documenter_reference(
                self.sources.workspace(),
                context.document,
                context.owner,
                spelling,
            )
        {
            return target;
        }
        if let Some(spelling) = semantic_target(context.document, kind, spelling) {
            if matches!(&context.document.source_format, DocumentFormat::Extracted { name } if name == "rd")
                && kind == ReferenceKind::Link
            {
                return references::resolve_rd_help(
                    self.sources.workspace(),
                    context.owner,
                    spelling,
                );
            }
            return references::resolve_item(self.sources.workspace(), context.owner, spelling)
                .map(|item| ReferenceTarget::Item { item });
        }
        if spelling.is_empty() || spelling.chars().any(|c| c.is_control() || c == '\\') {
            return Err(invalid);
        }
        let decoded = percent_encoding::percent_decode_str(spelling)
            .decode_utf8()
            .map_err(|_| invalid)?;
        if decoded.chars().any(|c| c.is_control() || c == '\\') {
            return Err(invalid);
        }
        if url::Url::parse(spelling).is_ok() {
            if external_url_allowed(kind, spelling, generated) {
                return Ok(ReferenceTarget::External {
                    url: spelling.into(),
                });
            }
            return Err(invalid);
        }
        if decoded.starts_with('/') || spelling.contains('?') || url::Url::parse(&decoded).is_ok() {
            return Err(invalid);
        }
        let (file, fragment) = spelling
            .split_once('#')
            .map_or((spelling, None), |(f, anchor)| (f, Some(anchor)));
        let file = percent_encoding::percent_decode_str(file)
            .decode_utf8()
            .map_err(|_| invalid)?;
        let fragment = fragment
            .map(|f| {
                percent_encoding::percent_decode_str(f)
                    .decode_utf8()
                    .map(|s| s.into_owned())
            })
            .transpose()
            .map_err(|_| invalid)?;
        if file.is_empty() {
            let fragment = fragment.filter(|f| !f.is_empty()).ok_or(invalid)?;
            if kind == ReferenceKind::Image
                || !self
                    .anchors
                    .get(&context.identity)
                    .is_some_and(|a| a.contains(&fragment))
            {
                return Err(invalid);
            }
            return Ok(ReferenceTarget::Anchor { fragment });
        }
        // Execution has already replaced image targets with staged asset paths.
        // Links still use the owning page's source context for pages and downloads.
        let rd_figure =
            (spelling.starts_with("rd-example-assets/")
                && context.document.provenance.iter().any(|record| {
                    matches!(record.activity, ProvenanceActivity::RdExamples { .. })
                }))
                || (spelling.starts_with("rmd-assets/sha256/")
                    && context.document.provenance.iter().any(|record| {
                        matches!(record.activity, ProvenanceActivity::RMarkdown { .. })
                    }))
                || (spelling.starts_with("documenter-assets/sha256/")
                    && context.document.provenance.iter().any(|record| {
                        matches!(
                            record.activity,
                            ProvenanceActivity::DocumenterExamples { .. }
                        )
                    }));
        if (generated || rd_figure) && kind == ReferenceKind::Image {
            let path = DiagnosticPath::try_from(file.as_ref()).map_err(|_| invalid)?;
            let asset = self.generated.get(&path).ok_or(invalid)?;
            if fragment.is_some() {
                return Err(invalid);
            }
            return Ok(ReferenceTarget::Asset {
                asset: AssetReference {
                    path: if rd_figure {
                        DiagnosticPath::try_from(format!(
                            "content-assets/sha256/{}",
                            asset.fingerprint.value
                        ))
                        .map_err(|_| invalid)?
                    } else {
                        path
                    },
                    fingerprint: asset.fingerprint.clone(),
                },
                fragment: None,
            });
        }
        let source = context.path.as_ref().ok_or(invalid)?;
        let candidate = source.parent().ok_or(invalid)?.join(file.as_ref());
        let included_repository = match &context.identity {
            DocumentIdentity::Page { page } => self
                .sources
                .prepared_pages()
                .get(page)
                .filter(|prepared| prepared.included_resource_targets.contains(spelling))
                .and_then(|prepared| {
                    self.sources
                        .paths()
                        .repositories
                        .iter()
                        .find(|repository| repository.id == prepared.location.repository)
                }),
            _ => None,
        };
        let canonical = if let Some(repository) = included_repository {
            // Validate the authored traversal before canonicalization can hide a
            // symlink that leaves and reenters the repository.
            let path = crate::paths::resolve_repository_target(
                candidate
                    .strip_prefix(&repository.path)
                    .map_err(|_| invalid)?,
                &repository.path,
            )
            .map_err(|_| invalid)?;
            if crate::generated_storage::is_reserved(&path) {
                return Err(invalid);
            }
            path
        } else {
            fs::canonicalize(&candidate).map_err(|_| invalid)?
        };
        if kind != ReferenceKind::Image
            && let Some(ids) = self.pages.get(&canonical)
        {
            let [page] = ids.as_slice() else {
                return Err(invalid);
            };
            if let Some(fragment) = &fragment
                && !fragment.is_empty()
                && !self
                    .anchors
                    .get(&DocumentIdentity::Page { page: page.clone() })
                    .is_some_and(|a| a.contains(fragment))
            {
                return Err(invalid);
            }
            return Ok(ReferenceTarget::Page {
                page: page.clone(),
                fragment,
            });
        }
        let boundary = self
            .sources
            .paths()
            .content
            .iter()
            .map(|c| &c.source_root)
            .chain(self.sources.paths().packages.iter().map(|p| &p.path))
            .chain(included_repository.map(|repository| &repository.path))
            .filter(|root| canonical.starts_with(root))
            .max_by_key(|root| root.components().count());
        // Unselected documents remain source links rather than downloadable pages.
        if canonical.is_dir()
            || matches!(
                canonical.extension().and_then(|s| s.to_str()),
                Some("md" | "qmd" | "rmd" | "Rmd")
            )
            || boundary.is_none()
        {
            return self.repository_link(context, kind, candidate, fragment);
        }
        let boundary = boundary.ok_or(invalid)?;
        let path = crate::paths::resolve_input_file(
            boundary,
            "asset",
            canonical.strip_prefix(boundary).map_err(|_| invalid)?,
            boundary,
        )
        .map_err(|_| invalid)?;
        let asset = self.collect_asset(candidate, path, boundary, kind)?;
        Ok(ReferenceTarget::Asset { asset, fragment })
    }

    fn collect_asset(
        &mut self,
        candidate: PathBuf,
        path: PathBuf,
        boundary: &Path,
        kind: ReferenceKind,
    ) -> Result<AssetReference, DiagnosticCode> {
        let invalid = DiagnosticCode::UnresolvedDocumentReference;
        let bytes = fs::read(&path).map_err(|_| invalid)?;
        let media_type = match path
            .extension()
            .and_then(|s| s.to_str())
            .map(str::to_ascii_lowercase)
            .as_deref()
        {
            Some("png") => "image/png",
            Some("jpeg" | "jpg") => "image/jpeg",
            Some("svg") => "image/svg+xml",
            _ => "application/octet-stream",
        };
        if (kind == ReferenceKind::Image || media_type.starts_with("image/"))
            && validate_authored_image_bytes(media_type, &bytes).is_err()
        {
            return Err(DiagnosticCode::InvalidContentImage);
        }
        let fingerprint = fingerprint_bytes(&bytes);
        let asset = AssetReference {
            path: DiagnosticPath::try_from(format!("content-assets/sha256/{}", fingerprint.value))
                .map_err(|_| invalid)?,
            fingerprint: fingerprint.clone(),
        };
        insert_asset(
            &mut self.result.assets,
            ContentAsset {
                fingerprint: fingerprint.clone(),
                media_type: media_type.into(),
                bytes,
            },
        )?;
        let observation = AssetObservation {
            path,
            boundary: boundary.to_owned(),
            fingerprint,
        };
        if let Some(old) = self.result.inputs.get_mut(&candidate) {
            if old.path != observation.path || old.fingerprint != observation.fingerprint {
                return Err(invalid);
            }
            // Branding and document images can share bytes under different declared roots.
            // Retain the narrower boundary for the publication recheck.
            if observation.boundary.starts_with(&old.boundary) {
                *old = observation;
            }
        } else {
            self.result.inputs.insert(candidate, observation);
        }
        Ok(asset)
    }
}

fn insert_asset(
    assets: &mut BTreeMap<String, ContentAsset>,
    asset: ContentAsset,
) -> Result<(), DiagnosticCode> {
    if let Some(previous) = assets.get_mut(&asset.fingerprint.value) {
        if previous.bytes != asset.bytes {
            return Err(DiagnosticCode::UnresolvedDocumentReference);
        }
        if previous.media_type == "application/octet-stream" {
            previous.media_type = asset.media_type;
        } else if asset.media_type != "application/octet-stream"
            && previous.media_type != asset.media_type
        {
            return Err(DiagnosticCode::UnresolvedDocumentReference);
        }
    } else {
        assets.insert(asset.fingerprint.value.clone(), asset);
    }
    Ok(())
}