pub const EXPECTATIONS_SCHEMA_VERSION: u32 = 1;
#[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TextView {
Final,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct Target {
pub short_id: String,
pub long_id: String,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CheckKind {
TextEquals,
TextContains,
TextAbsent,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct Check {
pub kind: CheckKind,
pub target: Target,
pub text: String,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct Requirement {
pub key: String,
pub description: String,
pub checks: Vec<Check>,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct Source {
pub sha256: String,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct ExpectationsV1 {
pub schema_version: u32,
pub source: Source,
pub text_view: TextView,
pub requirements: Vec<Requirement>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Outcome {
Passed,
Failed,
Refused,
Unassessed,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RefusalReason {
TargetMissing,
Merged,
Split,
Ambiguous,
Unsupported,
StaleSource,
InvalidOutput,
StaleCorrespondence,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct CheckOutcome {
pub key: String,
pub target: String,
pub kind: CheckKind,
pub outcome: Outcome,
pub evidence: Option<String>,
pub reason: Option<RefusalReason>,
}
fn is_false(value: &bool) -> bool {
!*value
}
impl std::fmt::Display for RefusalReason {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let name = match self {
Self::TargetMissing => "target missing",
Self::Merged => "merged target",
Self::Split => "split or removed target",
Self::Ambiguous => "ambiguous target ids",
Self::Unsupported => "unsupported target",
Self::StaleSource => "stale source binding",
Self::InvalidOutput => "unopenable output",
Self::StaleCorrespondence => "stale correspondence",
};
f.write_str(name)
}
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct ExpectationReceipt {
pub schema_version: u32,
pub source_sha256: String,
pub expectations_sha256: Option<String>,
pub expectations_path: Option<String>,
pub text_view: TextView,
pub checks_run: usize,
pub checks_refused: usize,
pub checks_unsupported: usize,
pub requirements_unassessed: usize,
pub targets: Vec<String>,
pub declared_provenance: Option<String>,
#[serde(default, skip_serializing_if = "is_false")]
pub independent: bool,
#[serde(default, skip_serializing_if = "is_false")]
pub complete_task: bool,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CorrespondenceEntry {
pub short_id: String,
pub output: Vec<usize>,
pub identity_ok: bool,
}
impl ExpectationReport {
pub fn blocking_failure(&self) -> Option<&CheckOutcome> {
self.checks
.iter()
.find(|c| matches!(c.outcome, Outcome::Failed | Outcome::Refused))
}
pub fn has_blocking_failure(&self) -> bool {
self.blocking_failure().is_some()
}
}
impl CorrespondenceEntry {
pub fn one_to_one(short_id: impl Into<String>, output: usize) -> Self {
Self {
short_id: short_id.into(),
output: vec![output],
identity_ok: true,
}
}
pub fn merged(short_id: impl Into<String>, outputs: &[usize]) -> Self {
Self {
short_id: short_id.into(),
output: outputs.to_vec(),
identity_ok: true,
}
}
pub fn split(short_id: impl Into<String>) -> Self {
Self {
short_id: short_id.into(),
output: Vec::new(),
identity_ok: true,
}
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct SourceToOutputCorrespondence {
entries: Vec<CorrespondenceEntry>,
index: std::collections::HashMap<String, usize>,
}
impl SourceToOutputCorrespondence {
pub fn from_entries(entries: Vec<CorrespondenceEntry>) -> Result<Self, String> {
let mut index = std::collections::HashMap::with_capacity(entries.len());
for (position, entry) in entries.iter().enumerate() {
if index.insert(entry.short_id.clone(), position).is_some() {
return Err(format!(
"duplicate correspondence short id: {}",
entry.short_id
));
}
}
Ok(Self { entries, index })
}
pub fn entries(&self) -> &[CorrespondenceEntry] {
&self.entries
}
pub fn lookup(&self, short_id: &str) -> Option<&CorrespondenceEntry> {
self.index
.get(short_id)
.map(|&position| &self.entries[position])
}
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct ExpectationReport {
pub checks: Vec<CheckOutcome>,
pub unassessed_requirements: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub output_bound: Option<ExpectationsV1>,
pub receipt: ExpectationReceipt,
}
pub fn parse_expectations(json: &str) -> Result<ExpectationsV1, String> {
let parsed: ExpectationsV1 =
serde_json::from_str(json).map_err(|e| format!("expectations Rust type rejected: {e}"))?;
if parsed.schema_version != EXPECTATIONS_SCHEMA_VERSION {
return Err(format!(
"schema_version {} is not supported (expected {})",
parsed.schema_version, EXPECTATIONS_SCHEMA_VERSION
));
}
if !is_lowercase_hex_64(&parsed.source.sha256) {
return Err(
"source.sha256 must be exactly 64 lowercase hexadecimal characters".to_string(),
);
}
if !matches!(parsed.text_view, TextView::Final) {
return Err("text_view must be \"final\"".to_string());
}
if parsed.requirements.is_empty() {
return Err("requirements must contain at least one item".to_string());
}
let mut seen: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
for requirement in &parsed.requirements {
if !is_valid_key(&requirement.key) {
return Err(format!(
"requirement key {:?} must match ^[A-Za-z][A-Za-z0-9_.-]*$",
requirement.key
));
}
if requirement.description.is_empty() {
return Err(format!(
"requirement {:?} description must be non-empty",
requirement.key
));
}
if !seen.insert(requirement.key.as_str()) {
return Err(format!("duplicate requirement key: {}", requirement.key));
}
for check in &requirement.checks {
if check.target.short_id.is_empty() || check.target.long_id.is_empty() {
return Err(format!(
"requirement {:?} check target requires non-empty short_id and long_id",
requirement.key
));
}
if matches!(check.kind, CheckKind::TextContains | CheckKind::TextAbsent)
&& check.text.is_empty()
{
return Err(format!(
"requirement {:?} text_contains/text_absent requires non-empty text",
requirement.key
));
}
}
}
Ok(parsed)
}
fn is_lowercase_hex_64(s: &str) -> bool {
let bytes = s.as_bytes();
bytes.len() == 64
&& bytes
.iter()
.all(|&b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
fn is_valid_key(s: &str) -> bool {
let bytes = s.as_bytes();
if bytes.is_empty() {
return false;
}
let first = bytes[0];
if !first.is_ascii_alphabetic() {
return false;
}
bytes[1..]
.iter()
.all(|&b| b.is_ascii_alphanumeric() || b == b'_' || b == b'.' || b == b'-')
}
pub fn content_sha256(bytes: &[u8]) -> String {
use sha2::{Digest, Sha256};
let digest = Sha256::digest(bytes);
digest.iter().map(|b| format!("{b:02x}")).collect()
}
pub fn identity_correspondence(
source_bytes: &[u8],
) -> Result<SourceToOutputCorrespondence, String> {
let paragraphs =
projected_paragraphs(source_bytes).map_err(|e| format!("cannot open source: {e}"))?;
let entries = paragraphs
.into_iter()
.enumerate()
.map(|(index, p)| CorrespondenceEntry::one_to_one(p.id, index))
.collect();
Ok(SourceToOutputCorrespondence::from_entries(entries)
.expect("the inspector reports each paragraph id once"))
}
fn projected_paragraphs(
bytes: &[u8],
) -> Result<Vec<crate::inspect::Paragraph>, crate::inspect::InspectError> {
let mut all = crate::inspect::paragraphs(bytes)?;
for story in crate::inspect::stories(bytes)? {
all.extend(story.paragraphs);
}
Ok(all)
}
pub fn evaluate(
spec: &ExpectationsV1,
source: &[u8],
output: &[u8],
correspondence: &SourceToOutputCorrespondence,
) -> ExpectationReport {
evaluate_with_receipt(spec, source, output, correspondence, ReceiptMeta::default())
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ReceiptMeta {
pub path: Option<String>,
pub digest: Option<String>,
pub declared_provenance: Option<String>,
}
pub fn evaluate_with_receipt(
spec: &ExpectationsV1,
source: &[u8],
output: &[u8],
correspondence: &SourceToOutputCorrespondence,
meta: ReceiptMeta,
) -> ExpectationReport {
let mut checks: Vec<CheckOutcome> = Vec::new();
let mut unassessed_requirements: Vec<String> = Vec::new();
let mut targets: Vec<String> = Vec::new();
let mut seen_targets: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
let output_paragraphs = match projected_paragraphs(output) {
Ok(paragraphs) => paragraphs,
Err(error) => {
for requirement in &spec.requirements {
if requirement.checks.is_empty() {
unassessed_requirements.push(requirement.key.clone());
} else {
for check in &requirement.checks {
checks.push(CheckOutcome {
key: requirement.key.clone(),
target: check.target.short_id.clone(),
kind: check.kind,
outcome: Outcome::Refused,
evidence: Some(error.to_string()),
reason: Some(RefusalReason::InvalidOutput),
});
}
}
}
return assemble_report(spec, meta, checks, unassessed_requirements, targets);
}
};
let source_sha = content_sha256(source);
let stale_source = source_sha != spec.source.sha256;
let native_keys = native_key_inventory(source);
for requirement in &spec.requirements {
if requirement.checks.is_empty() {
unassessed_requirements.push(requirement.key.clone());
continue;
}
for check in &requirement.checks {
let target_label = check.target.short_id.clone();
if stale_source {
checks.push(CheckOutcome {
key: requirement.key.clone(),
target: target_label,
kind: check.kind,
outcome: Outcome::Refused,
evidence: Some(
"source.sha256 does not name the bytes the correspondence was built from"
.to_string(),
),
reason: Some(RefusalReason::StaleSource),
});
continue;
}
if !is_paragraph_target(&check.target.short_id) {
checks.push(CheckOutcome {
key: requirement.key.clone(),
target: target_label,
kind: check.kind,
outcome: Outcome::Refused,
evidence: Some(
"target is not a paragraph the initial profile supports".to_string(),
),
reason: Some(RefusalReason::Unsupported),
});
continue;
}
if !ids_name_one_entity(&check.target.short_id, &check.target.long_id, &native_keys) {
checks.push(CheckOutcome {
key: requirement.key.clone(),
target: target_label,
kind: check.kind,
outcome: Outcome::Refused,
evidence: Some(
"the target's short id and long id do not name the same entity".to_string(),
),
reason: Some(RefusalReason::Ambiguous),
});
continue;
}
let Some(entry) = correspondence.lookup(&check.target.short_id) else {
checks.push(CheckOutcome {
key: requirement.key.clone(),
target: target_label,
kind: check.kind,
outcome: Outcome::Refused,
evidence: Some("target is not in the correspondence".to_string()),
reason: Some(RefusalReason::TargetMissing),
});
continue;
};
if !entry.identity_ok {
checks.push(CheckOutcome {
key: requirement.key.clone(),
target: target_label,
kind: check.kind,
outcome: Outcome::Refused,
evidence: Some("target ids disagree".to_string()),
reason: Some(RefusalReason::Ambiguous),
});
continue;
}
if entry.output.is_empty() {
checks.push(CheckOutcome {
key: requirement.key.clone(),
target: target_label,
kind: check.kind,
outcome: Outcome::Refused,
evidence: Some("target mapped to no output paragraph".to_string()),
reason: Some(RefusalReason::Split),
});
continue;
}
if entry.output.len() != 1 {
checks.push(CheckOutcome {
key: requirement.key.clone(),
target: target_label,
kind: check.kind,
outcome: Outcome::Refused,
evidence: Some(format!(
"target mapped to {} output paragraphs (one-to-one required)",
entry.output.len()
)),
reason: Some(RefusalReason::Merged),
});
continue;
}
let Some(paragraph) = output_paragraphs.get(entry.output[0]) else {
checks.push(CheckOutcome {
key: requirement.key.clone(),
target: target_label,
kind: check.kind,
outcome: Outcome::Refused,
evidence: Some(format!(
"correspondence maps the target to output paragraph {}, but the \
reopened output's projection holds {} paragraphs",
entry.output[0],
output_paragraphs.len()
)),
reason: Some(RefusalReason::StaleCorrespondence),
});
continue;
};
let evidence = paragraph.text.clone();
let outcome = match check.kind {
CheckKind::TextEquals => {
if paragraph.text == check.text {
Outcome::Passed
} else {
Outcome::Failed
}
}
CheckKind::TextContains => {
if paragraph.text.contains(&check.text) {
Outcome::Passed
} else {
Outcome::Failed
}
}
CheckKind::TextAbsent => {
if paragraph.text.contains(&check.text) {
Outcome::Failed
} else {
Outcome::Passed
}
}
};
if seen_targets.insert(target_label.clone()) {
targets.push(target_label.clone());
}
checks.push(CheckOutcome {
key: requirement.key.clone(),
target: target_label,
kind: check.kind,
outcome,
evidence: Some(evidence),
reason: None,
});
}
}
assemble_report(spec, meta, checks, unassessed_requirements, targets)
}
fn assemble_report(
spec: &ExpectationsV1,
meta: ReceiptMeta,
checks: Vec<CheckOutcome>,
unassessed_requirements: Vec<String>,
targets: Vec<String>,
) -> ExpectationReport {
let checks_run = checks
.iter()
.filter(|c| matches!(c.outcome, Outcome::Passed | Outcome::Failed))
.count();
let checks_unsupported = checks
.iter()
.filter(|c| {
matches!(
(c.outcome, &c.reason),
(Outcome::Refused, Some(RefusalReason::Unsupported))
)
})
.count();
let checks_refused = checks
.iter()
.filter(|c| {
c.outcome == Outcome::Refused
&& !matches!(c.reason.as_ref(), Some(RefusalReason::Unsupported))
})
.count();
let requirements_unassessed = unassessed_requirements.len();
ExpectationReport {
checks,
unassessed_requirements,
output_bound: None,
receipt: ExpectationReceipt {
schema_version: spec.schema_version,
source_sha256: spec.source.sha256.clone(),
expectations_sha256: meta.digest,
expectations_path: meta.path,
text_view: spec.text_view,
checks_run,
checks_refused,
checks_unsupported,
requirements_unassessed,
targets,
declared_provenance: meta.declared_provenance,
independent: false,
complete_task: false,
},
}
}
fn ids_name_one_entity(
short_id: &str,
long_id: &str,
native_keys: &std::collections::HashMap<String, String>,
) -> bool {
use crate::ids::{ShortId, Story};
let Ok(short) = short_id.parse::<ShortId>() else {
return false;
};
let ShortId::Block { story, .. } = &short else {
return false;
};
let fields: Vec<&str> = long_id.splitn(4, '.').collect();
let [part, element, attribute, value] = fields.as_slice() else {
return false;
};
if *element != "w:p" {
return false;
}
let part_matches = match story {
Story::Body => *part == "document",
Story::Part(stem) => *part == stem.as_str(),
};
if !part_matches {
return false;
}
match *attribute {
"j:short" => value.parse::<ShortId>().is_ok_and(|named| named == short),
"w14:paraId" => native_keys
.get(short_id)
.is_some_and(|named| named == value),
_ => false,
}
}
fn native_key_inventory(source: &[u8]) -> std::collections::HashMap<String, String> {
let mut keys = std::collections::HashMap::new();
let Ok(opened) = crate::inspect::Opened::open(source) else {
return keys;
};
story_keys(
&opened.dom,
&crate::inspect::body_paragraph_nodes(&opened.dom, opened.body),
crate::inspect::BODY_STORY,
&mut keys,
);
for (id, _, part) in opened.story_parts() {
if let Ok((dom, _, root)) = crate::inspect::parse_part(&opened.pkg, &part) {
story_keys(
&dom,
&crate::inspect::story_paragraph_nodes(&dom, root),
&id,
&mut keys,
);
}
}
keys
}
fn story_keys(
dom: &crate::xmllinq::Dom,
nodes: &[crate::xmllinq::NodeId],
story: &str,
out: &mut std::collections::HashMap<String, String>,
) {
let para_id = crate::namespaces::W14::name("paraId");
let mut counts: std::collections::HashMap<u32, usize> = std::collections::HashMap::new();
for &node in nodes {
if let Some(key) = dom
.attribute(node, ¶_id)
.and_then(crate::edit::native_keys::para_id)
{
*counts.entry(key).or_default() += 1;
}
}
for (index, &node) in nodes.iter().enumerate() {
let Some(raw) = dom.attribute(node, ¶_id) else {
continue;
};
if crate::edit::native_keys::para_id(raw).is_some_and(|key| counts[&key] == 1) {
out.insert(crate::ids::paragraph_id(story, index), raw.to_string());
}
}
}
fn is_paragraph_target(short_id: &str) -> bool {
use crate::ids::{ShortId, Step, Story};
match short_id.parse::<ShortId>() {
Ok(ShortId::Block { story, path }) => matches!(
(story, path.as_slice()),
(Story::Body, [Step::Paragraph(_)]) | (Story::Part(_), [] | [Step::Paragraph(_)])
),
Ok(ShortId::Range { .. }) => false,
Ok(_) => false,
Err(_) => false,
}
}
pub fn rebind_to_output(
spec: &ExpectationsV1,
correspondence: &SourceToOutputCorrespondence,
output: &[u8],
) -> Option<ExpectationsV1> {
let identity = identity_correspondence(output).ok()?;
let mut by_index = std::collections::HashMap::new();
for entry in identity.entries() {
if let [index] = entry.output.as_slice() {
by_index.insert(index, entry.short_id.clone());
}
}
let long_id_of = |short: &str| -> Option<String> {
use crate::ids::{ShortId, Story};
let parsed = short.parse::<ShortId>().ok()?;
let part = match &parsed {
ShortId::Block { story, .. } => match story {
Story::Body => "document",
Story::Part(stem) => stem.as_str(),
},
_ => return None,
};
Some(format!("{part}.w:p.j:short.{short}"))
};
let mut requirements = Vec::with_capacity(spec.requirements.len());
for requirement in &spec.requirements {
let mut checks = Vec::with_capacity(requirement.checks.len());
for check in &requirement.checks {
let entry = correspondence.lookup(&check.target.short_id)?;
let [index] = entry.output.as_slice() else {
return None;
};
let short = by_index.get(&index)?.clone();
let long = long_id_of(&short)?;
checks.push(Check {
kind: check.kind,
target: Target {
short_id: short,
long_id: long,
},
text: check.text.clone(),
});
}
requirements.push(Requirement {
key: requirement.key.clone(),
description: requirement.description.clone(),
checks,
});
}
Some(ExpectationsV1 {
schema_version: spec.schema_version,
source: Source {
sha256: content_sha256(output),
},
text_view: spec.text_view,
requirements,
})
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod shape_branch_tests {
use super::*;
#[test]
fn keys_start_with_a_letter_and_take_word_dots_and_dashes() {
for good in ["a", "a_b", "a.b", "a-b", "A9"] {
assert!(is_valid_key(good), "{good}");
}
for bad in ["", "9a", "_a", "a b", "a/b"] {
assert!(!is_valid_key(bad), "{bad}");
}
}
#[test]
fn a_pair_names_one_paragraph_only_in_its_own_part() {
let keys = std::collections::HashMap::from([("p1".to_string(), "1A2B3C4D".to_string())]);
assert!(ids_name_one_entity("p0", "document.w:p.j:short.p0", &keys));
assert!(ids_name_one_entity(
"p1",
"document.w:p.w14:paraId.1A2B3C4D",
&keys
));
assert!(ids_name_one_entity(
"header1.p0",
"header1.w:p.j:short.header1.p0",
&keys
));
for (short, long) in [
("not an id", "document.w:p.j:short.p0"),
("c5", "comments.w:comment.w:id.5"),
("p0", "document.w:p"),
("p0", "document.w:tbl.j:short.p0"),
("p0", "header1.w:p.j:short.p0"),
("header1.p0", "document.w:p.j:short.header1.p0"),
("p0", "document.w:p.j:short.p1"),
("p2", "document.w:p.w14:paraId.1A2B3C4D"),
("p0", "document.w:p.w:id.0"),
] {
assert!(!ids_name_one_entity(short, long, &keys), "{short} {long}");
}
}
#[test]
fn unopenable_output_refuses_checks_and_leaves_prose_unassessed() {
let source =
crate::markdown::markdown_to_docx("One.\n", &crate::markdown::DocxOptions::default())
.unwrap()
.docx;
let spec = parse_expectations(
&serde_json::json!({
"schema_version": 1,
"source": {"sha256": crate::inspect::source_sha256(&source)},
"text_view": "final",
"requirements": [
{"key": "prose", "description": "reads well", "checks": []},
{"key": "typed", "description": "keeps one", "checks": [{
"kind": "text_equals",
"target": {"short_id": "p0", "long_id": "document.w:p.j:short.p0"},
"text": "One.",
}]},
],
})
.to_string(),
)
.unwrap();
let identity = identity_correspondence(&source).unwrap();
let report = evaluate(&spec, &source, b"not a docx", &identity);
assert_eq!(report.unassessed_requirements, vec!["prose".to_string()]);
assert_eq!(report.checks.len(), 1);
assert_eq!(report.checks[0].reason, Some(RefusalReason::InvalidOutput));
}
}