Reviewing links and reading order
A definition link should save the reader a search. The plugin extracts links from existing units; reviewers check whether any are missing and whether their destinations explain the right subject. No extra Markdown annotations are needed.
Inspect the inventory
From v2/, run:
cargo run -p mdbook-dada --bin dada-spec -- links
cargo run -p mdbook-dada --bin dada-spec -- links --json
The output lists occurrences, destinations, reading order, candidate cycles, and required audit subjects. The JSON is useful for preparing review work; it is a derived inventory, not another source file to maintain.
The link inventory records each authored link in a structured unit: its source
range, destination, label, syntax, and position in the book. It recognizes
Markdown links, including reference-style links, anchor-reference roles, and
MathJax \href commands. Literal code and comments do not introduce links. Authored HTML links and
unsupported local URL forms are rejected rather than silently omitted. A
published chapter cannot link to a chapter absent from SUMMARY.md.
An internal destination must resolve to the specified chapter and anchor;
finding the same ID in another chapter is insufficient. Reading order follows
SUMMARY.md, then source position within each chapter. A link into its own
containing definition is classified as local, pending review of the actual
defining passage. Chapters absent from the table of contents have unknown
relative order; repair the table of contents before treating such a dependency
as backward. Candidate cycles are reported without treating them as justified
forward references.
Future notes receive the same link audits: proposals need readable explanations too. These editorial reviews do not claim that a proposal has a formalization.
#![allow(unused)]
fn main() {
pub fn build(inventory: &Inventory) -> Result<Self> {
let markdown_root = inventory::relative_path(
&inventory.root,
&inventory
.source_configuration
.markdown_root(&inventory.root)?,
)?;
let summary_path = format!("{markdown_root}/SUMMARY.md");
let summary = inventory
.sources
.get(&summary_path)
.context("link order requires the configured book's SUMMARY.md")?;
let mut chapters = Vec::new();
let mut chapter_orders = BTreeMap::new();
for (event, range) in Parser::new(summary).into_offset_iter() {
if let Event::Start(Tag::Link { dest_url, .. }) = event {
ensure!(
!external(&dest_url)?,
"{summary_path}:{}: external SUMMARY entries have no source order",
location(&summary_path, summary, range.clone()).line
);
ensure!(
!dest_url.contains(['#', '?']),
"{summary_path}: SUMMARY chapters cannot contain fragments or queries"
);
let path = chapter_path(&summary_path, &dest_url, &markdown_root)?;
ensure!(
inventory.sources.contains_key(&path),
"{summary_path}: SUMMARY references missing chapter `{path}`"
);
ensure!(
!chapter_orders.contains_key(&path),
"{summary_path}: duplicate chapter `{path}` makes reading order ambiguous"
);
let order = chapters.len();
chapter_orders.insert(path.clone(), order);
chapters.push(Chapter {
path,
order,
summary_location: location(&summary_path, summary, range),
});
}
}
let mut targets = BTreeMap::new();
let mut global_anchors = BTreeMap::new();
let mut documents = BTreeMap::new();
for (path, source) in &inventory.sources {
let doc = document(source, path)?;
let chapter_order = chapter_orders.get(path).copied();
insert_target(
&mut targets,
Target {
key: path.clone(),
location: location(path, source, 0..source.len()),
anchor_location: location(path, source, 0..0),
kind: TargetKind::Chapter,
unit_id: None,
chapter_order,
},
)?;
for unit in inventory
.units
.values()
.filter(|unit| &unit.source_path == path)
{
let key = format!("{path}#claim-{}", unit.id);
ensure!(
global_anchors
.insert(unit.id.clone(), key.clone())
.is_none(),
"{path}:{}: duplicate anchor `{}`",
location(path, source, unit.range.clone()).line,
unit.id
);
// The generated anchor is on the unit header, not at the actual
// defining sentence. Target review must inspect the complete unit.
insert_target(
&mut targets,
Target {
key,
location: location(path, source, unit.range.clone()),
anchor_location: location(
path,
source,
unit.range.start
..unit.range.start
+ unit.raw.find('\n').map_or(unit.raw.len(), |end| end + 1),
),
kind: TargetKind::Unit,
unit_id: Some(unit.id.clone()),
chapter_order,
},
)?;
}
for role in crate::roles(&doc.markdown)? {
if role.definition {
let key = format!("{path}#claim-{}", role.id);
ensure!(
global_anchors
.insert(role.id.clone(), key.clone())
.is_none(),
"{path}:{}: duplicate anchor `{}`",
location(path, source, role.range.clone()).line,
role.id
);
let unit_id = inventory
.units
.values()
.find(|unit| {
unit.source_path == *path && unit.range.contains(&role.range.start)
})
.map(|unit| unit.id.clone());
insert_target(
&mut targets,
Target {
key,
location: location(path, source, role.range.clone()),
anchor_location: location(path, source, role.range),
kind: TargetKind::LegacyAnchor,
unit_id,
chapter_order,
},
)?;
}
}
let mut heading = None;
let mut used = BTreeSet::new();
let mut headings = Vec::new();
for (event, range) in Parser::new_ext(&doc.markdown, Options::ENABLE_HEADING_ATTRIBUTES)
.into_offset_iter()
{
match event {
Event::Start(Tag::Heading { id, level, .. }) => {
heading = Some((range, level, id.map(|id| id.into_string()), String::new()))
}
Event::Text(text) | Event::Code(text) if heading.is_some() => {
heading.as_mut().unwrap().3.push_str(&text)
}
Event::End(TagEnd::Heading(_)) => {
if let Some((range, level, explicit, text)) = heading.take() {
let base = explicit.unwrap_or_else(|| slug(&text));
let mut id = base.clone();
let mut suffix = 0;
while !used.insert(id.clone()) {
suffix += 1;
id = format!("{base}-{suffix}");
}
headings.push((range, level, id));
}
}
_ => {}
}
}
for (index, (range, level, id)) in headings.iter().enumerate() {
let unit = inventory
.units
.values()
.find(|unit| unit.source_path == *path && unit.range.contains(&range.start));
let end = headings[index + 1..]
.iter()
.find(|(_, next_level, _)| next_level <= level)
.map_or(source.len(), |(next, _, _)| next.start)
.min(unit.map_or(source.len(), |unit| unit.range.end));
insert_target(
&mut targets,
Target {
key: format!("{path}#{id}"),
location: location(path, source, range.start..end),
anchor_location: location(path, source, range.clone()),
kind: TargetKind::Heading,
unit_id: unit.map(|unit| unit.id.clone()),
chapter_order,
},
)?;
}
let boundaries: Vec<_> = targets
.values()
.filter(|target| {
target.location.path == *path && target.kind != TargetKind::Chapter
})
.map(|target| target.anchor_location.range.start)
.collect();
for target in targets.values_mut().filter(|target| {
target.location.path == *path && target.kind == TargetKind::LegacyAnchor
}) {
let end = if let Some(unit) = target
.unit_id
.as_ref()
.and_then(|id| inventory.units.get(id))
{
unit.range.end
} else {
boundaries
.iter()
.copied()
.filter(|start| *start > target.location.range.start)
.min()
.unwrap_or(source.len())
};
target.location.range.end = end;
}
documents.insert(path.clone(), doc);
}
let mut sources = BTreeMap::new();
for unit in inventory.units.values() {
let source = &inventory.sources[&unit.source_path];
let mut occurrences = Vec::new();
for raw in documents[&unit.source_path]
.links
.iter()
.filter(|link| unit.range.contains(&link.range.start))
{
let source_location = location(&unit.source_path, source, raw.range.clone());
let target = resolve(
raw,
&unit.source_path,
&markdown_root,
inventory,
&targets,
&global_anchors,
)
.with_context(|| {
format!(
"{}:{}: link `{}`",
source_location.path, source_location.line, raw.destination
)
})?;
if let LinkTarget::Internal { target } = &target {
ensure!(
!chapter_orders.contains_key(&unit.source_path) || target.chapter_order.is_some(),
"{}:{}: published chapter links to unpublished target `{}`; add the target chapter to SUMMARY.md so its .html page exists",
source_location.path, source_location.line, target.key
);
}
let direction = match &target {
LinkTarget::Internal { target }
if target.unit_id.as_deref() == Some(&unit.id)
|| (target.location.path == unit.source_path
&& target.location.range.contains(&raw.range.start)) =>
{
Direction::Local
}
LinkTarget::Internal { target } if target.location.path == unit.source_path => {
if target.location.range.start < raw.range.start {
Direction::Backward
} else {
Direction::Forward
}
}
LinkTarget::Internal { target } => {
match (chapter_orders.get(&unit.source_path), target.chapter_order) {
(Some(from), Some(to)) if *from < to => Direction::Forward,
(Some(_), Some(_)) => Direction::Backward,
_ => Direction::Unordered,
}
}
_ => Direction::External,
};
occurrences.push(LinkOccurrence {
id: format!("{}:{}", unit.id, occurrences.len() + 1),
source: source_location,
destination: raw.destination.clone(),
label: raw.label.clone(),
syntax: raw.syntax,
target,
direction,
});
}
sources.insert(
unit.id.clone(),
SourceLinks {
unit_id: unit.id.clone(),
unit_kind: unit.kind,
audit_required: true,
location: location(&unit.source_path, source, unit.range.clone()),
occurrences,
},
);
}
let cycles = cycles(&sources);
Ok(Self {
sources,
chapters,
targets,
cycles,
summary_path,
})
}
}
#![allow(unused)]
fn main() {
#[test]
fn inventory_reads_markdown_reference_roles_and_math_with_exact_ranges() {
let body = r"A [direct link](second.html#claim-second), [reference][ref], and {anchor-ref}`second`.
\\[ \href{second.html#claim-second}{\operatorname{target}_{x}} \\]
[ref]: second.md#claim-second
`[literal](missing.md)` and `\href{missing.md}{literal}`.
```text
[literal](missing.md)
\\[ \href{missing.md}{literal} \\]
```
<!-- [comment](missing.md) \\(\href{missing.md}{comment}\\) -->";
let first = unit("first", body);
let fixture = Fixture::new(
"[First](first.md)\n- [Second](second.md)\n",
&[
("first.md", first.clone()),
("second.md", unit("second", "Definition.")),
],
);
let inventory = fixture.inventory();
let links = Links::build(&inventory).unwrap();
let occurrences = &links.sources["first"].occurrences;
assert_eq!(occurrences.len(), 4);
assert_eq!(
occurrences
.iter()
.map(|link| link.syntax)
.collect::<Vec<_>>(),
[
LinkSyntax::Markdown,
LinkSyntax::Markdown,
LinkSyntax::AnchorRef,
LinkSyntax::MathJax
]
);
for link in occurrences {
assert_eq!(link.direction, Direction::Forward);
assert!(first[link.source.range.clone()].contains(
if link.syntax == LinkSyntax::Markdown {
"["
} else if link.syntax == LinkSyntax::MathJax {
"\\href"
} else {
"{anchor-ref}"
}
));
assert!(
matches!(&link.target, LinkTarget::Internal { target } if target.key == "md/second.md#claim-second")
);
assert!(links.occurrence(&link.id).is_some());
}
assert_eq!(links.inputs(&inventory).len(), inventory.sources.len());
}
}
#![allow(unused)]
fn main() {
#[test]
fn reference_definitions_outside_unit_and_bare_math_directives_are_inventoried() {
let first = format!(
"{}\n[outside]: second.md#claim-second\n",
unit("first", "See [the definition][outside].")
);
let math = "```{grammar} grammar\n:status: draft\n\np ::= \\href{second.html#claim-second}{x}\\mid p.f\n```\n".to_owned();
let fixture = Fixture::new(
"- [First](first.md)\n- [Math](math.md)\n- [Second](second.md)",
&[
("first.md", first),
("math.md", math),
("second.md", unit("second", "Definition.")),
],
);
let links = fixture.build().unwrap();
assert_eq!(links.sources["first"].occurrences.len(), 1);
assert_eq!(links.sources["grammar"].occurrences.len(), 1);
assert_eq!(
links.sources["grammar"].occurrences[0].syntax,
LinkSyntax::MathJax
);
}
}
#![allow(unused)]
fn main() {
#[test]
fn relative_paths_preserve_target_chapter_and_wrong_path_does_not_match_global_id() {
let fixture = Fixture::new(
"- [A](nested/a.md)\n- [B](b.md)",
&[
("nested/a.md", unit("a", "[B](.././b.html#claim-b)")),
("b.md", unit("b", "B.")),
],
);
assert!(
matches!(&fixture.build().unwrap().sources["a"].occurrences[0].target, LinkTarget::Internal { target } if target.key == "md/b.md#claim-b")
);
fs::write(
fixture.0.join("md/nested/a.md"),
unit("a", "[B](a.md#claim-b)"),
)
.unwrap();
let error = format!("{:#}", fixture.build().unwrap_err());
assert!(error.contains("md/nested/a.md:4"), "{error}");
assert!(error.contains("path and anchor"), "{error}");
}
}
#![allow(unused)]
fn main() {
#[test]
fn order_comes_from_summary_and_byte_position_not_filename_or_unit_id() {
let fixture = Fixture::new("[Last filename first](z.md)\n- [Group](group.md)\n - [Then A](a.md)\n\n[Appendix](appendix.md)", &[
("z.md", unit("z", "[forward](a.md#claim-a)")),
("group.md", "# Group".into()),
("a.md", format!("{}{}", unit("a", "[back](z.md#claim-z), [later](#claim-local), [self](#claim-a)"), unit("local", "[earlier](#claim-a)"))),
("appendix.md", unit("appendix", "[earlier](a.md#claim-a)")),
("hidden.md", unit("hidden", "[unordered](a.md#claim-a)")),
]);
let links = fixture.build().unwrap();
assert_eq!(
links
.chapters
.iter()
.map(|c| c.path.as_str())
.collect::<Vec<_>>(),
["md/z.md", "md/group.md", "md/a.md", "md/appendix.md"]
);
assert_eq!(
links.sources["z"].occurrences[0].direction,
Direction::Forward
);
assert_eq!(
links.sources["a"]
.occurrences
.iter()
.map(|l| l.direction)
.collect::<Vec<_>>(),
[Direction::Backward, Direction::Forward, Direction::Local]
);
assert_eq!(
links.sources["hidden"].occurrences[0].direction,
Direction::Unordered
);
assert!(links
.cycles
.iter()
.any(|cycle| cycle == &["a", "local", "z"]));
}
}
#![allow(unused)]
fn main() {
#[test]
fn configured_renderer_rejects_a_correct_claim_in_the_wrong_chapter() {
let fixture = Fixture::new();
fixture.write("md/other.md", "# Other chapter\n");
let source = MODEL.replace(
"The empty list has no variables:",
"[Variables](other.md#claim-model.variable) are the list elements:",
);
fixture.write("md/model.md", &source);
let mut book = chapter(&source);
let error = mdbook_dada::process_configured(&configured_context(&fixture, "lean"), &mut book)
.unwrap_err();
let diagnostic = format!("{error:#}");
assert!(diagnostic.contains("md/model.md:"), "{diagnostic}");
assert!(
diagnostic.contains("other.md#claim-model.variable"),
"{diagnostic}"
);
}
}
Review three questions
A link-coverage review examines one complete unit, including prose, inline math, and display math. Every referenced concept, operation, judgment, and equation must have a definition link. The defining occurrence needs no self-link, and locally bound variables need an introduction and scope rather than links.
The review explains coverage separately for prose and mathematics and classifies every occurrence in the link inventory as conceptual or navigation, with a reason. A navigation link offers optional further reading; it cannot stand in for a definition the passage needs. Reviewers must also look for unlinked uses: the extractor cannot discover a missing link by examining existing links alone.
The validator requires exactly the extracted occurrence set, including repeated links. Missing, extra, or duplicate assessments fail. It checks the existence and freshness of the review, not whether its coverage judgment is correct.
#![allow(unused)]
fn main() {
pub fn build(inventory: &Inventory) -> Result<Self> {
let links = LinkInventory::build(inventory)?;
let mut manifests = BTreeMap::new();
for source in links
.sources
.values()
.filter(|source| source.audit_required)
{
let coverage = Manifest::Coverage {
source: source.clone(),
};
manifests.insert(coverage.subject(), coverage);
for occurrence in &source.occurrences {
if let LinkTarget::Internal { target } = &occurrence.target {
let target = Manifest::Target {
target: target.clone(),
};
manifests.insert(target.subject(), target);
if matches!(
occurrence.direction,
Direction::Forward | Direction::Local | Direction::Unordered
) {
let forward = Manifest::Forward {
source_unit: source.unit_id.clone(),
source: source.location.clone(),
occurrence: occurrence.clone(),
};
manifests.insert(forward.subject(), forward);
}
}
}
}
Ok(Self { links, manifests })
}
}
#![allow(unused)]
fn main() {
/// Validate against the bundle's immutable manifest as well as the general
/// review schema. Current-source comparison remains the evidence engine's job.
pub fn validate_review(bundle: &ReviewBundle, review: &ReviewRecord) -> Vec<String> {
if !is_subject(&bundle.unit) {
return if review.audit.is_some() {
vec!["correspondence review cannot carry a link audit assessment".into()]
} else {
Vec::new()
};
}
let manifest = match manifest(bundle) {
Ok(manifest) => manifest,
Err(error) => return vec![format!("{error:#}")],
};
let Some(assessment) = &review.audit else {
return vec!["link audit review requires a purpose-specific audit assessment".into()];
};
let mut errors = Vec::new();
match (&manifest, assessment) {
(
Manifest::Coverage { source },
Assessment::Coverage {
prose,
mathematics,
links,
},
) => {
nonempty(&mut errors, "prose coverage rationale", prose);
nonempty(&mut errors, "mathematics coverage rationale", mathematics);
let expected: BTreeSet<_> = source
.occurrences
.iter()
.map(|link| link.id.as_str())
.collect();
let actual: BTreeSet<_> = links.iter().map(|link| link.occurrence.as_str()).collect();
if actual.len() != links.len() {
errors.push("duplicate link occurrence assessment".into());
}
if actual != expected {
errors
.push("coverage must classify exactly every generated link occurrence".into());
}
for link in links {
nonempty(
&mut errors,
"link classification rationale",
&link.rationale,
);
if review.conclusion == Conclusion::Corresponds
&& link.role == LinkRole::Conceptual
&& source.occurrences.iter().any(|occurrence| {
occurrence.id == link.occurrence
&& !matches!(occurrence.target, LinkTarget::Internal { .. })
})
{
errors.push("conceptual links need a local, snapshotted defining target; external and asset links may only be navigation/source citations".into());
}
}
}
(
Manifest::Target { target },
Assessment::Target {
subject,
definition,
clarity,
independence,
},
) => {
nonempty(&mut errors, "target subject", subject);
nonempty(&mut errors, "target clarity rationale", clarity);
nonempty(&mut errors, "target independence rationale", independence);
errors.extend(span_errors(bundle, definition, &target.location));
}
(Manifest::Forward { .. }, Assessment::Forward { assessment }) => match assessment {
OrderAssessment::Forward {
necessity,
signposting,
signpost,
minimal_use,
} => {
for (name, value) in [
(
"necessity (including rearrangement alternatives)",
necessity,
),
("explicit forward signposting", signposting),
("minimal reliance", minimal_use),
] {
nonempty(&mut errors, name, value);
}
// The source-unit range is independently derived and hashed in
// the manifest, rather than trusting mutable retrieval line numbers.
if let Manifest::Forward { source, .. } = &manifest {
errors.extend(span_errors(bundle, signpost, source));
}
}
OrderAssessment::Backward { rationale } | OrderAssessment::Navigation { rationale } => {
nonempty(&mut errors, "order disposition rationale", rationale)
}
},
_ => {
errors.push("audit assessment has the wrong purpose for this generated subject".into())
}
}
errors
}
}
#![allow(unused)]
fn main() {
#[test]
fn coverage_requires_each_occurrence_once_and_both_prose_and_math_rationales() {
let fixture = Fixture::new();
let bundle = fixture.prepare("links.coverage/alpha");
for mutation in 0..4 {
let mut review = synthetic_review(&bundle);
if let Some(Assessment::Coverage {
prose,
mathematics,
links,
}) = &mut review.audit
{
match mutation {
0 => links.clear(),
1 => links.push(links[0].clone()),
2 => prose.clear(),
_ => mathematics.clear(),
}
}
assert!(!evidence::validate_review(&bundle, &review).is_empty());
}
let mut review = synthetic_review(&bundle);
review.audit = None;
assert!(!evidence::validate_review(&bundle, &review).is_empty());
}
}
#![allow(unused)]
fn main() {
#[test]
fn complete_link_audits_pass_but_preparation_alone_does_not() {
let fixture = Fixture::new();
for id in fixture.ids() {
evidence::save_bundle(&fixture.inventory(), &fixture.prepare(&id)).unwrap();
}
let report = evidence::check(&fixture.inventory()).unwrap();
assert!(!report.is_ok());
assert!(report
.issues
.iter()
.any(|issue| issue.unit.as_deref() == Some("links.coverage/alpha")));
fixture.complete();
let report = evidence::check(&fixture.inventory()).unwrap();
assert!(report.is_ok(), "{}", report.render(&fixture.inventory()));
}
}
#![allow(unused)]
fn main() {
#[test]
fn conceptual_external_links_require_an_inspectable_local_definition() {
let fixture = Fixture::new();
fixture.write(
"md/model.md",
&SOURCE.replace(
"[Beta](#claim-beta)",
"[Beta](https://example.invalid/beta)",
),
);
let bundle = fixture.prepare("links.coverage/alpha");
let mut review = synthetic_review(&bundle);
assert!(evidence::validate_review(&bundle, &review)
.iter()
.any(|error| error.contains("local, snapshotted")));
review.conclusion = Conclusion::Mismatch;
assert!(evidence::validate_review(&bundle, &review).is_empty());
}
}
A target-clarity review names a subject in the link inventory and selects its defining passage in the retained source. It explains why the landing immediately identifies that subject and why the definition is independently understandable. A precise source span does not excuse a buried destination: split the block or retarget the link when a reader would still have to search.
The validator checks that the selected span is nonempty UTF-8 text within the resolved destination. Review supplies the judgment that it is the relevant definition. A chapter or section link used only for navigation is reviewed as such; it must not be presented as a precise concept definition.
#![allow(unused)]
fn main() {
/// Validate against the bundle's immutable manifest as well as the general
/// review schema. Current-source comparison remains the evidence engine's job.
pub fn validate_review(bundle: &ReviewBundle, review: &ReviewRecord) -> Vec<String> {
if !is_subject(&bundle.unit) {
return if review.audit.is_some() {
vec!["correspondence review cannot carry a link audit assessment".into()]
} else {
Vec::new()
};
}
let manifest = match manifest(bundle) {
Ok(manifest) => manifest,
Err(error) => return vec![format!("{error:#}")],
};
let Some(assessment) = &review.audit else {
return vec!["link audit review requires a purpose-specific audit assessment".into()];
};
let mut errors = Vec::new();
match (&manifest, assessment) {
(
Manifest::Coverage { source },
Assessment::Coverage {
prose,
mathematics,
links,
},
) => {
nonempty(&mut errors, "prose coverage rationale", prose);
nonempty(&mut errors, "mathematics coverage rationale", mathematics);
let expected: BTreeSet<_> = source
.occurrences
.iter()
.map(|link| link.id.as_str())
.collect();
let actual: BTreeSet<_> = links.iter().map(|link| link.occurrence.as_str()).collect();
if actual.len() != links.len() {
errors.push("duplicate link occurrence assessment".into());
}
if actual != expected {
errors
.push("coverage must classify exactly every generated link occurrence".into());
}
for link in links {
nonempty(
&mut errors,
"link classification rationale",
&link.rationale,
);
if review.conclusion == Conclusion::Corresponds
&& link.role == LinkRole::Conceptual
&& source.occurrences.iter().any(|occurrence| {
occurrence.id == link.occurrence
&& !matches!(occurrence.target, LinkTarget::Internal { .. })
})
{
errors.push("conceptual links need a local, snapshotted defining target; external and asset links may only be navigation/source citations".into());
}
}
}
(
Manifest::Target { target },
Assessment::Target {
subject,
definition,
clarity,
independence,
},
) => {
nonempty(&mut errors, "target subject", subject);
nonempty(&mut errors, "target clarity rationale", clarity);
nonempty(&mut errors, "target independence rationale", independence);
errors.extend(span_errors(bundle, definition, &target.location));
}
(Manifest::Forward { .. }, Assessment::Forward { assessment }) => match assessment {
OrderAssessment::Forward {
necessity,
signposting,
signpost,
minimal_use,
} => {
for (name, value) in [
(
"necessity (including rearrangement alternatives)",
necessity,
),
("explicit forward signposting", signposting),
("minimal reliance", minimal_use),
] {
nonempty(&mut errors, name, value);
}
// The source-unit range is independently derived and hashed in
// the manifest, rather than trusting mutable retrieval line numbers.
if let Manifest::Forward { source, .. } = &manifest {
errors.extend(span_errors(bundle, signpost, source));
}
}
OrderAssessment::Backward { rationale } | OrderAssessment::Navigation { rationale } => {
nonempty(&mut errors, "order disposition rationale", rationale)
}
},
_ => {
errors.push("audit assessment has the wrong purpose for this generated subject".into())
}
}
errors
}
}
#![allow(unused)]
fn main() {
#[test]
fn target_spans_cannot_escape_or_select_empty_text() {
let fixture = Fixture::new();
let bundle = fixture.prepare(&link_audit::target_subject("md/model.md#claim-beta"));
for mutation in 0..4 {
let mut review = synthetic_review(&bundle);
if let Some(Assessment::Target {
definition,
clarity,
..
}) = &mut review.audit
{
match mutation {
0 => definition.path = "md/other.md".into(),
1 => definition.start = 0,
2 => definition.end = definition.start,
_ => clarity.clear(),
}
}
assert!(!evidence::validate_review(&bundle, &review).is_empty());
}
fixture.write(
"md/model.md",
&SOURCE.replace("Beta denotes", "Beta α denotes"),
);
let bundle = fixture.prepare(&link_audit::target_subject("md/model.md#claim-beta"));
let mut review = synthetic_review(&fixture.prepare("links.coverage/alpha"));
let chapter = &bundle
.inputs
.iter()
.find(|input| input.key == "context:link-chapter:md/model.md")
.unwrap()
.content;
let offset = chapter.find('α').unwrap();
review.bundle = bundle.digest.clone();
review.examined = bundle
.inputs
.iter()
.filter(|input| input.requires_examination())
.map(|input| input.key.clone())
.collect();
review.audit = Some(Assessment::Target {
subject: "Beta".into(),
definition: DefinitionSpan {
path: "md/model.md".into(),
start: offset + 1,
end: offset + 2,
},
clarity: "Synthetic clarity.".into(),
independence: "Synthetic independence.".into(),
});
assert!(evidence::validate_review(&bundle, &review)
.iter()
.any(|error| error.contains("UTF-8")));
}
}
#![allow(unused)]
fn main() {
#[test]
fn independent_positive_reviews_cannot_disagree_on_backward_links_or_target_spans() {
let fixture = Fixture::new();
fixture.complete();
let bundle = fixture.prepare("links.coverage/beta");
let mut conflict = synthetic_review(&bundle);
if let Some(Assessment::Coverage { links, .. }) = &mut conflict.audit {
links[0].role = LinkRole::Navigation;
}
evidence::record(&fixture.inventory(), &bundle, &conflict).unwrap();
let report = evidence::check(&fixture.inventory()).unwrap();
assert!(report
.issues
.iter()
.any(|issue| issue.message.contains("coverage reviews disagree")));
let bundle = fixture.prepare(&link_audit::target_subject("md/model.md#claim-alpha"));
let mut conflict = synthetic_review(&bundle);
if let Some(Assessment::Target { definition, .. }) = &mut conflict.audit {
definition.end -= 1;
}
evidence::record(&fixture.inventory(), &bundle, &conflict).unwrap();
let report = evidence::check(&fixture.inventory()).unwrap();
assert!(report
.issues
.iter()
.any(|issue| issue.message.contains("target reviews disagree")));
}
}
A reference-order review resolves each forward, local, or unordered internal occurrence in the link inventory. It agrees with the coverage classification and uses the reviewed defining passage, not merely the block’s header, to establish whether a concept has already been introduced.
Prefer moving the definition earlier, moving its use later, or splitting a multi-part explanation. Retaining a forward conceptual reference requires all three explanations:
- Necessity: which rearrangements were considered and why they would prevent a coherent introduction.
- Signposting: the exact source passage that explicitly tells the reader the definition comes later, and where to find it.
- Minimal use: the facts needed at this point, where the text states them, and which details it defers.
A motivating example may justify a forward reference; being an example is not an automatic exemption. A dependency cycle is not an exemption either. Navigation-only links need an explicit classification, and a local backward reference must point to a defining passage before its use. Conflicting active reviews block validation.
#![allow(unused)]
fn main() {
pub fn build(inventory: &Inventory) -> Result<Self> {
let links = LinkInventory::build(inventory)?;
let mut manifests = BTreeMap::new();
for source in links
.sources
.values()
.filter(|source| source.audit_required)
{
let coverage = Manifest::Coverage {
source: source.clone(),
};
manifests.insert(coverage.subject(), coverage);
for occurrence in &source.occurrences {
if let LinkTarget::Internal { target } = &occurrence.target {
let target = Manifest::Target {
target: target.clone(),
};
manifests.insert(target.subject(), target);
if matches!(
occurrence.direction,
Direction::Forward | Direction::Local | Direction::Unordered
) {
let forward = Manifest::Forward {
source_unit: source.unit_id.clone(),
source: source.location.clone(),
occurrence: occurrence.clone(),
};
manifests.insert(forward.subject(), forward);
}
}
}
}
Ok(Self { links, manifests })
}
}
#![allow(unused)]
fn main() {
/// Validate against the bundle's immutable manifest as well as the general
/// review schema. Current-source comparison remains the evidence engine's job.
pub fn validate_review(bundle: &ReviewBundle, review: &ReviewRecord) -> Vec<String> {
if !is_subject(&bundle.unit) {
return if review.audit.is_some() {
vec!["correspondence review cannot carry a link audit assessment".into()]
} else {
Vec::new()
};
}
let manifest = match manifest(bundle) {
Ok(manifest) => manifest,
Err(error) => return vec![format!("{error:#}")],
};
let Some(assessment) = &review.audit else {
return vec!["link audit review requires a purpose-specific audit assessment".into()];
};
let mut errors = Vec::new();
match (&manifest, assessment) {
(
Manifest::Coverage { source },
Assessment::Coverage {
prose,
mathematics,
links,
},
) => {
nonempty(&mut errors, "prose coverage rationale", prose);
nonempty(&mut errors, "mathematics coverage rationale", mathematics);
let expected: BTreeSet<_> = source
.occurrences
.iter()
.map(|link| link.id.as_str())
.collect();
let actual: BTreeSet<_> = links.iter().map(|link| link.occurrence.as_str()).collect();
if actual.len() != links.len() {
errors.push("duplicate link occurrence assessment".into());
}
if actual != expected {
errors
.push("coverage must classify exactly every generated link occurrence".into());
}
for link in links {
nonempty(
&mut errors,
"link classification rationale",
&link.rationale,
);
if review.conclusion == Conclusion::Corresponds
&& link.role == LinkRole::Conceptual
&& source.occurrences.iter().any(|occurrence| {
occurrence.id == link.occurrence
&& !matches!(occurrence.target, LinkTarget::Internal { .. })
})
{
errors.push("conceptual links need a local, snapshotted defining target; external and asset links may only be navigation/source citations".into());
}
}
}
(
Manifest::Target { target },
Assessment::Target {
subject,
definition,
clarity,
independence,
},
) => {
nonempty(&mut errors, "target subject", subject);
nonempty(&mut errors, "target clarity rationale", clarity);
nonempty(&mut errors, "target independence rationale", independence);
errors.extend(span_errors(bundle, definition, &target.location));
}
(Manifest::Forward { .. }, Assessment::Forward { assessment }) => match assessment {
OrderAssessment::Forward {
necessity,
signposting,
signpost,
minimal_use,
} => {
for (name, value) in [
(
"necessity (including rearrangement alternatives)",
necessity,
),
("explicit forward signposting", signposting),
("minimal reliance", minimal_use),
] {
nonempty(&mut errors, name, value);
}
// The source-unit range is independently derived and hashed in
// the manifest, rather than trusting mutable retrieval line numbers.
if let Manifest::Forward { source, .. } = &manifest {
errors.extend(span_errors(bundle, signpost, source));
}
}
OrderAssessment::Backward { rationale } | OrderAssessment::Navigation { rationale } => {
nonempty(&mut errors, "order disposition rationale", rationale)
}
},
_ => {
errors.push("audit assessment has the wrong purpose for this generated subject".into())
}
}
errors
}
}
#![allow(unused)]
fn main() {
/// Cross-review consistency is checked from current, active positive records.
/// No review output is smuggled into another review's source hash. A later
/// classification or defining-span change therefore causes a new check.
pub fn cross_validate(
audits: &AuditInventory,
active: &BTreeMap<String, Vec<ReviewRecord>>,
) -> Vec<(String, String)> {
let mut errors = Vec::new();
let positives = |id: &str| -> Vec<&ReviewRecord> {
active
.get(id)
.into_iter()
.flatten()
.filter(|review| review.conclusion == Conclusion::Corresponds)
.collect()
};
// Independent positive reviews cannot disagree silently, even when the
// link is unambiguously backward and needs no forward-reference subject.
for (id, records) in active {
match audits.manifests.get(id) {
Some(Manifest::Coverage { source }) => {
for occurrence in &source.occurrences {
let roles: BTreeSet<_> = records
.iter()
.filter_map(|review| match &review.audit {
Some(Assessment::Coverage { links, .. }) => links
.iter()
.find(|link| link.occurrence == occurrence.id)
.map(|link| match link.role {
LinkRole::Conceptual => 0,
LinkRole::Navigation => 1,
}),
_ => None,
})
.collect();
if roles.len() > 1 {
errors.push((
id.clone(),
format!("active coverage reviews disagree about {}", occurrence.id),
));
}
}
}
Some(Manifest::Target { .. }) => {
let definitions: Vec<_> = records
.iter()
.filter_map(|review| match &review.audit {
Some(Assessment::Target { definition, .. }) => Some(definition),
_ => None,
})
.collect();
if definitions.windows(2).any(|pair| pair[0] != pair[1]) {
errors.push((
id.clone(),
"active target reviews disagree about the defining occurrence".into(),
));
}
}
_ => {}
}
}
for (id, records) in active {
let Some(Manifest::Forward {
source_unit,
occurrence,
..
}) = audits.manifests.get(id)
else {
continue;
};
let LinkTarget::Internal { target } = &occurrence.target else {
continue;
};
let coverage = positives(&coverage_subject(source_unit));
let targets = positives(&target_subject(&target.key));
let roles: BTreeSet<_> = coverage
.iter()
.filter_map(|review| match &review.audit {
Some(Assessment::Coverage { links, .. }) => links
.iter()
.find(|link| link.occurrence == occurrence.id)
.map(|link| match link.role {
LinkRole::Conceptual => 0,
LinkRole::Navigation => 1,
}),
_ => None,
})
.collect();
if coverage.is_empty() || targets.is_empty() {
continue;
} // Their missing evidence is separately blocking.
if roles.len() != 1 {
errors.push((
id.clone(),
"active coverage reviews disagree about this link's conceptual role".into(),
));
continue;
}
let role = *roles.first().unwrap();
let definitions: Vec<_> = targets
.iter()
.filter_map(|review| match &review.audit {
Some(Assessment::Target { definition, .. }) => Some(definition),
_ => None,
})
.collect();
for review in records
.iter()
.filter(|review| review.conclusion == Conclusion::Corresponds)
{
let Some(Assessment::Forward { assessment }) = &review.audit else {
continue;
};
let valid = match assessment {
OrderAssessment::Navigation { .. } => role == 1,
OrderAssessment::Forward { .. } => {
role == 0
&& !definitions.is_empty()
&& definitions.iter().all(|definition| {
matches!(
definition_direction(&audits.links, occurrence, target, definition),
Direction::Forward | Direction::Unordered
)
})
}
OrderAssessment::Backward { .. } => {
role == 0
&& !definitions.is_empty()
&& definitions.iter().all(|definition| {
definition_direction(&audits.links, occurrence, target, definition)
== Direction::Backward
})
}
};
if !valid {
errors.push((id.clone(), "order disposition disagrees with current coverage or the actual defining occurrence".into()));
}
}
}
errors
}
}
#![allow(unused)]
fn main() {
#[test]
fn forward_exceptions_require_all_three_reasons_and_a_real_source_span() {
let fixture = Fixture::new();
let bundle = fixture.prepare(&fixture.candidate("alpha"));
for mutation in 0..4 {
let mut review = synthetic_review(&bundle);
if let Some(Assessment::Forward {
assessment:
OrderAssessment::Forward {
necessity,
signposting,
signpost,
minimal_use,
},
}) = &mut review.audit
{
match mutation {
0 => necessity.clear(),
1 => signposting.clear(),
2 => minimal_use.clear(),
_ => signpost.start = 0,
}
}
assert!(!evidence::validate_review(&bundle, &review).is_empty());
}
}
}
#![allow(unused)]
fn main() {
#[test]
fn a_local_link_before_its_actual_definition_cannot_be_called_backward() {
let fixture = Fixture::new();
fixture.complete();
let id = fixture.candidate("local");
let bundle = fixture.prepare(&id);
let mut review = synthetic_review(&bundle);
review.audit = Some(Assessment::Forward {
assessment: OrderAssessment::Backward {
rationale: "The block anchor is earlier; this is insufficient.".into(),
},
});
fixture.save_replacement(&id, review);
let report = evidence::check(&fixture.inventory()).unwrap();
assert!(report
.issues
.iter()
.any(|issue| issue.message.contains("actual defining occurrence")));
}
}
#![allow(unused)]
fn main() {
#[test]
fn navigation_exemption_must_agree_with_current_coverage() {
let fixture = Fixture::new();
fixture.complete();
let id = fixture.candidate("alpha");
let bundle = fixture.prepare(&id);
let mut review = synthetic_review(&bundle);
review.audit = Some(Assessment::Forward {
assessment: OrderAssessment::Navigation {
rationale: "Synthetic navigation classification.".into(),
},
});
fixture.save_replacement(&id, review);
assert!(!evidence::check(&fixture.inventory()).unwrap().is_ok());
let coverage_id = "links.coverage/alpha";
let mut coverage = synthetic_review(&fixture.prepare(coverage_id));
if let Some(Assessment::Coverage { links, .. }) = &mut coverage.audit {
links[0].role = LinkRole::Navigation;
}
fixture.save_replacement(coverage_id, coverage);
let report = evidence::check(&fixture.inventory()).unwrap();
assert!(report.is_ok(), "{}", report.render(&fixture.inventory()));
}
}
#![allow(unused)]
fn main() {
#[test]
fn source_movement_summary_order_and_reference_definitions_invalidate_inputs() {
let fixture = Fixture::new();
let bundle = fixture.prepare("links.coverage/alpha");
fixture.write("md/model.md", &format!("\n{SOURCE}"));
assert!(!evidence::validate_bundle(&fixture.inventory(), &bundle)
.unwrap()
.is_empty());
fixture.write("md/model.md", SOURCE);
fixture.write("md/other.md", "# Other\n");
fixture.write(
"md/SUMMARY.md",
"# Summary\n\n- [Other](other.md)\n- [Fixture](model.md)\n",
);
assert!(!evidence::validate_bundle(&fixture.inventory(), &bundle)
.unwrap()
.is_empty());
fixture.write(
"md/model.md",
&SOURCE
.replace("[Beta](#claim-beta)", "[Beta][beta-ref]")
.replace(
"Beta denotes the second thing.",
"Beta denotes the second thing.\n\n[beta-ref]: #claim-beta\n",
),
);
let bundle = fixture.prepare("links.coverage/alpha");
let changed = fs::read_to_string(fixture.0.join("md/model.md"))
.unwrap()
.replace("[beta-ref]: #claim-beta", "[beta-ref]: #claim-alpha");
fixture.write("md/model.md", &changed);
assert!(!evidence::validate_bundle(&fixture.inventory(), &bundle)
.unwrap()
.is_empty());
}
}
Prepare and record evidence
Use the subject IDs printed by dada-spec links with the existing
preparation and recording workflow:
dada-spec prepare links.coverage/UNIT_ID
dada-spec prepare links.target/TARGET_HASH
dada-spec prepare links.forward/OCCURRENCE_HASH
dada-spec record BUNDLE_PATH REVIEW_JSON_PATH
Each decision retains the ordinary reviewer, provenance, examined inputs,
conclusion, rationale, limitations, and superseded decisions. Its audit field
adds the question-specific assessment. See the Rust Assessment schema in
mdbook-dada/src/link_audit.rs for the exact JSON fields. Preparation never
creates an affirmative decision.
Coverage packets retain the complete source unit, its explicit context, and
linked destinations. Target packets retain the destination. Order packets
retain both ends. All three also retain relevant complete chapters, a serialized
position/order inventory, SUMMARY.md, policy, and tool/rendering inputs.
Reviewers examine the required audit: inputs and consult the retained chapter
context to assess landing clarity and possible rearrangements. Byte positions
participate in freshness, so moving unchanged text can invalidate an audit.
Whole-chapter snapshots conservatively invalidate affected audits after other
edits in those chapters too.
Evidence outputs are not inputs to other evidence; current active decisions are
cross-checked for consistency instead.
dada-spec check and cargo test --workspace require these reviews alongside
formal correspondence evidence. Draft units still receive editorial audits;
their unfinished formalization separately blocks correspondence. The checker
never invokes an agent, fetches a website, or decides whether a rationale is
persuasive. An independent reader can inspect the retained inputs and reasoning.