Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

Accessibility: persist human review decisions for an exact PDF revision (#1239)

Earl Coe4527a855fd3
diff --git a/crates/automation/src/a11y.rs b/crates/automation/src/a11y.rs
index ac30694a8..f56ed5664 100644
--- a/crates/automation/src/a11y.rs
+++ b/crates/automation/src/a11y.rs
@@ -4,6 +4,7 @@ use pdfcraft_engine::DocId;
use pdfcraft_engine::a11y::{Category, Options, Report, Rule, Status};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
+use std::collections::BTreeSet;
use crate::{Args, Automation, Result, ToolError, child, failed, unused, write_atomic};
@@ -58,6 +59,81 @@ pub(crate) fn report_json(r: &Report) -> Value {
})
}
+fn review_hash(bytes: &[u8]) -> String {
+ Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect()
+}
+
+fn review_decisions(value: &Value, pages: usize) -> Result<Vec<Value>> {
+ let rows = value.as_array().ok_or_else(|| ToolError::InvalidArgs("decisions must be an array".into()))?;
+ let mut seen = BTreeSet::new();
+ rows.iter()
+ .map(|row| {
+ let fields = row.as_object().ok_or_else(|| ToolError::InvalidArgs("each decision must be an object".into()))?;
+ if fields.keys().any(|key| !matches!(key.as_str(), "rule" | "decision" | "page" | "note")) {
+ return Err(ToolError::InvalidArgs("unknown decision property".into()));
+ }
+ let rule = row["rule"].as_str().and_then(Rule::from_id).ok_or_else(|| ToolError::InvalidArgs("decision has an unknown rule".into()))?;
+ let decision = row["decision"].as_str().ok_or_else(|| ToolError::InvalidArgs("decision status is required".into()))?;
+ if !matches!(decision, "accepted" | "needs_work" | "skipped") {
+ return Err(ToolError::InvalidArgs("decision must be accepted, needs_work or skipped".into()));
+ }
+ let page = match row.get("page").filter(|value| !value.is_null()) {
+ Some(value) => {
+ let page = value.as_u64().ok_or_else(|| ToolError::InvalidArgs("decision page must be positive".into()))?;
+ if page == 0 || page > pages as u64 {
+ return Err(ToolError::InvalidArgs("decision page is outside the document".into()));
+ }
+ Some(page)
+ }
+ None => None,
+ };
+ let note = match row.get("note").filter(|value| !value.is_null()) {
+ Some(value) => {
+ let note = value.as_str().ok_or_else(|| ToolError::InvalidArgs("decision note must be text".into()))?;
+ if note.len() > 4096 {
+ return Err(ToolError::InvalidArgs("decision note exceeds 4096 bytes".into()));
+ }
+ Some(note)
+ }
+ None => None,
+ };
+ if !seen.insert((rule.id(), page)) {
+ return Err(ToolError::InvalidArgs("duplicate decision for a rule and page".into()));
+ }
+ Ok(json!({ "rule": rule.id(), "decision": decision, "page": page, "note": note }))
+ })
+ .collect()
+}
+
+/// A review sidecar is a few KiB of JSON; anything larger is not one.
+const MAX_REVIEW_SIDECAR_BYTES: u64 = 1 << 20;
+
+/// Read a review sidecar without trusting its size: the path is the caller's
+/// and may name any file, so the read stops past `MAX_REVIEW_SIDECAR_BYTES` and
+/// an oversized file is refused as not being a sidecar.
+fn read_review_sidecar(path: &std::path::Path) -> Result<Vec<u8>> {
+ use std::io::Read;
+ let mut bytes = Vec::new();
+ std::fs::File::open(path).and_then(|file| file.take(MAX_REVIEW_SIDECAR_BYTES.saturating_add(1)).read_to_end(&mut bytes)).map_err(failed)?;
+ if bytes.len() as u64 > MAX_REVIEW_SIDECAR_BYTES {
+ return Err(failed("file is not an accessibility review sidecar"));
+ }
+ Ok(bytes)
+}
+
+fn parse_review_sidecar(bytes: &[u8]) -> Result<Value> {
+ let value: Value = serde_json::from_slice(bytes).map_err(|_| failed("file is not an accessibility review sidecar"))?;
+ let hash = value["sha256"].as_str().ok_or_else(|| failed("review sidecar has no document hash"))?;
+ let Some(pages) = value["pages"].as_u64().and_then(|n| usize::try_from(n).ok()).filter(|n| *n > 0) else {
+ return Err(failed("unsupported or invalid accessibility review sidecar"));
+ };
+ if value["schema"] != 1 || hash.len() != 64 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
+ return Err(failed("unsupported or invalid accessibility review sidecar"));
+ }
+ review_decisions(&value["decisions"], pages).map_err(failed)?;
+ Ok(value)
+}
+
fn html_escape(value: &str) -> String {
value.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;").replace('\'', "&#39;")
}
@@ -252,6 +328,35 @@ impl Automation {
Ok(json!({ "path": path.to_string_lossy(), "record": record }))
}
+ pub(crate) fn a11y_review_save(&self, a: &Args) -> Result<Value> {
+ let doc = self.doc(a)?;
+ let decisions = review_decisions(a.get("decisions").ok_or_else(|| Args::missing("decisions"))?, doc.info.pages.len())?;
+ let hash = review_hash(doc.bytes.as_slice());
+ let path = self.resolve(a.str("path")?, true)?;
+ if path.exists() {
+ let prior = read_review_sidecar(&path)?;
+ let prior = parse_review_sidecar(&prior)?;
+ if prior["sha256"] != hash && !a.opt_bool("replace")?.unwrap_or(false) {
+ return Err(failed("review sidecar belongs to a different PDF revision; pass replace: true to replace it"));
+ }
+ }
+ let (y, m, d) = self.session.today();
+ let sidecar =
+ json!({ "schema": 1, "date": format!("{y}-{m:02}-{d:02}"), "sha256": hash, "pages": doc.info.pages.len(), "decisions": decisions });
+ write_atomic(&path, &serde_json::to_vec_pretty(&sidecar).map_err(failed)?)?;
+ Ok(json!({ "path": path.to_string_lossy(), "review": sidecar }))
+ }
+
+ pub(crate) fn a11y_review_load(&self, a: &Args) -> Result<Value> {
+ let doc = self.doc(a)?;
+ let path = self.resolve(a.str("path")?, false)?;
+ let review = parse_review_sidecar(&read_review_sidecar(&path)?)?;
+ if review["sha256"] != review_hash(doc.bytes.as_slice()) {
+ return Err(failed("review sidecar belongs to a different PDF revision"));
+ }
+ Ok(json!({ "path": path.to_string_lossy(), "review": review }))
+ }
+
pub(crate) fn a11y_review_html(&self, a: &Args) -> Result<Value> {
let record = self.review_record_value(a)?;
let html = review_html(&record)?;
diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs
index 725f394e6..a84763b4c 100644
--- a/crates/automation/src/lib.rs
+++ b/crates/automation/src/lib.rs
@@ -736,6 +736,8 @@ impl Automation {
"ocr_recognize_files" => self.ocr_recognize_files(&a)?,
"accessibility_report" => self.a11y_report(&a)?,
"accessibility_review_record" => self.a11y_review_record(&a)?,
+ "accessibility_review_save" => self.a11y_review_save(&a)?,
+ "accessibility_review_load" => self.a11y_review_load(&a)?,
"accessibility_review_html" => self.a11y_review_html(&a)?,
"accessibility_fix" => self.a11y_fix(&a)?,
"accessibility_figures" => self.accessibility_figures(&a)?,
diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs
index 6cdc4eca3..c87250561 100644
--- a/crates/automation/src/tools.rs
+++ b/crates/automation/src/tools.rs
@@ -882,6 +882,12 @@ pub fn tools() -> Vec<ToolDef> {
}),
&["before", "after", "path"],
)),
+ t("accessibility_review_save", "Save accessibility review decisions", "Write a local JSON sidecar for an open PDF with rule-level human review decisions. The sidecar records the PDF SHA-256; replacing one tied to different bytes requires replace: true. Does not change the PDF or assert compliance.")
+ .destructive()
+ .with(schema(json!({ "doc": doc(), "path": { "type": "string" }, "decisions": { "type": "array", "items": { "type": "object", "properties": { "rule": { "type": "string" }, "decision": { "type": "string", "enum": ["accepted", "needs_work", "skipped"] }, "page": { "type": "integer", "minimum": 1 }, "note": { "type": "string" } }, "required": ["rule", "decision"], "additionalProperties": false } }, "replace": { "type": "boolean" } }), &["doc", "path", "decisions"])),
+ t("accessibility_review_load", "Open accessibility review decisions", "Read a local review sidecar only when its recorded SHA-256 matches the open PDF. Returns the decisions without changing the PDF.")
+ .ro()
+ .with(schema(json!({ "doc": doc(), "path": { "type": "string" } }), &["doc", "path"])),
t("accessibility_review_html", "Accessibility review summary", "Compare two open versions of a PDF and write a self-contained HTML summary of the same evidence as accessibility_review_record: document hashes, outcome counts, rule changes, and rules still requiring review. Does not change either PDF or claim accessibility compliance.")
.destructive()
.with(schema(
diff --git a/crates/automation/tests/automation.rs b/crates/automation/tests/automation.rs
index 19434dd36..f14e913f7 100644
--- a/crates/automation/tests/automation.rs
+++ b/crates/automation/tests/automation.rs
@@ -1829,6 +1829,68 @@ fn accessibility_review_record_compares_two_versions_without_changing_them() {
assert!(!dir.parent().unwrap().join("escape.html").exists());
}
+#[test]
+fn accessibility_review_sidecar_tracks_human_decisions_for_exact_pdf_revision() {
+ let dir = workdir("a11y-review-sidecar");
+ let source = std::fs::read(dir.join("a.pdf")).unwrap();
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
+ let decisions = json!([
+ { "rule": "logical-reading-order", "decision": "needs_work", "page": 1, "note": "Check heading order" },
+ { "rule": "figures-alt-text", "decision": "accepted", "page": 2 }
+ ]);
+ let saved = ok(&mut a, "accessibility_review_save", json!({ "doc": doc, "path": "review.json", "decisions": decisions }));
+ assert_eq!(saved["review"]["schema"], 1);
+ assert_eq!(saved["review"]["sha256"].as_str().unwrap().len(), 64);
+ let original_sidecar = std::fs::read(dir.join("review.json")).unwrap();
+ assert_eq!(ok(&mut a, "accessibility_review_load", json!({ "doc": doc, "path": "review.json" }))["review"], saved["review"]);
+ let mut reopened = auto(&dir);
+ let reopened_doc = ok(&mut reopened, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
+ assert_eq!(ok(&mut reopened, "accessibility_review_load", json!({ "doc": reopened_doc, "path": "review.json" }))["review"], saved["review"]);
+ assert!(matches!(
+ reopened.call("accessibility_review_save", &json!({ "doc": reopened_doc, "path": "a.pdf", "decisions": [], "replace": true })),
+ Err(ToolError::Failed(_))
+ ));
+ assert_eq!(std::fs::read(dir.join("a.pdf")).unwrap(), source);
+
+ assert!(matches!(
+ a.call(
+ "accessibility_review_save",
+ &json!({ "doc": doc, "path": "review.json", "decisions": [
+ { "rule": "title", "decision": "accepted" }, { "rule": "title", "decision": "skipped" }
+ ] })
+ ),
+ Err(ToolError::InvalidArgs(_))
+ ));
+ assert_eq!(std::fs::read(dir.join("review.json")).unwrap(), original_sidecar);
+ ok(&mut a, "accessibility_fix", json!({ "doc": doc, "rule": "primary-language", "value": "en-GB" }));
+ assert!(matches!(a.call("accessibility_review_load", &json!({ "doc": doc, "path": "review.json" })), Err(ToolError::Failed(_))));
+ assert!(matches!(a.call("accessibility_review_save", &json!({ "doc": doc, "path": "review.json", "decisions": [] })), Err(ToolError::Failed(_))));
+ assert_eq!(std::fs::read(dir.join("review.json")).unwrap(), original_sidecar);
+ let replacement = ok(&mut a, "accessibility_review_save", json!({ "doc": doc, "path": "review.json", "decisions": decisions, "replace": true }));
+ assert_ne!(replacement["review"]["sha256"], saved["review"]["sha256"]);
+ assert_eq!(ok(&mut a, "accessibility_review_load", json!({ "doc": doc, "path": "review.json" }))["review"], replacement["review"]);
+ assert_eq!(std::fs::read(dir.join("a.pdf")).unwrap(), source);
+ assert!(a.call("accessibility_review_save", &json!({ "doc": doc, "path": "../escape.json", "decisions": [] })).is_err());
+ assert!(!dir.parent().unwrap().join("escape.json").exists());
+
+ // Malformed or oversized files are not sidecars: loading fails cleanly and
+ // saving leaves them alone, without reading more than the size cap.
+ let oversized = [b"{\"schema\": 1, \"pad\": \"".as_slice(), &vec![b'x'; (1 << 20) + 16], b"\"}"].concat();
+ for (name, bytes) in [("malformed.json", b"{ not json".to_vec()), ("binary.json", vec![0xff, 0x00, 0xfe]), ("oversized.json", oversized)] {
+ std::fs::write(dir.join(name), &bytes).unwrap();
+ assert!(matches!(a.call("accessibility_review_load", &json!({ "doc": doc, "path": name })), Err(ToolError::Failed(_))), "{name}");
+ assert!(
+ matches!(
+ a.call("accessibility_review_save", &json!({ "doc": doc, "path": name, "decisions": [], "replace": true })),
+ Err(ToolError::Failed(_))
+ ),
+ "{name}"
+ );
+ assert_eq!(std::fs::read(dir.join(name)).unwrap(), bytes, "{name}");
+ }
+}
+
#[test]
fn editing_existing_text_through_tools() {
let dir = workdir("edit-text");
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index 2461a5d97..956b6f1bc 100644
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@ -9015,7 +9015,7 @@ status = "planned"
commands = []
tools = []
evidence = []
-notes = ""
+notes = "Headless review sidecar tools save and reopen human decisions against the exact working PDF SHA-256. The guided GUI action and step-by-step remediation are still missing."
[[feature]]
id = "a11y.setup-assistant"
@@ -9027,7 +9027,7 @@ status = "planned"
commands = []
tools = []
evidence = []
-notes = ""
+notes = "Review decisions can be saved and reopened through accessibility_review_save and accessibility_review_load. A GUI assistant is still missing."
[[feature]]
id = "a11y.read-aloud"