resumark 0.1.1

ATS-safe resume typesetting from Markdown — extraction order as a verified contract
Documentation
//! The extraction-order harness: round-trip the rendered PDF through
//! `pdftotext` and assert the text layer reads in declared order.
//!
//! Two modes are checked:
//! - **raw** (`pdftotext -raw`): content-stream order — what stream-order
//!   extractors and many ATS parsers see. This must match the declared order
//!   exactly, as a strict total order; the engine controls the stream, so
//!   any deviation is a bug.
//! - **reading** (`pdftotext` default): position-derived reading order.
//!   Positional layout analysis is heuristic — poppler may scan a run of
//!   stacked two-line entry rows column-wise (all roles/asides, then all
//!   companies/metas), and the header's contact block sits inside the tall
//!   name line's vertical span. So the reading-mode assertion is structural
//!   rather than total: the name precedes the sections, section labels
//!   appear in order, every string lands inside its own section's span,
//!   roles appear in order, an entry's fields appear after its role, and
//!   bullets follow their role in sequence — everything a parser needs to
//!   reconstruct the resume correctly. Contact lines are asserted in raw
//!   mode only.

use std::path::Path;
use std::process::Command;

use crate::inline::plain;
use crate::parse::ResumeDoc;

#[derive(Debug, Clone)]
pub struct Expected {
    pub what: &'static str,
    pub text: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
    Raw,
    Reading,
}

#[derive(Debug, Clone)]
pub struct OrderCheck {
    pub mode: Mode,
    pub ok: bool,
    pub total: usize,
    pub matched: usize,
    pub first_miss: Option<Expected>,
}

/// The declared reading order of every visible string, mirroring layout
/// emission order. This is the strict sequence raw mode asserts.
pub fn expected_sequence(doc: &ResumeDoc, include_contact: bool) -> Vec<Expected> {
    let mut v: Vec<Expected> = Vec::new();
    let mut push = |what: &'static str, text: String| {
        let t = norm(&text);
        if !t.is_empty() {
            v.push(Expected { what, text: t });
        }
    };
    push("name", doc.name.clone());
    if include_contact {
        for c in &doc.contact {
            push("contact", plain(c));
        }
    }
    for sec in &doc.sections {
        push("section label", sec.label.clone());
        if sec.kind == "skills" {
            for (label, value) in &sec.rows {
                push("skills label", plain(label));
                push("skills value", plain(value));
            }
        } else {
            for e in &sec.entries {
                // Mirrors layout emission: a two-line left column (aside
                // present) reads column-wise, a single-line one row-wise.
                push("role", e.role.clone());
                push("aside", e.aside.clone());
                push("company", e.company.clone());
                push("extra", e.extra.clone());
                push("meta", e.meta.clone());
                for b in &e.bullets {
                    push("bullet", plain(b));
                }
            }
        }
        for n in &sec.notes {
            push("note", plain(n));
        }
    }
    v
}

/// Run `pdftotext` on the file. Returns None when the binary is missing.
pub fn pdftotext(path: &Path, mode: Mode) -> Option<String> {
    let mut cmd = Command::new("pdftotext");
    if mode == Mode::Raw {
        cmd.arg("-raw");
    }
    cmd.arg("-q").arg(path).arg("-");
    let out = cmd.output().ok()?;
    if !out.status.success() {
        return None;
    }
    Some(String::from_utf8_lossy(&out.stdout).into_owned())
}

/// Assert `expected` appears as an in-order subsequence of the extraction.
/// Used for raw (stream-order) mode, where the order is a strict contract.
pub fn check_order(expected: &[Expected], extracted: &str, mode: Mode) -> OrderCheck {
    let haystack = norm(extracted);
    let mut cursor = 0usize;
    let mut matched = 0usize;
    for exp in expected {
        match haystack[cursor..].find(&exp.text) {
            Some(pos) => {
                cursor += pos + exp.text.len();
                matched += 1;
            }
            None => {
                return OrderCheck {
                    mode,
                    ok: false,
                    total: expected.len(),
                    matched,
                    first_miss: Some(exp.clone()),
                };
            }
        }
    }
    OrderCheck {
        mode,
        ok: true,
        total: expected.len(),
        matched,
        first_miss: None,
    }
}

