Skip to main content

adk_site/gate/
mod.rs

1//! The launch gate: fixed checks outside the agent's write scope (spec 3.5 §7.8.1, §7.8.2
2//! step 2, §7.8.3 "Tiered checks").
3//!
4//! | Check | Pass condition | Fast | Full |
5//! |-------|----------------|------|------|
6//! | Server code | Zero server-executable files or server-side include directives (A-I1); always fatal | written files | every file |
7//! | Claims | Zero published claims from facts that are not `Known` (A-I18), through a [`ClaimCheck`]; review quotes only with the reviewer's public name and the owner's approval ([`QuotableReview`]) | changed items | every item |
8//! | Links | Zero broken internal links | written pages | every page |
9//! | Accessibility | Zero serious WCAG 2.2 AA violations; image alt text confirmed; theme contrast | written pages | every page, contrast |
10//! | Performance | Critical path within the budget (LCP recorded as not measured) | — | every page |
11//! | Legal | Privacy, consent and terms pages for every jurisdiction | — | yes |
12//! | Machine views | Every page has its twins, linked and valid | written pages | every page |
13//! | Quarantine | Zero quarantined items or files in the output | yes | yes |
14//! | Required languages | Every item in every required language | changed items | every item |
15//! | Red lines | No item states a charter red line | changed items | every item |
16//! | Structured data | Fields each kind needs; JSON-LD parses | changed items | every item |
17//!
18//! Further checks plug in as [`GateExtension`]s: migration parity (`migrate` feature),
19//! [`ThirdPartyResources`] for kinds that ship no third-party scripts or trackers,
20//! [`ReleaseDelegation`] for a served site whose release key the owner's root delegates, and
21//! `PreviewVerification` (`verify` feature), which runs `awp verify` against the preview.
22
23mod extensions;
24mod html;
25mod links;
26mod reviews;
27#[cfg(feature = "verify")]
28mod verify;
29
30use std::collections::{BTreeMap, BTreeSet};
31use std::path::Path;
32use std::sync::Arc;
33
34use async_trait::async_trait;
35use awp_types::{
36    ContentId, ContentItem, ContentKind, ContentState, FactRef, MachineView, RedLine, RedLineKind,
37};
38use scraper::Html;
39use serde::{Deserialize, Serialize};
40use serde_json::Value;
41
42use crate::content::SiteProject;
43use crate::error::{Result, SiteError};
44use crate::generator::BuildReport;
45use crate::scan::scan_file;
46
47pub use extensions::{ReleaseDelegation, ThirdPartyResources};
48pub use html::{A11yViolation, Severity};
49pub use reviews::{QuotableReview, review_findings};
50#[cfg(feature = "verify")]
51pub use verify::PreviewVerification;
52
53/// A launch-gate check (spec 3.5 §7.8.1).
54#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
55#[serde(rename_all = "snake_case")]
56#[non_exhaustive]
57pub enum GateCheck {
58    /// A-I1.
59    ServerCode,
60    /// A-I18.
61    Claims,
62    /// Internal links.
63    Links,
64    /// WCAG 2.2 AA automated checks.
65    Accessibility,
66    /// The performance budget.
67    Performance,
68    /// Legal pages per jurisdiction.
69    Legal,
70    /// Twins of every page.
71    MachineViews,
72    /// Migration parity (a [`GateExtension`]).
73    MigrationParity,
74    /// Quarantined items.
75    Quarantine,
76    /// Required languages.
77    RequiredLanguages,
78    /// Charter red lines.
79    RedLines,
80    /// Structured data per content kind.
81    StructuredData,
82    /// Resources loaded from other origins ([`ThirdPartyResources`], spec 3.5 §7.16.1).
83    ThirdPartyResources,
84    /// Release signing and its delegation by the owner's root ([`ReleaseDelegation`], D-11).
85    Signing,
86    /// `awp verify` against the preview (`PreviewVerification`, feature `verify`; spec 3.5
87    /// §7.8.1 "Machine views").
88    AwpVerify,
89}
90
91/// Which tier runs (spec 3.5 §7.8.3).
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
93#[serde(rename_all = "snake_case")]
94pub enum GateMode {
95    /// Per change: the changed items and the files the build wrote.
96    Fast,
97    /// Before launch and on schedule: everything.
98    Full,
99}
100
101/// How a check ended.
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
103#[serde(rename_all = "snake_case")]
104pub enum CheckStatus {
105    /// No blocking finding.
106    Passed,
107    /// At least one blocking finding.
108    Failed,
109    /// The check could not measure; see the note.
110    NotMeasured,
111    /// The tier does not run the check.
112    Skipped,
113}
114
115/// One finding of a check.
116#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
117#[serde(rename_all = "camelCase")]
118pub struct Finding {
119    /// The rule, such as `image-alt` or `broken-link`.
120    pub rule: String,
121    /// How serious it is.
122    pub severity: Severity,
123    /// Whether it fails the gate.
124    pub blocking: bool,
125    /// The file, when the finding is a file's.
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub path: Option<String>,
128    /// The item, when the finding is an item's.
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    pub item: Option<ContentId>,
131    /// What is wrong and what to do.
132    pub message: String,
133}
134
135impl Finding {
136    fn blocking(
137        rule: &str,
138        path: Option<String>,
139        item: Option<ContentId>,
140        message: String,
141    ) -> Self {
142        Self { rule: rule.into(), severity: Severity::Serious, blocking: true, path, item, message }
143    }
144}
145
146/// The result of one check.
147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
148#[serde(rename_all = "camelCase")]
149pub struct CheckResult {
150    /// The check.
151    pub check: GateCheck,
152    /// How it ended.
153    pub status: CheckStatus,
154    /// Its findings, blocking or not.
155    #[serde(default, skip_serializing_if = "Vec::is_empty")]
156    pub findings: Vec<Finding>,
157    /// What it did not measure, and why.
158    #[serde(default, skip_serializing_if = "Option::is_none")]
159    pub note: Option<String>,
160}
161
162impl CheckResult {
163    fn from_findings(check: GateCheck, findings: Vec<Finding>) -> Self {
164        let status = if findings.iter().any(|f| f.blocking) {
165            CheckStatus::Failed
166        } else {
167            CheckStatus::Passed
168        };
169        Self { check, status, findings, note: None }
170    }
171
172    fn skipped(check: GateCheck) -> Self {
173        Self {
174            check,
175            status: CheckStatus::Skipped,
176            findings: Vec::new(),
177            note: Some("not in the fast tier".into()),
178        }
179    }
180
181    fn note(mut self, note: impl Into<String>) -> Self {
182        self.note = Some(note.into());
183        self
184    }
185}
186
187/// The gate's verdict.
188#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
189#[serde(rename_all = "camelCase")]
190pub struct GateReport {
191    /// The tier that ran.
192    pub mode: GateMode,
193    /// Every check, in table order.
194    pub checks: Vec<CheckResult>,
195}
196
197impl GateReport {
198    /// Whether every check passed, measured nothing it could not, or was skipped.
199    pub fn passed(&self) -> bool {
200        self.checks.iter().all(|c| c.status != CheckStatus::Failed)
201    }
202
203    /// The result of `check`.
204    pub fn check(&self, check: GateCheck) -> Option<&CheckResult> {
205        self.checks.iter().find(|c| c.check == check)
206    }
207
208    /// Every blocking finding.
209    pub fn blocking(&self) -> impl Iterator<Item = (GateCheck, &Finding)> {
210        self.checks
211            .iter()
212            .flat_map(|c| c.findings.iter().filter(|f| f.blocking).map(move |f| (c.check, f)))
213    }
214
215    /// Whether the release must be refused whole: a server-code finding (A-I1).
216    pub fn refuses_release(&self) -> bool {
217        self.check(GateCheck::ServerCode).is_some_and(|c| c.status == CheckStatus::Failed)
218    }
219
220    /// The items a fast-tier failure holds; the rest of a batch may proceed unless the
221    /// release is refused (spec 3.5 §7.8.3).
222    pub fn held_items(&self) -> BTreeSet<ContentId> {
223        self.blocking().filter_map(|(_, f)| f.item.clone()).collect()
224    }
225
226    /// A one-line summary of the blocking findings.
227    pub fn summary(&self) -> String {
228        let failed: Vec<String> = self
229            .checks
230            .iter()
231            .filter(|c| c.status == CheckStatus::Failed)
232            .map(|c| format!("{:?}: {}", c.check, c.findings.iter().filter(|f| f.blocking).count()))
233            .collect();
234        if failed.is_empty() { "passed".into() } else { failed.join(", ") }
235    }
236}
237
238/// A claim that does not rest on a `Known` fact.
239#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
240#[serde(rename_all = "camelCase")]
241pub struct ClaimFinding {
242    /// The claim or field.
243    pub claim: String,
244    /// The fact it cites, if any.
245    #[serde(default, skip_serializing_if = "Option::is_none")]
246    pub fact: Option<FactRef>,
247    /// Why it fails.
248    pub reason: String,
249}
250
251/// Decides whether an item's claims rest on `Known` facts (spec 3.5 A-I18). The caller
252/// implements it over its facts store; [`FactTable`] is a static one.
253#[async_trait]
254pub trait ClaimCheck: Send + Sync {
255    /// The claims in `item` that do not rest on `Known` facts; empty when every one does.
256    ///
257    /// # Errors
258    ///
259    /// Returns an error when the facts cannot be read.
260    async fn unsupported_claims(&self, item: &ContentItem) -> Result<Vec<ClaimFinding>>;
261}
262
263/// The standing of a fact.
264#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
265#[serde(rename_all = "snake_case")]
266pub enum FactStatus {
267    /// Confirmed by the owner.
268    Known,
269    /// Found or inferred, not confirmed.
270    Assumed,
271}
272
273/// A [`ClaimCheck`] over a fixed table: every fact an item cites must be `Known`.
274///
275/// # Example
276///
277/// ```rust
278/// use adk_site::gate::{FactStatus, FactTable};
279/// use awp_types::FactRef;
280///
281/// let facts = FactTable::new([(FactRef("founded-2019".into()), FactStatus::Known)]);
282/// # let _ = facts;
283/// ```
284#[derive(Debug, Clone, Default)]
285pub struct FactTable {
286    facts: BTreeMap<FactRef, FactStatus>,
287}
288
289impl FactTable {
290    /// A table of facts.
291    pub fn new(facts: impl IntoIterator<Item = (FactRef, FactStatus)>) -> Self {
292        Self { facts: facts.into_iter().collect() }
293    }
294}
295
296#[async_trait]
297impl ClaimCheck for FactTable {
298    async fn unsupported_claims(&self, item: &ContentItem) -> Result<Vec<ClaimFinding>> {
299        Ok(item
300            .sources
301            .iter()
302            .filter_map(|fact| match self.facts.get(fact) {
303                Some(FactStatus::Known) => None,
304                Some(FactStatus::Assumed) => Some(ClaimFinding {
305                    claim: fact.0.clone(),
306                    fact: Some(fact.clone()),
307                    reason: "the fact is Assumed; the owner has not confirmed it".into(),
308                }),
309                None => Some(ClaimFinding {
310                    claim: fact.0.clone(),
311                    fact: Some(fact.clone()),
312                    reason: "the fact is not in the site's facts".into(),
313                }),
314            })
315            .collect())
316    }
317}
318
319/// Items and files the sanitiser quarantined; none may ship without a per-item decision.
320#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
321#[serde(rename_all = "camelCase")]
322pub struct Quarantine {
323    /// Quarantined items.
324    pub items: BTreeSet<ContentId>,
325    /// Quarantined output paths.
326    pub paths: BTreeSet<String>,
327}
328
329/// What the gate checks.
330#[derive(Debug, Clone, Copy)]
331pub struct GateInput<'a> {
332    /// The project that was built.
333    pub project: &'a SiteProject,
334    /// The build output directory.
335    pub out: &'a Path,
336    /// The build's report.
337    pub report: &'a BuildReport,
338    /// The changed items, for the fast tier; `None` checks every item.
339    pub changed: Option<&'a BTreeSet<ContentId>>,
340    /// The quarantine.
341    pub quarantine: &'a Quarantine,
342}
343
344/// A check the gate runs beside its own: migration parity, `awp verify` against a preview.
345#[async_trait]
346pub trait GateExtension: Send + Sync {
347    /// The check it reports as.
348    fn check(&self) -> GateCheck;
349
350    /// Whether it runs in `mode`.
351    fn runs_in(&self, mode: GateMode) -> bool {
352        mode == GateMode::Full
353    }
354
355    /// Runs the check.
356    ///
357    /// # Errors
358    ///
359    /// Returns an error when the check cannot run; the gate reports it as failed.
360    async fn run(&self, input: &GateInput<'_>) -> Result<CheckResult>;
361}
362
363/// The launch gate (spec 3.5 §7.8.1).
364///
365/// # Example
366///
367/// ```rust,no_run
368/// use std::collections::BTreeSet;
369/// use std::sync::Arc;
370/// use adk_site::gate::{FactTable, GateInput, GateMode, LaunchGate, Quarantine};
371/// # use adk_site::{content::SiteProject, generator::BuildReport};
372///
373/// # async fn demo(project: &SiteProject, report: &BuildReport, out: &std::path::Path) -> adk_site::Result<()> {
374/// let gate = LaunchGate::new().with_claim_check(Arc::new(FactTable::default()));
375/// let quarantine = Quarantine::default();
376/// let verdict = gate
377///     .run(GateMode::Full, &GateInput { project, out, report, changed: None, quarantine: &quarantine })
378///     .await?;
379/// assert!(verdict.passed(), "{}", verdict.summary());
380/// # Ok(())
381/// # }
382/// ```
383#[derive(Clone, Default)]
384pub struct LaunchGate {
385    claims: Option<Arc<dyn ClaimCheck>>,
386    red_lines: Vec<RedLine>,
387    reviews: Vec<QuotableReview>,
388    extensions: Vec<Arc<dyn GateExtension>>,
389}
390
391impl std::fmt::Debug for LaunchGate {
392    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
393        f.debug_struct("LaunchGate")
394            .field("claims", &self.claims.is_some())
395            .field("red_lines", &self.red_lines)
396            .field("reviews", &self.reviews.len())
397            .field("extensions", &self.extensions.len())
398            .finish()
399    }
400}
401
402const REQUIRED_LEGAL: &[&str] = &["privacy", "consent", "terms"];
403
404fn is_html(path: &str) -> bool {
405    path.ends_with(".html") || path.ends_with(".htm")
406}
407
408impl LaunchGate {
409    /// A gate with no claim check, no red lines and no extensions.
410    pub fn new() -> Self {
411        Self::default()
412    }
413
414    /// Checks claims with `check`.
415    pub fn with_claim_check(mut self, check: Arc<dyn ClaimCheck>) -> Self {
416        self.claims = Some(check);
417        self
418    }
419
420    /// Refuses items that state one of the charter's red lines.
421    pub fn with_red_lines(mut self, red_lines: Vec<RedLine>) -> Self {
422        self.red_lines = red_lines;
423        self
424    }
425
426    /// The reviews discovery found, with their attribution and the owner's approvals: an
427    /// item quoting one fails the claims check unless it names the reviewer and the owner
428    /// approved quoting it (spec 3.5 S2).
429    pub fn with_reviews(mut self, reviews: Vec<QuotableReview>) -> Self {
430        self.reviews = reviews;
431        self
432    }
433
434    /// Adds a check.
435    pub fn with_extension(mut self, extension: Arc<dyn GateExtension>) -> Self {
436        self.extensions.push(extension);
437        self
438    }
439
440    /// Runs the tier `mode` over a build.
441    ///
442    /// # Errors
443    ///
444    /// [`SiteError::Io`] when the output cannot be read; errors from the claim check.
445    pub async fn run(&self, mode: GateMode, input: &GateInput<'_>) -> Result<GateReport> {
446        let changed = match mode {
447            GateMode::Fast => input.changed,
448            GateMode::Full => None,
449        };
450        let on_disk = {
451            let out = input.out.to_path_buf();
452            tokio::task::spawn_blocking(move || crate::generator::list_files(&out))
453                .await
454                .map_err(|e| SiteError::Pipeline(e.to_string()))??
455        };
456        let scope: BTreeSet<String> = match mode {
457            GateMode::Fast => input.report.written.intersection(&on_disk).cloned().collect(),
458            GateMode::Full => on_disk.clone(),
459        };
460        let mut files: BTreeMap<String, Vec<u8>> = BTreeMap::new();
461        for path in &scope {
462            let full = input.out.join(path);
463            let bytes = tokio::fs::read(&full).await.map_err(|e| SiteError::io(full, e))?;
464            files.insert(path.clone(), bytes);
465        }
466        let live: Vec<&ContentItem> = {
467            let shown: BTreeSet<&ContentId> =
468                input.report.pages.iter().filter_map(|p| p.item.as_ref()).collect();
469            input.project.items.iter().filter(|item| shown.contains(&item.id)).collect()
470        };
471        let items: Vec<&ContentItem> = live
472            .iter()
473            .copied()
474            .filter(|item| changed.is_none_or(|c| c.contains(&item.id)))
475            .collect();
476
477        let mut checks = vec![
478            server_code(&files),
479            self.claims(&items).await?,
480            check_links(input, &files, &on_disk),
481            accessibility(mode, input, &files, &items),
482            match mode {
483                GateMode::Full => performance(input, &files, &on_disk),
484                GateMode::Fast => CheckResult::skipped(GateCheck::Performance),
485            },
486            match mode {
487                GateMode::Full => legal(input, &live),
488                GateMode::Fast => CheckResult::skipped(GateCheck::Legal),
489            },
490            machine_views(mode, input, &files, &on_disk),
491            quarantine(input, &on_disk),
492            required_languages(input, &items),
493            self.red_lines(&items),
494            structured_data(&items, &files),
495        ];
496        for extension in &self.extensions {
497            if !extension.runs_in(mode) {
498                continue;
499            }
500            let result = match extension.run(input).await {
501                Ok(result) => result,
502                Err(error) => CheckResult::from_findings(
503                    extension.check(),
504                    vec![Finding::blocking("extension-error", None, None, error.to_string())],
505                ),
506            };
507            checks.push(result);
508        }
509        Ok(GateReport { mode, checks })
510    }
511
512    async fn claims(&self, items: &[&ContentItem]) -> Result<CheckResult> {
513        let quotes: Vec<Finding> =
514            items.iter().flat_map(|item| reviews::review_findings(item, &self.reviews)).collect();
515        let Some(check) = &self.claims else {
516            let citing: Vec<&&ContentItem> =
517                items.iter().filter(|i| !i.sources.is_empty()).collect();
518            if citing.is_empty() && quotes.is_empty() {
519                return Ok(CheckResult {
520                    check: GateCheck::Claims,
521                    status: CheckStatus::NotMeasured,
522                    findings: Vec::new(),
523                    note: Some("no claim check is configured and no item cites a fact".into()),
524                });
525            }
526            let mut findings: Vec<Finding> = citing
527                .iter()
528                .map(|item| {
529                    Finding::blocking(
530                        "claims-unverified",
531                        None,
532                        Some(item.id.clone()),
533                        "the item cites facts and no claim check is configured; configure one so claims are checked against Known facts (A-I18)".into(),
534                    )
535                })
536                .collect();
537            findings.extend(quotes);
538            return Ok(CheckResult::from_findings(GateCheck::Claims, findings));
539        };
540        let mut findings = quotes;
541        for item in items {
542            for claim in check.unsupported_claims(item).await? {
543                findings.push(Finding::blocking(
544                    "claim-not-known",
545                    None,
546                    Some(item.id.clone()),
547                    format!(
548                        "claim '{}' is not from a Known fact: {} (A-I18)",
549                        claim.claim, claim.reason
550                    ),
551                ));
552            }
553        }
554        Ok(CheckResult::from_findings(GateCheck::Claims, findings))
555    }
556
557    fn red_lines(&self, items: &[&ContentItem]) -> CheckResult {
558        let mut findings = Vec::new();
559        for item in items {
560            let mut text = item.body.as_ref().map(|b| b.0.to_lowercase()).unwrap_or_default();
561            for value in item.fields.values() {
562                collect_text(value, &mut text);
563            }
564            for line in &self.red_lines {
565                if !matches!(line.kind, RedLineKind::Claim | RedLineKind::Topic) {
566                    continue;
567                }
568                let phrase = line.text.trim().to_lowercase();
569                if !phrase.is_empty() && text.contains(&phrase) {
570                    findings.push(Finding::blocking(
571                        "red-line",
572                        None,
573                        Some(item.id.clone()),
574                        format!("the item states the red line '{}'", line.text),
575                    ));
576                }
577            }
578        }
579        CheckResult::from_findings(GateCheck::RedLines, findings)
580    }
581}
582
583fn collect_text(value: &Value, out: &mut String) {
584    match value {
585        Value::String(s) => {
586            out.push('\n');
587            out.push_str(&s.to_lowercase());
588        }
589        Value::Array(values) => values.iter().for_each(|v| collect_text(v, out)),
590        Value::Object(map) => map.values().for_each(|v| collect_text(v, out)),
591        _ => {}
592    }
593}
594
595fn server_code(files: &BTreeMap<String, Vec<u8>>) -> CheckResult {
596    let findings = files
597        .iter()
598        .flat_map(|(path, bytes)| scan_file(path, bytes))
599        .map(|f| Finding {
600            rule: "server-code".into(),
601            severity: Severity::Critical,
602            blocking: true,
603            message: format!("{:?} (A-I1: no flag overrides this)", f.kind),
604            path: Some(f.path),
605            item: None,
606        })
607        .collect();
608    CheckResult::from_findings(GateCheck::ServerCode, findings)
609}
610
611fn item_of_path<'a>(report: &'a BuildReport, path: &str) -> Option<&'a ContentId> {
612    report
613        .pages
614        .iter()
615        .find(|p| {
616            p.html == path
617                || p.markdown.as_deref() == Some(path)
618                || p.machine_view.as_deref() == Some(path)
619        })
620        .and_then(|p| p.item.as_ref())
621}
622
623fn check_links(
624    input: &GateInput<'_>,
625    files: &BTreeMap<String, Vec<u8>>,
626    on_disk: &BTreeSet<String>,
627) -> CheckResult {
628    let redirects: BTreeSet<String> =
629        input.report.redirects.iter().filter(|r| r.status != 410).map(|r| r.from.clone()).collect();
630    let domain = &input.project.config.domain;
631    let mut findings = Vec::new();
632    for (path, bytes) in files.iter().filter(|(p, _)| is_html(p)) {
633        let document = Html::parse_document(&String::from_utf8_lossy(bytes));
634        let mut seen = BTreeSet::new();
635        for link in html::links(&document) {
636            if let links::LinkTarget::Internal(target) = links::resolve(path, &link.url, domain)
637                && !links::exists(&target, on_disk, &redirects)
638                && seen.insert(target.clone())
639            {
640                findings.push(Finding::blocking(
641                    "broken-link",
642                    Some(path.clone()),
643                    item_of_path(input.report, path).cloned(),
644                    format!(
645                        "<{}> links to '{}', which the release does not contain",
646                        link.tag, link.url
647                    ),
648                ));
649            }
650        }
651    }
652    CheckResult::from_findings(GateCheck::Links, findings)
653}
654
655fn accessibility(
656    mode: GateMode,
657    input: &GateInput<'_>,
658    files: &BTreeMap<String, Vec<u8>>,
659    items: &[&ContentItem],
660) -> CheckResult {
661    let mut findings = Vec::new();
662    for (path, bytes) in files.iter().filter(|(p, _)| is_html(p)) {
663        let document = Html::parse_document(&String::from_utf8_lossy(bytes));
664        for violation in html::accessibility(&document) {
665            findings.push(Finding {
666                rule: violation.rule.into(),
667                severity: violation.severity,
668                blocking: violation.severity.fails_gate(),
669                path: Some(path.clone()),
670                item: item_of_path(input.report, path).cloned(),
671                message: format!(
672                    "WCAG {} {}: {}",
673                    violation.wcag, violation.element, violation.help
674                ),
675            });
676        }
677    }
678    for item in items {
679        for media in item.media.iter().filter(|m| m.content_type.starts_with("image/")) {
680            if !media.alt_confirmed || media.alt.is_none() {
681                findings.push(Finding {
682                    rule: "media-alt-confirmed".into(),
683                    severity: Severity::Critical,
684                    blocking: true,
685                    path: Some(media.path.clone()),
686                    item: Some(item.id.clone()),
687                    message: "WCAG 1.1.1: the image's alt text is not confirmed by a person".into(),
688                });
689            }
690        }
691    }
692    let mut result = CheckResult::from_findings(GateCheck::Accessibility, findings);
693    if mode == GateMode::Full {
694        if input.report.theme == input.project.theme.name {
695            for pair in input.project.theme.tokens.contrast_pairs() {
696                if !pair.passes() {
697                    result.findings.push(Finding::blocking(
698                        "color-contrast",
699                        None,
700                        None,
701                        format!(
702                            "WCAG 1.4.3: theme pair {} ({} on {}) is {:.2}:1; it needs {}:1",
703                            pair.name, pair.foreground, pair.background, pair.ratio, pair.required
704                        ),
705                    ));
706                    result.status = CheckStatus::Failed;
707                }
708            }
709        } else {
710            result.note =
711                Some("the theme's tokens are not the project's; contrast not measured".into());
712        }
713    }
714    result
715}
716
717fn performance(
718    input: &GateInput<'_>,
719    files: &BTreeMap<String, Vec<u8>>,
720    on_disk: &BTreeSet<String>,
721) -> CheckResult {
722    let budget = input.project.config.performance.critical_path_bytes;
723    let domain = &input.project.config.domain;
724    let size_of = |path: &str| -> u64 {
725        files.get(path).map(|b| b.len() as u64).unwrap_or_else(|| {
726            std::fs::metadata(input.out.join(path)).map(|m| m.len()).unwrap_or(0)
727        })
728    };
729    let mut findings = Vec::new();
730    let mut external = 0;
731    for (path, bytes) in files.iter().filter(|(p, _)| is_html(p)) {
732        let document = Html::parse_document(&String::from_utf8_lossy(bytes));
733        let mut total = bytes.len() as u64;
734        for resource in html::critical_resources(&document) {
735            match links::resolve(path, &resource, domain) {
736                links::LinkTarget::Internal(target) => {
737                    let target = if target.ends_with('/') || target.is_empty() {
738                        format!("{target}index.html")
739                    } else {
740                        target
741                    };
742                    if on_disk.contains(&target) {
743                        total += size_of(&target);
744                    }
745                }
746                links::LinkTarget::External => external += 1,
747                links::LinkTarget::Fragment => {}
748            }
749        }
750        if total > budget {
751            findings.push(Finding::blocking(
752                "critical-path-budget",
753                Some(path.clone()),
754                item_of_path(input.report, path).cloned(),
755                format!("the critical path is {total} bytes; the budget is {budget}"),
756            ));
757        }
758    }
759    let mut note = format!(
760        "LCP not measured: the built-in gate renders nothing; the {} ms budget needs a browser on the reference profile",
761        input.project.config.performance.lcp_ms
762    );
763    if external > 0 {
764        note.push_str(&format!("; {external} external render-blocking resource(s) not counted"));
765    }
766    CheckResult::from_findings(GateCheck::Performance, findings).note(note)
767}
768
769fn legal(input: &GateInput<'_>, live: &[&ContentItem]) -> CheckResult {
770    let jurisdictions: Vec<String> = if input.project.config.jurisdictions.is_empty() {
771        vec!["*".into()]
772    } else {
773        input.project.config.jurisdictions.clone()
774    };
775    let mut findings = Vec::new();
776    for jurisdiction in &jurisdictions {
777        for kind in REQUIRED_LEGAL {
778            let present = live.iter().any(|item| {
779                let legal = item.fields.get("legal").and_then(Value::as_str);
780                let covers =
781                    item.fields.get("jurisdictions").and_then(Value::as_array).is_none_or(|list| {
782                        jurisdiction == "*"
783                            || list.iter().any(|j| j.as_str() == Some(jurisdiction.as_str()))
784                    });
785                legal == Some(kind) && covers
786            });
787            if !present {
788                findings.push(Finding::blocking(
789                    "legal-page-missing",
790                    None,
791                    None,
792                    format!("no published {kind} page covers jurisdiction '{jurisdiction}'; add a page with `legal: {kind}`"),
793                ));
794            }
795        }
796    }
797    CheckResult::from_findings(GateCheck::Legal, findings)
798}
799
800fn machine_views(
801    mode: GateMode,
802    input: &GateInput<'_>,
803    files: &BTreeMap<String, Vec<u8>>,
804    on_disk: &BTreeSet<String>,
805) -> CheckResult {
806    let mut findings = Vec::new();
807    for page in &input.report.pages {
808        if !files.contains_key(&page.html) {
809            continue;
810        }
811        let (Some(md), Some(view)) = (&page.markdown, &page.machine_view) else { continue };
812        let missing = |what: &str, file: &str| {
813            Finding::blocking(
814                "twin-missing",
815                Some(page.html.clone()),
816                page.item.clone(),
817                format!("the page has no {what} at '{file}'"),
818            )
819        };
820        if !on_disk.contains(md) {
821            findings.push(missing("Markdown twin", md));
822        }
823        if !on_disk.contains(view) {
824            findings.push(missing("machine view", view));
825        } else {
826            let bytes = files
827                .get(view)
828                .cloned()
829                .or_else(|| std::fs::read(input.out.join(view)).ok())
830                .unwrap_or_default();
831            match serde_json::from_slice::<MachineView>(&bytes) {
832                Ok(parsed) if parsed.path == page.path => {}
833                Ok(parsed) => findings.push(Finding::blocking(
834                    "machine-view-invalid",
835                    Some(view.clone()),
836                    page.item.clone(),
837                    format!("the machine view names path '{}', not '{}'", parsed.path, page.path),
838                )),
839                Err(e) => findings.push(Finding::blocking(
840                    "machine-view-invalid",
841                    Some(view.clone()),
842                    page.item.clone(),
843                    format!("the machine view is not an AWP machine view: {e}"),
844                )),
845            }
846        }
847        let document = Html::parse_document(&String::from_utf8_lossy(&files[&page.html]));
848        let alternates = html::alternates(&document);
849        for (kind, file) in [("text/markdown", md), ("application/awp+json", view)] {
850            let expected = format!("/{file}");
851            if !alternates
852                .iter()
853                .any(|(t, href)| t == kind && (href == &expected || href.ends_with(&expected)))
854            {
855                findings.push(Finding::blocking(
856                    "twin-not-linked",
857                    Some(page.html.clone()),
858                    page.item.clone(),
859                    format!("the page does not link its {kind} twin with <link rel=\"alternate\">"),
860                ));
861            }
862        }
863    }
864    let mut result = CheckResult::from_findings(GateCheck::MachineViews, findings);
865    if mode == GateMode::Full {
866        let contract = ".well-known/awp.json";
867        if on_disk.contains(contract) {
868            let bytes = std::fs::read(input.out.join(contract)).unwrap_or_default();
869            if let Err(e) = serde_json::from_slice::<awp_types::SiteContract>(&bytes) {
870                result.findings.push(Finding::blocking(
871                    "contract-invalid",
872                    Some(contract.into()),
873                    None,
874                    e.to_string(),
875                ));
876                result.status = CheckStatus::Failed;
877            }
878        }
879        result.note = Some("`awp verify` against the preview runs as a gate extension".into());
880    }
881    result
882}
883
884fn quarantine(input: &GateInput<'_>, on_disk: &BTreeSet<String>) -> CheckResult {
885    let mut findings = Vec::new();
886    for page in &input.report.pages {
887        if let Some(item) = &page.item
888            && input.quarantine.items.contains(item)
889        {
890            findings.push(Finding::blocking(
891                "quarantined-item",
892                Some(page.html.clone()),
893                Some(item.clone()),
894                "the item is quarantined; it publishes only after a per-item decision".into(),
895            ));
896        }
897    }
898    for path in input.quarantine.paths.intersection(on_disk) {
899        findings.push(Finding::blocking(
900            "quarantined-file",
901            Some(path.clone()),
902            None,
903            "the file is quarantined; it publishes only after a per-item decision".into(),
904        ));
905    }
906    CheckResult::from_findings(GateCheck::Quarantine, findings)
907}
908
909fn required_languages(input: &GateInput<'_>, items: &[&ContentItem]) -> CheckResult {
910    let policy = &input.project.config.translation;
911    let mut findings = Vec::new();
912    if !policy.required.is_empty() {
913        for item in items {
914            let group: Vec<&ContentItem> = input
915                .project
916                .items
917                .iter()
918                .filter(|other| other.kind == item.kind && other.slug == item.slug)
919                .collect();
920            let missing = policy.missing_languages(group.iter().copied());
921            if !missing.is_empty() {
922                let list: Vec<&str> = missing.iter().map(|l| l.as_str()).collect();
923                findings.push(Finding::blocking(
924                    "language-missing",
925                    None,
926                    Some(item.id.clone()),
927                    format!("the item has no version in {}", list.join(", ")),
928                ));
929            }
930        }
931    }
932    CheckResult::from_findings(GateCheck::RequiredLanguages, findings)
933}
934
935fn structured_data(items: &[&ContentItem], files: &BTreeMap<String, Vec<u8>>) -> CheckResult {
936    let mut findings = Vec::new();
937    let mut push = |item: &ContentItem, rule: &str, message: String| {
938        findings.push(Finding::blocking(rule, None, Some(item.id.clone()), message));
939    };
940    for item in items {
941        let str_field = |key: &str| {
942            item.fields.get(key).and_then(Value::as_str).filter(|s| !s.trim().is_empty())
943        };
944        if str_field("title").is_none() {
945            push(item, "title-missing", "the item has no title".into());
946        }
947        match item.kind {
948            ContentKind::Product => {
949                if let Some(price) = item.fields.get("price") {
950                    if !price.as_f64().is_some_and(|p| p >= 0.0) {
951                        push(
952                            item,
953                            "price-invalid",
954                            "price must be a number of zero or more".into(),
955                        );
956                    }
957                    let currency_ok = str_field("currency").is_some_and(|c| {
958                        c.len() == 3 && c.chars().all(|ch| ch.is_ascii_uppercase())
959                    });
960                    if !currency_ok && !item.is_volatile("price") {
961                        push(
962                            item,
963                            "currency-invalid",
964                            "a price needs an ISO 4217 currency such as KES".into(),
965                        );
966                    }
967                }
968            }
969            ContentKind::Event => {
970                let start = item.fields.get("startsAt").and_then(Value::as_str);
971                let parse = |s: &str| {
972                    chrono::DateTime::parse_from_rfc3339(s).map(|d| d.timestamp()).ok().or_else(
973                        || {
974                            chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d").ok().map(|d| {
975                                d.and_hms_opt(0, 0, 0).unwrap_or_default().and_utc().timestamp()
976                            })
977                        },
978                    )
979                };
980                match start.and_then(parse) {
981                    None => push(
982                        item,
983                        "start-invalid",
984                        "an event needs startsAt as an RFC 3339 time or a date".into(),
985                    ),
986                    Some(starts) => {
987                        if let Some(ends) =
988                            item.fields.get("endsAt").and_then(Value::as_str).and_then(parse)
989                            && ends < starts
990                        {
991                            push(item, "end-before-start", "endsAt is before startsAt".into());
992                        }
993                    }
994                }
995            }
996            ContentKind::Article if item.state == ContentState::Corrected => {
997                let has_note =
998                    item.fields.get("corrections").and_then(Value::as_array).is_some_and(|c| {
999                        c.iter().any(|n| {
1000                            n.get("note")
1001                                .and_then(Value::as_str)
1002                                .is_some_and(|t| !t.trim().is_empty())
1003                        })
1004                    });
1005                if !has_note {
1006                    push(
1007                        item,
1008                        "correction-note-missing",
1009                        "a corrected article needs a visible correction note".into(),
1010                    );
1011                }
1012            }
1013            _ => {}
1014        }
1015    }
1016    for (path, bytes) in files.iter().filter(|(p, _)| is_html(p)) {
1017        let document = Html::parse_document(&String::from_utf8_lossy(bytes));
1018        for block in html::json_ld(&document) {
1019            if serde_json::from_str::<Value>(&block).is_err() {
1020                findings.push(Finding::blocking(
1021                    "json-ld-invalid",
1022                    Some(path.clone()),
1023                    None,
1024                    "a JSON-LD block does not parse".into(),
1025                ));
1026            }
1027        }
1028    }
1029    CheckResult::from_findings(GateCheck::StructuredData, findings)
1030}