/// Assert the structural reading-order contract (see the module doc for why
/// this is not a strict total order).
pub fn check_reading(doc: &ResumeDoc, extracted: &str) -> OrderCheck {
    let hay = norm(extracted);
    let total = expected_sequence(doc, false).len();
    let mut matched = 0usize;

    let fail = |matched: usize, what: &'static str, text: &str| OrderCheck {
        mode: Mode::Reading,
        ok: false,
        total,
        matched,
        first_miss: Some(Expected {
            what,
            text: text.to_string(),
        }),
    };
    // Find `needle` in hay[from..until); both bounds always fall on prior
    // match boundaries, so the slice is char-safe.
    let find = |from: usize, until: usize, needle: &str| -> Option<(usize, usize)> {
        let until = until.min(hay.len());
        if from >= until {
            return None;
        }
        let pos = hay[from..until].find(needle)?;
        if from + pos + needle.len() > until {
            return None;
        }
        Some((from + pos, from + pos + needle.len()))
    };

    // Name first, before everything else.
    let mut cursor = 0usize;
    let name = norm(&doc.name);
    if !name.is_empty() {
        match find(0, hay.len(), &name) {
            Some((_, end)) => {
                matched += 1;
                cursor = end;
            }
            None => return fail(matched, "name", &name),
        }
    }

    // Section labels are full-width separators: strictly ordered. Their
    // match positions bound each section's span.
    let mut window_starts: Vec<usize> = Vec::new();
    let mut label_starts: Vec<usize> = Vec::new();
    for sec in &doc.sections {
        let label = norm(&sec.label);
        if label.is_empty() {
            window_starts.push(cursor);
            label_starts.push(cursor);
            continue;
        }
        match find(cursor, hay.len(), &label) {
            Some((start, end)) => {
                matched += 1;
                window_starts.push(end);
                label_starts.push(start);
                cursor = end;
            }
            None => return fail(matched, "section label", &label),
        }
    }

    for (i, sec) in doc.sections.iter().enumerate() {
        let wstart = window_starts[i];
        let wend = label_starts.get(i + 1).copied().unwrap_or(hay.len());

        if sec.kind == "skills" {
            // Rows share a visual line each; strictly ordered.
            let mut cur = wstart;
            for (label, value) in &sec.rows {
                for (what, text) in [
                    ("skills label", norm(&plain(label))),
                    ("skills value", norm(&plain(value))),
                ] {
                    if text.is_empty() {
                        continue;
                    }
                    match find(cur, wend, &text) {
                        Some((_, end)) => {
                            matched += 1;
                            cur = end;
                        }
                        None => return fail(matched, what, &text),
                    }
                }
            }
        } else {
            let mut role_cursor = wstart;
            for e in &sec.entries {
                // Roles are the large left-column anchors: strictly ordered.
                let role = norm(&e.role);
                let anchor = if role.is_empty() {
                    wstart
                } else {
                    match find(role_cursor, wend, &role) {
                        Some((_, end)) => {
                            matched += 1;
                            role_cursor = end;
                            end
                        }
                        None => return fail(matched, "role", &role),
                    }
                };
                // The entry's other fields may be regrouped by column
                // detection; each must simply appear after its own role,
                // inside the section.
                for (what, raw_text) in [
                    ("aside", &e.aside),
                    ("company", &e.company),
                    ("extra", &e.extra),
                    ("meta", &e.meta),
                ] {
                    let text = norm(raw_text);
                    if text.is_empty() {
                        continue;
                    }
                    if find(anchor, wend, &text).is_none() {
                        return fail(matched, what, &text);
                    }
                    matched += 1;
                }
                // Bullets are full-width lines: ordered, after their role.
                let mut bcur = anchor;
                for b in &e.bullets {
                    let text = norm(&plain(b));
                    if text.is_empty() {
                        continue;
                    }
                    match find(bcur, wend, &text) {
                        Some((_, end)) => {
                            matched += 1;
                            bcur = end;
                        }
                        None => return fail(matched, "bullet", &text),
                    }
                }
            }
        }

        let mut ncur = wstart;
        for n in &sec.notes {
            let text = norm(&plain(n));
            if text.is_empty() {
                continue;
            }
            match find(ncur, wend, &text) {
                Some((_, end)) => {
                    matched += 1;
                    ncur = end;
                }
                None => return fail(matched, "note", &text),
            }
        }
    }

    OrderCheck {
        mode: Mode::Reading,
        ok: true,
        total,
        matched,
        first_miss: None,
    }
}

/// Verify a rendered PDF against its source document in both modes.
/// Returns None when pdftotext is unavailable.
pub fn verify(path: &Path, doc: &ResumeDoc) -> Option<(OrderCheck, OrderCheck)> {
    let raw_text = pdftotext(path, Mode::Raw)?;
    let reading_text = pdftotext(path, Mode::Reading)?;
    let raw = check_order(&expected_sequence(doc, true), &raw_text, Mode::Raw);
    let reading = check_reading(doc, &reading_text);
    Some((raw, reading))
}

fn norm(s: &str) -> String {
    s.split_whitespace().collect::<Vec<_>>().join(" ")
}