@rebilder/agent-readability 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts","../src/profiles.ts","../src/ruleset.ts","../src/html.ts","../src/parse-money.ts","../src/extract.ts","../src/classify.ts","../src/recommend.ts","../src/score.ts"],"names":["child","deepFreeze","a","b","score"],"mappings":";;;AA2BO,IAAM,gBAAA,GAAmB;;;AC0CzB,IAAM,eAAA,GAAkB;AAAA,EAC7B,OAAA,EAAS;AAAA,IACP,QAAA,EAAU,SAAA;AAAA,IACV,IAAA,EAAM,CAAC,OAAA,EAAS,OAAA,EAAS,YAAY,cAAc,CAAA;AAAA,IACnD,UAAU,CAAC,OAAA,EAAS,KAAA,EAAO,UAAA,EAAY,WAAW,aAAa,CAAA;AAAA,IAC/D,eAAe,CAAA,GAAI;AAAA,GACrB;AAAA,EACA,UAAA,EAAY;AAAA,IACV,QAAA,EAAU,YAAA;AAAA,IACV,IAAA,EAAM,CAAC,OAAA,EAAS,YAAA,EAAc,WAAW,CAAA;AAAA,IACzC,QAAA,EAAU,CAAC,OAAA,EAAS,cAAA,EAAgB,aAAa,CAAA;AAAA,IACjD,eAAe,EAAA,GAAK;AAAA,GACtB;AAAA,EACA,OAAA,EAAS;AAAA,IACP,QAAA,EAAU,SAAA;AAAA,IACV,IAAA,EAAM,CAAC,OAAA,EAAS,QAAA,EAAU,WAAW,CAAA;AAAA,IACrC,QAAA,EAAU,CAAC,SAAA,EAAW,SAAA,EAAW,aAAa,CAAA;AAAA,IAC9C,eAAe,EAAA,GAAK;AAAA,GACtB;AAAA,EACA,KAAA,EAAO;AAAA,IACL,QAAA,EAAU,OAAA;AAAA,IACV,IAAA,EAAM,CAAC,UAAA,EAAY,SAAA,EAAW,SAAS,OAAO,CAAA;AAAA,IAC9C,QAAA,EAAU,CAAC,OAAA,EAAS,cAAA,EAAgB,sBAAsB,aAAa,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AAA,KAAS,IAAA,IAAQ,KAAA,CAAM,MAAA,GAAS,IAAA,CAAK,KAAA,CAAM,MAAA,EAAQ,IAAA,GAAO,EAAE,KAAA,EAAO,OAAA,EAAS,KAAA,EAAM;AAAA,IACxF;AACA,IAAA,KAAA,MAAW,KAAA,IAAS,MAAM,QAAA,EAAU;AAClC,MAAA,IAAI,CAAC,WAAA,CAAY,KAAA,EAAO,IAAI,CAAA,EAAG;AAC/B,MAAA,IAAI,IAAA,KAAS,IAAA,IAAQ,KAAA,CAAM,MAAA,GAAS,IAAA,CAAK,KAAA,CAAM,MAAA,EAAQ,IAAA,GAAO,EAAE,KAAA,EAAO,UAAA,EAAY,KAAA,EAAM;AAAA,IAC3F;AACA,IAAA,IAAI,IAAA,KAAS,IAAA,IAAQ,IAAA,CAAK,KAAA,KAAU,UAAA,EAAY;AAC9C,MAAA,OAAO,CAAA,YAAA,EAAe,aAAa,CAAA,aAAA,EAAgB,IAAA,CAAK,KAAK,CAAA,CAAA;AAAA,IAC/D;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT","file":"index.cjs","sourcesContent":["/**\n * types.ts — the public contract of the Agent Readability Score, ARS 0.1.\n *\n * Transcribed from `docs/design/universal-gateway-and-public-surfaces.md` §3.9,\n * which is the decided contract. Where §3.9 abbreviates (it writes `id: string`\n * for a check id whose format it then demonstrates), this file fills the gap\n * consistently with the §3.4 dimension table and the §3.6 scoring tables. Two\n * deliberate narrowings and one addition are marked NARROWED / ADDED below;\n * nothing else departs from the design.\n *\n * WHY THE TYPES MATTER MORE THAN USUAL HERE. ARS is published as a standard\n * (`docs/spec/ars-0.1.md`, rendered at `/spec/ars`), and its determinism\n * guarantee is stated as: *for a given `evidenceHash`, `rulesetHash` and\n * `corpusHash`, `score()` returns a byte-identical `ArsResult` in any conformant\n * implementation, in any language.* A second implementation in Go or Python\n * reproduces `expected.json` from the conformance corpus, and these types are\n * the schema of that file. A field added casually here is a field an outside\n * team has to reverse-engineer.\n *\n * SHAPE OF THE SYSTEM. The impure half (`./probe`) produces exactly one thing:\n * an `ArsEvidence` bundle. The pure half (`.`) consumes exactly that, plus an\n * `ArsRuleset`, and produces an `ArsResult`. There is no third input — no\n * clock, no network, no randomness, no LLM. The ESLint rule in\n * `eslint.config.mjs` enforces that at build time.\n */\n\n/** The spec version this package implements. See §3.1 for the versioning rules. */\nexport const ARS_SPEC_VERSION = '0.1.0' as const\n\n/**\n * Where the scan was taken from.\n * - `public` — an anonymous third-party scan. The only vantage that is robots-gated.\n * - `authenticated` — a signed-in Rebilder user scanning a domain they have verified.\n * - `self` — the site's own operator (Console, or the CLI run against their own\n * origin). Bypasses the `rebilder-ars` token check, because the owner can\n * consent for their own origin (§3.7).\n */\nexport type ArsVantage = 'public' | 'authenticated' | 'self'\n\n/**\n * Whether a check's earned points come from an observation or from an inference.\n * Published per check, and the total heuristic weight is capped at 40 of 100\n * (36 in 0.1) and printed. See §3.4.\n */\nexport type ArsBasis = 'measured' | 'heuristic'\n\nexport type ArsGrade = 'A' | 'B' | 'C' | 'D' | 'F'\n\n/**\n * The three crawler audiences (§3.7). `training` is strictly neutral: blocking\n * training crawlers while allowing assistants scores identically to a fully open\n * site (conformance fixtures 021 and 022 exist to prove exactly that).\n */\nexport type ArsAudience = 'assistant' | 'training' | 'search'\n\nexport type ArsUnscoredReason =\n | 'blocked-at-edge'\n | 'unreachable'\n | 'non-2xx'\n | 'too-many-redirects'\n | 'robots-disallow-scanner'\n | 'robots-unavailable'\n | 'truncated-evidence'\n | 'evidence-incomplete'\n\n/**\n * The three outcomes. Two of them carry no letter grade at all: a deliberate\n * opt-out is a choice, not a failure, and an unscored target is a missing\n * observation, not a bad one. Neither is ever ranked or listed (§3.6).\n */\nexport type ArsOutcome =\n | { kind: 'scored'; grade: ArsGrade; score: number }\n | { kind: 'opt-out'; audience: ArsAudience; wellFormed: true }\n | { kind: 'unscored'; reason: ArsUnscoredReason; detail?: string }\n\n/* ── evidence: the impure half's output, the pure half's only input ───────── */\n\nexport interface ArsHttpCapture {\n requestedUrl: string\n finalUrl: string\n redirects: { status: number; location: string }[]\n status: number\n /**\n * Lowercased header names → all values. An array, not a string, because\n * `Link` is routinely sent multiple times and is scored (D2.2, D6.5).\n * Volatile headers (`date`, `age`, `set-cookie`, `x-request-id`, `cf-ray`,\n * `report-to`) are excluded before hashing — without that exclusion the\n * evidence hash changes on every scan of every real site and replay dies.\n */\n headers: Record<string, string[]>\n /**\n * Decoded byte length. NORMATIVE MEASUREMENT — bodies are decoded per the\n * `Content-Type` charset (default UTF-8) and this is the UTF-8 byte length of\n * the result, so a Go implementation reproduces D3.2 and D4 offsets exactly.\n */\n bytes: number\n /** SHA-256 of the raw decoded body, hex. Published; the body is not. */\n bodySha256: string\n /** Present in-process and for a verified owner. NEVER in a published bundle. */\n body?: string\n /**\n * True when the 2 MiB body cap was hit. Surfaced in the UI and the byte figure\n * rendered as \"≥ N bytes\": silently scoring a truncated body makes the worst\n * sites score best on the one number the product is built on (§3.3).\n */\n truncated: boolean\n}\n\nexport type ArsProbeError =\n | 'timeout'\n | 'unreachable'\n | 'non-2xx'\n | 'blocked-redirect'\n | 'too-many-redirects'\n | 'challenge'\n | 'policy-rejected'\n\nexport interface ArsProbeRecord {\n requestHeaders: Record<string, string>\n result:\n | { ok: true; capture: ArsHttpCapture }\n | { ok: false; error: ArsProbeError; detail?: string }\n}\n\nexport interface ArsEvidence {\n evidenceVersion: '0.1.0'\n target: { url: string; origin: string }\n /**\n * `agent` and `browser` differ ONLY in the `Accept` header — same User-Agent,\n * same everything else. That is what makes the D2.4 parity check meaningful\n * and what stops a correctly installed gateway (which negotiates on `Accept`,\n * not on UA) from being scored as a cloaker (§3.3).\n */\n probes: {\n agent: ArsProbeRecord\n browser: ArsProbeRecord\n /** Third probe, ≥30s later, taken only when divergence was detected (§3.8). */\n parityConfirm: ArsProbeRecord | null\n robotsTxt: ArsProbeRecord | null\n llmsTxt: ArsProbeRecord | null\n wellKnownUcp: ArsProbeRecord | null\n }\n vantage: ArsVantage\n /** Wall clock. EXCLUDED from evidenceHash — never an input to scoring. */\n capturedAt: string\n}\n\n/* ── facts ───────────────────────────────────────────────────────────────── */\n\n/**\n * A closed set of 8. Every kind has exactly one complete profile (see\n * `./profiles`); a property test asserts the mapping is total. `unknown` is not\n * an easy exit — it still scores D5.2 against \"any recognised schema.org type\n * present\", so hiding your page kind costs points and gains nothing (§3.5).\n */\nexport type ArsPageKind =\n | 'product'\n | 'collection'\n | 'article'\n | 'place'\n | 'service'\n | 'faq'\n | 'document'\n | 'unknown'\n\n/**\n * Every fact name any profile may reference. Conformance fixture `058` asserts\n * that every name in every profile is a member of this union — the union is the\n * vocabulary, and a profile naming a fact outside it is a spec bug.\n */\nexport type ArsFactKind =\n | 'title'\n | 'description'\n | 'updated'\n | 'published'\n | 'price'\n | 'currency'\n | 'availability'\n | 'brand'\n | 'sku'\n | 'shipping'\n | 'returns'\n | 'org-name'\n | 'address'\n | 'hours'\n | 'phone'\n | 'email'\n | 'service-area'\n | 'author'\n | 'section'\n | 'authority'\n | 'primary-action-url'\n | 'eligibility'\n | 'duration'\n | 'question-answer'\n | 'item-count'\n | 'item-link'\n\nexport interface ArsFactProfile {\n pageKind: ArsPageKind\n core: readonly ArsFactKind[]\n extended: readonly ArsFactKind[]\n /**\n * Byte reference for D3.2, in bytes. Varies by kind; weights never do. This\n * is the mechanism that stops long-form content (articles, docs) being\n * structurally capped around C — the defect in every design that used\n * absolute byte bands (§3.5).\n */\n byteReference: number\n}\n\nexport interface ArsFactObservation {\n kind: ArsFactKind\n /** Normalised (money → minor units + ISO currency; dates → ISO 8601). */\n normalized: string\n source: 'json-ld' | 'microdata' | 'meta' | 'html-text' | 'negotiated'\n /**\n * UTF-8 byte offset of the first occurrence in the decoded body. A measured\n * offset of a heuristic fact — the offset itself is not a guess, which is why\n * D4 reports it as evidence even though D4's checks are heuristic.\n */\n offset: number\n /** Observed in ≥2 sources (e.g. JSON-LD and visible text). §3.6. */\n corroborated: boolean\n}\n\n/* ── scoring ─────────────────────────────────────────────────────────────── */\n\nexport type ArsDimensionId =\n | 'retrievability'\n | 'machine-representation'\n | 'fact-coverage'\n | 'fact-position'\n | 'structured-data'\n | 'contract-discovery'\n\n/**\n * Every check id in ARS 0.1, in dimension order, matching the §3.4 table row for\n * row. The `<dimension>.<check>` shape is normative: the prefix IS the\n * `ArsDimensionId`, so a check's dimension is derivable from its id and the two\n * can never disagree. §3.9 demonstrates the format with\n * `'retrievability.render-independence'` and leaves the rest implied; this is\n * that list, written out.\n *\n * NARROWED vs §3.9: `ArsCheck['id']` is this union rather than `string`. These\n * ids are published in the spec and appear in every `expected.json`; an\n * unconstrained string in a frozen contract is a typo waiting to ship.\n */\nexport type ArsCheckId =\n // D1 Retrievability — 20\n | 'retrievability.reachable' // D1.1, 8, measured\n | 'retrievability.robots-policy' // D1.2, 6, measured\n | 'retrievability.render-independence' // D1.3, 6, heuristic\n // D2 Machine representation — 20\n | 'machine-representation.negotiated-response' // D2.1, 10, measured\n | 'machine-representation.declared-alternates' // D2.2, 4, measured\n | 'machine-representation.vary-accept' // D2.3, 3, measured\n | 'machine-representation.substance-parity' // D2.4, 3, heuristic\n // D3 Fact coverage — 20\n | 'fact-coverage.core-facts' // D3.1, 14, heuristic\n | 'fact-coverage.context-cost' // D3.2, 6, measured\n // D4 Fact position — 10\n | 'fact-position.first-core-fact-offset' // D4.1, 5, heuristic\n | 'fact-position.front-window' // D4.2, 5, heuristic\n // D5 Structured data — 15\n | 'structured-data.present' // D5.1, 5, measured\n | 'structured-data.required-properties' // D5.2, 7, measured\n | 'structured-data.text-agreement' // D5.3, 3, heuristic\n // D6 Contract & discovery — 15\n | 'contract-discovery.canonical' // D6.1, 4, measured\n | 'contract-discovery.cache-validators' // D6.2, 3, measured\n | 'contract-discovery.llms-txt' // D6.3, 2, measured\n | 'contract-discovery.sitemap' // D6.4, 2, measured\n | 'contract-discovery.machine-endpoint' // D6.5, 4, measured\n\nexport interface ArsCheckEvidence {\n label: string\n value: string\n basis: ArsBasis\n}\n\nexport interface ArsCheck {\n /** e.g. 'retrievability.render-independence'. */\n id: ArsCheckId\n label: string\n basis: ArsBasis\n weight: number\n /** Integer, 0..weight. No floating point anywhere in the scoring path (§3.6). */\n earned: number\n evidence: ArsCheckEvidence[]\n remedy?: string\n}\n\nexport interface ArsDimension {\n id: ArsDimensionId\n label: string\n weight: number\n earned: number\n /** 'heuristic' if ANY constituent check is heuristic. */\n basis: ArsBasis\n checks: ArsCheck[]\n}\n\nexport type ArsFlagId =\n | 'substance-divergence'\n | 'structured-data-divergence'\n | 'robots-contradiction'\n | 'paywalled'\n | 'render-dependent'\n | 'scanner-blocked'\n | 'training-opt-out'\n | 'assistant-opt-out'\n | 'vary-missing'\n | 'canonical-mismatch'\n | 'body-truncated'\n | 'vantage-variance'\n\nexport interface ArsFlag {\n id: ArsFlagId\n /**\n * No 'critical'. No check publicly accuses anyone: a divergence flag reports\n * *\"the agent representation reported price X; the HTML representation\n * reported price Y at capture time\"*, which is an observation, not a charge of\n * cloaking (§3.8).\n */\n severity: 'info' | 'warn'\n basis: ArsBasis\n message: string\n evidence: ArsCheckEvidence[]\n}\n\nexport interface ArsAudienceDecision {\n decision: 'allow' | 'disallow' | 'unspecified'\n matchedGroup: string | null\n matchedRule: string | null\n}\n\nexport interface ArsPolicyReport {\n robotsTxtStatus: 'ok' | 'missing' | 'error' | 'unparseable'\n audiences: Record<ArsAudience, ArsAudienceDecision>\n deliberateOptOut: boolean\n /** NEUTRAL. Never lowers the score. */\n trainingOptOut: boolean\n sitemapDeclared: boolean\n}\n\nexport interface ArsCostReport {\n htmlBytes: number\n negotiatedBytes: number | null\n /** HEURISTIC (chars/4). Always rendered with ≈ and an \"est.\" chip. */\n approxHtmlTokens: number\n approxNegotiatedTokens: number | null\n reductionRatio: number | null\n firstCoreFactOffset: number | null\n truncated: boolean\n}\n\nexport interface ArsRecommendation {\n id: string\n title: string\n /**\n * Points recoverable, after dependency dedup: a recommendation counts only\n * checks not claimed by a higher-ranked recommendation, plus the checks it\n * uniquely unlocks. Sums per dimension are capped at the dimension weight, and\n * a property test asserts `Σ pointsAvailable ≤ 100 − score` (§3.9). Merchants\n * act on this surface, so the arithmetic is specified rather than implied.\n */\n pointsAvailable: number\n effort: 'config' | 'template' | 'engineering'\n detail: string\n /** Check ids this closes. */\n checks: ArsCheckId[]\n /** Check ids it unlocks (e.g. D2.1 unlocks D2.3, which is gated on it). */\n unlocks: ArsCheckId[]\n}\n\nexport interface ArsResult {\n spec: 'ars'\n specVersion: string\n /** SHA-256 of RFC 8785 canonical JSON of the frozen ruleset. */\n rulesetHash: string\n /** SHA-256 over the conformance corpus; pins observable behaviour. */\n corpusHash: string\n evidenceHash: string\n vantage: ArsVantage\n target: { url: string; finalUrl: string; origin: string }\n\n outcome: ArsOutcome\n score: number | null\n grade: ArsGrade | null\n bandLabel: string | null\n\n pageKind: ArsPageKind\n pageKindBasis: ArsBasis // always 'heuristic' in 0.1\n pageKindConfidence: 'high' | 'medium' | 'low'\n factProfile: ArsFactProfile\n facts: ArsFactObservation[]\n\n /** Always 6 entries, weights always summing to 100. */\n dimensions: ArsDimension[]\n flags: ArsFlag[]\n policy: ArsPolicyReport\n cost: ArsCostReport\n recommendations: ArsRecommendation[]\n\n measuredWeight: number // 64 in 0.1\n heuristicWeight: number // 36 in 0.1; ceiling 40, enforced by fixture 053\n}\n\nexport interface ArsBand {\n grade: ArsGrade\n min: number\n max: number\n label: string\n /** Descriptive only. Never predictive of third-party AI behaviour (§3.6). */\n meaning: string\n}\n\n/**\n * The frozen, hashed ruleset. Everything a second implementation needs to\n * reproduce a score, and nothing that varies between runs.\n *\n * ADDED vs §3.9: `timeoutMs`. §3.9's listing stops at `maxRedirects`, but §5.2\n * pins the probe timeout at 5 000ms in the same breath as the body cap and the\n * redirect limit, and the same argument applies to all three — two\n * implementations with different timeouts disagree about which pages are\n * scoreable at all, which is a score difference wearing a disguise.\n */\nexport interface ArsRuleset {\n version: string\n /** Check id → points. Must sum to exactly 100. Frozen per version. */\n weights: Readonly<Record<string, number>>\n /**\n * The §3.6 numeric bands, as flat integer arrays. Each key documents its own\n * encoding in `./ruleset`; all of them are `[threshold, value]` pairs so that a\n * second implementation reads one shape, not five.\n */\n thresholds: Readonly<Record<string, readonly number[]>>\n /** Robots `User-agent:` tokens per audience. Matched case-insensitively. */\n audienceTokens: Readonly<Record<ArsAudience, readonly string[]>>\n /** Hand-curated required properties per page kind. Provenance in the spec. */\n requiredProperties: Readonly<Record<ArsPageKind, readonly string[]>>\n /** Anchor/action phrases that qualify a link as `primary-action-url` (§3.5). */\n actionLexicon: readonly string[]\n maxBodyBytes: number // 2 MiB, normative\n maxRedirects: number // 3, normative\n timeoutMs: number // 5_000, normative (see the ADDED note above)\n profiles: readonly ArsFactProfile[] // total over ArsPageKind\n bands: readonly ArsBand[]\n}\n","/**\n * profiles.ts — the eight page-kind fact profiles. Design §3.5, table verbatim.\n *\n * THE ONE IDEA IN THIS FILE. ARS uses fixed weights for every page kind. What\n * varies is *what counts as a fact* and *what a page of that kind reasonably\n * costs*:\n *\n * > ARS does not measure how much you say. It measures whether the facts a\n * > caller needs **for this kind of page** are present, findable, and cheap\n * > **relative to what that kind of page costs**.\n *\n * Per-vertical *weights* would be the wrong design — it makes an 88 mean\n * different things on different pages and invites site-type shopping. A\n * per-vertical *fact set* and *byte reference* are not weights: an article that\n * spends 38 KB saying something is not penalised against a 40 KB reference,\n * while a product page that spends 38 KB to state four facts is. The byte\n * reference is specifically what stops long-form content being structurally\n * capped around C, which every source design that used absolute byte bands did.\n *\n * The set is CLOSED at eight, and every kind has a complete profile — there is\n * no \"no profile\" path. Conformance fixture `058-profiles-total-and-typed`\n * asserts both halves of that: the mapping is total over `ArsPageKind`, and\n * every fact name is a member of `ArsFactKind`. `PROFILE_BY_KIND` is typed as a\n * total `Record`, so the first half is also a compile error.\n *\n * `unknown` is deliberately not an easy exit. It carries the smallest core set,\n * but it still scores D5.2 against \"any recognised schema.org type present\",\n * which requires having a type at all. Hiding your page kind costs up to 7\n * points and gains nothing on coverage.\n *\n * ── Definitions of the fact terms the source designs left undefined (§3.5) ──\n *\n * `primary-action-url` — a same-origin-or-declared URL reachable from an\n * `<a href>`, a `<form action>`, or JSON-LD `potentialAction.target`, whose\n * anchor text or `name` matches the ruleset's action lexicon (`book`, `apply`,\n * `contact`, `buy`, `subscribe`, `start`, `request`, `download`, `sign up`,\n * `get a quote` and their pinned synonyms). The lexicon is pinned in\n * `DEFAULT_RULESET.actionLexicon`, not inferred per page.\n *\n * `authority` — an organisation or person named as the publisher of the content,\n * extracted from JSON-LD `publisher`/`author`, `<meta name=\"author\">`, or a\n * `rel=\"publisher\"` link.\n *\n * `org-name` — JSON-LD `Organization.name` / `LocalBusiness.name`,\n * `og:site_name`, or `<meta itemprop=\"name\">` on an org-typed scope.\n *\n * `item-count` / `item-link` — for `collection`: the number of distinct item\n * links inside the largest repeated-structure block, and whether those links\n * resolve to same-origin URLs. Counted from the largest repeated block\n * specifically so that a nav menu is not mistaken for a product grid.\n *\n * `question-answer` — a `FAQPage`/`Question` JSON-LD pair, or a `<dt>/<dd>`, a\n * `<details><summary>`, or a heading-followed-by-paragraph pair. Counted ONCE\n * as present, not per item: a page with 40 questions is not four times better\n * than a page with 10.\n *\n * `price` is satisfied by an explicit \"no published price\" signal as well as by\n * a number. We score honesty, not disclosure — a service page that says\n * \"pricing on request\" has told the agent what it needs to know.\n */\n\nimport type { ArsFactProfile, ArsPageKind } from './types'\n\n/**\n * The §3.5 table, one entry per `ArsPageKind`. Core facts score at full weight,\n * extended facts at ¼ credit (the single definition — the source designs used\n * ¼, ½ and \"half credit\" in three different places). Byte references are the\n * D3.2 denominator, in bytes.\n */\nexport const PROFILE_BY_KIND = {\n product: {\n pageKind: 'product',\n core: ['title', 'price', 'currency', 'availability'],\n extended: ['brand', 'sku', 'shipping', 'returns', 'description'],\n byteReference: 8 * 1024,\n },\n collection: {\n pageKind: 'collection',\n core: ['title', 'item-count', 'item-link'],\n extended: ['price', 'availability', 'description'],\n byteReference: 16 * 1024,\n },\n article: {\n pageKind: 'article',\n core: ['title', 'author', 'published'],\n extended: ['updated', 'section', 'description'],\n byteReference: 40 * 1024,\n },\n place: {\n pageKind: 'place',\n core: ['org-name', 'address', 'hours', 'phone'],\n extended: ['email', 'service-area', 'primary-action-url', 'description'],\n byteReference: 8 * 1024,\n },\n service: {\n pageKind: 'service',\n core: ['title', 'price', 'primary-action-url'],\n extended: ['duration', 'eligibility', 'service-area', 'description', 'updated'],\n byteReference: 8 * 1024,\n },\n faq: {\n pageKind: 'faq',\n core: ['title', 'question-answer'],\n extended: ['updated', 'description'],\n byteReference: 16 * 1024,\n },\n document: {\n pageKind: 'document',\n core: ['title', 'updated', 'authority'],\n extended: ['description', 'primary-action-url', 'section'],\n byteReference: 24 * 1024,\n },\n unknown: {\n pageKind: 'unknown',\n core: ['title', 'description', 'primary-action-url'],\n extended: ['updated', 'org-name'],\n byteReference: 16 * 1024,\n },\n} as const satisfies Record<ArsPageKind, ArsFactProfile>\n\n/**\n * The same eight profiles as the array `ArsRuleset.profiles` expects, in\n * declaration order (which is the order they appear in the §3.5 table, and is\n * therefore the order the spec renders them in).\n *\n * Runtime immutability: `as const` above makes every profile deeply readonly to\n * TypeScript, and `DEFAULT_RULESET` deep-freezes these exact objects at module\n * load, so a consumer cannot mutate a shared profile and silently change every\n * subsequent score.\n */\nexport const PROFILES: readonly ArsFactProfile[] = Object.freeze(Object.values(PROFILE_BY_KIND))\n\n/** Total by construction — `PROFILE_BY_KIND` is typed as a total Record. */\nexport function profileFor(pageKind: ArsPageKind): ArsFactProfile {\n return PROFILE_BY_KIND[pageKind]\n}\n","/**\n * ruleset.ts — `DEFAULT_RULESET`, the frozen ARS 0.1 ruleset.\n *\n * WHAT THIS FILE IS. Every number a second implementation needs in order to\n * reproduce a score, and nothing that varies between runs. `rulesetHash()` is\n * the SHA-256 of the RFC 8785 canonical JSON of this object, it is printed on\n * every result, and the determinism guarantee is stated in terms of it: a\n * number without `rulesetHash`, `corpusHash` and `evidenceHash` is not an ARS\n * score. That makes this file a published artifact, not configuration.\n *\n * CONSEQUENCE: editing a number here is a spec version change, not a code\n * change. Per §3.1, any edit that moves a conformance `expected.json` is at\n * minimum a MINOR — and MINOR means scores stop being comparable and every\n * published surface re-scores in a batch. The CI gate on PATCH releases exists\n * precisely so that \"just tweaking a threshold\" cannot happen quietly.\n *\n * WHY THE BODY CAP, REDIRECT LIMIT AND TIMEOUT LIVE HERE rather than in the\n * probe: two implementations with different caps produce different scores. A\n * 3 MiB cap turns a `truncated-evidence` non-grade into an F, and a 10s timeout\n * scores pages a 5s timeout reports as unreachable. They are inputs to the\n * score, so they are inputs to the hash.\n *\n * SHAPE. Everything is `as const satisfies <contract>`: the `satisfies` clause\n * proves the object matches the published type (and, for the tables keyed by\n * `ArsCheckId` / `ArsPageKind`, that it is TOTAL), while `as const` keeps the\n * literal types so callers get `number`, not `number | undefined`, from a known\n * key. `deepFreeze` then makes it immutable at runtime as well — a mutated\n * shared ruleset would corrupt every subsequent score in the process, silently.\n */\n\nimport { PROFILES } from './profiles'\nimport type {\n ArsBand,\n ArsBasis,\n ArsCheckId,\n ArsDimensionId,\n ArsPageKind,\n ArsRuleset,\n} from './types'\n\n// ---------------------------------------------------------------------------\n// Deep freeze\n// ---------------------------------------------------------------------------\n\n/**\n * Recursively freezes a plain data structure. Used once, on `DEFAULT_RULESET`.\n * `as const` is a compile-time guarantee only; this is the runtime half.\n */\nfunction deepFreeze<T>(value: T): T {\n if (typeof value !== 'object' || value === null) return value\n for (const child of Object.values(value as Record<string, unknown>)) deepFreeze(child)\n return Object.freeze(value)\n}\n\n// ---------------------------------------------------------------------------\n// Check weights — the §3.4 table, row for row\n// ---------------------------------------------------------------------------\n\n/**\n * Check id → points. Sums to exactly 100 across 19 checks.\n *\n * NO CONDITIONAL WEIGHTS. NO REDISTRIBUTION. NO HEURISTIC GATES OVER MEASURED\n * POINTS. Redistribution is a gaming vector (make the dimension you are bad at\n * inapplicable and the rest inflate), and a heuristic that can zero measured\n * points makes those points heuristic. So D2.4 and D5.3 are scored checks, not\n * gates: a parity failure loses its own 3 points and raises a `warn`, and does\n * not touch D2's other 17 measured points. That is what makes \"measured 64 /\n * heuristic 36\" an honest figure rather than a presentational one, and fixture\n * `053` re-derives the heuristic-*controlled* weight to prove it.\n *\n * `satisfies Record<ArsCheckId, number>` makes the table total: a check id\n * added to the union without a weight here is a compile error.\n */\nconst WEIGHTS = {\n // D1 Retrievability — 20\n 'retrievability.reachable': 8,\n 'retrievability.robots-policy': 6,\n 'retrievability.render-independence': 6,\n // D2 Machine representation — 20\n 'machine-representation.negotiated-response': 10,\n 'machine-representation.declared-alternates': 4,\n 'machine-representation.vary-accept': 3,\n 'machine-representation.substance-parity': 3,\n // D3 Fact coverage — 20\n 'fact-coverage.core-facts': 14,\n 'fact-coverage.context-cost': 6,\n // D4 Fact position — 10\n 'fact-position.first-core-fact-offset': 5,\n 'fact-position.front-window': 5,\n // D5 Structured data — 15\n 'structured-data.present': 5,\n 'structured-data.required-properties': 7,\n 'structured-data.text-agreement': 3,\n // D6 Contract & discovery — 15\n 'contract-discovery.canonical': 4,\n 'contract-discovery.cache-validators': 3,\n 'contract-discovery.llms-txt': 2,\n 'contract-discovery.sitemap': 2,\n 'contract-discovery.machine-endpoint': 4,\n} as const satisfies Record<ArsCheckId, number>\n\n/** Descriptive metadata per check: which dimension it belongs to, its published label, its basis. */\nexport interface ArsCheckMeta {\n dimension: ArsDimensionId\n label: string\n basis: ArsBasis\n}\n\n/**\n * The published catalogue of checks. `dimension` is redundant with the check id\n * prefix by construction — the id shape `<dimension>.<check>` is normative — and\n * is spelled out anyway so consumers never parse an id string to group results.\n *\n * `basis` is spec data (it appears in every `expected.json` and is printed next\n * to every check in the UI) but it is not part of `ArsRuleset` in §3.9, so it is\n * exported here rather than folded into the hashed object. A second\n * implementation reads it from the published §3.4 table.\n */\nexport const CHECK_META = {\n 'retrievability.reachable': {\n dimension: 'retrievability',\n label: 'Reachable on the agent path',\n basis: 'measured',\n },\n 'retrievability.robots-policy': {\n dimension: 'retrievability',\n label: 'Robots policy for assistants',\n basis: 'measured',\n },\n 'retrievability.render-independence': {\n dimension: 'retrievability',\n label: 'Core facts present without JavaScript',\n basis: 'heuristic',\n },\n 'machine-representation.negotiated-response': {\n dimension: 'machine-representation',\n label: 'Machine representation on Accept negotiation',\n basis: 'measured',\n },\n 'machine-representation.declared-alternates': {\n dimension: 'machine-representation',\n label: 'Declared alternate representations',\n basis: 'measured',\n },\n 'machine-representation.vary-accept': {\n dimension: 'machine-representation',\n label: 'Vary: Accept declared correctly',\n basis: 'measured',\n },\n 'machine-representation.substance-parity': {\n dimension: 'machine-representation',\n label: 'Same substance across representations',\n basis: 'heuristic',\n },\n 'fact-coverage.core-facts': {\n dimension: 'fact-coverage',\n label: 'Core facts for this page kind',\n basis: 'heuristic',\n },\n 'fact-coverage.context-cost': {\n dimension: 'fact-coverage',\n label: 'Context cost relative to this page kind',\n basis: 'measured',\n },\n 'fact-position.first-core-fact-offset': {\n dimension: 'fact-position',\n label: 'Byte offset of the first core fact',\n basis: 'heuristic',\n },\n 'fact-position.front-window': {\n dimension: 'fact-position',\n label: 'Core facts inside the front window',\n basis: 'heuristic',\n },\n 'structured-data.present': {\n dimension: 'structured-data',\n label: 'Structured data present and parsing',\n basis: 'measured',\n },\n 'structured-data.required-properties': {\n dimension: 'structured-data',\n label: 'Recognised type with its required properties',\n basis: 'measured',\n },\n 'structured-data.text-agreement': {\n dimension: 'structured-data',\n label: 'Structured data agrees with visible text',\n basis: 'heuristic',\n },\n 'contract-discovery.canonical': {\n dimension: 'contract-discovery',\n label: 'Canonical URL present and self-consistent',\n basis: 'measured',\n },\n 'contract-discovery.cache-validators': {\n dimension: 'contract-discovery',\n label: 'Cache validators',\n basis: 'measured',\n },\n 'contract-discovery.llms-txt': {\n dimension: 'contract-discovery',\n label: 'llms.txt present and spec-shaped',\n basis: 'measured',\n },\n 'contract-discovery.sitemap': {\n dimension: 'contract-discovery',\n label: 'Sitemap declared in robots.txt',\n basis: 'measured',\n },\n 'contract-discovery.machine-endpoint': {\n dimension: 'contract-discovery',\n label: 'Declared machine endpoint',\n basis: 'measured',\n },\n} as const satisfies Record<ArsCheckId, ArsCheckMeta>\n\n/**\n * The six dimensions and their frozen weights (§3.4): 20 · 20 · 20 · 10 · 15 ·\n * 15 = 100, identical for every page kind. Each weight is the sum of its\n * checks' weights in `WEIGHTS`; both are written out because both are published,\n * and conformance fixture `052` asserts they agree and that the total is 100.\n */\nexport const DIMENSION_META = {\n retrievability: { label: 'Retrievability', weight: 20 },\n 'machine-representation': { label: 'Machine representation', weight: 20 },\n 'fact-coverage': { label: 'Fact coverage', weight: 20 },\n 'fact-position': { label: 'Fact position', weight: 10 },\n 'structured-data': { label: 'Structured data', weight: 15 },\n 'contract-discovery': { label: 'Contract & discovery', weight: 15 },\n} as const satisfies Record<ArsDimensionId, { label: string; weight: number }>\n\n/** Published totals (§3.4). Heuristic weight has a spec ceiling of 40; fixture `053` enforces it. */\nexport const ARS_MEASURED_WEIGHT = 64\nexport const ARS_HEURISTIC_WEIGHT = 36\nexport const ARS_HEURISTIC_WEIGHT_CEILING = 40\n\n// ---------------------------------------------------------------------------\n// Thresholds — the §3.6 scoring tables, as integer pairs\n// ---------------------------------------------------------------------------\n\n/**\n * All numeric bands from §3.6, encoded as flat `[threshold, value]` pairs so a\n * second implementation reads one shape rather than five. Integer arithmetic\n * only: no floating point anywhere in the scoring path, because cross-language\n * conformance is impossible with float rounding drift. All values are\n * non-negative, so rounding is unambiguous half-up via\n * `(numerator + denominator / 2) / denominator` in integer division.\n *\n * Two encodings, each stated per key:\n * AT-LEAST — descending pairs; the first pair whose `threshold <= input` wins.\n * AT-MOST — ascending pairs; the first pair whose `input <= threshold` wins;\n * no match scores 0.\n */\nconst THRESHOLDS = {\n /**\n * D3.1 fact weighting, in quarter-units (§3.6), as\n * `[corroboratedCore, uncorroboratedCore, corroboratedExtended, uncorroboratedExtended]`:\n * coreUnits = 4 × corroborated core + 2 × uncorroborated core\n * extendedUnits = 1 × corroborated extended + 0 × uncorroborated extended\n * \"Extended = ¼ credit\" is the single definition of extended credit.\n */\n 'fact-coverage.fact-units': [4, 2, 1, 0],\n /**\n * D3.1 denominator multiplier: `denominator = 4 × coreSize`, i.e. full credit\n * is every core fact corroborated. `coveragePct` is then\n * `min(100, (100 × (coreUnits + extendedUnits) + denominator / 2) / denominator)`.\n */\n 'fact-coverage.core-denominator-multiplier': [4],\n /**\n * D3.1 density band. AT-LEAST over\n * `factsPerKiB100 = (coreFound × 100 + extendedFound × 25) × 1024 / max(1, bytes)`.\n * The `max(1, bytes)` clamp is normative and replaces `max(1, bytes / 1024)`,\n * which let a 200-byte stub top the band. Density saturates at ≥2 facts/KiB so\n * that keyword stuffing is pointless — fixtures `031` and `032` must score\n * identically.\n * Earned = `(14 × coveragePct × densityPct + 5000) / 10000`.\n */\n 'fact-coverage.density': [200, 100, 100, 85, 50, 70, 20, 50, 5, 30, 0, 15],\n /**\n * D3.2 context cost, 6 pts. AT-MOST over\n * `ratio = 100 × bytes / byteReference[pageKind]`; above the last threshold, 0.\n */\n 'fact-coverage.context-cost': [100, 6, 200, 5, 500, 3, 1500, 1],\n /** D4.1 first-core-fact byte offset, 5 pts. AT-MOST over the offset in bytes; else 0. */\n 'fact-position.first-core-fact-offset': [512, 5, 2048, 4, 8192, 2, 32768, 1],\n /**\n * D4.2 front window, 5 pts. AT-LEAST over the percentage of core facts whose\n * offset falls inside the window; below the last threshold, 0.\n */\n 'fact-position.front-window': [90, 5, 70, 4, 50, 3, 25, 1],\n /**\n * D4.2 window size: `max(2048, bytes / 5)`, as `[floor, divisor]`. ONE\n * expression, integer division — the `0.2 × bytes` form is deleted, because\n * two implementations rounding a float disagree at the boundary.\n */\n 'fact-position.front-window-size': [2048, 5],\n /**\n * Approximate token estimate, as `[bytesPerToken]`. HEURISTIC: decoded UTF-8\n * bytes are the normative measurement and approximate tokens are always\n * rendered with `≈` and an \"est.\" chip. chars/4 is not a token count and the\n * spec says so.\n */\n 'cost.approx-bytes-per-token': [4],\n} as const satisfies Readonly<Record<string, readonly number[]>>\n\n// ---------------------------------------------------------------------------\n// Crawler audiences (§3.7)\n// ---------------------------------------------------------------------------\n\n/**\n * Robots `User-agent:` product tokens per audience, in their published casing.\n * Matching is case-insensitive (RFC 9309 §2.2.1) — the casing here is for the\n * rendered spec table.\n *\n * The `training` list exists so it can be treated NEUTRALLY. Blocking training\n * crawlers while allowing assistants scores identically to a fully open site,\n * and fixtures `021`/`022` exist solely to prove it, because it is the first\n * thing a hostile reviewer tests. `search` is reported only, and feeds the\n * `robots-contradiction` input; it never scores.\n *\n * This list is versioned data, not a heuristic: adding a token changes scores\n * for sites that named it, so additions land as a MINOR.\n */\nconst AUDIENCE_TOKENS = {\n /** User-triggered assistant fetches. THE audience ARS scores. */\n assistant: [\n 'ChatGPT-User',\n 'Claude-User',\n 'Claude-SearchBot',\n 'DuckAssistBot',\n 'Meta-ExternalFetcher',\n 'MistralAI-User',\n 'OAI-SearchBot',\n 'Perplexity-User',\n ],\n /** Corpus/model-training crawlers. STRICTLY NEUTRAL — never lowers the score. */\n training: [\n 'AI2Bot',\n 'Applebot-Extended',\n 'Bytespider',\n 'CCBot',\n 'ClaudeBot',\n 'Diffbot',\n 'FacebookBot',\n 'Google-Extended',\n 'GPTBot',\n 'Meta-ExternalAgent',\n 'PanguBot',\n 'Timpibot',\n 'anthropic-ai',\n 'cohere-ai',\n 'omgili',\n ],\n /** Classic search indexers. Reported only. */\n search: ['Applebot', 'Baiduspider', 'Bingbot', 'DuckDuckBot', 'Googlebot', 'Slurp', 'YandexBot'],\n} as const satisfies Record<'assistant' | 'training' | 'search', readonly string[]>\n\n// ---------------------------------------------------------------------------\n// D5.2 required properties (§3.6)\n// ---------------------------------------------------------------------------\n\n/**\n * The hand-curated required-property table, per page kind.\n *\n * PROVENANCE, stated because D5.2 is 7 points and merchants will ask where the\n * list came from: it is NOT \"schema.org validity\" — schema.org defines no\n * required properties at all — and it is NOT Google's rich-results guidelines by\n * reference, which change without a version and would make ARS scores move\n * without an ARS release. It is the CORE FACT SET of each page kind (see\n * `./profiles`) expressed in schema.org vocabulary, plus the properties without\n * which those facts are not actionable — a price with no `priceCurrency` cannot\n * be used by a buying agent, so `product` and `service` require both. The table\n * is bounded because it covers 8 kinds, not the full vocabulary, and it is\n * published in the spec next to this rationale.\n *\n * NOTATION: a dot is a property path from the top-level node; traversal enters\n * array members (`offers.price` matches `offers[0].price`). Alias handling\n * (`openingHours` vs `openingHoursSpecification`, `Article.headline` vs `name`)\n * belongs to the extractor, not to this table.\n *\n * `unknown` requires only `name`, deliberately: §3.5 scores `unknown` against\n * \"any recognised schema.org type present\", which requires having a type but\n * cannot require properties of a kind we did not identify.\n */\nconst REQUIRED_PROPERTIES = {\n product: ['name', 'offers.price', 'offers.priceCurrency', 'offers.availability'],\n collection: ['name', 'numberOfItems', 'itemListElement'],\n article: ['headline', 'author', 'datePublished'],\n place: ['name', 'address', 'openingHours', 'telephone'],\n service: ['name', 'offers.price', 'offers.priceCurrency', 'potentialAction.target'],\n faq: ['name', 'mainEntity', 'mainEntity.acceptedAnswer'],\n document: ['name', 'dateModified', 'publisher'],\n unknown: ['name'],\n} as const satisfies Record<ArsPageKind, readonly string[]>\n\n// ---------------------------------------------------------------------------\n// Action lexicon (§3.5)\n// ---------------------------------------------------------------------------\n\n/**\n * Phrases that qualify a link, form or `potentialAction` as the page's\n * `primary-action-url`. Matched case-insensitively against normalised anchor\n * text / `name`, whitespace collapsed.\n *\n * PINNED, not inferred. §3.5 names ten stems — `book`, `apply`, `contact`,\n * `buy`, `subscribe`, `start`, `request`, `download`, `sign up`, `get a quote` —\n * \"and their pinned synonyms\"; this is that list. A lexicon that grew per page\n * (or per LLM call) would make `primary-action-url` non-deterministic, and\n * `primary-action-url` is a core fact for `service` and `unknown`, so it would\n * take the whole score with it. Sorted for readability; order is not\n * significant.\n */\nconst ACTION_LEXICON = [\n 'add to bag',\n 'add to basket',\n 'add to cart',\n 'apply',\n 'apply now',\n 'book',\n 'book now',\n 'buy',\n 'buy now',\n 'call now',\n 'checkout',\n 'contact',\n 'contact us',\n 'donate',\n 'download',\n 'email us',\n 'enroll',\n 'get a quote',\n 'get quote',\n 'get started',\n 'join',\n 'make an appointment',\n 'order',\n 'order now',\n 'purchase',\n 'register',\n 'request',\n 'request a demo',\n 'request a quote',\n 'reserve',\n 'schedule',\n 'sign up',\n 'signup',\n 'start',\n 'start free trial',\n 'subscribe',\n] as const satisfies readonly string[]\n\n// ---------------------------------------------------------------------------\n// Bands (§3.6)\n// ---------------------------------------------------------------------------\n\n/**\n * The five grade bands. Bands headline, integers are secondary, and there are no\n * decimals ever: ARS is ORDINAL, and \"you gave me 81 and my competitor 83\" is a\n * conversation about noise.\n *\n * The `meaning` strings are DESCRIPTIVE ONLY, and the phrasing is load-bearing.\n * Three labels from the source designs are deliberately gone: *\"expect wrong or\n * missing details in AI answers about this page\"* is a predictive assertion\n * about third-party AI output that ARS does not measure; *\"effectively closed to\n * agents\"* is falsifiable and wrong for a site at 39 serving clean HTML; *\"and\n * can trust it\"* asserts veracity, and ARS measures format, not truth. Two lines\n * print on every surface that shows a grade:\n *\n * ARS measures format and retrievability. It does not measure whether the\n * facts are true, or whether any assistant cites this page.\n */\nconst BANDS = [\n {\n grade: 'A',\n min: 90,\n max: 100,\n label: 'Agent-native',\n meaning:\n 'Facts are in a machine representation, complete for this page kind, front-loaded, and cheap to fetch.',\n },\n {\n grade: 'B',\n min: 75,\n max: 89,\n label: 'Agent-friendly',\n meaning:\n 'All core facts are present and findable; the agent pays more bytes than it needs, or one signal is missing.',\n },\n {\n grade: 'C',\n min: 60,\n max: 74,\n label: 'Readable with effort',\n meaning: 'Core facts are extractable from HTML, at high cost.',\n },\n {\n grade: 'D',\n min: 40,\n max: 59,\n label: 'Partial',\n meaning: 'Some core facts for this page kind were not found in the fetched response.',\n },\n {\n grade: 'F',\n min: 0,\n max: 39,\n label: 'Not extractable',\n meaning: 'Few or no core facts for this page kind were found in the fetched response.',\n },\n] as const satisfies readonly ArsBand[]\n\n// ---------------------------------------------------------------------------\n// The ruleset\n// ---------------------------------------------------------------------------\n\n/**\n * ARS 0.1's frozen ruleset.\n *\n * DESIGNED CEILINGS, printed in the spec as intentional rather than discovered:\n * no content negotiation loses D2.1 (10) + D2.3 (3, gated on D2.1) + D2.4 (3,\n * uncomparable) → max 84, capped at B. No valid structured data loses all of D5\n * (15) → max 85, capped at B. Reaching an A therefore requires BOTH a machine\n * representation and valid structured data — provable from these numbers alone,\n * which is why it is disclosed next to the conflict-of-interest note rather than\n * left for someone to discover.\n */\nexport const DEFAULT_RULESET = deepFreeze({\n version: '0.1.0',\n weights: WEIGHTS,\n thresholds: THRESHOLDS,\n audienceTokens: AUDIENCE_TOKENS,\n requiredProperties: REQUIRED_PROPERTIES,\n actionLexicon: ACTION_LEXICON,\n /** 2 MiB decoded. Streamed and aborted at the cap; `await response.text()` is forbidden. */\n maxBodyBytes: 2 * 1024 * 1024,\n /** 3 hops. Every hop re-resolves DNS and re-validates (§5.2). */\n maxRedirects: 3,\n /** 5s per request. See the ADDED note on `ArsRuleset` in ./types. */\n timeoutMs: 5_000,\n profiles: PROFILES,\n bands: BANDS,\n} as const satisfies ArsRuleset)\n","/**\n * html.ts — a tolerant, NON-EXECUTING HTML tokenizer, hand-rolled.\n *\n * WHY NOT parse5, cheerio, jsdom, or htmlparser2 (design §3.2, stated as a\n * normative reason rather than a preference): **a third-party parser version is\n * an unversioned input to a deterministic score.** ARS publishes the guarantee\n * that for a given `evidenceHash`, `rulesetHash` and `corpusHash`, `score()`\n * returns a byte-identical result in any conformant implementation, in any\n * language. A dependency that changes how a malformed `<div` is recovered\n * changes scores on a `pnpm update`, with no ARS version bump, no conformance\n * diff, and nothing in the release notes. It would also put a transitive\n * dependency tree into a package whose whole claim is that it has none.\n *\n * The second reason is the same one that rules out a cascade engine: this\n * tokenizer's recovery rules ARE the spec. They are written here, in ~600 lines,\n * where a second implementation in Go can read them.\n *\n * NON-EXECUTING is literal and load-bearing. `<script>` and `<style>` contents\n * are captured as opaque raw text and never evaluated, never fed to a JS engine,\n * never resolved. The probe fetches attacker-controlled bytes from arbitrary\n * origins; the only safe posture is that those bytes are data all the way down.\n *\n * WHAT IT EXTRACTS\n * - every start/end tag, with attributes (lowercased names, entity-decoded values)\n * - every text node, with its **UTF-8 byte offset** into the source\n * - `<script type=\"application/ld+json\">` contents, verbatim\n * - `<meta>` tags (name / property / http-equiv / itemprop / charset / content)\n * - `<link>` tags, including the multi-value `rel` token list\n *\n * BYTE OFFSETS ARE LOAD-BEARING. D4 scores the byte offset of the first core\n * fact (`≤512B → 5 · ≤2KiB → 4 · ≤8KiB → 2 · ≤32KiB → 1`) and the fraction of\n * core facts inside a `max(2048, bytes / 5)` front window. `ArsHttpCapture.bytes`\n * is defined as the *decoded UTF-8 byte length*, so offsets here are UTF-8 byte\n * offsets, NOT JavaScript string indices. On a page with any multibyte character\n * before the price — a `€`, a `—`, a CJK product name — those two numbers differ,\n * and a Go implementation counting real bytes would disagree with us. See\n * `Utf8Cursor`.\n *\n * TEXT EXTRACTION (normative, §3.6). Counted text is every text node except:\n * `<script>`, `<style>`, `<template>`, elements carrying the `hidden`\n * attribute, and elements carrying inline `style=\"display:none\"`.\n * **No CSS resolution** — a cascade engine would not be deterministic across\n * implementations, so a class that hides an element in a stylesheet does not\n * hide it here, and the spec says so rather than pretending otherwise.\n *\n * ONE READING DECISION, FLAGGED. §3.6 writes the rule as \"except `<script>`\n * (excluding `application/ld+json`)\", which can be read either way. We implement:\n * **JSON-LD script contents are NOT counted text**; they are surfaced separately\n * as `HtmlDocument.jsonLd`. The other reading breaks two mechanisms that the rest\n * of the spec depends on — D5.3 checks that structured data agrees with *visible*\n * text, and \"corroborated\" means observed in ≥2 sources (e.g. JSON-LD *and*\n * visible text). If JSON-LD were visible text, both would be satisfied by a\n * single JSON-LD block, trivially and always. Every text node reports\n * `excludedBy`, so the distinction is visible to callers rather than baked in.\n *\n * TOLERANCE CONTRACT: `tokenizeHtml` never throws, for any input string —\n * unterminated tags, unterminated comments, stray `<`, lone surrogates, 100k\n * nested `<div>`s, binary noise. Conformance fixture `057-tokenizer-fuzz` and\n * `tests/html.test.ts` both assert it. A scanner that can be crashed by the page\n * it is scanning is a denial-of-service endpoint.\n */\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/** Why a text node is not counted text. `null` means it is counted. */\nexport type HtmlExclusionReason =\n | 'script'\n | 'script-ld-json'\n | 'style'\n | 'template'\n | 'hidden-attribute'\n | 'inline-display-none'\n\nexport interface HtmlElement {\n /** Index into `HtmlDocument.elements`; ascending in source order. */\n index: number\n /** Lowercased tag name. */\n tag: string\n /** Lowercased attribute names → entity-decoded values. First occurrence wins (HTML5). */\n attrs: Readonly<Record<string, string>>\n /** UTF-8 byte offset of the `<` that opens this tag. */\n offset: number\n /** Index of the enclosing open element, or -1 at document level. */\n parent: number\n /** Nesting depth; 0 at document level. */\n depth: number\n /**\n * Effective exclusion for text inside this element — its own reason, or the\n * nearest ancestor's. `null` when text inside it counts.\n */\n excludedBy: HtmlExclusionReason | null\n}\n\nexport interface HtmlText {\n /** Entity-decoded text (raw, undecoded inside `<script>`/`<style>`). */\n text: string\n /** UTF-8 byte offset of the first character of the RAW source text. */\n offset: number\n /** UTF-8 byte length of the RAW source text. */\n bytes: number\n /** Index of the innermost enclosing element, or -1 at document level. */\n parent: number\n /** `null` when this node is counted text; otherwise why it is not. */\n excludedBy: HtmlExclusionReason | null\n}\n\nexport interface HtmlJsonLd {\n /** Script contents, verbatim. Not entity-decoded: `<script>` is a raw-text element. */\n text: string\n /** UTF-8 byte offset of the first character of the contents. */\n offset: number\n /** Index of the `<script>` element in `HtmlDocument.elements`. */\n element: number\n}\n\nexport interface HtmlMeta {\n /** Lowercased `name`, or null. */\n name: string | null\n /** Lowercased `property` (Open Graph), or null. */\n property: string | null\n /** Lowercased `http-equiv`, or null. */\n httpEquiv: string | null\n /** Lowercased `itemprop`, or null. */\n itemprop: string | null\n /** Lowercased `charset`, or null. */\n charset: string | null\n /** `content`, decoded, case preserved. */\n content: string | null\n element: number\n offset: number\n}\n\nexport interface HtmlLink {\n /**\n * `rel` as a token list, lowercased, source order, duplicates removed.\n * `rel=\"alternate canonical\"` is one link declaring two relations, and D2.2\n * (declared alternates) and D6.1 (canonical) both read it — collapsing it to a\n * string would lose one of them.\n */\n rel: readonly string[]\n href: string | null\n /** Lowercased `type`, or null. */\n type: string | null\n /** Lowercased `hreflang`, or null. */\n hreflang: string | null\n title: string | null\n element: number\n offset: number\n}\n\nexport interface HtmlDocument {\n readonly elements: readonly HtmlElement[]\n readonly texts: readonly HtmlText[]\n readonly jsonLd: readonly HtmlJsonLd[]\n readonly metas: readonly HtmlMeta[]\n readonly links: readonly HtmlLink[]\n /** Total UTF-8 byte length of the source. */\n readonly bytes: number\n}\n\n// ---------------------------------------------------------------------------\n// UTF-8 offsets\n// ---------------------------------------------------------------------------\n\n/**\n * Maps JavaScript string indices to UTF-8 byte offsets in one forward pass.\n *\n * The tokenizer advances monotonically, so `at()` is amortised O(1); a\n * non-monotonic call restarts from zero rather than returning a wrong number,\n * because a silently wrong offset is a silently wrong D4 score.\n *\n * Surrogate handling matches `TextEncoder`: a well-formed pair costs 4 bytes,\n * and a LONE surrogate costs 3 — WHATWG encoding replaces it with U+FFFD, so\n * that is what its byte cost actually is on the wire.\n */\nclass Utf8Cursor {\n private charIndex = 0\n private byteIndex = 0\n\n constructor(private readonly source: string) {}\n\n at(target: number): number {\n if (target < this.charIndex) {\n this.charIndex = 0\n this.byteIndex = 0\n }\n const limit = Math.min(target, this.source.length)\n while (this.charIndex < limit) {\n const code = this.source.charCodeAt(this.charIndex)\n if (code < 0x80) {\n this.byteIndex += 1\n this.charIndex += 1\n } else if (code < 0x800) {\n this.byteIndex += 2\n this.charIndex += 1\n } else if (code >= 0xd800 && code <= 0xdbff) {\n const next =\n this.charIndex + 1 < this.source.length ? this.source.charCodeAt(this.charIndex + 1) : 0\n if (next >= 0xdc00 && next <= 0xdfff && this.charIndex + 1 < limit) {\n this.byteIndex += 4\n this.charIndex += 2\n } else {\n // Lone high surrogate, or a pair straddling `limit`: 3 bytes for U+FFFD.\n this.byteIndex += 3\n this.charIndex += 1\n }\n } else {\n this.byteIndex += 3\n this.charIndex += 1\n }\n }\n return this.byteIndex\n }\n}\n\n// ---------------------------------------------------------------------------\n// Entity decoding\n// ---------------------------------------------------------------------------\n\n/**\n * Pinned named character references.\n *\n * The full HTML5 named-reference table is ~2 200 entries. This is the subset\n * that appears in the parts of a page ARS reads — money symbols, typography,\n * and the five XML entities — and it is PINNED per spec version for the same\n * reason the tokenizer is hand-rolled: growing the table changes extracted text,\n * which changes facts, which changes scores. Additions land as a MINOR.\n *\n * A named reference outside this table is left verbatim, which is also the only\n * safe failure: `&hearts;` surviving as literal text costs nothing, whereas\n * guessing would be non-deterministic.\n */\nconst NAMED_ENTITIES: Readonly<Record<string, string>> = {\n amp: '&',\n lt: '<',\n gt: '>',\n quot: '\"',\n apos: \"'\",\n nbsp: '\\u00a0',\n ensp: '\\u2002',\n emsp: '\\u2003',\n thinsp: '\\u2009',\n shy: '\\u00ad',\n zwnj: '\\u200c',\n zwj: '\\u200d',\n // Currency\n cent: '¢',\n pound: '£',\n curren: '¤',\n yen: '¥',\n euro: '€',\n dollar: '$',\n // Typography\n ndash: '–',\n mdash: '—',\n hellip: '…',\n lsquo: '‘',\n rsquo: '’',\n sbquo: '‚',\n ldquo: '“',\n rdquo: '”',\n bdquo: '„',\n laquo: '«',\n raquo: '»',\n lsaquo: '‹',\n rsaquo: '›',\n bull: '•',\n middot: '·',\n dagger: '†',\n Dagger: '‡',\n prime: '′',\n Prime: '″',\n // Marks and math\n copy: '©',\n reg: '®',\n trade: '™',\n sect: '§',\n para: '¶',\n deg: '°',\n plusmn: '±',\n times: '×',\n divide: '÷',\n minus: '−',\n permil: '‰',\n frac12: '½',\n frac14: '¼',\n frac34: '¾',\n sup2: '²',\n sup3: '³',\n le: '≤',\n ge: '≥',\n ne: '≠',\n // Directionality (invisible, but they do occupy bytes)\n lrm: '\\u200e',\n rlm: '\\u200f',\n}\n\n/**\n * The HTML spec's windows-1252 override for numeric references in 0x80–0x9F.\n * `&#146;` is a right single quote on real pages, not a C1 control, and\n * decoding it as one would corrupt product titles.\n */\nconst C1_REPLACEMENTS: Readonly<Record<number, number>> = {\n 0x80: 0x20ac,\n 0x82: 0x201a,\n 0x83: 0x0192,\n 0x84: 0x201e,\n 0x85: 0x2026,\n 0x86: 0x2020,\n 0x87: 0x2021,\n 0x88: 0x02c6,\n 0x89: 0x2030,\n 0x8a: 0x0160,\n 0x8b: 0x2039,\n 0x8c: 0x0152,\n 0x8e: 0x017d,\n 0x91: 0x2018,\n 0x92: 0x2019,\n 0x93: 0x201c,\n 0x94: 0x201d,\n 0x95: 0x2022,\n 0x96: 0x2013,\n 0x97: 0x2014,\n 0x98: 0x02dc,\n 0x99: 0x2122,\n 0x9a: 0x0161,\n 0x9b: 0x203a,\n 0x9c: 0x0153,\n 0x9e: 0x017e,\n 0x9f: 0x0178,\n}\n\n/**\n * A trailing `;` is REQUIRED. HTML's legacy semicolon-less forms\n * (`&copy` inside `?a=1&copy=2`) are exactly the cases where decoding mangles a\n * URL, and every reference that matters on a page ARS reads is written properly.\n * Bounded name length keeps the match linear.\n */\nconst ENTITY_RE = /&(#[xX][0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z][a-zA-Z0-9]{0,31});/g\n\nfunction codePointToString(raw: number): string {\n const mapped = C1_REPLACEMENTS[raw]\n const code = mapped ?? raw\n // Null, surrogates and out-of-range all become U+FFFD, per the HTML spec.\n if (code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) return '\\ufffd'\n return String.fromCodePoint(code)\n}\n\n/** Decodes the pinned named references plus numeric references. Never throws. */\nexport function decodeEntities(text: string): string {\n if (!text.includes('&')) return text\n return text.replace(ENTITY_RE, (match, body: string) => {\n if (body.startsWith('#')) {\n const isHex = body[1] === 'x' || body[1] === 'X'\n const digits = isHex ? body.slice(2) : body.slice(1)\n const value = Number.parseInt(digits, isHex ? 16 : 10)\n return Number.isNaN(value) ? match : codePointToString(value)\n }\n return NAMED_ENTITIES[body] ?? match\n })\n}\n\n// ---------------------------------------------------------------------------\n// Element tables\n// ---------------------------------------------------------------------------\n\n/** Void elements: no contents, never pushed onto the open-element stack. */\nconst VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n])\n\n/** Raw-text elements: contents are opaque, entities are NOT decoded. */\nconst RAW_TEXT_ELEMENTS = new Set(['script', 'style'])\n\n/** RCDATA elements: contents are text, entities ARE decoded, tags are not. */\nconst RCDATA_ELEMENTS = new Set(['textarea', 'title'])\n\n/**\n * Optional-end-tag recovery, in the small form that matters here. A start tag\n * listed as a key implicitly closes any open element in its value set. Without\n * this, `<li>a<li>b` nests forever and `<dt>q<dd>a` puts the answer inside the\n * question — and `<dt>/<dd>` pairs are one of the recognised `question-answer`\n * shapes for the `faq` page kind, so getting it wrong costs real points.\n */\nconst IMPLIED_END_TAGS: Readonly<Record<string, readonly string[]>> = {\n li: ['li'],\n dt: ['dt', 'dd'],\n dd: ['dt', 'dd'],\n option: ['option'],\n optgroup: ['option', 'optgroup'],\n tr: ['td', 'th', 'tr'],\n td: ['td', 'th'],\n th: ['td', 'th'],\n tbody: ['td', 'th', 'tr', 'thead', 'tbody'],\n tfoot: ['td', 'th', 'tr', 'thead', 'tbody'],\n}\n\n/** Block-level start tags that implicitly close an open `<p>`. */\nconst CLOSES_OPEN_P = new Set([\n 'address',\n 'article',\n 'aside',\n 'blockquote',\n 'details',\n 'div',\n 'dl',\n 'fieldset',\n 'figcaption',\n 'figure',\n 'footer',\n 'form',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'header',\n 'hr',\n 'main',\n 'nav',\n 'ol',\n 'p',\n 'pre',\n 'section',\n 'table',\n 'ul',\n])\n\n/**\n * Cap on open-element depth. Beyond it, elements are still recorded but not\n * pushed, so a page with 200 000 nested `<div>`s costs memory proportional to\n * its bytes and nothing more. Real documents do not approach this.\n */\nconst MAX_DEPTH = 256\n\n// ---------------------------------------------------------------------------\n// Small helpers\n// ---------------------------------------------------------------------------\n\nfunction isAsciiAlpha(ch: string | undefined): boolean {\n if (ch === undefined) return false\n return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')\n}\n\nfunction isHtmlSpace(ch: string): boolean {\n return ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r' || ch === '\\f'\n}\n\n/**\n * Inline `display:none`, with whitespace stripped first so the test itself is a\n * plain substring match rather than a regex with a backtracking profile. Only\n * the element's own `style` attribute is consulted: NO CSS RESOLUTION (§3.6).\n */\nconst DISPLAY_NONE_RE = /(^|;)display:none(!important)?(;|$)/\n\nfunction hasInlineDisplayNone(style: string | undefined): boolean {\n if (style === undefined) return false\n return DISPLAY_NONE_RE.test(style.toLowerCase().replace(/\\s+/g, ''))\n}\n\n/** Reads an attribute, or null. Attribute names are lowercased by the tokenizer. */\nexport function attr(element: HtmlElement, name: string): string | null {\n return element.attrs[name] ?? null\n}\n\n// ---------------------------------------------------------------------------\n// Tag parsing\n// ---------------------------------------------------------------------------\n\ninterface ParsedTag {\n tag: string\n attrs: Record<string, string>\n selfClosing: boolean\n /** Index just past the closing `>` (or past the end of input if unterminated). */\n end: number\n}\n\n/**\n * Parses a start tag beginning at `start` (the `<`). Tolerant: an unterminated\n * tag consumes to end of input and returns what it read.\n */\nfunction parseStartTag(html: string, start: number): ParsedTag {\n let i = start + 1\n const nameStart = i\n while (i < html.length) {\n const ch = html[i] ?? ''\n if (isHtmlSpace(ch) || ch === '/' || ch === '>') break\n i++\n }\n const tag = html.slice(nameStart, i).toLowerCase()\n const attrs: Record<string, string> = {}\n let selfClosing = false\n\n while (i < html.length) {\n while (i < html.length && isHtmlSpace(html[i] ?? '')) i++\n if (i >= html.length) break\n const ch = html[i] ?? ''\n if (ch === '>') {\n i++\n return { tag, attrs, selfClosing, end: i }\n }\n if (ch === '/') {\n selfClosing = true\n i++\n continue\n }\n // Attribute name.\n const attrNameStart = i\n while (i < html.length) {\n const c = html[i] ?? ''\n if (isHtmlSpace(c) || c === '=' || c === '>' || c === '/') break\n i++\n }\n if (i === attrNameStart) {\n // Nothing consumed (e.g. a stray '='): skip a character so we always advance.\n i++\n continue\n }\n const attrName = html.slice(attrNameStart, i).toLowerCase()\n let value = ''\n while (i < html.length && isHtmlSpace(html[i] ?? '')) i++\n if (html[i] === '=') {\n i++\n while (i < html.length && isHtmlSpace(html[i] ?? '')) i++\n const quote = html[i]\n if (quote === '\"' || quote === \"'\") {\n i++\n const valueStart = i\n const close = html.indexOf(quote, i)\n if (close === -1) {\n value = html.slice(valueStart)\n i = html.length\n } else {\n value = html.slice(valueStart, close)\n i = close + 1\n }\n } else {\n const valueStart = i\n while (i < html.length) {\n const c = html[i] ?? ''\n if (isHtmlSpace(c) || c === '>') break\n i++\n }\n value = html.slice(valueStart, i)\n }\n }\n // First occurrence wins, per the HTML parsing spec.\n if (!(attrName in attrs)) attrs[attrName] = decodeEntities(value)\n }\n return { tag, attrs, selfClosing, end: i }\n}\n\n/** Locates the matching `</tag` for a raw-text or RCDATA element, case-insensitively. */\nfunction findRawTextEnd(html: string, from: number, tag: string): number {\n const needle = `</${tag}`\n const lower = html.toLowerCase()\n const at = lower.indexOf(needle, from)\n return at === -1 ? -1 : at\n}\n\n// ---------------------------------------------------------------------------\n// tokenizeHtml\n// ---------------------------------------------------------------------------\n\n/** The element's own exclusion reason, ignoring ancestors. */\nfunction ownExclusion(\n tag: string,\n attrs: Readonly<Record<string, string>>,\n): HtmlExclusionReason | null {\n if (tag === 'script') {\n const type = (attrs['type'] ?? '').toLowerCase().split(';')[0]?.trim() ?? ''\n return type === 'application/ld+json' ? 'script-ld-json' : 'script'\n }\n if (tag === 'style') return 'style'\n if (tag === 'template') return 'template'\n // `hidden` is a boolean attribute: its presence hides, whatever the value\n // (including `hidden=\"until-found\"`, which is still hidden until found).\n if ('hidden' in attrs) return 'hidden-attribute'\n if (hasInlineDisplayNone(attrs['style'])) return 'inline-display-none'\n return null\n}\n\n/**\n * Tokenizes `html` into the flat, offset-annotated structure ARS scores against.\n * Never throws. `html` is the DECODED response body; offsets are UTF-8 byte\n * offsets into that decoded body, matching `ArsHttpCapture.bytes`.\n */\nexport function tokenizeHtml(html: string): HtmlDocument {\n const elements: HtmlElement[] = []\n const texts: HtmlText[] = []\n const jsonLd: HtmlJsonLd[] = []\n const metas: HtmlMeta[] = []\n const links: HtmlLink[] = []\n const stack: number[] = []\n const cursor = new Utf8Cursor(html)\n\n const topIndex = (): number => stack[stack.length - 1] ?? -1\n const exclusionAt = (elementIndex: number): HtmlExclusionReason | null =>\n elementIndex >= 0 ? (elements[elementIndex]?.excludedBy ?? null) : null\n\n const emitText = (\n from: number,\n to: number,\n decode: boolean,\n override?: HtmlExclusionReason,\n ): void => {\n if (to <= from) return\n const raw = html.slice(from, to)\n const parent = topIndex()\n const offset = cursor.at(from)\n texts.push({\n text: decode ? decodeEntities(raw) : raw,\n offset,\n bytes: cursor.at(to) - offset,\n parent,\n excludedBy: override ?? exclusionAt(parent),\n })\n }\n\n const popTo = (tag: string): void => {\n for (let depth = stack.length - 1; depth >= 0; depth--) {\n const candidate = stack[depth]\n if (candidate === undefined) continue\n if (elements[candidate]?.tag === tag) {\n stack.length = depth\n return\n }\n }\n // No matching open element: a stray end tag. Ignore it, as browsers do.\n }\n\n const applyImpliedEndTags = (tag: string): void => {\n const closes = IMPLIED_END_TAGS[tag]\n if (closes !== undefined) {\n while (stack.length > 0) {\n const top = stack[stack.length - 1]\n const openTag = top === undefined ? undefined : elements[top]?.tag\n if (openTag === undefined || !closes.includes(openTag)) break\n stack.pop()\n }\n }\n if (CLOSES_OPEN_P.has(tag)) {\n const top = stack[stack.length - 1]\n if (top !== undefined && elements[top]?.tag === 'p') stack.pop()\n }\n }\n\n // `textStart` trails `i`: a `<` that turns out NOT to open markup stays inside\n // the current text run rather than splitting it. `a < b` is one text node, not\n // three — and since `countedText` joins nodes with a space, splitting it would\n // silently rewrite the page's own text before any fact is extracted from it.\n let i = 0\n let textStart = 0\n while (i < html.length) {\n const lt = html.indexOf('<', i)\n if (lt === -1) break\n\n const next = html[lt + 1]\n // A `<` opens markup only before `!`, `/`, or an ASCII letter. Anything else\n // — `3<4`, a stray `<` at end of input — is text.\n if (next !== '!' && next !== '/' && !isAsciiAlpha(next)) {\n i = lt + 1\n continue\n }\n emitText(textStart, lt, true)\n\n // --- Comments, doctypes, CDATA, bogus comments ---\n if (next === '!') {\n if (html.startsWith('<!--', lt)) {\n const close = html.indexOf('-->', lt + 4)\n i = close === -1 ? html.length : close + 3\n } else {\n const close = html.indexOf('>', lt + 2)\n i = close === -1 ? html.length : close + 1\n }\n textStart = i\n continue\n }\n\n // --- End tags ---\n if (next === '/') {\n const close = html.indexOf('>', lt + 2)\n const end = close === -1 ? html.length : close + 1\n const rawName = html.slice(lt + 2, close === -1 ? html.length : close).trim()\n const tag = rawName.toLowerCase()\n if (tag.length > 0) popTo(tag)\n i = end\n textStart = i\n continue\n }\n\n // --- Start tags ---\n const parsed = parseStartTag(html, lt)\n applyImpliedEndTags(parsed.tag)\n\n const parent = topIndex()\n const own = ownExclusion(parsed.tag, parsed.attrs)\n const element: HtmlElement = {\n index: elements.length,\n tag: parsed.tag,\n attrs: parsed.attrs,\n offset: cursor.at(lt),\n parent,\n depth: stack.length,\n excludedBy: exclusionAt(parent) ?? own,\n }\n elements.push(element)\n collectMetaOrLink(element, metas, links)\n i = parsed.end\n\n const isVoid = VOID_ELEMENTS.has(parsed.tag)\n const isRawText = RAW_TEXT_ELEMENTS.has(parsed.tag)\n const isRcdata = RCDATA_ELEMENTS.has(parsed.tag)\n\n if (isRawText || isRcdata) {\n // Contents are opaque: no nested tags, no stack push. Entities are decoded\n // for RCDATA (`<title>`, `<textarea>`) and NOT for raw text (`<script>`,\n // `<style>`) — a JSON-LD block must survive byte-for-byte.\n const contentStart = i\n const close = findRawTextEnd(html, contentStart, parsed.tag)\n const contentEnd = close === -1 ? html.length : close\n if (contentEnd > contentStart) {\n const wasTop = stack.length\n stack.push(element.index)\n emitText(contentStart, contentEnd, isRcdata, element.excludedBy ?? own ?? undefined)\n stack.length = wasTop\n if (own === 'script-ld-json') {\n jsonLd.push({\n text: html.slice(contentStart, contentEnd),\n offset: cursor.at(contentStart),\n element: element.index,\n })\n }\n }\n if (close === -1) {\n i = html.length\n } else {\n const gt = html.indexOf('>', close)\n i = gt === -1 ? html.length : gt + 1\n }\n textStart = i\n continue\n }\n\n if (!isVoid && !parsed.selfClosing && stack.length < MAX_DEPTH) stack.push(element.index)\n textStart = i\n }\n emitText(textStart, html.length, true)\n\n return {\n elements,\n texts,\n jsonLd,\n metas,\n links,\n bytes: cursor.at(html.length),\n }\n}\n\n/** Records `<meta>` and `<link>` elements into their typed side-tables. */\nfunction collectMetaOrLink(element: HtmlElement, metas: HtmlMeta[], links: HtmlLink[]): void {\n const lower = (value: string | undefined): string | null =>\n value === undefined ? null : value.toLowerCase()\n\n if (element.tag === 'meta') {\n metas.push({\n name: lower(element.attrs['name']),\n property: lower(element.attrs['property']),\n httpEquiv: lower(element.attrs['http-equiv']),\n itemprop: lower(element.attrs['itemprop']),\n charset: lower(element.attrs['charset']),\n content: element.attrs['content'] ?? null,\n element: element.index,\n offset: element.offset,\n })\n return\n }\n\n if (element.tag === 'link') {\n const rawRel = element.attrs['rel'] ?? ''\n const rel: string[] = []\n for (const token of rawRel.toLowerCase().split(/\\s+/)) {\n if (token.length > 0 && !rel.includes(token)) rel.push(token)\n }\n links.push({\n rel,\n href: element.attrs['href'] ?? null,\n type: lower(element.attrs['type']),\n hreflang: lower(element.attrs['hreflang']),\n title: element.attrs['title'] ?? null,\n element: element.index,\n offset: element.offset,\n })\n }\n}\n\n// ---------------------------------------------------------------------------\n// Text views\n// ---------------------------------------------------------------------------\n\n/**\n * Joins text nodes with a single space and collapses whitespace runs.\n *\n * A single space rather than an empty string: `<b>Blue</b><i>Shirt</i>` renders\n * as two words to a reader, and \"BlueShirt\" is not a title. Joining always,\n * rather than only across block boundaries, avoids needing a display-model —\n * which is the same reason there is no CSS resolution anywhere in this file.\n */\nfunction joinText(parts: readonly string[]): string {\n return parts.join(' ').replace(/\\s+/g, ' ').trim()\n}\n\n/** All counted text in the document, per the §3.6 normative extraction rule. */\nexport function countedText(doc: HtmlDocument): string {\n const parts: string[] = []\n for (const node of doc.texts) {\n if (node.excludedBy === null) parts.push(node.text)\n }\n return joinText(parts)\n}\n\n/**\n * Counted text inside one element's subtree — anchor text for\n * `primary-action-url`, a `<summary>`'s question, a heading. `includeExcluded`\n * opts into hidden subtrees, which the extractor needs for exactly one thing:\n * reporting hidden facts as evidence (fixture `037-hidden-text-facts`) without\n * letting them score.\n */\nexport function elementText(\n doc: HtmlDocument,\n elementIndex: number,\n includeExcluded = false,\n): string {\n const parts: string[] = []\n for (const node of doc.texts) {\n if (!includeExcluded && node.excludedBy !== null) continue\n if (isSelfOrDescendant(doc, node.parent, elementIndex)) parts.push(node.text)\n }\n return joinText(parts)\n}\n\n/** Walks `parent` links upward. Bounded by MAX_DEPTH + 1 so a cycle cannot hang. */\nfunction isSelfOrDescendant(doc: HtmlDocument, from: number, ancestor: number): boolean {\n let current = from\n for (let hops = 0; hops <= MAX_DEPTH + 1 && current >= 0; hops++) {\n if (current === ancestor) return true\n current = doc.elements[current]?.parent ?? -1\n }\n return false\n}\n","/**\n * parse-money.ts — text → `Money`, or `null` when ambiguous. Design §3.11.\n *\n * WHY THIS IS ITS OWN FILE, AND WHY IT IS BIG. `packages/render-md/src/money.ts`\n * only *formats* an already-structured `Money`. It cannot parse text, and the\n * claim that it could hid the largest single piece of extraction work in the\n * program. Price is a core fact for `product` and `service`, it is one of the\n * four values compared by the D2.4 substance-parity check, and it is the value a\n * buying agent acts on. Everything downstream of a wrong price is wrong.\n *\n * FAILS CLOSED, like `formatMoney`. Ambiguous input returns `null`, and a `null`\n * price is simply not a fact — it costs coverage points and nothing else. A\n * *wrong* price would be reported as truth on a public scanner page, and would\n * make a parity check accuse a merchant of divergence they did not commit.\n * Every rule below resolves in favour of `null`.\n *\n * WHY `Money` IS DECLARED HERE RATHER THAN IMPORTED. It is structurally\n * identical to `@rebilder/render-md`'s `Money`, and duplicating it is\n * deliberate: `tooling/check-package-graph.ts` forbids\n * `agent-readability → render-md` (and the reverse) in the `ars-boundary` rule.\n * The two packages point in opposite directions — gateway/render-md turn a\n * source of truth into output; the scorer turns a response into a judgment — so\n * a dependency either way is a design error before it is a size one. Four bytes\n * of duplicated interface is the cheap side of that trade.\n *\n * NO `String.prototype.normalize()`. Unicode normalisation is deterministic only\n * for a fixed Unicode version, and the Unicode version is a property of the\n * host's ICU build. That is the same class of unversioned input as a\n * third-party HTML parser, and the same answer applies: every character this\n * parser special-cases is listed here, in a pinned table.\n *\n * SUPPORTED FORMATS (§3.11 enumerates these; each has a test):\n * leading symbol `$1,499.00` `€49` `¥4,900`\n * trailing symbol `1.499,00 €` `49 zł`\n * ISO code prefix/suffix `USD 1499` `1499 USD`\n * comma and period as BOTH group and decimal separator, disambiguated by\n * position and by the minor-unit digits of the resolved currency\n * space / NBSP / narrow-NBSP / apostrophe group separators `1 499,00` `1'499.00`\n * zero-decimal currencies `¥4,900` → 4900, not 490000\n * ranges `$148.00 – $198.00` → the LOWER bound, `qualified: true`\n * qualifiers `From $9`, `$9+` → the stated bound, `qualified: true`\n *\n * `qualified: true` EXISTS FOR ONE REASON: qualified values are excluded from\n * the D2.4 parity comparison. \"From $9\" in markdown against \"$9 – $40\" in HTML is\n * the same page saying the same thing in two shapes, and flagging it as a\n * substance divergence would be a false accusation.\n */\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * Structural duplicate of `@rebilder/render-md`'s `Money` — same field names,\n * same semantics, deliberately not imported (see the file header).\n * `amount` is an INTEGER NUMBER OF MINOR UNITS: 4900 is $49.00 in USD and ¥4,900\n * in JPY, because JPY has no minor unit.\n */\nexport interface Money {\n amount: number\n currency: string\n}\n\n/**\n * What `parseMoneyText` returns: a `Money`, plus whether the source text stated\n * a bound rather than a price.\n */\nexport interface ParsedMoney extends Money {\n /** True for ranges (`$148 – $198`) and qualifiers (`From $9`, `$9+`). */\n qualified: boolean\n}\n\nexport interface MoneyHints {\n /**\n * ISO 4217 code the page is known to price in — from JSON-LD `priceCurrency`,\n * a `<meta itemprop=\"priceCurrency\">`, or the negotiated representation.\n * Does two jobs: it resolves symbols shared by several currencies (`$`, `¥`,\n * `kr`), and its minor-unit digit count disambiguates a lone separator\n * followed by three digits.\n */\n currency?: string\n}\n\n// ---------------------------------------------------------------------------\n// Currency tables\n// ---------------------------------------------------------------------------\n\n/**\n * ISO 4217 active alphabetic codes. Pinned: a bare three-letter token is\n * accepted as a currency ONLY if it is on this list, which is what stops\n * `50 OFF` parsing as 50 of some currency \"OFF\".\n *\n * Codes that are also English words do exist — `ALL` (Albanian lek), `TOP`\n * (Tongan paʻanga), `MAD`, `PEN`, `CUP`, `BOB`, `TRY`. They are handled by the\n * two structural rules rather than by a blocklist: a code must be immediately\n * adjacent to the number, and the text must contain exactly ONE number. `TRY 2\n * FOR 1` has two numbers and returns `null`.\n */\nconst ISO_4217 = new Set(\n (\n 'AED AFN ALL AMD ANG AOA ARS AUD AWG AZN BAM BBD BDT BGN BHD BIF BMD BND BOB BOV BRL BSD ' +\n 'BTN BWP BYN BZD CAD CDF CHE CHF CHW CLF CLP CNY COP COU CRC CUP CVE CZK DJF DKK DOP DZD ' +\n 'EGP ERN ETB EUR FJD FKP GBP GEL GHS GIP GMD GNF GTQ GYD HKD HNL HTG HUF IDR ILS INR IQD ' +\n 'IRR ISK JMD JOD JPY KES KGS KHR KMF KPW KRW KWD KYD KZT LAK LBP LKR LRD LSL LYD MAD MDL ' +\n 'MGA MKD MMK MNT MOP MRU MUR MVR MWK MXN MXV MYR MZN NAD NGN NIO NOK NPR NZD OMR PAB PEN ' +\n 'PGK PHP PKR PLN PYG QAR RON RSD RUB RWF SAR SBD SCR SDG SEK SGD SHP SLE SOS SRD SSP STN ' +\n 'SVC SYP SZL THB TJS TMT TND TOP TRY TTD TWD TZS UAH UGX USD USN UYI UYU UYW UZS VED VES ' +\n 'VND VUV WST XAF XAG XAU XCD XCG XDR XOF XPD XPF XPT YER ZAR ZMW ZWG'\n ).split(' '),\n)\n\n/**\n * Currencies with no minor unit — `amount` is already whole currency units.\n * Mirrors `render-md`'s table exactly (see the file header on why it is copied).\n */\nconst ZERO_DECIMAL = new Set([\n 'BIF',\n 'CLP',\n 'DJF',\n 'GNF',\n 'ISK',\n 'JPY',\n 'KMF',\n 'KRW',\n 'MGA',\n 'PYG',\n 'RWF',\n 'UGX',\n 'VND',\n 'VUV',\n 'XAF',\n 'XOF',\n 'XPF',\n])\n\n/** Currencies with three-digit minor units. Mirrors `render-md`'s table. */\nconst THREE_DECIMAL = new Set(['BHD', 'IQD', 'JOD', 'KWD', 'LYD', 'OMR', 'TND'])\n\n/** Minor-unit digit count for an ISO 4217 code. Unknown codes are treated as 2. */\nexport function minorUnitDigits(code: string): number {\n const upper = code.toUpperCase()\n if (ZERO_DECIMAL.has(upper)) return 0\n if (THREE_DECIMAL.has(upper)) return 3\n return 2\n}\n\ninterface SymbolEntry {\n /** Resolution when `hints.currency` says nothing useful. `null` = unresolvable alone. */\n fallback: string | null\n /** Codes this symbol may legitimately denote; `hints.currency` selects among them. */\n alternatives: readonly string[]\n}\n\n/**\n * Currency symbols, longest-first at match time so `CA$` beats `$`.\n *\n * `$`, `¥` and `kr` are shared. `$` and `¥` carry a pinned fallback (USD, JPY)\n * because a bare `$` on an unhinted page is overwhelmingly USD and `¥4,900` is\n * §3.11's own worked example of zero-decimal handling; `hints.currency`\n * overrides both. `kr` has NO fallback — SEK, NOK, DKK and ISK are genuinely\n * indistinguishable, and ISK is zero-decimal while the others are not, so\n * guessing would corrupt the amount and not merely the label.\n */\nconst SYMBOLS: Readonly<Record<string, SymbolEntry>> = {\n US$: { fallback: 'USD', alternatives: [] },\n CA$: { fallback: 'CAD', alternatives: [] },\n C$: { fallback: 'CAD', alternatives: [] },\n AU$: { fallback: 'AUD', alternatives: [] },\n A$: { fallback: 'AUD', alternatives: [] },\n NZ$: { fallback: 'NZD', alternatives: [] },\n HK$: { fallback: 'HKD', alternatives: [] },\n NT$: { fallback: 'TWD', alternatives: [] },\n S$: { fallback: 'SGD', alternatives: [] },\n R$: { fallback: 'BRL', alternatives: [] },\n MX$: { fallback: 'MXN', alternatives: [] },\n $: {\n fallback: 'USD',\n alternatives: [\n 'USD',\n 'CAD',\n 'AUD',\n 'NZD',\n 'SGD',\n 'HKD',\n 'MXN',\n 'TWD',\n 'BRL',\n 'ARS',\n 'CLP',\n 'COP',\n 'UYU',\n ],\n },\n '¥': { fallback: 'JPY', alternatives: ['JPY', 'CNY'] },\n kr: { fallback: null, alternatives: ['SEK', 'NOK', 'DKK', 'ISK'] },\n '€': { fallback: 'EUR', alternatives: [] },\n '£': { fallback: 'GBP', alternatives: [] },\n '₹': { fallback: 'INR', alternatives: [] },\n '₩': { fallback: 'KRW', alternatives: [] },\n '₽': { fallback: 'RUB', alternatives: [] },\n '₺': { fallback: 'TRY', alternatives: [] },\n '₪': { fallback: 'ILS', alternatives: [] },\n '₫': { fallback: 'VND', alternatives: [] },\n '₱': { fallback: 'PHP', alternatives: [] },\n '₴': { fallback: 'UAH', alternatives: [] },\n '₦': { fallback: 'NGN', alternatives: [] },\n '₡': { fallback: 'CRC', alternatives: [] },\n '₸': { fallback: 'KZT', alternatives: [] },\n '₾': { fallback: 'GEL', alternatives: [] },\n '฿': { fallback: 'THB', alternatives: [] },\n zł: { fallback: 'PLN', alternatives: [] },\n Kč: { fallback: 'CZK', alternatives: [] },\n}\n\n/** Symbols longest-first, so `CA$1.00` does not resolve through the bare `$` entry. */\nconst SYMBOLS_BY_LENGTH = Object.keys(SYMBOLS).sort((a, b) => b.length - a.length)\n\n// ---------------------------------------------------------------------------\n// Lexicons and limits\n// ---------------------------------------------------------------------------\n\n/**\n * Prefix qualifiers. Matched at the start of the text, case-insensitively, and\n * only when followed by a non-letter — so `fromage` is not `from`.\n */\nconst PREFIX_QUALIFIERS = [\n 'starting from',\n 'starting at',\n 'prices from',\n 'priced from',\n 'as little as',\n 'as much as',\n 'as low as',\n 'starts at',\n 'up to',\n 'from',\n] as const\n\n/** Suffix qualifiers, matched at the end of the text, case-insensitively. */\nconst SUFFIX_QUALIFIERS = ['and above', 'or more', 'or less', 'and up', '+'] as const\n\n/**\n * Range separators: em dash, en dash, Unicode hyphen, ASCII hyphen-minus. The\n * ASCII hyphen is included even though it is also a minus sign, because\n * `$148-$198` is a common real form; the \"exactly one separator in the whole\n * string\" rule below is what keeps `1-800-555-1212` and `2024-01-15` out.\n */\nconst RANGE_DASHES = ['\\u2014', '\\u2013', '\\u2010', '-'] as const\n\n/**\n * Whitespace normalised to a plain space before parsing: the ASCII controls,\n * NBSP, OGHAM SPACE MARK, the EN QUAD..HAIR SPACE block, NARROW NBSP, MEDIUM\n * MATHEMATICAL SPACE and IDEOGRAPHIC SPACE. NBSP and NARROW NBSP are the group\n * separators in fr-FR and ru-RU prices, which is why they are here as well as\n * in `GROUP_SPACERS`.\n */\nconst SPACE_RE = /[\\t\\n\\r\\f\\v\\u00a0\\u1680\\u2000-\\u200a\\u202f\\u205f\\u3000]/g\n\n/**\n * Characters that may separate digit groups in place of a comma or period: a\n * plain space (every exotic space has already been normalised to one) and the\n * de-CH apostrophe forms.\n */\nconst GROUP_SPACERS = [' ', \"'\", '\\u2019'] as const\n\n/**\n * Longest input accepted. A price does not occur inside 256 characters of prose,\n * and the cap also bounds the parser's work on adversarial input — the probe\n * fetches arbitrary bytes, and this function is called per fact candidate.\n */\nconst MAX_INPUT_LENGTH = 256\n\n/**\n * Digits allowed in a value before it is rejected. 15 significant digits is the\n * range in which `Number` is an exact integer; beyond it a price would round,\n * and a rounded price is a wrong price (Hard Rule 2).\n */\nconst MAX_SIGNIFICANT_DIGITS = 15\n\n/** A run of digits plus the characters that may appear inside a formatted number. */\nconst NUMBER_RUN_RE = /\\d[\\d.,'’ ]*/g\n\n// ---------------------------------------------------------------------------\n// Numeric parsing\n// ---------------------------------------------------------------------------\n\n/** True when every part is a plausible digit group: 1–3 leading digits, then exact 3s. */\nfunction isGroupedInteger(parts: readonly string[]): boolean {\n if (parts.length < 2) return false\n const first = parts[0] ?? ''\n // A grouped number never starts with 0: `0,500` is not five hundred.\n if (first.length < 1 || first.length > 3 || first.startsWith('0')) return false\n for (let i = 1; i < parts.length; i++) {\n if ((parts[i] ?? '').length !== 3) return false\n }\n return true\n}\n\n/**\n * Removes space/apostrophe group separators, or returns null if they are not in\n * valid group positions. `1 499,00` → `1499,00`; `12 34` → null.\n */\nfunction stripGroupSpacers(token: string): string | null {\n if (!GROUP_SPACERS.some((c) => token.includes(c))) return token\n\n // Split off a trailing decimal part first, so `1'499.00` keeps its `.00`.\n let head = token\n let tail = ''\n const lastDot = token.lastIndexOf('.')\n const lastComma = token.lastIndexOf(',')\n const lastSep = Math.max(lastDot, lastComma)\n if (lastSep > 0) {\n const after = token.slice(lastSep + 1)\n const afterIsDigits = after.length > 0 && !/\\D/.test(after)\n if (afterIsDigits) {\n head = token.slice(0, lastSep)\n tail = token.slice(lastSep)\n }\n }\n\n const parts: string[] = []\n let current = ''\n for (const ch of head) {\n if (GROUP_SPACERS.includes(ch as (typeof GROUP_SPACERS)[number])) {\n parts.push(current)\n current = ''\n } else if (ch >= '0' && ch <= '9') {\n current += ch\n } else {\n // A comma or period inside the head alongside spacers: two separator\n // systems in one number. Ambiguous.\n return null\n }\n }\n parts.push(current)\n if (!isGroupedInteger(parts)) return null\n return parts.join('') + tail\n}\n\n/**\n * Splits a `major`/`fraction` pair out of a token containing only digits, `.`\n * and `,`, or returns null when the two readings cannot be told apart.\n *\n * THE HARD CASE is a single separator followed by exactly three digits.\n * `1,500` is one thousand five hundred in en-US and one and a half in de-DE.\n * The resolver is the currency's minor-unit count, which is why\n * `hints.currency` matters:\n * 2 minor digits (USD, EUR) → a decimal separator cannot be followed by three\n * digits and still be minor units, so it is a GROUP separator → 1500.\n * 0 minor digits (JPY) → same conclusion → 4900, per §3.11's `¥4,900`.\n * 3 minor digits (KWD, BHD) → both readings are valid → AMBIGUOUS → null.\n */\nfunction splitMajorFraction(\n token: string,\n minorDigits: number,\n): { major: string; fraction: string } | null {\n const dots = token.split('.').length - 1\n const commas = token.split(',').length - 1\n\n if (dots === 0 && commas === 0) return { major: token, fraction: '' }\n\n if (dots > 0 && commas > 0) {\n // The LAST separator is the decimal point; the other groups.\n const decimal = token.lastIndexOf('.') > token.lastIndexOf(',') ? '.' : ','\n const group = decimal === '.' ? ',' : '.'\n const decimalAt = token.lastIndexOf(decimal)\n const head = token.slice(0, decimalAt)\n const fraction = token.slice(decimalAt + 1)\n if (fraction.length === 0 || head.includes(decimal)) return null\n if (!isGroupedInteger(head.split(group))) return null\n return { major: head.split(group).join(''), fraction }\n }\n\n const separator = dots > 0 ? '.' : ','\n const count = dots > 0 ? dots : commas\n const parts = token.split(separator)\n\n if (count > 1) {\n // Repeated separators can only be group separators.\n return isGroupedInteger(parts) ? { major: parts.join(''), fraction: '' } : null\n }\n\n const left = parts[0] ?? ''\n const right = parts[1] ?? ''\n if (left.length === 0 || right.length === 0) return null\n\n if (right.length === 3 && isGroupedInteger(parts)) {\n if (minorDigits === 3) return null // genuinely ambiguous; fail closed\n return { major: left + right, fraction: '' }\n }\n return { major: left, fraction: right }\n}\n\n/** Converts a validated major/fraction pair to integer minor units, or null. */\nfunction toMinorUnits(major: string, fraction: string, minorDigits: number): number | null {\n let frac = fraction\n if (frac.length > minorDigits) {\n // Extra precision is acceptable only when it is all zeros: `JPY 4900.00` is\n // 4900, but `USD 1.4990` states a sub-cent price we cannot represent.\n const extra = frac.slice(minorDigits)\n if (/[^0]/.test(extra)) return null\n frac = frac.slice(0, minorDigits)\n }\n frac = frac.padEnd(minorDigits, '0')\n const digits = (major + frac).replace(/^0+(?=\\d)/, '')\n if (digits.length > MAX_SIGNIFICANT_DIGITS) return null\n const value = Number.parseInt(digits, 10)\n return Number.isSafeInteger(value) ? value : null\n}\n\n// ---------------------------------------------------------------------------\n// Currency resolution\n// ---------------------------------------------------------------------------\n\ninterface CurrencyContext {\n /** Text before the number run, qualifiers already stripped. */\n before: string\n /** Text after the number run. */\n after: string\n}\n\n/** The ISO code immediately adjacent to the number, or null; `false` on conflict. */\nfunction adjacentIsoCode(ctx: CurrencyContext): string | null | false {\n const beforeMatch = /([A-Z]{3})\\s?$/.exec(ctx.before)\n const afterMatch = /^\\s?([A-Z]{3})(?![A-Za-z])/.exec(ctx.after)\n const codes: string[] = []\n for (const match of [beforeMatch, afterMatch]) {\n const code = match?.[1]\n if (code !== undefined && ISO_4217.has(code) && !codes.includes(code)) codes.push(code)\n }\n if (codes.length > 1) return false\n return codes[0] ?? null\n}\n\n/** Trailing minus sign, removed so `$-5.00` still sees its `$` as adjacent. */\nfunction stripTrailingSign(text: string): string {\n const trimmed = text.trimEnd()\n return /[-−]$/.test(trimmed) ? trimmed.slice(0, -1).trimEnd() : trimmed\n}\n\n/** The currency symbol immediately adjacent to the number, or null; `false` on conflict. */\nfunction adjacentSymbol(ctx: CurrencyContext): string | null | false {\n const before = stripTrailingSign(ctx.before)\n const after = ctx.after.trimStart()\n const found: string[] = []\n for (const symbol of SYMBOLS_BY_LENGTH) {\n if (before.endsWith(symbol) && !found.some((s) => s.endsWith(symbol))) found.push(symbol)\n }\n for (const symbol of SYMBOLS_BY_LENGTH) {\n if (after.startsWith(symbol) && !found.some((s) => s.startsWith(symbol))) found.push(symbol)\n }\n if (found.length > 1) return false\n return found[0] ?? null\n}\n\n/** Applies `hints.currency` to a symbol that denotes more than one currency. */\nfunction resolveSymbol(symbol: string, hint: string | undefined): string | null {\n const entry = SYMBOLS[symbol]\n if (entry === undefined) return null\n if (hint !== undefined) {\n const upper = hint.toUpperCase()\n if (upper === entry.fallback || entry.alternatives.includes(upper)) return upper\n }\n return entry.fallback\n}\n\n// ---------------------------------------------------------------------------\n// Text preparation\n// ---------------------------------------------------------------------------\n\ninterface Prepared {\n text: string\n qualified: boolean\n}\n\n/** Collapses every whitespace variant to a single plain space and trims. */\nfunction normalizeSpaces(text: string): string {\n return text.replace(SPACE_RE, ' ').replace(/ {2,}/g, ' ').trim()\n}\n\n/** Strips one leading and one trailing qualifier, recording that it was there. */\nfunction stripQualifiers(text: string): Prepared {\n let out = text\n let qualified = false\n\n const lower = out.toLowerCase()\n for (const phrase of PREFIX_QUALIFIERS) {\n if (!lower.startsWith(phrase)) continue\n const next = out.charAt(phrase.length)\n if (next !== '' && /[a-z]/i.test(next)) continue\n out = out.slice(phrase.length).trim()\n qualified = true\n break\n }\n\n const lowerEnd = out.toLowerCase()\n for (const phrase of SUFFIX_QUALIFIERS) {\n if (!lowerEnd.endsWith(phrase)) continue\n const prev = out.charAt(out.length - phrase.length - 1)\n if (/[a-z]/i.test(prev)) continue\n out = out.slice(0, out.length - phrase.length).trim()\n qualified = true\n break\n }\n\n return { text: out, qualified }\n}\n\n/**\n * Splits a range into its two operands, or returns null when the text is not a\n * range.\n *\n * The rule is EXACTLY ONE separator in the whole string, with digits on both\n * sides. `1-800-555-1212` has three and `2024-01-15` has two, so neither is a\n * range — and neither survives the one-number rule afterwards either.\n */\nfunction splitRange(text: string): [string, string] | null {\n let separatorIndex = -1\n let separatorLength = 0\n let count = 0\n\n for (const dash of RANGE_DASHES) {\n let at = text.indexOf(dash)\n while (at !== -1) {\n count++\n if (count === 1) {\n separatorIndex = at\n separatorLength = dash.length\n }\n at = text.indexOf(dash, at + dash.length)\n }\n }\n\n if (count === 0) {\n const word = / to /i.exec(text)\n if (word === null) return null\n separatorIndex = word.index\n separatorLength = word[0].length\n } else if (count > 1) {\n return null\n }\n\n const left = text.slice(0, separatorIndex).trim()\n const right = text.slice(separatorIndex + separatorLength).trim()\n if (!/\\d/.test(left) || !/\\d/.test(right)) return null\n return [left, right]\n}\n\n// ---------------------------------------------------------------------------\n// Single-operand parsing\n// ---------------------------------------------------------------------------\n\nfunction parseOperand(text: string, hints: MoneyHints | undefined): Money | null {\n if (text.includes('%')) return null // `20% off` is not a price\n\n // Exactly one number, or we cannot tell which one is the price.\n NUMBER_RUN_RE.lastIndex = 0\n const runs: { value: string; start: number; end: number }[] = []\n let match: RegExpExecArray | null\n while ((match = NUMBER_RUN_RE.exec(text)) !== null) {\n let value = match[0]\n // The run regex is greedy over separators; a run must end on a digit.\n while (value.length > 0 && !/\\d$/.test(value)) value = value.slice(0, -1)\n runs.push({ value, start: match.index, end: match.index + value.length })\n if (runs.length > 1) return null\n }\n const run = runs[0]\n if (run === undefined) return null\n\n const ctx: CurrencyContext = { before: text.slice(0, run.start), after: text.slice(run.end) }\n\n const isoCode = adjacentIsoCode(ctx)\n if (isoCode === false) return null\n const symbol = adjacentSymbol(ctx)\n if (symbol === false) return null\n\n let currency: string | null\n if (isoCode !== null && symbol !== null) {\n // Both present: they must agree. `$49.00 USD` is fine; `$49.00 EUR` is not.\n const fromSymbol = resolveSymbol(symbol, isoCode)\n if (fromSymbol !== isoCode) return null\n currency = isoCode\n } else if (isoCode !== null) {\n currency = isoCode\n } else if (symbol !== null) {\n currency = resolveSymbol(symbol, hints?.currency)\n } else {\n // No marker at all. `hints.currency` may supply one, but ONLY when the text\n // is a bare number: with a hint of USD, `1499` is a price and `4.5 stars`\n // is not, and the difference is the letters.\n const hint = hints?.currency?.toUpperCase()\n if (hint === undefined || !ISO_4217.has(hint)) return null\n if (/[A-Za-z]/.test(ctx.before + ctx.after)) return null\n currency = hint\n }\n if (currency === null || !ISO_4217.has(currency)) return null\n\n const negative = /[-−]\\s?$/.test(stripTrailingSymbol(ctx.before))\n\n const spaced = stripGroupSpacers(run.value)\n if (spaced === null) return null\n const split = splitMajorFraction(spaced, minorUnitDigits(currency))\n if (split === null) return null\n const magnitude = toMinorUnits(split.major, split.fraction, minorUnitDigits(currency))\n if (magnitude === null) return null\n\n return { amount: negative ? -magnitude : magnitude, currency }\n}\n\n/** Removes a trailing currency symbol so a sign in front of it is still visible. */\nfunction stripTrailingSymbol(before: string): string {\n const trimmed = before.trimEnd()\n for (const symbol of SYMBOLS_BY_LENGTH) {\n if (trimmed.endsWith(symbol)) return trimmed.slice(0, trimmed.length - symbol.length)\n }\n return trimmed\n}\n\n// ---------------------------------------------------------------------------\n// parseMoneyText\n// ---------------------------------------------------------------------------\n\n/**\n * Text → `Money`, or `null` when ambiguous. Fails closed, like `formatMoney`.\n *\n * Ranges and qualifiers return the lower bound with `qualified: true`, which\n * excludes them from the D2.4 parity comparison.\n */\nexport function parseMoneyText(text: string, hints?: MoneyHints): ParsedMoney | null {\n if (typeof text !== 'string' || text.length === 0 || text.length > MAX_INPUT_LENGTH) return null\n\n const normalized = normalizeSpaces(text)\n if (!/\\d/.test(normalized)) return null\n\n const prepared = stripQualifiers(normalized)\n const range = splitRange(prepared.text)\n\n if (range === null) {\n const single = parseOperand(prepared.text, hints)\n return single === null ? null : { ...single, qualified: prepared.qualified }\n }\n\n // A range. Only one end usually carries the currency — `$148 – 198` and\n // `148 to 198 USD` are both common — so each end is retried with the other's\n // currency before giving up. The result is the numerically LOWER end, always\n // `qualified`.\n const [leftText, rightText] = range\n let left = parseOperand(leftText, hints)\n const right = parseOperand(rightText, left === null ? hints : { currency: left.currency })\n if (left === null && right !== null) left = parseOperand(leftText, { currency: right.currency })\n\n if (left !== null && right !== null) {\n if (left.currency !== right.currency) return null\n const lower = right.amount < left.amount ? right : left\n return { ...lower, qualified: true }\n }\n const only = left ?? right\n return only === null ? null : { ...only, qualified: true }\n}\n","/**\n * extract.ts — pass 2 of the ARS pipeline: turn one fetched representation into\n * a set of normalised fact observations, scored against the resolved page-kind\n * profile (design §3.5, §3.6).\n *\n * WHAT A \"REPRESENTATION\" IS. The probe returns two captures that differ only in\n * their `Accept` header (§3.3). Each one is turned into an `ArsRepresentation`:\n * a decoded body, its byte length as the probe measured it, the tokenized\n * document when the bytes are HTML, the JSON-LD blocks, and the counted text.\n * Everything downstream reads a representation, never a raw capture, so the\n * markdown path and the HTML path go through the same scoring code.\n *\n * WHICH REPRESENTATION SCORES WHAT — the decision that makes the golden pair\n * (`001-pdp-gateway-md` vs `002-pdp-raw-html`) mean anything:\n *\n * D3 (coverage) and D4 (position) score the AGENT representation, because ARS\n * measures what a caller actually receives. A merchant whose markdown omits\n * `availability` loses coverage even though the HTML declares it — the agent\n * never saw it.\n *\n * D1.3 (render independence) and D5 (structured data) score the HTML\n * representation, because those checks are about the document a caller that\n * only reads HTML gets. JSON-LD does not live in markdown, and \"would this\n * page work without JavaScript\" is a question about HTML.\n *\n * CORROBORATION CROSSES THE TWO. §3.6 defines corroborated as \"observed in ≥2\n * sources (e.g. JSON-LD and visible text)\". A price stated in the negotiated\n * markdown *and* in the HTML's JSON-LD is observed in two sources and is\n * corroborated; that is the only reason a correctly installed gateway can reach\n * an A. But a fact observed ONLY in the HTML does not enter the scored fact set\n * at all — corroboration strengthens a fact the agent received, it never\n * conjures one it did not. See `mergeFacts`.\n *\n * VALUE FACTS vs PRESENCE FACTS. Some facts are compared by value (a price, a\n * title, a phone number); others are only ever \"declared or not\" (shipping,\n * returns, opening hours, question/answer shape). Presence facts normalise to\n * the literal string `declared` from EVERY source, deliberately: two sources\n * that describe the same shipping policy in different words must still\n * corroborate each other, and a free-text comparison would make that\n * non-deterministic. The split is pinned in `PRESENCE_FACTS` below and printed\n * in the spec, because it is the difference between \"we compared the values\" and\n * \"we compared whether you said anything\".\n *\n * EVERYTHING HERE IS PINNED DATA, NOT INFERENCE. The label lexicon, the\n * availability vocabulary, the no-published-price phrases, the schema.org\n * property aliases: all tables, all versioned. An extractor that guessed would\n * make `score()` non-reproducible in a second implementation, which is the one\n * property the whole package exists to provide.\n */\n\nimport { attr, countedText, elementText, tokenizeHtml } from './html'\nimport type { HtmlDocument } from './html'\nimport { parseMoneyText } from './parse-money'\nimport type {\n ArsAudience,\n ArsAudienceDecision,\n ArsFactKind,\n ArsFactObservation,\n ArsFactProfile,\n ArsHttpCapture,\n ArsPolicyReport,\n ArsRuleset,\n} from './types'\n\n// ---------------------------------------------------------------------------\n// UTF-8 offsets\n// ---------------------------------------------------------------------------\n\n/**\n * UTF-8 byte length of a JavaScript string, counting a lone surrogate as 3\n * bytes — the width WHATWG encoding gives U+FFFD, which is what a lone\n * surrogate actually costs on the wire. Matches `Utf8Cursor` in `./html`, which\n * is why offsets from the two files are in the same address space.\n */\nexport function utf8Length(text: string): number {\n let bytes = 0\n for (let i = 0; i < text.length; i++) {\n const code = text.charCodeAt(i)\n if (code < 0x80) bytes += 1\n else if (code < 0x800) bytes += 2\n else if (code >= 0xd800 && code <= 0xdbff) {\n const next = i + 1 < text.length ? text.charCodeAt(i + 1) : 0\n if (next >= 0xdc00 && next <= 0xdfff) {\n bytes += 4\n i++\n } else bytes += 3\n } else bytes += 3\n }\n return bytes\n}\n\n// ---------------------------------------------------------------------------\n// JSON-LD\n// ---------------------------------------------------------------------------\n\n/** A flattened JSON-LD node: one object with an `@type`, wherever it was nested. */\nexport interface JsonLdNode {\n /** `@type` values with any `http(s)://schema.org/` prefix stripped. Always ≥1 entry. */\n readonly types: readonly string[]\n readonly value: Readonly<Record<string, unknown>>\n /** UTF-8 byte offset of the block the node came from. */\n readonly offset: number\n}\n\n/** What `parseJsonLd` observed, including the blocks that failed — D5.1 scores both. */\nexport interface JsonLdReport {\n readonly nodes: readonly JsonLdNode[]\n readonly blocks: number\n readonly parsed: number\n}\n\nconst SCHEMA_PREFIX = /^https?:\\/\\/schema\\.org\\//\n\nfunction stripSchemaPrefix(type: string): string {\n return type.replace(SCHEMA_PREFIX, '')\n}\n\n/** Types from a node's `@type`, which may be a string or an array of strings. */\nfunction typesOf(value: Record<string, unknown>): string[] {\n const raw = value['@type']\n if (typeof raw === 'string') return [stripSchemaPrefix(raw)]\n if (Array.isArray(raw)) {\n const out: string[] = []\n for (const entry of raw) if (typeof entry === 'string') out.push(stripSchemaPrefix(entry))\n return out\n }\n return []\n}\n\n/** Depth cap on JSON-LD traversal. Deeper than any real graph; stops a hostile nesting bomb. */\nconst JSON_LD_MAX_DEPTH = 12\n\nfunction collectNodes(\n value: unknown,\n offset: number,\n depth: number,\n out: JsonLdNode[],\n seen: Set<object>,\n): void {\n if (depth > JSON_LD_MAX_DEPTH || value === null || typeof value !== 'object') return\n if (seen.has(value)) return\n seen.add(value)\n\n if (Array.isArray(value)) {\n for (const entry of value) collectNodes(entry, offset, depth + 1, out, seen)\n return\n }\n\n const record = value as Record<string, unknown>\n const types = typesOf(record)\n if (types.length > 0) out.push({ types, value: record, offset })\n\n for (const [key, child] of Object.entries(record)) {\n if (key === '@context') continue\n collectNodes(child, offset, depth + 1, out, seen)\n }\n}\n\n/**\n * Parses every JSON-LD block. A block that does not parse is counted and\n * dropped: D5.1 scores \"present **and parses**\", so fixture `033-invalid-jsonld`\n * needs the block count and the parsed count to differ.\n */\nexport function parseJsonLd(blocks: readonly { text: string; offset: number }[]): JsonLdReport {\n const nodes: JsonLdNode[] = []\n let parsed = 0\n for (const block of blocks) {\n let value: unknown\n try {\n value = JSON.parse(block.text) as unknown\n } catch {\n continue\n }\n parsed++\n collectNodes(value, block.offset, 0, nodes, new Set<object>())\n }\n return { nodes, blocks: blocks.length, parsed }\n}\n\n/**\n * Reads a dotted property path off a node, entering array members: `offers.price`\n * matches `offers[0].price`. Returns the first non-empty scalar found, or null.\n * The notation is the one `DEFAULT_RULESET.requiredProperties` is written in.\n */\nexport function readPath(node: JsonLdNode, path: string): string | null {\n const segments = path.split('.')\n let frontier: unknown[] = [node.value]\n for (const segment of segments) {\n const next: unknown[] = []\n for (const current of frontier) {\n if (current === null || typeof current !== 'object') continue\n if (Array.isArray(current)) {\n for (const entry of current) {\n if (entry !== null && typeof entry === 'object' && !Array.isArray(entry)) {\n const child = (entry as Record<string, unknown>)[segment]\n if (child !== undefined) next.push(child)\n }\n }\n continue\n }\n const child = (current as Record<string, unknown>)[segment]\n if (child !== undefined) next.push(child)\n }\n frontier = next\n if (frontier.length === 0) return null\n }\n for (const found of frontier) {\n const scalar = scalarOf(found)\n if (scalar !== null) return scalar\n }\n return null\n}\n\n/**\n * A scalar reading of a JSON-LD value. Objects yield their `name`, `@id` or\n * `value` — `brand: {\"@type\":\"Brand\",\"name\":\"X\"}` is the common real shape and\n * refusing to read it would cost merchants points for correct markup.\n */\nfunction scalarOf(value: unknown): string | null {\n if (typeof value === 'string') return value.trim().length > 0 ? value.trim() : null\n if (typeof value === 'number' && Number.isFinite(value)) return String(value)\n if (typeof value === 'boolean') return String(value)\n if (Array.isArray(value)) {\n for (const entry of value) {\n const scalar = scalarOf(entry)\n if (scalar !== null) return scalar\n }\n return null\n }\n if (value !== null && typeof value === 'object') {\n const record = value as Record<string, unknown>\n for (const key of ['name', 'value', '@id', 'url', 'headline']) {\n const scalar = scalarOf(record[key])\n if (scalar !== null) return scalar\n }\n }\n return null\n}\n\n/** True when the path resolves to anything at all — what D5.2 counts. */\nexport function hasPath(node: JsonLdNode, path: string): boolean {\n return readPath(node, path) !== null\n}\n\n// ---------------------------------------------------------------------------\n// Representations\n// ---------------------------------------------------------------------------\n\nexport type ArsRepresentationKind = 'html' | 'markdown' | 'text' | 'json' | 'other'\n\nexport interface ArsRepresentation {\n /** Classified from the `Content-Type` header alone. See `looksLikeHtml` for the body's opinion. */\n readonly kind: ArsRepresentationKind\n /** Lowercased media type without parameters, or null when the header is absent. */\n readonly contentType: string | null\n /** The decoded body. */\n readonly body: string\n /** Byte length AS THE PROBE MEASURED IT (`ArsHttpCapture.bytes`), not recomputed. */\n readonly bytes: number\n /** Tokenized document, present whenever the bytes are HTML however they are labelled. */\n readonly doc: HtmlDocument | null\n readonly jsonLd: JsonLdReport\n /** Counted text (§3.6) for HTML; the body itself for every other kind. */\n readonly text: string\n /** The body's own opinion, independent of the header. D2.1 scores the disagreement. */\n readonly looksLikeHtml: boolean\n readonly truncated: boolean\n readonly finalUrl: string\n readonly headers: Readonly<Record<string, readonly string[]>>\n}\n\n/** First value of a header, or null. Header names are lowercased by the probe. */\nexport function header(\n headers: Readonly<Record<string, readonly string[]>>,\n name: string,\n): string | null {\n const values = headers[name]\n return values !== undefined && values.length > 0 ? (values[0] ?? null) : null\n}\n\n/** All values of a header, in order. `Link` is routinely repeated and is scored twice over. */\nexport function headerAll(\n headers: Readonly<Record<string, readonly string[]>>,\n name: string,\n): readonly string[] {\n return headers[name] ?? []\n}\n\n/** Media type without parameters, lowercased. */\nexport function mediaType(contentType: string | null): string | null {\n if (contentType === null) return null\n const semi = contentType.indexOf(';')\n const value = (semi === -1 ? contentType : contentType.slice(0, semi)).trim().toLowerCase()\n return value.length > 0 ? value : null\n}\n\nfunction classifyMediaType(type: string | null): ArsRepresentationKind {\n if (type === null) return 'other'\n if (type === 'text/html' || type === 'application/xhtml+xml') return 'html'\n if (type === 'text/markdown' || type === 'text/x-markdown') return 'markdown'\n if (type === 'text/plain') return 'text'\n if (type === 'application/json' || type === 'application/ld+json' || type.endsWith('+json')) {\n return 'json'\n }\n return 'other'\n}\n\n/**\n * Does the body look like HTML regardless of what the header claims? Bounded to\n * the first 1 KiB so the test is O(1) on a 2 MiB body. Fixture\n * `036-negotiation-wrong-content-type` is exactly the case where the header and\n * this function disagree, and D2.1 pays for it.\n */\nfunction bodyLooksLikeHtml(body: string): boolean {\n const head = body.slice(0, 1024).trimStart().toLowerCase()\n return head.startsWith('<!doctype html') || head.startsWith('<html') || head.startsWith('<?xml')\n ? true\n : head.includes('<html') || head.includes('<head>') || head.includes('<body')\n}\n\n/**\n * Builds a representation from a capture. Returns null when the body is absent:\n * `ArsHttpCapture.body` is optional because a PUBLISHED evidence bundle carries\n * the hash and not the bytes (§3.9), and a bundle without bytes cannot be\n * re-scored — `score()` reports `unscored / evidence-incomplete` rather than\n * inventing a zero.\n */\nexport function buildRepresentation(capture: ArsHttpCapture): ArsRepresentation | null {\n if (typeof capture.body !== 'string') return null\n const contentType = mediaType(header(capture.headers, 'content-type'))\n const declared = classifyMediaType(contentType)\n const looksLikeHtml = bodyLooksLikeHtml(capture.body)\n\n // Tokenize whenever the BYTES are HTML, whatever the header says. A merchant\n // with a mislabelled content type already loses 10 points on D2.1; taking\n // their fact coverage as well would charge them twice for one mistake.\n const doc = declared === 'html' || looksLikeHtml ? tokenizeHtml(capture.body) : null\n\n const jsonLd =\n doc !== null\n ? parseJsonLd(doc.jsonLd.map((block) => ({ text: block.text, offset: block.offset })))\n : declared === 'json'\n ? parseJsonLd([{ text: capture.body, offset: 0 }])\n : { nodes: [], blocks: 0, parsed: 0 }\n\n return {\n kind: declared,\n contentType,\n body: capture.body,\n bytes: capture.bytes,\n doc,\n jsonLd,\n text: doc !== null ? countedText(doc) : capture.body,\n looksLikeHtml,\n truncated: capture.truncated,\n finalUrl: capture.finalUrl,\n headers: capture.headers,\n }\n}\n\n// ---------------------------------------------------------------------------\n// Facts — the internal shape\n// ---------------------------------------------------------------------------\n\nexport type ArsFactSource = ArsFactObservation['source']\n\n/**\n * One observation before merging. `qualified` and `element` are internal:\n * `ArsFactObservation` (§3.9) carries neither, and this file exists to keep the\n * published shape exactly as the design wrote it.\n */\nexport interface ExtractedFact {\n readonly kind: ArsFactKind\n readonly normalized: string\n readonly source: ArsFactSource\n readonly offset: number\n /** True for ranges and qualifiers. Excluded from the D2.4 parity comparison (§3.11). */\n readonly qualified: boolean\n}\n\n/** A merged fact: the published observation plus what merging learned. */\nexport interface MergedFact extends ArsFactObservation {\n readonly qualified: boolean\n /** Distinct sources that reported THIS value. `corroborated` is `length >= 2`. */\n readonly sources: readonly ArsFactSource[]\n}\n\n/**\n * Source precedence, used only to break an offset tie. Declaration order is the\n * order of the union in §3.9, so a second implementation reads it off the\n * published type rather than out of this file.\n */\nconst SOURCE_ORDER: readonly ArsFactSource[] = [\n 'json-ld',\n 'microdata',\n 'meta',\n 'html-text',\n 'negotiated',\n]\n\n/**\n * Facts that are only ever \"declared or not\". Every source normalises them to\n * the literal `declared`, so two sources that word the same shipping policy\n * differently still corroborate one another. See the file header.\n */\nconst PRESENCE_FACTS: ReadonlySet<ArsFactKind> = new Set<ArsFactKind>([\n 'shipping',\n 'returns',\n 'hours',\n 'service-area',\n 'eligibility',\n 'question-answer',\n 'item-link',\n])\n\nconst DECLARED = 'declared'\n\n/**\n * Merges observations into the published fact set.\n *\n * `primary` is the representation the agent received; `corroborating` is the\n * other one. A fact appears in the output only if the AGENT saw it. The\n * representative observation is the one with the lowest byte offset (ties broken\n * by `SOURCE_ORDER`, then lexicographically by value) — lowest offset, because\n * D4.1 scores the byte offset at which a fact first becomes available.\n * `corroborated` counts the distinct sources, across BOTH representations, that\n * reported the representative's exact normalised value; a source reporting a\n * different value corroborates nothing, which is what makes fixture\n * `034-jsonld-price-mismatch` fail to corroborate rather than agree.\n */\nexport function mergeFacts(\n primary: readonly ExtractedFact[],\n corroborating: readonly ExtractedFact[],\n): MergedFact[] {\n const byKind = new Map<ArsFactKind, ExtractedFact[]>()\n for (const fact of primary) {\n const list = byKind.get(fact.kind)\n if (list === undefined) byKind.set(fact.kind, [fact])\n else list.push(fact)\n }\n\n const merged: MergedFact[] = []\n for (const [kind, observations] of byKind) {\n const representative = observations.reduce((best, candidate) =>\n betterObservation(best, candidate),\n )\n const sources: ArsFactSource[] = []\n for (const fact of [...observations, ...corroborating]) {\n if (fact.kind !== kind) continue\n if (fact.normalized !== representative.normalized) continue\n if (!sources.includes(fact.source)) sources.push(fact.source)\n }\n merged.push({\n kind,\n normalized: representative.normalized,\n source: representative.source,\n offset: representative.offset,\n corroborated: sources.length >= 2,\n qualified: representative.qualified,\n sources,\n })\n }\n\n merged.sort((a, b) => (a.offset === b.offset ? cmp(a.kind, b.kind) : a.offset - b.offset))\n return merged\n}\n\nfunction betterObservation(a: ExtractedFact, b: ExtractedFact): ExtractedFact {\n if (a.offset !== b.offset) return a.offset < b.offset ? a : b\n const rank = SOURCE_ORDER.indexOf(a.source) - SOURCE_ORDER.indexOf(b.source)\n if (rank !== 0) return rank < 0 ? a : b\n return cmp(a.normalized, b.normalized) <= 0 ? a : b\n}\n\nfunction cmp(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0\n}\n\n// ---------------------------------------------------------------------------\n// Normalisation\n// ---------------------------------------------------------------------------\n\nconst TITLE_SEPARATORS = [' | ', ' — ', ' – ', ' · ', ' :: ', ' » ']\n\n/**\n * Collapse whitespace, cut at the first pinned separator, lowercase.\n *\n * The cut is what lets `<title>Alpine Trail Pack 28L — 420D Ripstop | Basecamp\n * Supply Co</title>` corroborate a JSON-LD `name` of `Alpine Trail Pack 28L`.\n * Without it, essentially no real page would ever have a corroborated title,\n * and `title` is a core fact for seven of the eight page kinds.\n */\nexport function normalizeTitle(text: string): string {\n const collapsed = text.replace(/\\s+/g, ' ').trim()\n let cut = collapsed\n for (const separator of TITLE_SEPARATORS) {\n const at = cut.indexOf(separator)\n if (at > 0) cut = cut.slice(0, at)\n }\n return cut.trim().toLowerCase()\n}\n\n/** Collapse whitespace + lowercase, capped so one long description cannot bloat a result. */\nconst MAX_NORMALIZED_TEXT = 200\n\nexport function normalizeText(text: string): string {\n return text.replace(/\\s+/g, ' ').trim().toLowerCase().slice(0, MAX_NORMALIZED_TEXT)\n}\n\n/**\n * Money → `<ISO> <minor units>`, e.g. `USD 14800`. Currency travels with the\n * amount so the D2.4 parity comparison cannot match 14800 JPY against 14800 USD,\n * and `currency` is still reported separately because it is its own core fact.\n */\nfunction normalizeMoney(amount: number, currency: string): string {\n return `${currency} ${amount}`\n}\n\n/** ISO 8601 date, day precision. Anything that is not a recognisable date is not a fact. */\nexport function normalizeDate(text: string): string | null {\n const trimmed = text.trim()\n const iso = /^(\\d{4})-(\\d{2})-(\\d{2})/.exec(trimmed)\n if (iso !== null) return `${iso[1]}-${iso[2]}-${iso[3]}`\n const slashes = /^(\\d{4})\\/(\\d{2})\\/(\\d{2})/.exec(trimmed)\n if (slashes !== null) return `${slashes[1]}-${slashes[2]}-${slashes[3]}`\n const named = /^(\\d{1,2}) ([A-Za-z]{3,9}) (\\d{4})$/.exec(trimmed)\n if (named !== null) {\n const month = MONTHS.indexOf((named[2] ?? '').slice(0, 3).toLowerCase())\n if (month >= 0) return `${named[3]}-${pad2(month + 1)}-${pad2(Number(named[1]))}`\n }\n const american = /^([A-Za-z]{3,9}) (\\d{1,2}), (\\d{4})$/.exec(trimmed)\n if (american !== null) {\n const month = MONTHS.indexOf((american[1] ?? '').slice(0, 3).toLowerCase())\n if (month >= 0) return `${american[3]}-${pad2(month + 1)}-${pad2(Number(american[2]))}`\n }\n return null\n}\n\nconst MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']\n\nfunction pad2(value: number): string {\n return value < 10 ? `0${value}` : String(value)\n}\n\n/**\n * The availability vocabulary, pinned. schema.org URLs, the bare enum names and\n * the visible-text phrases all collapse to one of six tokens, because \"In stock\"\n * on the page and `https://schema.org/InStock` in the JSON-LD are the same fact\n * and must corroborate.\n */\nconst AVAILABILITY_TOKENS: readonly (readonly [string, string])[] = [\n ['limitedavailability', 'limited'],\n ['onlineonly', 'instock'],\n ['instoreonly', 'instock'],\n ['presale', 'preorder'],\n ['preorder', 'preorder'],\n ['backorder', 'backorder'],\n ['discontinued', 'discontinued'],\n ['soldout', 'outofstock'],\n ['outofstock', 'outofstock'],\n ['instock', 'instock'],\n]\n\n/** Visible-text phrases, matched against normalised text. Longest first. */\nconst AVAILABILITY_PHRASES: readonly (readonly [string, string])[] = [\n ['limited availability', 'limited'],\n ['limited stock', 'limited'],\n ['currently unavailable', 'outofstock'],\n ['temporarily unavailable', 'outofstock'],\n ['out of stock', 'outofstock'],\n ['discontinued', 'discontinued'],\n ['back order', 'backorder'],\n ['backorder', 'backorder'],\n ['pre-order', 'preorder'],\n ['preorder', 'preorder'],\n ['sold out', 'outofstock'],\n ['in stock', 'instock'],\n ['available now', 'instock'],\n]\n\nexport function normalizeAvailability(value: string): string | null {\n const squashed = value.toLowerCase().replace(/[^a-z]/g, '')\n for (const [needle, token] of AVAILABILITY_TOKENS) {\n if (squashed.endsWith(needle) || squashed === needle) return token\n }\n return null\n}\n\n/**\n * \"We score honesty, not disclosure\" (§3.5): an explicit statement that there is\n * no published price satisfies the `price` core fact. The list is pinned and\n * deliberately short — it contains only phrases that state the absence of a\n * price, never phrases that merely fail to state one.\n */\nconst NO_PUBLISHED_PRICE: readonly string[] = [\n 'price on request',\n 'pricing on request',\n 'price on application',\n 'contact us for pricing',\n 'contact for pricing',\n 'contact us for a quote',\n 'no published price',\n 'pricing available on request',\n]\n\nconst UNPRICED = 'unpriced'\n\n/** Phone → `+` and digits. `(415) 555-0142` and `+1 415 555 0142` are one fact. */\nexport function normalizePhone(value: string): string | null {\n const trimmed = value.trim()\n const plus = trimmed.startsWith('+') || trimmed.startsWith('tel:+')\n const digits = trimmed.replace(/\\D/g, '')\n if (digits.length < 7 || digits.length > 15) return null\n return plus ? `+${digits}` : digits\n}\n\n// ---------------------------------------------------------------------------\n// Money tokens in free text\n// ---------------------------------------------------------------------------\n\n/**\n * Single-character currency symbols that may START a money span. Multi-character\n * markers (`R$`, `kr`, `CHF`) are reached through the ISO-code branch instead: a\n * scanner that treated `R` or `k` as a currency start would open a span on every\n * capital R on the page and hand `parseMoneyText` garbage to reject.\n */\nconst CURRENCY_SYMBOLS = '$€£¥₹₩₪₫₴₦₱฿₺'\nconst DIGITS = '0123456789'\n/** Comma, period, both apostrophes, plain space, NBSP, NARROW NBSP. */\nconst MONEY_SEPARATORS = \".,'’   \"\nconst MONEY_PREFIX_QUALIFIERS = [\n 'starting from',\n 'starting at',\n 'prices from',\n 'priced from',\n 'as little as',\n 'as low as',\n 'starts at',\n 'from',\n]\nconst RANGE_JOINERS = ['—', '–', '-', ' to ']\n\n/**\n * Finds money-shaped substrings and hands each to `parseMoneyText`.\n *\n * Written as a scanner rather than a regex on purpose: the pattern that would\n * express this correctly needs nested quantifiers over overlapping character\n * classes, which is both a backtracking hazard on attacker-supplied bytes and\n * much harder to reimplement in another language than twenty lines of loop.\n *\n * The window handed to the parser includes an immediately preceding qualifier\n * (`From $9`) and a following range operand (`$148 – $198`), because\n * `parseMoneyText` resolves both to the lower bound with `qualified: true`, and a\n * qualified price is excluded from D2.4 parity (§3.11). Slicing the bare token\n * would silently turn a range into an exact price.\n */\nexport function findMoneyPhrases(text: string): { phrase: string; index: number }[] {\n const found: { phrase: string; index: number }[] = []\n const limit = Math.min(text.length, MAX_SCAN_CHARS)\n let i = 0\n while (i < limit) {\n const spanEnd = readMoneySpan(text, i, limit)\n if (spanEnd === null) {\n i++\n continue\n }\n let start = i\n let end = spanEnd\n\n // Leading qualifier.\n const before = text.slice(Math.max(0, start - 20), start).toLowerCase()\n for (const qualifier of MONEY_PREFIX_QUALIFIERS) {\n if (before.trimEnd().endsWith(qualifier)) {\n start = Math.max(0, start - (before.length - before.trimEnd().length) - qualifier.length)\n break\n }\n }\n\n // Trailing range operand.\n for (const joiner of RANGE_JOINERS) {\n const after = text.slice(end, end + joiner.length + 2)\n const at = after.indexOf(joiner)\n if (at === -1 || at > 1) continue\n const secondStart = end + at + joiner.length\n const secondEnd = readMoneySpan(text, skipSpaces(text, secondStart, limit), limit)\n if (secondEnd !== null) end = secondEnd\n break\n }\n\n found.push({ phrase: text.slice(start, end), index: start })\n i = end\n }\n return found\n}\n\n/** Bounded scan window. A 2 MiB body is data, not a budget. */\nconst MAX_SCAN_CHARS = 400_000\n\nfunction skipSpaces(text: string, from: number, limit: number): number {\n let i = from\n while (i < limit && text.charAt(i) === ' ') i++\n return i\n}\n\n/**\n * Reads one money-shaped span starting at `from`, or null. A span is a currency\n * marker adjacent to a digit run, in either order; the marker is a symbol from\n * the pinned set or an uppercase three-letter token.\n */\nfunction readMoneySpan(text: string, from: number, limit: number): number | null {\n const char = text.charAt(from)\n if (CURRENCY_SYMBOLS.includes(char) && char !== '') {\n let i = from + 1\n if (text.charAt(i) === ' ') i++\n if (!DIGITS.includes(text.charAt(i))) return null\n return readNumberRun(text, i, limit)\n }\n if (DIGITS.includes(char)) {\n // Only start a span at the beginning of a number run.\n const previous = from > 0 ? text.charAt(from - 1) : ''\n if (DIGITS.includes(previous) || MONEY_SEPARATORS.includes(previous)) return null\n const end = readNumberRun(text, from, limit)\n let i = end\n if (text.charAt(i) === ' ') i++\n const symbol = text.charAt(i)\n if (CURRENCY_SYMBOLS.includes(symbol) && symbol !== '') return i + 1\n const code = text.slice(i, i + 3)\n if (/^[A-Z]{3}$/.test(code) && !/[A-Za-z]/.test(text.charAt(i + 3))) return i + 3\n return null\n }\n if (/[A-Z]/.test(char) && from + 3 <= limit) {\n const code = text.slice(from, from + 3)\n if (!/^[A-Z]{3}$/.test(code)) return null\n if (from > 0 && /[A-Za-z]/.test(text.charAt(from - 1))) return null\n let i = from + 3\n if (text.charAt(i) === ' ') i++\n if (!DIGITS.includes(text.charAt(i))) return null\n return readNumberRun(text, i, limit)\n }\n return null\n}\n\nfunction readNumberRun(text: string, from: number, limit: number): number {\n let i = from\n let end = from\n while (i < limit) {\n const char = text.charAt(i)\n if (DIGITS.includes(char)) {\n i++\n end = i\n continue\n }\n if (MONEY_SEPARATORS.includes(char) && char !== '') {\n i++\n continue\n }\n break\n }\n return end\n}\n\n// ---------------------------------------------------------------------------\n// Label lexicon — the key/value shape of markdown and of `<dt>`-style HTML\n// ---------------------------------------------------------------------------\n\n/**\n * Pinned label → fact mapping. This is how facts are read out of the negotiated\n * markdown representation, whose shape is `- **Price:** $148.00` (see\n * `@rebilder/render-md`), and out of definition-list HTML.\n *\n * Pinned rather than fuzzy-matched for the usual reason: a lexicon that grew per\n * page would make the same bytes score differently in two implementations.\n * Additions land as a MINOR.\n */\nconst LABEL_LEXICON: readonly (readonly [string, ArsFactKind])[] = [\n ['price', 'price'],\n ['cost', 'price'],\n ['currency', 'currency'],\n ['availability', 'availability'],\n ['stock', 'availability'],\n ['brand', 'brand'],\n ['manufacturer', 'brand'],\n ['sku', 'sku'],\n ['item number', 'sku'],\n ['product code', 'sku'],\n ['mpn', 'sku'],\n ['shipping', 'shipping'],\n ['delivery', 'shipping'],\n ['returns', 'returns'],\n ['return policy', 'returns'],\n ['refunds', 'returns'],\n ['description', 'description'],\n ['summary', 'description'],\n ['updated', 'updated'],\n ['last updated', 'updated'],\n ['modified', 'updated'],\n ['published', 'published'],\n ['date published', 'published'],\n ['author', 'author'],\n ['written by', 'author'],\n ['publisher', 'authority'],\n ['organization', 'org-name'],\n ['organisation', 'org-name'],\n ['company', 'org-name'],\n ['business', 'org-name'],\n ['address', 'address'],\n ['location', 'address'],\n ['phone', 'phone'],\n ['telephone', 'phone'],\n ['tel', 'phone'],\n ['email', 'email'],\n ['e-mail', 'email'],\n ['hours', 'hours'],\n ['opening hours', 'hours'],\n ['duration', 'duration'],\n ['length', 'duration'],\n ['eligibility', 'eligibility'],\n ['requirements', 'eligibility'],\n ['section', 'section'],\n ['category', 'section'],\n ['topic', 'section'],\n ['service area', 'service-area'],\n ['areas served', 'service-area'],\n ['items', 'item-count'],\n ['item count', 'item-count'],\n]\n\n/** Strips markdown list bullets, emphasis and heading marks from a label. */\nfunction normalizeLabel(raw: string): string {\n return raw\n .replace(/^[\\s>*\\-+#]+/, '')\n .replace(/[*_`]/g, '')\n .trim()\n .toLowerCase()\n}\n\ninterface LabelledValue {\n kind: ArsFactKind\n value: string\n index: number\n}\n\n/**\n * Reads `Label: value` lines. Handles the markdown emphasis form\n * (`- **Price:** $148.00`), the plain form (`Price: $148.00`) and nothing else —\n * a colon inside prose is not a label, which is why the label must be the first\n * thing on the line and no longer than `MAX_LABEL_CHARS`.\n */\nfunction readLabelledLines(text: string): LabelledValue[] {\n const out: LabelledValue[] = []\n let cursor = 0\n for (const line of text.split('\\n')) {\n const lineStart = cursor\n cursor += line.length + 1\n const colon = line.indexOf(':')\n if (colon === -1 || colon > MAX_LABEL_CHARS) continue\n const label = normalizeLabel(line.slice(0, colon))\n if (label.length === 0) continue\n const value = line\n .slice(colon + 1)\n .replace(/^[\\s*_`]+/, '')\n .trim()\n if (value.length === 0) continue\n for (const [needle, kind] of LABEL_LEXICON) {\n if (label !== needle) continue\n out.push({ kind, value, index: lineStart + colon + 1 })\n break\n }\n }\n return out\n}\n\nconst MAX_LABEL_CHARS = 32\n\n// ---------------------------------------------------------------------------\n// Extraction context\n// ---------------------------------------------------------------------------\n\nexport interface ExtractContext {\n readonly profile: ArsFactProfile\n readonly ruleset: ArsRuleset\n /** Absolute URL the capture resolved to, used as the base for relative links. */\n readonly baseUrl: string\n /** Origin of the target, for the same-origin test on `item-link`. */\n readonly origin: string\n /** ISO code from structured data, if any. Disambiguates `$` and a bare `1.500`. */\n readonly currencyHint: string | undefined\n}\n\n/** Facts the caller wants: the profile's core plus extended set, as one lookup. */\nfunction wanted(profile: ArsFactProfile): ReadonlySet<ArsFactKind> {\n return new Set<ArsFactKind>([...profile.core, ...profile.extended])\n}\n\n/**\n * Pass 2 (§3.5): extract against the RESOLVED profile. Only facts the profile\n * names are extracted, which is the mechanism that caps coverage at the profile\n * size and makes fixtures `031-keyword-stuffed` and `032-density-baseline` score\n * identically — a page can invent a hundred extra facts and none of them counts.\n */\nexport function extractFacts(\n representation: ArsRepresentation,\n context: ExtractContext,\n): ExtractedFact[] {\n const facts: ExtractedFact[] = []\n const want = wanted(context.profile)\n const push = (fact: ExtractedFact): void => {\n if (want.has(fact.kind)) facts.push(fact)\n }\n\n for (const node of representation.jsonLd.nodes) extractFromJsonLd(node, context, push)\n\n if (representation.doc !== null) {\n extractFromHtml(representation.doc, context, push)\n } else {\n extractFromPlainText(representation, context, push)\n }\n\n return facts\n}\n\n// ---------------------------------------------------------------------------\n// JSON-LD extraction\n// ---------------------------------------------------------------------------\n\n/**\n * Property aliases per fact, in precedence order. Written as paths so\n * `offers.price` reaches into an `Offer` and `offers.lowPrice` reaches into an\n * `AggregateOffer` — the shape Shopify actually emits.\n */\nconst JSON_LD_PATHS: readonly (readonly [ArsFactKind, readonly string[]])[] = [\n ['title', ['name', 'headline']],\n ['description', ['description', 'abstract']],\n ['price', ['offers.price', 'offers.lowPrice', 'offers.priceSpecification.price', 'price']],\n ['currency', ['offers.priceCurrency', 'offers.priceSpecification.priceCurrency', 'priceCurrency']],\n ['availability', ['offers.availability', 'availability']],\n ['brand', ['brand']],\n ['sku', ['sku', 'mpn', 'gtin13', 'gtin']],\n ['shipping', ['offers.shippingDetails', 'shippingDetails']],\n ['returns', ['offers.hasMerchantReturnPolicy', 'hasMerchantReturnPolicy']],\n ['org-name', ['name']],\n ['address', ['address']],\n ['hours', ['openingHours', 'openingHoursSpecification']],\n ['phone', ['telephone', 'contactPoint.telephone']],\n ['email', ['email', 'contactPoint.email']],\n ['service-area', ['areaServed', 'serviceArea']],\n ['author', ['author']],\n ['authority', ['publisher', 'author']],\n ['section', ['articleSection', 'genre']],\n ['published', ['datePublished', 'dateCreated']],\n ['updated', ['dateModified']],\n ['duration', ['duration', 'timeRequired']],\n ['eligibility', ['eligibleCustomerType', 'audience']],\n ['primary-action-url', ['potentialAction.target', 'potentialAction.url']],\n ['question-answer', ['mainEntity.acceptedAnswer']],\n ['item-count', ['numberOfItems']],\n ['item-link', ['itemListElement.url', 'itemListElement.item']],\n]\n\n/** Types whose `name` is an organisation name rather than a page title. */\nconst ORG_TYPES = new Set([\n 'Organization',\n 'LocalBusiness',\n 'Store',\n 'Restaurant',\n 'Corporation',\n 'NGO',\n 'GovernmentOrganization',\n 'EducationalOrganization',\n 'MedicalBusiness',\n 'ProfessionalService',\n 'FoodEstablishment',\n 'LodgingBusiness',\n 'AutomotiveBusiness',\n 'HealthAndBeautyBusiness',\n 'SportsActivityLocation',\n 'Place',\n])\n\nfunction extractFromJsonLd(\n node: JsonLdNode,\n context: ExtractContext,\n push: (fact: ExtractedFact) => void,\n): void {\n const isOrg = node.types.some((type) => ORG_TYPES.has(type))\n for (const [kind, paths] of JSON_LD_PATHS) {\n // `name` means two different things depending on the node's type; reading it\n // as both would let one string corroborate itself across two fact kinds.\n if (kind === 'title' && isOrg) continue\n if (kind === 'org-name' && !isOrg) continue\n\n for (const path of paths) {\n const raw = readPath(node, path)\n if (raw === null) continue\n const normalized = normalizeFactValue(kind, raw, context)\n if (normalized === null) continue\n push({ kind, normalized: normalized.value, source: 'json-ld', offset: node.offset, qualified: normalized.qualified })\n break\n }\n }\n}\n\ninterface NormalizedValue {\n value: string\n qualified: boolean\n}\n\n/** One normaliser, shared by every source, so the same fact from two places matches. */\nfunction normalizeFactValue(\n kind: ArsFactKind,\n raw: string,\n context: ExtractContext,\n): NormalizedValue | null {\n if (PRESENCE_FACTS.has(kind)) return { value: DECLARED, qualified: false }\n\n switch (kind) {\n case 'title':\n return raw.trim().length === 0 ? null : { value: normalizeTitle(raw), qualified: false }\n case 'price': {\n const lowered = raw.trim().toLowerCase()\n if (NO_PUBLISHED_PRICE.some((phrase) => lowered.includes(phrase))) {\n return { value: UNPRICED, qualified: false }\n }\n const money = parseMoneyText(raw, { currency: context.currencyHint })\n return money === null\n ? null\n : { value: normalizeMoney(money.amount, money.currency), qualified: money.qualified }\n }\n case 'currency': {\n const code = raw.trim().toUpperCase()\n return /^[A-Z]{3}$/.test(code) ? { value: code, qualified: false } : null\n }\n case 'availability': {\n const token = normalizeAvailability(raw)\n return token === null ? null : { value: token, qualified: false }\n }\n case 'phone': {\n const phone = normalizePhone(raw)\n return phone === null ? null : { value: phone, qualified: false }\n }\n case 'email': {\n const email = raw.trim().replace(/^mailto:/i, '').toLowerCase()\n return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email) ? { value: email, qualified: false } : null\n }\n case 'published':\n case 'updated': {\n const date = normalizeDate(raw)\n return date === null ? null : { value: date, qualified: false }\n }\n case 'duration': {\n const minutes = normalizeDuration(raw)\n return minutes === null ? null : { value: minutes, qualified: false }\n }\n case 'item-count': {\n const count = Number.parseInt(raw.replace(/[^0-9]/g, ''), 10)\n return Number.isFinite(count) && count > 0 ? { value: String(count), qualified: false } : null\n }\n case 'primary-action-url': {\n const absolute = absoluteUrl(raw, context.baseUrl)\n return absolute === null ? null : { value: absolute, qualified: false }\n }\n default:\n return raw.trim().length === 0 ? null : { value: normalizeText(raw), qualified: false }\n }\n}\n\n/** ISO 8601 durations and the two visible forms, normalised to whole minutes. */\nexport function normalizeDuration(raw: string): string | null {\n const iso = /^P(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?)?$/.exec(raw.trim().toUpperCase())\n if (iso !== null && (iso[1] ?? iso[2] ?? iso[3]) !== undefined) {\n const minutes = Number(iso[1] ?? 0) * 1440 + Number(iso[2] ?? 0) * 60 + Number(iso[3] ?? 0)\n return minutes > 0 ? String(minutes) : null\n }\n const spoken = /^(\\d{1,4})\\s?(min|mins|minute|minutes|h|hr|hrs|hour|hours)\\b/i.exec(raw.trim())\n if (spoken !== null) {\n const amount = Number(spoken[1])\n const unit = (spoken[2] ?? '').toLowerCase()\n const minutes = unit.startsWith('h') ? amount * 60 : amount\n return minutes > 0 ? String(minutes) : null\n }\n return null\n}\n\n/** Resolves a possibly relative URL. Returns null rather than throwing on garbage. */\nexport function absoluteUrl(href: string, base: string): string | null {\n try {\n return new URL(href, base).toString()\n } catch {\n return null\n }\n}\n\n// ---------------------------------------------------------------------------\n// HTML extraction\n// ---------------------------------------------------------------------------\n\n/** `<meta>` name/property → fact. Pinned; `og:` and the Twitter card are the whole set. */\nconst META_LEXICON: readonly (readonly [string, ArsFactKind])[] = [\n ['og:title', 'title'],\n ['twitter:title', 'title'],\n ['description', 'description'],\n ['og:description', 'description'],\n ['twitter:description', 'description'],\n ['og:price:amount', 'price'],\n ['product:price:amount', 'price'],\n ['og:price:currency', 'currency'],\n ['product:price:currency', 'currency'],\n ['og:availability', 'availability'],\n ['product:availability', 'availability'],\n ['product:brand', 'brand'],\n ['og:site_name', 'org-name'],\n ['author', 'author'],\n ['article:author', 'author'],\n ['article:published_time', 'published'],\n ['article:modified_time', 'updated'],\n ['article:section', 'section'],\n]\n\n/** `itemprop` → fact, for microdata. The same vocabulary as JSON-LD, one level flat. */\nconst ITEMPROP_LEXICON: readonly (readonly [string, ArsFactKind])[] = [\n ['name', 'title'],\n ['price', 'price'],\n ['pricecurrency', 'currency'],\n ['availability', 'availability'],\n ['brand', 'brand'],\n ['sku', 'sku'],\n ['description', 'description'],\n ['telephone', 'phone'],\n ['email', 'email'],\n ['address', 'address'],\n ['openinghours', 'hours'],\n ['author', 'author'],\n ['datepublished', 'published'],\n ['datemodified', 'updated'],\n ['articlesection', 'section'],\n]\n\nfunction extractFromHtml(\n doc: HtmlDocument,\n context: ExtractContext,\n push: (fact: ExtractedFact) => void,\n): void {\n // <title> and the first <h1>.\n for (const element of doc.elements) {\n if (element.tag !== 'title') continue\n const text = elementText(doc, element.index)\n const normalized = normalizeFactValue('title', text, context)\n if (normalized !== null) {\n push({ kind: 'title', normalized: normalized.value, source: 'html-text', offset: element.offset, qualified: false })\n }\n break\n }\n for (const element of doc.elements) {\n if (element.tag !== 'h1' || element.excludedBy !== null) continue\n const normalized = normalizeFactValue('title', elementText(doc, element.index), context)\n if (normalized !== null) {\n push({ kind: 'title', normalized: normalized.value, source: 'html-text', offset: element.offset, qualified: false })\n }\n break\n }\n\n // <meta>.\n for (const meta of doc.metas) {\n if (meta.content === null) continue\n const key = meta.property ?? meta.name\n if (key === null) continue\n for (const [needle, kind] of META_LEXICON) {\n if (key !== needle) continue\n const normalized = normalizeFactValue(kind, meta.content, context)\n if (normalized !== null) {\n push({ kind, normalized: normalized.value, source: 'meta', offset: meta.offset, qualified: normalized.qualified })\n }\n break\n }\n }\n\n // Microdata: itemprop, with content= preferred over text (schema.org's own advice).\n for (const element of doc.elements) {\n const itemprop = attr(element, 'itemprop')\n if (itemprop === null) continue\n const key = itemprop.toLowerCase()\n for (const [needle, kind] of ITEMPROP_LEXICON) {\n if (key !== needle) continue\n const raw =\n attr(element, 'content') ??\n attr(element, 'datetime') ??\n attr(element, 'href') ??\n elementText(doc, element.index)\n const normalized = normalizeFactValue(kind, raw, context)\n if (normalized !== null) {\n push({ kind, normalized: normalized.value, source: 'microdata', offset: element.offset, qualified: normalized.qualified })\n }\n break\n }\n }\n\n // Visible text: money, availability phrases, the no-published-price signal.\n extractVisibleText(doc, context, push)\n\n // Links and forms.\n extractLinks(doc, context, push)\n\n // Structural shapes: question/answer, opening hours, definition lists.\n extractStructures(doc, context, push)\n}\n\n/**\n * Facts read out of counted text. Every text node is visited individually so the\n * fact's offset is the offset of the node it was found in — a measured offset of\n * a heuristic fact, which is exactly how §3.9 describes `ArsFactObservation`.\n *\n * Hidden nodes (`hidden`, inline `display:none`, `<template>`) are skipped:\n * fixture `037-hidden-text-facts` asserts that facts stuffed into a hidden\n * element do not score.\n */\nfunction extractVisibleText(\n doc: HtmlDocument,\n context: ExtractContext,\n push: (fact: ExtractedFact) => void,\n): void {\n for (const node of doc.texts) {\n if (node.excludedBy !== null) continue\n const text = node.text\n if (text.trim().length === 0) continue\n\n for (const money of findMoneyPhrases(text)) {\n const parsed = parseMoneyText(money.phrase, { currency: context.currencyHint })\n if (parsed === null) continue\n push({\n kind: 'price',\n normalized: normalizeMoney(parsed.amount, parsed.currency),\n source: 'html-text',\n offset: node.offset,\n qualified: parsed.qualified,\n })\n push({\n kind: 'currency',\n normalized: parsed.currency,\n source: 'html-text',\n offset: node.offset,\n qualified: false,\n })\n }\n\n const lowered = text.toLowerCase()\n if (NO_PUBLISHED_PRICE.some((phrase) => lowered.includes(phrase))) {\n push({ kind: 'price', normalized: UNPRICED, source: 'html-text', offset: node.offset, qualified: false })\n }\n for (const [phrase, token] of AVAILABILITY_PHRASES) {\n if (!lowered.includes(phrase)) continue\n push({ kind: 'availability', normalized: token, source: 'html-text', offset: node.offset, qualified: false })\n break\n }\n for (const [kind, marker] of TEXT_PRESENCE_MARKERS) {\n if (!marker.some((phrase) => lowered.includes(phrase))) continue\n push({ kind, normalized: DECLARED, source: 'html-text', offset: node.offset, qualified: false })\n }\n const sku = /\\bsku[:\\s]+([A-Za-z0-9][A-Za-z0-9._-]{2,31})\\b/i.exec(text)\n if (sku !== null && sku[1] !== undefined) {\n push({ kind: 'sku', normalized: normalizeText(sku[1]), source: 'html-text', offset: node.offset, qualified: false })\n }\n }\n\n // Labelled lines inside HTML (`<dt>Price</dt><dd>$148</dd>` collapses to\n // \"Price $148\" in counted text, so this reads the whole document's text once).\n for (const labelled of readLabelledLines(countedText(doc))) {\n const normalized = normalizeFactValue(labelled.kind, labelled.value, context)\n if (normalized === null) continue\n push({\n kind: labelled.kind,\n normalized: normalized.value,\n source: 'html-text',\n offset: firstTextOffset(doc),\n qualified: normalized.qualified,\n })\n }\n}\n\n/** Presence facts detectable from prose, with their pinned phrase lists. */\nconst TEXT_PRESENCE_MARKERS: readonly (readonly [ArsFactKind, readonly string[]])[] = [\n ['shipping', ['free shipping', 'shipping', 'ships in', 'delivery', 'ships free']],\n ['returns', ['return policy', 'returns', 'money-back', 'money back', 'refund']],\n ['service-area', ['areas served', 'service area', 'we serve', 'serving']],\n ['eligibility', ['eligibility', 'who can apply', 'you must be', 'requirements']],\n]\n\nfunction firstTextOffset(doc: HtmlDocument): number {\n for (const node of doc.texts) {\n if (node.excludedBy === null && node.text.trim().length > 0) return node.offset\n }\n return 0\n}\n\nconst ACTION_MAX_TEXT_CHARS = 64\n\nfunction extractLinks(\n doc: HtmlDocument,\n context: ExtractContext,\n push: (fact: ExtractedFact) => void,\n): void {\n const lexicon = context.ruleset.actionLexicon\n for (const element of doc.elements) {\n if (element.excludedBy !== null) continue\n\n if (element.tag === 'a') {\n const href = attr(element, 'href')\n if (href === null) continue\n if (href.toLowerCase().startsWith('tel:')) {\n const phone = normalizePhone(href.slice(4))\n if (phone !== null) {\n push({ kind: 'phone', normalized: phone, source: 'html-text', offset: element.offset, qualified: false })\n }\n continue\n }\n if (href.toLowerCase().startsWith('mailto:')) {\n const normalized = normalizeFactValue('email', href, context)\n if (normalized !== null) {\n push({ kind: 'email', normalized: normalized.value, source: 'html-text', offset: element.offset, qualified: false })\n }\n continue\n }\n const text = elementText(doc, element.index).slice(0, ACTION_MAX_TEXT_CHARS)\n if (!matchesLexicon(text, lexicon)) continue\n const absolute = absoluteUrl(href, context.baseUrl)\n if (absolute === null) continue\n push({ kind: 'primary-action-url', normalized: absolute, source: 'html-text', offset: element.offset, qualified: false })\n continue\n }\n\n if (element.tag === 'form') {\n const action = attr(element, 'action')\n if (action === null) continue\n const text = elementText(doc, element.index).slice(0, ACTION_MAX_TEXT_CHARS)\n if (!matchesLexicon(text, lexicon)) continue\n const absolute = absoluteUrl(action, context.baseUrl)\n if (absolute === null) continue\n push({ kind: 'primary-action-url', normalized: absolute, source: 'html-text', offset: element.offset, qualified: false })\n }\n }\n\n const items = largestRepeatedLinkBlock(doc, context.origin)\n if (items.count > 0) {\n push({ kind: 'item-count', normalized: String(items.count), source: 'html-text', offset: items.offset, qualified: false })\n if (items.sameOrigin) {\n push({ kind: 'item-link', normalized: DECLARED, source: 'html-text', offset: items.offset, qualified: false })\n }\n }\n}\n\n/** Anchor text matches the action lexicon exactly, or begins with a lexicon phrase. */\nfunction matchesLexicon(text: string, lexicon: readonly string[]): boolean {\n const normalized = text.replace(/\\s+/g, ' ').trim().toLowerCase()\n if (normalized.length === 0) return false\n for (const phrase of lexicon) {\n if (normalized === phrase) return true\n if (normalized.startsWith(`${phrase} `)) return true\n }\n return false\n}\n\n/**\n * `item-count` / `item-link` for `collection` (§3.5): \"the number of distinct\n * item links inside the largest repeated-structure block, and whether those\n * links resolve to same-origin URLs.\"\n *\n * Made deterministic as: group every anchor by its GRANDPARENT element (the\n * container of the repeated item, e.g. `<ul>` for `<li><a>`), drop groups whose\n * container is inside `<nav>`, `<header>` or `<footer>`, and take the group with\n * the most distinct hrefs. The nav exclusion is the whole reason for the\n * \"largest repeated block\" phrasing — a site-wide menu is a repeated block of\n * links and is not a product grid.\n */\nfunction largestRepeatedLinkBlock(\n doc: HtmlDocument,\n origin: string,\n): { count: number; offset: number; sameOrigin: boolean } {\n const groups = new Map<number, { hrefs: Set<string>; sameOrigin: number; offset: number }>()\n for (const element of doc.elements) {\n if (element.tag !== 'a' || element.excludedBy !== null) continue\n const href = attr(element, 'href')\n if (href === null || href.startsWith('#')) continue\n const parent = element.parent >= 0 ? doc.elements[element.parent] : undefined\n const container = parent !== undefined && parent.parent >= 0 ? parent.parent : element.parent\n if (container < 0) continue\n if (isInsideChrome(doc, container)) continue\n\n const absolute = absoluteUrl(href, origin)\n if (absolute === null) continue\n const group = groups.get(container) ?? {\n hrefs: new Set<string>(),\n sameOrigin: 0,\n offset: doc.elements[container]?.offset ?? 0,\n }\n if (!group.hrefs.has(absolute)) {\n group.hrefs.add(absolute)\n if (absolute.startsWith(origin)) group.sameOrigin++\n }\n groups.set(container, group)\n }\n\n let best = { count: 0, offset: 0, sameOrigin: false }\n for (const [, group] of groups) {\n if (group.hrefs.size <= best.count) continue\n best = {\n count: group.hrefs.size,\n offset: group.offset,\n sameOrigin: group.sameOrigin * 2 >= group.hrefs.size,\n }\n }\n return best.count >= MIN_REPEATED_ITEMS ? best : { count: 0, offset: 0, sameOrigin: false }\n}\n\n/** Below this, a group of links is a paragraph with citations, not a listing. */\nconst MIN_REPEATED_ITEMS = 3\n\nconst CHROME_TAGS = new Set(['nav', 'header', 'footer'])\n\nfunction isInsideChrome(doc: HtmlDocument, from: number): boolean {\n let current = from\n for (let hops = 0; hops < 64 && current >= 0; hops++) {\n const element = doc.elements[current]\n if (element === undefined) return false\n if (CHROME_TAGS.has(element.tag)) return true\n if (element.attrs['role'] === 'navigation' || element.attrs['role'] === 'banner') return true\n current = element.parent\n }\n return false\n}\n\nconst DAY_NAMES = [\n 'monday',\n 'tuesday',\n 'wednesday',\n 'thursday',\n 'friday',\n 'saturday',\n 'sunday',\n 'mon',\n 'tue',\n 'wed',\n 'thu',\n 'fri',\n 'sat',\n 'sun',\n]\n\n/**\n * Day-name / `HH:MM` adjacency, the §3.5 pass-1 signal, reused here as the\n * visible-text source for `hours`. \"Adjacent\" is: a day name and a clock time\n * within 40 characters of each other in the same text node.\n */\nexport function hasOpeningHoursShape(text: string): boolean {\n const lowered = text.toLowerCase()\n for (const day of DAY_NAMES) {\n let at = lowered.indexOf(day)\n while (at !== -1) {\n const window = lowered.slice(at, at + 40)\n if (/\\d{1,2}[:.]\\d{2}/.test(window) || /\\d{1,2}\\s?(am|pm)/.test(window)) return true\n at = lowered.indexOf(day, at + day.length)\n }\n }\n return false\n}\n\nfunction extractStructures(\n doc: HtmlDocument,\n context: ExtractContext,\n push: (fact: ExtractedFact) => void,\n): void {\n for (const node of doc.texts) {\n if (node.excludedBy !== null) continue\n if (!hasOpeningHoursShape(node.text)) continue\n push({ kind: 'hours', normalized: DECLARED, source: 'html-text', offset: node.offset, qualified: false })\n break\n }\n\n for (const element of doc.elements) {\n if (element.excludedBy !== null) continue\n if (element.tag === 'address') {\n const normalized = normalizeFactValue('address', elementText(doc, element.index), context)\n if (normalized !== null) {\n push({ kind: 'address', normalized: normalized.value, source: 'html-text', offset: element.offset, qualified: false })\n }\n }\n }\n\n const qa = firstQuestionAnswer(doc)\n if (qa !== null) {\n push({ kind: 'question-answer', normalized: DECLARED, source: 'html-text', offset: qa, qualified: false })\n }\n}\n\nconst HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6'])\n\n/**\n * The §3.5 `question-answer` shapes: a `<dt>`/`<dd>` pair, a\n * `<details><summary>`, or a heading ending in `?` followed by a paragraph.\n * Counted ONCE as present, not per item — a page with 40 questions is not four\n * times better than a page with 10, and the offset returned is the first shape's.\n */\nfunction firstQuestionAnswer(doc: HtmlDocument): number | null {\n let sawDt = false\n let pendingQuestionHeading = false\n for (const element of doc.elements) {\n if (element.excludedBy !== null) continue\n if (element.tag === 'dt') {\n sawDt = true\n continue\n }\n if (element.tag === 'dd' && sawDt) return element.offset\n if (element.tag === 'details') {\n for (const child of doc.elements) {\n if (child.parent === element.index && child.tag === 'summary') return element.offset\n }\n continue\n }\n if (HEADING_TAGS.has(element.tag)) {\n pendingQuestionHeading = elementText(doc, element.index).trim().endsWith('?')\n continue\n }\n if (element.tag === 'p' && pendingQuestionHeading) return element.offset\n }\n return null\n}\n\n// ---------------------------------------------------------------------------\n// Plain-text / markdown extraction\n// ---------------------------------------------------------------------------\n\nconst MARKDOWN_LINK_RE = /\\[([^\\]\\n]{1,120})\\]\\(([^)\\s]{1,500})\\)/g\n\n/**\n * Extraction from a NEGOTIATED representation — markdown or plain text. Offsets\n * are UTF-8 byte offsets into the body, computed once per hit rather than by\n * scanning the whole body, so a 2 MiB markdown file does not become quadratic.\n *\n * The source is recorded as `negotiated` for everything found here, which is\n * what lets a fact stated in markdown corroborate the same fact in the HTML's\n * JSON-LD: two distinct sources, one value.\n */\nfunction extractFromPlainText(\n representation: ArsRepresentation,\n context: ExtractContext,\n push: (fact: ExtractedFact) => void,\n): void {\n const body = representation.body\n const offsetOf = (index: number): number => utf8Length(body.slice(0, index))\n\n // Title: the first ATX heading, with a wrapping markdown link unwrapped —\n // `render-md` emits `# [Alpine Trail Pack 28L](https://…)`.\n const heading = /^#{1,6}[ \\t]+(.+)$/m.exec(body)\n if (heading !== null && heading[1] !== undefined) {\n const linked = /^\\[([^\\]]+)\\]\\([^)]*\\)\\s*$/.exec(heading[1].trim())\n const raw = linked !== null && linked[1] !== undefined ? linked[1] : heading[1]\n const normalized = normalizeFactValue('title', raw, context)\n if (normalized !== null) {\n push({ kind: 'title', normalized: normalized.value, source: 'negotiated', offset: offsetOf(heading.index), qualified: false })\n }\n }\n\n for (const labelled of readLabelledLines(body)) {\n const normalized = normalizeFactValue(labelled.kind, labelled.value, context)\n if (normalized === null) continue\n push({ kind: labelled.kind, normalized: normalized.value, source: 'negotiated', offset: offsetOf(labelled.index), qualified: normalized.qualified })\n // A labelled price also states its currency.\n if (labelled.kind === 'price' && normalized.value !== UNPRICED) {\n const code = normalized.value.slice(0, 3)\n push({ kind: 'currency', normalized: code, source: 'negotiated', offset: offsetOf(labelled.index), qualified: false })\n }\n }\n\n for (const money of findMoneyPhrases(body)) {\n const parsed = parseMoneyText(money.phrase, { currency: context.currencyHint })\n if (parsed === null) continue\n push({ kind: 'price', normalized: normalizeMoney(parsed.amount, parsed.currency), source: 'negotiated', offset: offsetOf(money.index), qualified: parsed.qualified })\n push({ kind: 'currency', normalized: parsed.currency, source: 'negotiated', offset: offsetOf(money.index), qualified: false })\n }\n\n const lowered = body.toLowerCase()\n if (NO_PUBLISHED_PRICE.some((phrase) => lowered.includes(phrase))) {\n push({ kind: 'price', normalized: UNPRICED, source: 'negotiated', offset: 0, qualified: false })\n }\n for (const [phrase, token] of AVAILABILITY_PHRASES) {\n const at = lowered.indexOf(phrase)\n if (at === -1) continue\n push({ kind: 'availability', normalized: token, source: 'negotiated', offset: offsetOf(at), qualified: false })\n break\n }\n for (const [kind, markers] of TEXT_PRESENCE_MARKERS) {\n for (const phrase of markers) {\n const at = lowered.indexOf(phrase)\n if (at === -1) continue\n push({ kind, normalized: DECLARED, source: 'negotiated', offset: offsetOf(at), qualified: false })\n break\n }\n }\n if (hasOpeningHoursShape(body)) {\n push({ kind: 'hours', normalized: DECLARED, source: 'negotiated', offset: 0, qualified: false })\n }\n\n // Markdown links: the primary action, and the repeated-item block.\n const itemLinks = new Set<string>()\n let firstItemOffset = 0\n let match: RegExpExecArray | null\n MARKDOWN_LINK_RE.lastIndex = 0\n while ((match = MARKDOWN_LINK_RE.exec(body)) !== null) {\n const text = match[1] ?? ''\n const href = match[2] ?? ''\n const absolute = absoluteUrl(href, context.baseUrl)\n if (absolute === null) continue\n if (matchesLexicon(text, context.ruleset.actionLexicon)) {\n push({ kind: 'primary-action-url', normalized: absolute, source: 'negotiated', offset: offsetOf(match.index), qualified: false })\n }\n if (absolute.startsWith(context.origin) && !itemLinks.has(absolute)) {\n if (itemLinks.size === 0) firstItemOffset = offsetOf(match.index)\n itemLinks.add(absolute)\n }\n }\n if (itemLinks.size >= MIN_REPEATED_ITEMS) {\n push({ kind: 'item-count', normalized: String(itemLinks.size), source: 'negotiated', offset: firstItemOffset, qualified: false })\n push({ kind: 'item-link', normalized: DECLARED, source: 'negotiated', offset: firstItemOffset, qualified: false })\n }\n\n // A question/answer shape in markdown: a heading that ends in `?`.\n const question = /^#{1,6}[ \\t]+.*\\?[ \\t]*$/m.exec(body)\n if (question !== null) {\n push({ kind: 'question-answer', normalized: DECLARED, source: 'negotiated', offset: offsetOf(question.index), qualified: false })\n }\n}\n\n// ---------------------------------------------------------------------------\n// robots.txt\n// ---------------------------------------------------------------------------\n\nexport interface RobotsGroup {\n /** Lowercased user-agent tokens this group applies to. */\n readonly agents: readonly string[]\n readonly allow: readonly string[]\n readonly disallow: readonly string[]\n}\n\nexport interface RobotsFile {\n readonly groups: readonly RobotsGroup[]\n readonly sitemaps: readonly string[]\n /** Lines that are neither blank, a comment, nor a `field: value` pair. */\n readonly malformedLines: number\n /** Directives that appeared before any `User-agent:` line — the classic authoring bug. */\n readonly orphanRules: number\n}\n\n/**\n * RFC 9309 robots.txt, in the subset ARS reads. Deliberately small: we consume\n * `User-agent`, `Allow`, `Disallow` and `Sitemap`, count what we could not\n * parse, and ignore everything else. `Crawl-delay` is honoured by the PROBE, not\n * by the score — waiting longer is not worse markup.\n */\nexport function parseRobots(text: string): RobotsFile {\n /** Mutable while parsing; the exported shape is the readonly one. */\n interface MutableGroup {\n agents: string[]\n allow: string[]\n disallow: string[]\n }\n\n const groups: MutableGroup[] = []\n const sitemaps: string[] = []\n let malformedLines = 0\n let orphanRules = 0\n\n let current: MutableGroup | null = null\n /**\n * True while consecutive `User-agent:` lines are still accumulating into one\n * group. RFC 9309 §2.2.1: adjacent user-agent lines share the rules that\n * follow them; the first rule line closes the group to further agents.\n */\n let openingGroup = false\n\n for (const rawLine of text.split(/\\r?\\n/)) {\n const withoutComment = rawLine.split('#')[0] ?? ''\n const line = withoutComment.trim()\n if (line.length === 0) continue\n const colon = line.indexOf(':')\n if (colon <= 0) {\n malformedLines++\n continue\n }\n const field = line.slice(0, colon).trim().toLowerCase()\n const value = line.slice(colon + 1).trim()\n\n if (field === 'user-agent') {\n if (current === null || !openingGroup) {\n current = { agents: [], allow: [], disallow: [] }\n groups.push(current)\n openingGroup = true\n }\n current.agents.push(value.toLowerCase())\n continue\n }\n if (field === 'sitemap') {\n sitemaps.push(value)\n continue\n }\n if (field === 'allow' || field === 'disallow') {\n if (current === null) {\n orphanRules++\n continue\n }\n openingGroup = false\n if (field === 'allow') current.allow.push(value)\n else current.disallow.push(value)\n continue\n }\n if (field === 'crawl-delay' || field === 'host' || field === 'clean-param') continue\n malformedLines++\n }\n\n return { groups, sitemaps, malformedLines, orphanRules }\n}\n\n/**\n * RFC 9309 group selection: the most specific matching `User-agent` wins, `*` is\n * the fallback, and matching is case-insensitive. Returns the decision plus the\n * group and rule that produced it, because `ArsAudienceDecision` publishes both —\n * a merchant who disagrees with an `opt-out` verdict gets to see the line.\n */\nexport function decideRobots(\n robots: RobotsFile,\n tokens: readonly string[],\n path: string,\n): ArsAudienceDecision {\n let bestGroup: RobotsGroup | null = null\n let bestAgent: string | null = null\n let bestSpecificity = -1\n\n for (const group of robots.groups) {\n for (const agent of group.agents) {\n const specificity = agent === '*' ? 0 : matchesToken(agent, tokens) ? agent.length : -1\n if (specificity > bestSpecificity) {\n bestSpecificity = specificity\n bestGroup = group\n bestAgent = agent\n }\n }\n }\n\n if (bestGroup === null || bestAgent === null) {\n return { decision: 'unspecified', matchedGroup: null, matchedRule: null }\n }\n\n // Longest-match wins between Allow and Disallow; a tie goes to Allow (RFC 9309 §2.2.2).\n let bestRule: { field: 'allow' | 'disallow'; value: string } | null = null\n for (const value of bestGroup.allow) {\n if (!pathMatches(value, path)) continue\n if (bestRule === null || value.length > bestRule.value.length) {\n bestRule = { field: 'allow', value }\n }\n }\n for (const value of bestGroup.disallow) {\n if (!pathMatches(value, path)) continue\n if (bestRule === null || value.length > bestRule.value.length) {\n bestRule = { field: 'disallow', value }\n }\n }\n\n if (bestRule === null) {\n return { decision: 'allow', matchedGroup: bestAgent, matchedRule: null }\n }\n return {\n decision: bestRule.field === 'allow' ? 'allow' : 'disallow',\n matchedGroup: bestAgent,\n matchedRule: `${bestRule.field === 'allow' ? 'Allow' : 'Disallow'}: ${bestRule.value}`,\n }\n}\n\nfunction matchesToken(agent: string, tokens: readonly string[]): boolean {\n const lowered = agent.toLowerCase()\n return tokens.some((token) => token.toLowerCase() === lowered)\n}\n\n/**\n * Path matching with `*` and `$`, done as a bounded scan rather than a compiled\n * regex: a robots.txt is attacker-controlled input and\n * `new RegExp(pathFromTheInternet)` is a denial-of-service primitive.\n */\nexport function pathMatches(pattern: string, path: string): boolean {\n if (pattern === '') return false\n const anchored = pattern.endsWith('$')\n const body = anchored ? pattern.slice(0, -1) : pattern\n const segments = body.split('*')\n\n let cursor = 0\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i] ?? ''\n if (i === 0) {\n if (!path.startsWith(segment)) return false\n cursor = segment.length\n continue\n }\n if (segment === '') continue\n const at = path.indexOf(segment, cursor)\n if (at === -1) return false\n cursor = at + segment.length\n }\n if (anchored) {\n const last = segments[segments.length - 1] ?? ''\n return segments.length === 1 ? path === body : path.endsWith(last)\n }\n return true\n}\n\n/** Every audience decision plus the derived policy flags. Pure over a parsed robots file. */\nexport function buildPolicyReport(\n robots: RobotsFile | null,\n status: ArsPolicyReport['robotsTxtStatus'],\n ruleset: ArsRuleset,\n path: string,\n): ArsPolicyReport {\n const empty: ArsAudienceDecision = { decision: 'unspecified', matchedGroup: null, matchedRule: null }\n const audiences: Record<ArsAudience, ArsAudienceDecision> = {\n assistant: empty,\n training: empty,\n search: empty,\n }\n if (robots !== null) {\n for (const audience of ['assistant', 'training', 'search'] as const) {\n audiences[audience] = decideRobots(robots, ruleset.audienceTokens[audience], path)\n }\n }\n\n return {\n robotsTxtStatus: status,\n audiences,\n // A deliberate opt-out requires a group that NAMES an assistant token.\n // Consent has to be specific: a blanket `User-agent: *` disallow is the\n // accidental case (§3.7) and is scored, not excused.\n deliberateOptOut:\n robots !== null &&\n audiences.assistant.decision === 'disallow' &&\n audiences.assistant.matchedGroup !== '*' &&\n robots.malformedLines === 0 &&\n robots.orphanRules === 0,\n trainingOptOut: audiences.training.decision === 'disallow',\n sitemapDeclared: robots !== null && robots.sitemaps.length > 0,\n }\n}\n","/**\n * classify.ts — the two-pass page-kind classifier (design §3.5).\n *\n * THE CIRCULARITY THIS RESOLVES. Fact extraction needs a profile; the profile\n * comes from the page kind; the page kind looks like something you would infer\n * from the facts. Every source design had that loop and none of them cut it. The\n * decided answer is two passes with a hard wall between them:\n *\n * PASS 1 extracts a FIXED, KIND-INDEPENDENT probe set — JSON-LD `@type`,\n * microdata `itemtype`, RDFa `typeof`, `og:type`, URL path grammar,\n * currency-token presence, day-name/`HH:MM` adjacency, and `tel:` presence.\n * **Only pass-1 output may inform classification.** Nothing in this file reads\n * a profile, and `pass1Signals()` takes no page kind.\n *\n * PASS 2 (`./extract`) extracts against the resolved profile.\n *\n * Because pass 1 is fixed, two implementations classify the same bytes the same\n * way, and because it is small, a reader can check that it is fixed.\n *\n * PRECEDENCE, from §3.5: JSON-LD `@type` (through a pinned table) → microdata /\n * RDFa → `og:type` → URL path patterns → pass-1 structural signals. Ties are\n * broken by declared precedence, then lexicographically by `@type`.\n *\n * CONFIDENCE, AND WHY `unknown` IS NOT A PENALTY BOX. Below `medium` confidence\n * the kind is `unknown` — **we never guess into a vertical**, because guessing\n * `product` on an article scores that article against a fact set it has no\n * reason to carry, and the merchant cannot argue with a number. `unknown` is\n * also not an easy exit: it carries its own profile (title, description,\n * primary-action-url) and still scores D5.2 against \"any recognised schema.org\n * type present\", so hiding your page kind costs up to 7 points and gains nothing.\n *\n * THE TABLES BELOW ARE VERSIONED DATA. Adding a schema.org type or a URL pattern\n * changes the kind of some real page, which changes its profile, which changes\n * its score — so additions land as a MINOR, exactly like a ruleset edit. They\n * live here rather than in `DEFAULT_RULESET` because §3.9's `ArsRuleset` has no\n * field for them; that means they are NOT covered by `rulesetHash`, and the gap\n * is recorded in the package README as a known limitation of 0.1.\n */\n\nimport type { ArsRepresentation, JsonLdNode } from './extract'\nimport { absoluteUrl, findMoneyPhrases, hasOpeningHoursShape } from './extract'\nimport { attr } from './html'\nimport { parseMoneyText } from './parse-money'\nimport type { ArsPageKind } from './types'\n\n// ---------------------------------------------------------------------------\n// Pass 1 — the fixed, kind-independent probe set\n// ---------------------------------------------------------------------------\n\nexport interface ArsPass1Signals {\n /** `@type` values from every JSON-LD node, prefix-stripped, document order. */\n readonly jsonLdTypes: readonly string[]\n /** `itemtype` values, reduced to their final path segment. */\n readonly microdataTypes: readonly string[]\n /** RDFa `typeof` values, whitespace-split. */\n readonly rdfaTypes: readonly string[]\n /** `<meta property=\"og:type\">`, lowercased. */\n readonly ogType: string | null\n /** Lowercased, non-empty path segments of the target URL. */\n readonly pathSegments: readonly string[]\n /** At least one substring that `parseMoneyText` accepts. */\n readonly hasCurrencyToken: boolean\n /** A day name within 40 characters of a clock time. */\n readonly hasOpeningHours: boolean\n /** A `tel:` link, or a `telephone` property in structured data. */\n readonly hasTelephone: boolean\n}\n\n/**\n * Runs pass 1 over a representation. Takes the target URL rather than the\n * capture's final URL: the URL an operator typed is the one whose path grammar\n * describes their intent, and a redirect to a tracking URL should not reclassify\n * the page.\n */\nexport function pass1Signals(\n representation: ArsRepresentation,\n targetUrl: string,\n): ArsPass1Signals {\n const jsonLdTypes: string[] = []\n let hasTelephone = false\n for (const node of representation.jsonLd.nodes) {\n for (const type of node.types) jsonLdTypes.push(type)\n if (typeof node.value['telephone'] === 'string') hasTelephone = true\n }\n\n const microdataTypes: string[] = []\n const rdfaTypes: string[] = []\n if (representation.doc !== null) {\n for (const element of representation.doc.elements) {\n const itemtype = attr(element, 'itemtype')\n if (itemtype !== null) {\n for (const token of itemtype.split(/\\s+/)) {\n const segment = token.split('/').pop()\n if (segment !== undefined && segment.length > 0) microdataTypes.push(segment)\n }\n }\n const typeOf = attr(element, 'typeof')\n if (typeOf !== null) {\n for (const token of typeOf.split(/\\s+/)) {\n const segment = token.split(/[/:]/).pop()\n if (segment !== undefined && segment.length > 0) rdfaTypes.push(segment)\n }\n }\n if (element.tag === 'a') {\n const href = attr(element, 'href')\n if (href !== null && href.toLowerCase().startsWith('tel:')) hasTelephone = true\n }\n }\n }\n\n let ogType: string | null = null\n if (representation.doc !== null) {\n for (const meta of representation.doc.metas) {\n if (meta.property === 'og:type' && meta.content !== null) {\n ogType = meta.content.trim().toLowerCase()\n break\n }\n }\n }\n\n const text = representation.text\n let hasCurrencyToken = false\n for (const money of findMoneyPhrases(text)) {\n if (parseMoneyText(money.phrase) !== null) {\n hasCurrencyToken = true\n break\n }\n }\n if (!hasTelephone) hasTelephone = /\\btel:\\+?[0-9()\\-. ]{7,}/.test(text)\n\n return {\n jsonLdTypes,\n microdataTypes,\n rdfaTypes,\n ogType,\n pathSegments: pathSegmentsOf(targetUrl),\n hasCurrencyToken,\n hasOpeningHours: hasOpeningHoursShape(text),\n hasTelephone,\n }\n}\n\nfunction pathSegmentsOf(url: string): string[] {\n const absolute = absoluteUrl(url, 'https://invalid.example/')\n if (absolute === null) return []\n try {\n return new URL(absolute).pathname\n .toLowerCase()\n .split('/')\n .filter((segment) => segment.length > 0)\n } catch {\n return []\n }\n}\n\n// ---------------------------------------------------------------------------\n// The pinned type table\n// ---------------------------------------------------------------------------\n\n/**\n * schema.org type → ARS page kind. Sorted by kind for readability; lookup is\n * exact and case-sensitive, because schema.org type names are.\n *\n * A few placements are judgement calls and are stated rather than left implied:\n * - `Event` maps to `service`. A bookable event's core facts are title, price\n * and a primary action, which is the `service` profile exactly.\n * - `SoftwareApplication` maps to `product`: it carries `offers`, and an agent\n * asking about it wants a price and availability.\n * - `Organization` alone does NOT map to `place` — an org can be the publisher\n * of any page. Only `LocalBusiness` and its subtypes, which imply a physical\n * location with hours, do.\n */\nconst TYPE_TO_KIND: Readonly<Record<string, ArsPageKind>> = {\n // product\n Product: 'product',\n ProductGroup: 'product',\n ProductModel: 'product',\n IndividualProduct: 'product',\n SomeProducts: 'product',\n Vehicle: 'product',\n Car: 'product',\n Book: 'product',\n SoftwareApplication: 'product',\n MobileApplication: 'product',\n WebApplication: 'product',\n // collection\n CollectionPage: 'collection',\n ItemList: 'collection',\n OfferCatalog: 'collection',\n SearchResultsPage: 'collection',\n // article\n Article: 'article',\n NewsArticle: 'article',\n BlogPosting: 'article',\n TechArticle: 'article',\n ScholarlyArticle: 'article',\n ReportageNewsArticle: 'article',\n LiveBlogPosting: 'article',\n Blog: 'article',\n // place\n Place: 'place',\n LocalBusiness: 'place',\n Store: 'place',\n Restaurant: 'place',\n Hotel: 'place',\n LodgingBusiness: 'place',\n FoodEstablishment: 'place',\n CafeOrCoffeeShop: 'place',\n MedicalBusiness: 'place',\n MedicalClinic: 'place',\n Dentist: 'place',\n ProfessionalService: 'place',\n AutomotiveBusiness: 'place',\n HealthAndBeautyBusiness: 'place',\n HairSalon: 'place',\n SportsActivityLocation: 'place',\n ExerciseGym: 'place',\n // service\n Service: 'service',\n GovernmentService: 'service',\n FinancialProduct: 'service',\n LoanOrCredit: 'service',\n InsuranceAgency: 'service',\n Course: 'service',\n Event: 'service',\n BusinessEvent: 'service',\n EducationEvent: 'service',\n // faq\n FAQPage: 'faq',\n QAPage: 'faq',\n // document\n Dataset: 'document',\n DataCatalog: 'document',\n DigitalDocument: 'document',\n TextDigitalDocument: 'document',\n APIReference: 'document',\n WebAPI: 'document',\n Legislation: 'document',\n HowTo: 'document',\n Report: 'document',\n Manuscript: 'document',\n}\n\n/**\n * Types ARS recognises but which say nothing about the page kind. They matter\n * anyway: D5.2 scores `unknown` against *\"any recognised schema.org type\n * present\"*, so a page that declares `WebPage` has a recognised type and can\n * earn D5.2 while still classifying as `unknown`.\n */\nconst RECOGNISED_ONLY: ReadonlySet<string> = new Set([\n 'Thing',\n 'WebPage',\n 'WebSite',\n 'AboutPage',\n 'ContactPage',\n 'ProfilePage',\n 'ItemPage',\n 'Organization',\n 'Corporation',\n 'NGO',\n 'GovernmentOrganization',\n 'EducationalOrganization',\n 'Person',\n 'BreadcrumbList',\n 'Offer',\n 'AggregateOffer',\n 'PostalAddress',\n 'ImageObject',\n 'VideoObject',\n 'SiteNavigationElement',\n 'Brand',\n 'Review',\n 'AggregateRating',\n 'Question',\n 'Answer',\n 'MerchantReturnPolicy',\n 'OfferShippingDetails',\n 'SearchAction',\n 'ReadAction',\n 'OrderAction',\n])\n\n/** Is this a schema.org type ARS knows about at all? The D5.2 \"recognised\" test. */\nexport function isRecognisedType(type: string): boolean {\n return TYPE_TO_KIND[type] !== undefined || RECOGNISED_ONLY.has(type)\n}\n\n/** The kind a recognised type implies, or null when it implies none. */\nexport function kindForType(type: string): ArsPageKind | null {\n return TYPE_TO_KIND[type] ?? null\n}\n\n/**\n * The first node whose `@type` maps to `kind`. D5.2 scores required properties\n * against the node that decided the kind, not against whichever node came first —\n * a `BreadcrumbList` sitting above the `Product` must not be marked incomplete\n * for lacking `offers.price`.\n */\nexport function nodeForKind(\n nodes: readonly JsonLdNode[],\n kind: ArsPageKind,\n): JsonLdNode | null {\n for (const node of nodes) {\n for (const type of node.types) {\n if (kindForType(type) === kind) return node\n }\n }\n return null\n}\n\n// ---------------------------------------------------------------------------\n// og:type and URL grammar\n// ---------------------------------------------------------------------------\n\n/** Open Graph `og:type` → kind. The vocabulary is tiny and mostly commerce/article. */\nconst OG_TYPE_TO_KIND: Readonly<Record<string, ArsPageKind>> = {\n product: 'product',\n 'product.group': 'product',\n 'product.item': 'product',\n 'og:product': 'product',\n article: 'article',\n 'article:published_time': 'article',\n blog: 'article',\n book: 'product',\n place: 'place',\n business: 'place',\n 'business.business': 'place',\n restaurant: 'place',\n 'restaurant.restaurant': 'place',\n profile: 'unknown',\n website: 'unknown',\n}\n\n/**\n * URL path grammar, in precedence order. A pattern matches when any path segment\n * equals it, or when the first segment starts with it for the short forms.\n *\n * These are the conventional shapes of the platforms merchants actually run —\n * Shopify (`/products/`, `/collections/`), WordPress (`/blog/`, `/category/`),\n * documentation sites (`/docs/`, `/reference/`). A pattern earns `medium`\n * confidence and never `high`: a URL is a claim about a page, not the page.\n */\nconst PATH_PATTERNS: readonly (readonly [ArsPageKind, readonly string[]])[] = [\n ['product', ['products', 'product', 'p', 'item', 'items', 'dp', 'sku', 'buy']],\n ['collection', ['collections', 'collection', 'category', 'categories', 'catalog', 'c', 'shop']],\n ['article', ['blog', 'blogs', 'news', 'article', 'articles', 'post', 'posts', 'stories']],\n ['place', ['locations', 'location', 'stores', 'store-locator', 'branches', 'find-us', 'visit']],\n ['service', ['services', 'service', 'book', 'booking', 'appointments', 'pricing', 'plans']],\n ['faq', ['faq', 'faqs', 'questions', 'help']],\n ['document', ['docs', 'documentation', 'reference', 'guide', 'guides', 'manual', 'api', 'policies', 'legal', 'terms', 'privacy']],\n]\n\n// ---------------------------------------------------------------------------\n// The classifier\n// ---------------------------------------------------------------------------\n\nexport interface ArsClassification {\n readonly pageKind: ArsPageKind\n readonly confidence: 'high' | 'medium' | 'low'\n /** Which pass-1 signal decided it. Published as check evidence, not just logged. */\n readonly signal: string\n /** True when SOME recognised schema.org type was present, whatever the kind. */\n readonly hasRecognisedType: boolean\n}\n\n/**\n * Resolves the page kind from pass-1 signals and nothing else.\n *\n * The `low` → `unknown` collapse at the end is the \"never guess into a vertical\"\n * rule made mechanical: a lone currency token on a page with no type, no og:type\n * and no path grammar is not enough to call it a product, and a wrong vertical\n * is worse than no vertical because it scores the page against facts it was\n * never trying to state.\n */\nexport function classify(signals: ArsPass1Signals): ArsClassification {\n const hasRecognisedType =\n signals.jsonLdTypes.some(isRecognisedType) ||\n signals.microdataTypes.some(isRecognisedType) ||\n signals.rdfaTypes.some(isRecognisedType)\n\n // 1 — JSON-LD @type. Ties broken lexicographically by the type name (§3.5).\n const fromJsonLd = firstMappedType(signals.jsonLdTypes)\n if (fromJsonLd !== null) {\n return {\n pageKind: fromJsonLd.kind,\n confidence: 'high',\n signal: `json-ld @type ${fromJsonLd.type}`,\n hasRecognisedType,\n }\n }\n\n // 2 — microdata, then RDFa.\n const fromMicrodata = firstMappedType(signals.microdataTypes)\n if (fromMicrodata !== null) {\n return {\n pageKind: fromMicrodata.kind,\n confidence: 'high',\n signal: `microdata itemtype ${fromMicrodata.type}`,\n hasRecognisedType,\n }\n }\n const fromRdfa = firstMappedType(signals.rdfaTypes)\n if (fromRdfa !== null) {\n return {\n pageKind: fromRdfa.kind,\n confidence: 'high',\n signal: `rdfa typeof ${fromRdfa.type}`,\n hasRecognisedType,\n }\n }\n\n // 3 — og:type.\n if (signals.ogType !== null) {\n const kind = OG_TYPE_TO_KIND[signals.ogType]\n if (kind !== undefined && kind !== 'unknown') {\n return {\n pageKind: kind,\n confidence: 'medium',\n signal: `og:type ${signals.ogType}`,\n hasRecognisedType,\n }\n }\n }\n\n // 4 — URL path grammar.\n for (const [kind, patterns] of PATH_PATTERNS) {\n for (const segment of signals.pathSegments) {\n if (!patterns.includes(segment)) continue\n return {\n pageKind: kind,\n confidence: 'medium',\n signal: `url path segment /${segment}/`,\n hasRecognisedType,\n }\n }\n }\n\n // 5 — structural signals. Only ONE combination reaches `medium`: opening hours\n // AND a telephone number are two independent signals agreeing on `place`. A\n // lone currency token is `low`, which means `unknown`.\n if (signals.hasOpeningHours && signals.hasTelephone) {\n return {\n pageKind: 'place',\n confidence: 'medium',\n signal: 'opening-hours shape and telephone present',\n hasRecognisedType,\n }\n }\n\n return {\n pageKind: 'unknown',\n confidence: 'low',\n signal: signals.hasCurrencyToken\n ? 'currency token only — below medium confidence, not classified'\n : 'no classifying signal',\n hasRecognisedType,\n }\n}\n\n/**\n * First type that maps to a kind, preferring document order and breaking a\n * same-position tie lexicographically. Document order is the declared\n * precedence: a page that puts its `Product` node first has said which node is\n * the page.\n */\nfunction firstMappedType(\n types: readonly string[],\n): { type: string; kind: ArsPageKind } | null {\n const mapped: { type: string; kind: ArsPageKind }[] = []\n for (const type of types) {\n const kind = kindForType(type)\n if (kind !== null) mapped.push({ type, kind })\n }\n if (mapped.length === 0) return null\n\n const first = mapped[0]\n if (first === undefined) return null\n // Every type at the same document position (a node with `@type: [A, B]`) is\n // indistinguishable by order, so the lexicographically smaller name wins.\n let winner = first\n for (const candidate of mapped) {\n if (candidate.kind !== first.kind) break\n if (candidate.type < winner.type) winner = candidate\n }\n return winner\n}\n","/**\n * recommend.ts — what to fix, in what order, and what each fix is worth.\n *\n * WHY THIS FILE HAS A SPEC AT ALL. Recommendation arithmetic was undefined in\n * every source design, and it is the surface merchants actually act on: nobody\n * ships a change because a dimension moved, they ship it because a list said\n * \"this is worth 13 points\". A list that double-counts is a list that promises 30\n * points and delivers 16, and the second scan is where the product loses its\n * credibility. So §3.9's final paragraph pins the arithmetic and this file\n * implements exactly that:\n *\n * Recommendations are computed over a DEPENDENCY DAG. A recommendation's\n * `pointsAvailable` counts only the checks not already claimed by a\n * higher-ranked recommendation, plus the checks it uniquely UNLOCKS. Sums per\n * dimension are capped at the dimension weight. A property test asserts\n * `Σ pointsAvailable ≤ 100 − score`.\n *\n * WHAT \"UNLOCKS\" MEANS, PRECISELY. Two checks in ARS 0.1 are gated on D2.1: D2.3\n * (`Vary: Accept` is meaningless on a response that does not vary) and D2.4\n * (substance parity has nothing to compare against). While D2.1 is at zero,\n * their points are not reachable by any other action, so they belong to the\n * recommendation that closes D2.1 — and to no other, which is what stops\n * \"declare Vary: Accept\" from also claiming them. Once D2.1 is earned, the gate\n * is open and D2.3 stands on its own. `unlocks` is therefore CONDITIONAL, not a\n * fixed edge list, and each template says when its edge exists.\n *\n * ORDER IS THE RANKING. The output array is in priority order: biggest raw\n * recovery first, ties broken by effort (a config change before an engineering\n * project) and then by id, so two runs over the same result produce the same\n * list. The dedup walks that same order, which is what \"higher-ranked\" means.\n *\n * NO POINTS ARE INVENTED. Every number is the gap between a check's `earned` and\n * its `weight` in the result being explained. A recommendation whose checks are\n * all already full does not appear at all — an empty list is the correct output\n * for a page at 100, and a list of platitudes would be worse than nothing.\n */\n\nimport type { ArsCheck, ArsCheckId, ArsDimension, ArsRecommendation, ArsResult } from './types'\n\n/** What `recommend()` needs from a result. Callers holding an `ArsResult` can pass it directly. */\nexport type ArsRecommendationInput = Pick<ArsResult, 'dimensions' | 'score'>\n\ninterface Template {\n readonly id: string\n readonly title: string\n readonly effort: ArsRecommendation['effort']\n readonly detail: string\n readonly checks: readonly ArsCheckId[]\n /**\n * Checks this recommendation makes reachable that nothing else can, given the\n * current state. Returns the empty list when the gate is already open.\n */\n readonly unlocks: (state: CheckState) => readonly ArsCheckId[]\n}\n\n/** Earned/weight for every check in the result, by id. */\ntype CheckState = ReadonlyMap<ArsCheckId, ArsCheck>\n\nconst NO_UNLOCKS = (): readonly ArsCheckId[] => []\n\n/**\n * The catalogue. One entry per action a site owner can actually take; the\n * `detail` is the instruction, not a restatement of the check name.\n *\n * Declaration order is the tie-break of last resort, so it is written in the\n * order the spec presents the dimensions rather than in any order of preference.\n */\nconst TEMPLATES: readonly Template[] = [\n {\n id: 'fix-robots-policy',\n title: 'Let assistant crawlers fetch this page',\n effort: 'config',\n detail:\n \"robots.txt currently blocks or ambiguously blocks the crawlers that fetch pages on a user's behalf. Name them in their own group and allow them. Blocking model-training crawlers is a separate decision and costs nothing in ARS.\",\n checks: ['retrievability.robots-policy'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'render-without-javascript',\n title: 'Put the core facts in the HTML the server sends',\n effort: 'engineering',\n detail:\n 'The facts for this page kind were not all present in the served HTML. Agents do not execute JavaScript: server-render the core facts, or ship them in a <noscript> block or structured data.',\n checks: ['retrievability.render-independence'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'serve-machine-representation',\n title: 'Serve a machine representation on Accept negotiation',\n effort: 'config',\n detail:\n 'Return Markdown, plain text or JSON with a matching Content-Type when the request asks for one, and keep the same URL. This is the single largest recoverable block in ARS, and it is also what makes Vary: Accept and the substance-parity check scoreable at all.',\n checks: ['machine-representation.negotiated-response'],\n unlocks: (state) =>\n earnedOf(state, 'machine-representation.negotiated-response') === 0\n ? ['machine-representation.vary-accept', 'machine-representation.substance-parity']\n : [],\n },\n {\n id: 'declare-alternates',\n title: 'Declare the alternate representation',\n effort: 'config',\n detail:\n 'Add `Link: <…>; rel=\"alternate\"; type=\"text/markdown\"` or a typed `<link rel=\"alternate\">`. An endpoint an agent cannot find is an endpoint that does not exist.',\n checks: ['machine-representation.declared-alternates'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'declare-vary-accept',\n title: 'Send Vary: Accept',\n effort: 'config',\n detail:\n 'A URL that returns different representations by Accept must say so, or a shared cache will hand the Markdown to a browser and the HTML to an agent.',\n checks: ['machine-representation.vary-accept'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'resolve-substance-divergence',\n title: 'Make both representations state the same values',\n effort: 'engineering',\n detail:\n 'The two representations reported different values for a core fact. Render both from one source of truth. ARS reports what each one said and does not assert which is correct.',\n checks: ['machine-representation.substance-parity'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'add-core-facts',\n title: 'State the missing core facts for this page kind',\n effort: 'template',\n detail:\n 'Coverage is scored against the fact set this kind of page is expected to carry, and only against that set — adding facts outside it earns nothing. A fact stated in two places (structured data and visible text) counts double.',\n checks: ['fact-coverage.core-facts'],\n unlocks: (state) =>\n // Position can only be scored once something is there to position. While\n // no core fact exists, D4's points are reachable through this and nothing\n // else; once one exists, \"front-load the core facts\" owns them.\n earnedOf(state, 'fact-position.first-core-fact-offset') === 0 &&\n earnedOf(state, 'fact-position.front-window') === 0\n ? ['fact-position.first-core-fact-offset', 'fact-position.front-window']\n : [],\n },\n {\n id: 'reduce-page-weight',\n title: 'Cut the bytes an agent has to read',\n effort: 'engineering',\n detail:\n 'Context cost is scored against what a page of this kind reasonably costs, not an absolute budget. The cheapest fix is usually to serve a machine representation rather than to shrink the HTML.',\n checks: ['fact-coverage.context-cost'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'front-load-core-facts',\n title: 'Move the core facts to the front',\n effort: 'template',\n detail:\n 'A caller that reads the first few kilobytes should already have the facts. Everything after the front window costs a full read of the document.',\n checks: ['fact-position.first-core-fact-offset', 'fact-position.front-window'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'add-structured-data',\n title: 'Add JSON-LD for this page',\n effort: 'template',\n detail:\n 'Declare a schema.org type in a JSON-LD block. Choosing no type does not avoid the check: an unrecognised page is still scored against \"any recognised type present\".',\n checks: ['structured-data.present'],\n unlocks: (state) =>\n earnedOf(state, 'structured-data.present') === 0\n ? ['structured-data.required-properties', 'structured-data.text-agreement']\n : [],\n },\n {\n id: 'complete-required-properties',\n title: 'Complete the required properties for this page kind',\n effort: 'template',\n detail:\n 'The required-property table is published per page kind in the spec. It is not \"schema.org validity\" — schema.org defines no required properties — and it does not change without an ARS release.',\n checks: ['structured-data.required-properties'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'align-structured-data-with-text',\n title: 'Make the structured data agree with the page',\n effort: 'template',\n detail:\n 'The JSON-LD and the visible page reported different values for a core fact. Generate both from the same source so they cannot drift.',\n checks: ['structured-data.text-agreement'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'declare-canonical',\n title: 'Declare one canonical URL, in both representations',\n effort: 'config',\n detail:\n 'Add an absolute `<link rel=\"canonical\">` to the HTML and a `Link: <…>; rel=\"canonical\"` header to the machine representation, pointing at the same URL. A representation with no canonical cannot be attributed to a page.',\n checks: ['contract-discovery.canonical'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'add-cache-validators',\n title: 'Add cache headers an agent can act on',\n effort: 'config',\n detail:\n 'Send a Cache-Control a cache can use plus an ETag or Last-Modified. Repeat fetches are most of agent traffic, and a response with no validator has to be re-read in full every time.',\n checks: ['contract-discovery.cache-validators'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'publish-llms-txt',\n title: 'Publish /llms.txt',\n effort: 'config',\n detail:\n 'An H1 title, a short summary, and links to the pages that matter. It is worth 2 points of 100, deliberately: content negotiation is the mechanism that measurably improves retrieval, and we have observed no citation lift from llms.txt alone.',\n checks: ['contract-discovery.llms-txt'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'declare-sitemap',\n title: 'Declare a sitemap in robots.txt',\n effort: 'config',\n detail:\n 'Add a `Sitemap:` line. It is the one place an agent looks to find the rest of the site.',\n checks: ['contract-discovery.sitemap'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'declare-machine-endpoint',\n title: 'Declare a machine endpoint',\n effort: 'engineering',\n detail:\n 'A feed, an OpenAPI document, /.well-known/ucp — anything an agent can call — declared with a `Link` header or a `<link>`. ARS probes /robots.txt, /llms.txt and /.well-known/ucp and guesses at no other path.',\n checks: ['contract-discovery.machine-endpoint'],\n unlocks: NO_UNLOCKS,\n },\n]\n\n/** Effort order for the tie-break: the cheapest fix first. */\nconst EFFORT_ORDER: readonly ArsRecommendation['effort'][] = ['config', 'template', 'engineering']\n\nfunction earnedOf(state: CheckState, id: ArsCheckId): number {\n return state.get(id)?.earned ?? 0\n}\n\nfunction gapOf(state: CheckState, id: ArsCheckId): number {\n const check = state.get(id)\n return check === undefined ? 0 : Math.max(0, check.weight - check.earned)\n}\n\n/**\n * Ranked, deduplicated remedies for a scored result.\n *\n * Returns an empty array for a non-grade (`score: null`): an unscored or\n * opted-out target has no sub-scores, so there is nothing to recover and no\n * honest number to attach to advice.\n */\nexport function recommend(input: ArsRecommendationInput): ArsRecommendation[] {\n if (input.score === null) return []\n\n const state = new Map<ArsCheckId, ArsCheck>()\n const dimensionOf = new Map<ArsCheckId, ArsDimension>()\n for (const dimension of input.dimensions) {\n for (const check of dimension.checks) {\n state.set(check.id, check)\n dimensionOf.set(check.id, dimension)\n }\n }\n\n // Rank by RAW recovery — what the recommendation would be worth if it were the\n // only one — because the deduped value cannot be known until the order is\n // fixed. Ties: cheaper effort first, then declaration order for stability.\n //\n // A recommendation may only claim the checks it UNLOCKS if it also closes\n // something itself. Without that rule, a template whose own check is already\n // full could still claim a gated check's points and print advice that has\n // nothing to do with the gap it is being credited for.\n const ranked = TEMPLATES.map((template, index) => {\n const own = template.checks.reduce((sum, id) => sum + gapOf(state, id), 0)\n const unlocked = own > 0 ? template.unlocks(state) : []\n const ids = [...template.checks, ...unlocked]\n const raw = own + unlocked.reduce((sum, id) => sum + gapOf(state, id), 0)\n return { template, ids, raw, index }\n })\n .filter((entry) => entry.raw > 0)\n .sort((a, b) => {\n if (a.raw !== b.raw) return b.raw - a.raw\n const effort =\n EFFORT_ORDER.indexOf(a.template.effort) - EFFORT_ORDER.indexOf(b.template.effort)\n return effort !== 0 ? effort : a.index - b.index\n })\n\n const claimed = new Set<ArsCheckId>()\n /** Points already promised per dimension, so the total can never exceed its weight. */\n const spent = new Map<string, number>()\n const out: ArsRecommendation[] = []\n\n for (const entry of ranked) {\n let points = 0\n const closes: ArsCheckId[] = []\n const opens: ArsCheckId[] = []\n\n for (const id of entry.ids) {\n if (claimed.has(id)) continue\n const dimension = dimensionOf.get(id)\n if (dimension === undefined) continue\n const remaining = Math.max(\n 0,\n dimension.weight - dimension.earned - (spent.get(dimension.id) ?? 0),\n )\n const value = Math.min(gapOf(state, id), remaining)\n if (value <= 0) continue\n points += value\n spent.set(dimension.id, (spent.get(dimension.id) ?? 0) + value)\n claimed.add(id)\n if (entry.template.checks.includes(id)) closes.push(id)\n else opens.push(id)\n }\n\n if (points <= 0) continue\n out.push({\n id: entry.template.id,\n title: entry.template.title,\n pointsAvailable: points,\n effort: entry.template.effort,\n detail: entry.template.detail,\n checks: closes,\n unlocks: opens,\n })\n }\n\n return out\n}\n","/**\n * score.ts — the ARS 0.1 scoring engine. The whole pure half comes together here.\n *\n * THE CONTRACT. `score(evidence, ruleset)` is a pure function: same evidence,\n * same ruleset, same `ArsResult`, byte for byte, in any conformant\n * implementation in any language. No network, no clock, no randomness, no LLM.\n * The ESLint rule in `eslint.config.mjs` enforces the first three at build time;\n * the fourth has nowhere to hide, because there is no model call anywhere in this\n * package.\n *\n * INTEGER ARITHMETIC ONLY (§3.6). Every number below is produced by `idiv` /\n * `divRoundHalfUp`, never by `/` on values that do not divide, and never by\n * `Math.round`. Cross-language conformance is impossible with float rounding\n * drift, and publishing a standard whose scores differ in the third\n * implementation would be worse than publishing nothing. All inputs are\n * non-negative, so rounding is unambiguous half-up via\n * `(numerator + denominator / 2) / denominator`.\n *\n * FIXED WEIGHTS. 100 points for every page, whatever its kind. What varies by\n * page kind is the fact set and the byte reference (`./profiles`) — never a\n * weight. Redistribution would be a gaming vector: make the dimension you are bad\n * at inapplicable and everything else inflates.\n *\n * TWO GATES EXIST, AND THEY POINT THE SAFE WAY. D2.3 (`Vary: Accept`) and D2.4\n * (substance parity) are gated on D2.1 (a machine representation was served),\n * which is a MEASURED check gating others. That direction is fine and is what\n * makes the published ceiling provable: no content negotiation loses D2.1 (10) +\n * D2.3 (3) + D2.4 (3) → max 84 → capped at B. The forbidden direction — a\n * heuristic that can zero measured points — appears nowhere. In particular D2.4\n * and D5.3 are SCORED CHECKS, NOT GATES: a parity failure loses its own 3 points\n * and raises a `warn`, and leaves D2's other 17 measured points alone. That is\n * the whole reason \"measured 64 / heuristic 36\" is an honest split rather than a\n * presentational one.\n *\n * WHICH REPRESENTATION SCORES WHAT (the decision `./extract` states in its own\n * header, repeated here because it is the reason the golden pair means anything):\n * D3 (coverage) and D4 (position) score the AGENT representation, because ARS\n * measures what a caller actually receives. D1.3 (render independence) and D5\n * (structured data) score the representation that carries a document, because\n * those checks are about the HTML a caller that only reads HTML gets.\n *\n * MEASURED CHECKS NEVER AWARD POINTS FOR AN OBSERVATION WE DID NOT MAKE. When\n * the browser probe is missing, the sub-conditions that compare the two probes\n * (D1.1's \"no Accept-conditional redirect\", D6.1's \"self-consistent\") score 0 and\n * say so in their evidence. Awarding them by default would make a measured check\n * heuristic; deducting them silently would be unexplained. The evidence line is\n * the difference.\n *\n * WHAT LIVES IN THE RULESET AND WHAT LIVES HERE. `DEFAULT_RULESET.thresholds`\n * holds exactly the §3.6 numeric tables (density, context cost, offsets, front\n * window). The remaining checks are conjunctions of named conditions rather than\n * bands, and their point splits are `SUBPOINTS` below: published, frozen, and —\n * like the classification tables in `./classify` — NOT covered by `rulesetHash`,\n * because §3.9's `ArsRuleset` has no field for them. That gap is recorded in the\n * package README as a known limitation of 0.1 rather than papered over.\n */\n\nimport { classify, isRecognisedType, nodeForKind, pass1Signals } from './classify'\nimport type { ArsClassification } from './classify'\nimport {\n buildPolicyReport,\n buildRepresentation,\n extractFacts,\n hasPath,\n header,\n headerAll,\n mergeFacts,\n parseRobots,\n pathMatches,\n readPath,\n} from './extract'\nimport type {\n ArsRepresentation,\n ExtractedFact,\n JsonLdNode,\n MergedFact,\n RobotsFile,\n} from './extract'\nimport { attr, elementText } from './html'\nimport { profileFor } from './profiles'\nimport { recommend } from './recommend'\nimport { CHECK_META, DEFAULT_RULESET, DIMENSION_META } from './ruleset'\nimport type {\n ArsAudience,\n ArsBand,\n ArsBasis,\n ArsCheck,\n ArsCheckEvidence,\n ArsCheckId,\n ArsCostReport,\n ArsDimension,\n ArsDimensionId,\n ArsEvidence,\n ArsFactKind,\n ArsFactObservation,\n ArsFactProfile,\n ArsFlag,\n ArsFlagId,\n ArsGrade,\n ArsHttpCapture,\n ArsOutcome,\n ArsPolicyReport,\n ArsProbeRecord,\n ArsResult,\n ArsRuleset,\n ArsUnscoredReason,\n} from './types'\nimport { ARS_SPEC_VERSION } from './types'\n\n// ---------------------------------------------------------------------------\n// Integer arithmetic (§3.6)\n// ---------------------------------------------------------------------------\n\n/**\n * Exact integer division for non-negative safe integers. `%` is exact, the\n * subtraction is exact, and dividing by an exact multiple is exact, so this\n * never rounds — unlike `Math.floor(a / b)`, whose intermediate quotient is an\n * IEEE-754 double that can land on the wrong side of an integer boundary. A\n * scoring path that is \"almost always\" the same in two languages is not a\n * standard.\n */\nfunction idiv(numerator: number, denominator: number): number {\n if (denominator === 0) return 0\n return (numerator - (numerator % denominator)) / denominator\n}\n\n/** §3.6's half-up rounding, `(numerator + denominator / 2) / denominator`, in integers. */\nfunction divRoundHalfUp(numerator: number, denominator: number): number {\n if (denominator === 0) return 0\n return idiv(numerator + idiv(denominator, 2), denominator)\n}\n\n/**\n * AT-LEAST table lookup: flat `[threshold, value]` pairs in DESCENDING threshold\n * order; the first pair whose `threshold <= input` wins. No match scores 0, which\n * can only happen if a ruleset omits the table — a malformed ruleset must not\n * silently invent points.\n */\nfunction atLeast(pairs: readonly number[] | undefined, input: number): number {\n if (pairs === undefined) return 0\n for (let i = 0; i + 1 < pairs.length; i += 2) {\n const threshold = pairs[i]\n const value = pairs[i + 1]\n if (threshold === undefined || value === undefined) return 0\n if (input >= threshold) return value\n }\n return 0\n}\n\n/**\n * AT-MOST table lookup: flat `[threshold, value]` pairs in ASCENDING threshold\n * order; the first pair whose `input <= threshold` wins; no match scores 0.\n */\nfunction atMost(pairs: readonly number[] | undefined, input: number): number {\n if (pairs === undefined) return 0\n for (let i = 0; i + 1 < pairs.length; i += 2) {\n const threshold = pairs[i]\n const value = pairs[i + 1]\n if (threshold === undefined || value === undefined) return 0\n if (input <= threshold) return value\n }\n return 0\n}\n\n/** Recursively freezes a plain data structure. Used on `SUBPOINTS`. */\nfunction deepFreeze<T>(value: T): T {\n if (typeof value !== 'object' || value === null) return value\n for (const child of Object.values(value as Record<string, unknown>)) deepFreeze(child)\n return Object.freeze(value)\n}\n\n// ---------------------------------------------------------------------------\n// Sub-point splits\n// ---------------------------------------------------------------------------\n\n/**\n * The point split inside each check that scores a CONJUNCTION of named\n * conditions rather than a numeric band. §3.4 states the conditions (\"D1.1 2xx on\n * the agent path, ≤3 hops, no Accept-conditional redirect\"); this is how the\n * check's points are divided between them, and every split sums to the check's\n * weight in `DEFAULT_RULESET.weights`.\n *\n * Published here rather than in `DEFAULT_RULESET` because §3.9's `ArsRuleset` has\n * no field for them. The consequence is stated rather than hidden: these numbers\n * are NOT covered by `rulesetHash`, exactly like the classification tables in\n * `./classify`. Editing one moves conformance `expected.json` files and is\n * therefore a MINOR, and the corpus is what actually pins them.\n */\nexport const SUBPOINTS = deepFreeze({\n /** D1.1, 8 = 4 + 2 + 2. */\n reachable: { status2xx: 4, withinRedirectLimit: 2, noAcceptConditionalRedirect: 2 },\n /** D1.2, 6 = 3 + 1 + 1 + 1. A disallowed assistant audience scores 0 for all four (§3.7). */\n robotsPolicy: { assistantAllowed: 3, parsesClean: 1, noOrphanRules: 1, sitemapDeclared: 1 },\n /**\n * D1.3, 6. AT-LEAST band over `100 × coreFactsInHtml / coreProfileSize`, plus\n * the `<noscript>` floor: a page whose facts are all client-rendered but which\n * ships a non-empty `<noscript>` has told a JS-less caller something, and §3.8\n * says that earns partial credit.\n */\n renderIndependence: {\n band: [100, 6, 75, 5, 50, 3, 25, 1] as readonly number[],\n noscriptFloor: 1,\n },\n /** D2.1, 10. All-or-nothing: a machine media type AND a body that is not HTML. */\n negotiatedResponse: { full: 10 },\n /** D2.2, 4. All-or-nothing. */\n declaredAlternates: { full: 4 },\n /** D2.3, 3. All-or-nothing, and 0 unless D2.1 > 0. */\n varyAccept: { full: 3 },\n /** D2.4, 3. All-or-nothing, and 0 unless D2.1 > 0 and a browser capture exists. */\n substanceParity: { full: 3 },\n /** D5.1, 5. Structured data present AND parsing; a partly-broken graph scores 3. */\n structuredDataPresent: { clean: 5, partial: 3 },\n /** D5.2, 7 = 2 (a recognised type) + 5 (required-property completeness, scaled). */\n requiredProperties: { recognisedType: 2, completeness: 5 },\n /** D5.3, 3. All-or-nothing. */\n textAgreement: { full: 3 },\n /** D6.1, 4 = 2 + 1 + 1. */\n canonical: { present: 2, absolute: 1, consistentAcrossProbes: 1 },\n /** D6.2, 3 = 2 + 1. */\n cacheValidators: { saneCacheControl: 2, validator: 1 },\n /** D6.3, 2. `present` alone for a file that exists; `specShaped` for one that parses as llms.txt. */\n llmsTxt: { present: 1, specShaped: 2 },\n /** D6.4, 2. All-or-nothing. */\n sitemap: { full: 2 },\n /** D6.5, 4. All-or-nothing over any ONE declared machine endpoint. */\n machineEndpoint: { full: 4 },\n})\n\n// ---------------------------------------------------------------------------\n// SHA-256 and RFC 8785 canonical JSON\n// ---------------------------------------------------------------------------\n\n/**\n * WHY A HAND-ROLLED SHA-256 LIVES IN THE PURE HALF. `ArsResult` carries three\n * hashes and the determinism guarantee is stated in terms of them, so `score()`\n * has to compute two of them. `node:crypto` would make this package Node-only,\n * and `apps/rebilder-web` imports the root entry point; `crypto.subtle` is async\n * and `score()` is not. A dependency is out — the package's contract is zero\n * runtime dependencies, and a third-party hash version would be an unversioned\n * input to a hashed artifact, which is the same argument that made the tokenizer\n * hand-rolled. So: ~80 lines of FIPS 180-4, checked against the published test\n * vectors in `tests/score.test.ts`.\n */\nconst SHA256_K: readonly number[] = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]\n\nfunction rotr(value: number, bits: number): number {\n return ((value >>> bits) | (value << (32 - bits))) >>> 0\n}\n\n/** SHA-256 of a UTF-8 string, lowercase hex. FIPS 180-4. */\nexport function sha256Hex(message: string): string {\n const bytes = new TextEncoder().encode(message)\n const bitLength = bytes.length * 8\n // Padded length: message + 0x80 + zeros + 8 length bytes, to a 64-byte multiple.\n const padded = new Uint8Array((idiv(bytes.length + 9 + 63, 64) || 1) * 64)\n padded.set(bytes)\n padded[bytes.length] = 0x80\n // Length as a 64-bit big-endian bit count. Bodies are capped at 2 MiB, so the\n // high word is always zero; it is written anyway so the routine is correct for\n // any input a caller hands it.\n const view = new DataView(padded.buffer)\n view.setUint32(padded.length - 8, idiv(bitLength, 0x100000000), false)\n view.setUint32(padded.length - 4, bitLength >>> 0, false)\n\n const h = [\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n ]\n const w = new Uint32Array(64)\n\n for (let offset = 0; offset < padded.length; offset += 64) {\n for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4, false)\n for (let i = 16; i < 64; i++) {\n const a = w[i - 15] ?? 0\n const b = w[i - 2] ?? 0\n const s0 = (rotr(a, 7) ^ rotr(a, 18) ^ (a >>> 3)) >>> 0\n const s1 = (rotr(b, 17) ^ rotr(b, 19) ^ (b >>> 10)) >>> 0\n w[i] = ((w[i - 16] ?? 0) + s0 + (w[i - 7] ?? 0) + s1) >>> 0\n }\n\n let [a, b, c, d, e, f, g, hh] = h as [\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n ]\n for (let i = 0; i < 64; i++) {\n const s1 = (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) >>> 0\n const ch = ((e & f) ^ (~e & g)) >>> 0\n const temp1 = (hh + s1 + ch + (SHA256_K[i] ?? 0) + (w[i] ?? 0)) >>> 0\n const s0 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) >>> 0\n const maj = ((a & b) ^ (a & c) ^ (b & c)) >>> 0\n const temp2 = (s0 + maj) >>> 0\n hh = g\n g = f\n f = e\n e = (d + temp1) >>> 0\n d = c\n c = b\n b = a\n a = (temp1 + temp2) >>> 0\n }\n const next = [a, b, c, d, e, f, g, hh]\n for (let i = 0; i < 8; i++) h[i] = ((h[i] ?? 0) + (next[i] ?? 0)) >>> 0\n }\n\n let hex = ''\n for (const word of h) hex += word.toString(16).padStart(8, '0')\n return hex\n}\n\n/**\n * RFC 8785 (JCS) canonical JSON, over the value shapes ARS actually hashes:\n * objects, arrays, strings, booleans, null and JSON numbers.\n *\n * Two details make this RFC-conformant rather than merely deterministic:\n * object keys are sorted by UTF-16 code unit (JCS §3.2.3, which is what\n * JavaScript's default string comparison already does), and numbers are\n * serialised with `JSON.stringify`, whose output is the ECMAScript\n * `Number::toString` shortest round-trip form that JCS §3.2.2.3 mandates.\n * `undefined` and functions cannot appear in the data we hash and are dropped.\n */\nexport function canonicalJson(value: unknown): string {\n if (value === null) return 'null'\n if (typeof value === 'boolean') return value ? 'true' : 'false'\n if (typeof value === 'number') return Number.isFinite(value) ? JSON.stringify(value) : 'null'\n if (typeof value === 'string') return JSON.stringify(value)\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`\n if (typeof value === 'object') {\n const record = value as Record<string, unknown>\n const keys = Object.keys(record).filter((key) => record[key] !== undefined)\n keys.sort()\n return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(',')}}`\n }\n return 'null'\n}\n\n/** SHA-256 of the RFC 8785 canonical JSON of the frozen ruleset (§3.1). */\nexport function rulesetHash(ruleset: ArsRuleset): string {\n return sha256Hex(canonicalJson(ruleset))\n}\n\n/**\n * Headers excluded from `evidenceHash` (§3.3). Without this exclusion the hash\n * changes on every scan of every real site — `date` alone guarantees it — and the\n * replay story, which is the only reason the hash is published, dies.\n */\nconst VOLATILE_HEADERS: ReadonlySet<string> = new Set([\n 'date',\n 'age',\n 'set-cookie',\n 'x-request-id',\n 'cf-ray',\n 'report-to',\n])\n\nfunction stableHeaders(\n headers: Readonly<Record<string, readonly string[]>>,\n): Record<string, readonly string[]> {\n const out: Record<string, readonly string[]> = {}\n for (const [name, values] of Object.entries(headers)) {\n if (VOLATILE_HEADERS.has(name.toLowerCase())) continue\n out[name.toLowerCase()] = values\n }\n return out\n}\n\n/**\n * SHA-256 over the evidence bundle with the volatile fields removed: the header\n * denylist above, and `capturedAt`, which is wall-clock time and is never an\n * input to scoring. Bodies ARE hashed — `bodySha256` is already in the capture,\n * but hashing the body itself means a bundle whose body was edited without\n * updating its digest does not silently keep its identity.\n */\nexport function evidenceHash(evidence: ArsEvidence): string {\n const redactProbe = (probe: ArsProbeRecord | null): unknown => {\n if (probe === null) return null\n if (!probe.result.ok) return { requestHeaders: probe.requestHeaders, result: probe.result }\n const capture = probe.result.capture\n return {\n requestHeaders: probe.requestHeaders,\n result: {\n ok: true,\n capture: { ...capture, headers: stableHeaders(capture.headers) },\n },\n }\n }\n return sha256Hex(\n canonicalJson({\n evidenceVersion: evidence.evidenceVersion,\n target: evidence.target,\n vantage: evidence.vantage,\n probes: {\n agent: redactProbe(evidence.probes.agent),\n browser: redactProbe(evidence.probes.browser),\n parityConfirm: redactProbe(evidence.probes.parityConfirm),\n robotsTxt: redactProbe(evidence.probes.robotsTxt),\n llmsTxt: redactProbe(evidence.probes.llmsTxt),\n wellKnownUcp: redactProbe(evidence.probes.wellKnownUcp),\n },\n }),\n )\n}\n\n/**\n * `corpusHash` — SHA-256 over the FROZEN conformance corpus (§3.1). Computing it\n * requires reading the corpus directory, which the pure half cannot do, so it is\n * a constant regenerated at corpus freeze.\n *\n * ARS 0.1 ships as a DRAFT (§3.10, \"Calibration\") and its corpus is still open:\n * fixtures are landing. So the value below is deliberately NOT a corpus digest —\n * it is the SHA-256 of the ASCII string `ars-0.1-corpus-unfrozen`. Anyone who\n * recomputes the digest of the shipped corpus will find it does not match, which\n * is the correct signal: a score carrying this constant is a draft score. It is\n * computed rather than pasted so that no reader has to trust a magic literal.\n */\nexport const ARS_CORPUS_HASH = sha256Hex('ars-0.1-corpus-unfrozen')\n\n// ---------------------------------------------------------------------------\n// Header helpers\n// ---------------------------------------------------------------------------\n\n/** One entry of a `Link` header: the target IRI plus the parameters ARS reads. */\ninterface ParsedLink {\n readonly url: string\n readonly rel: readonly string[]\n readonly type: string | null\n}\n\n/**\n * Parses `Link` header values (RFC 8288) in the subset ARS scores: the target\n * IRI, `rel` as a token list, and `type`.\n *\n * Written as a scanner because the separator is a comma and target IRIs contain\n * commas — `<https://x/a,b>; rel=\"alternate\"` is one link, not two. Splitting on\n * `,` would silently drop half of the alternates a merchant declared and cost\n * them 4 points on D2.2.\n */\nexport function parseLinkHeaders(values: readonly string[]): ParsedLink[] {\n const out: ParsedLink[] = []\n for (const value of values) {\n for (const entry of splitLinkEntries(value)) {\n const open = entry.indexOf('<')\n const close = entry.indexOf('>', open + 1)\n if (open === -1 || close === -1) continue\n const url = entry.slice(open + 1, close).trim()\n if (url.length === 0) continue\n let rel: string[] = []\n let type: string | null = null\n for (const param of entry.slice(close + 1).split(';')) {\n const equals = param.indexOf('=')\n if (equals === -1) continue\n const name = param.slice(0, equals).trim().toLowerCase()\n const raw = param.slice(equals + 1).trim()\n const unquoted = raw.startsWith('\"') && raw.endsWith('\"') ? raw.slice(1, -1) : raw\n if (name === 'rel')\n rel = unquoted\n .toLowerCase()\n .split(/\\s+/)\n .filter((t) => t.length > 0)\n else if (name === 'type') type = unquoted.trim().toLowerCase()\n }\n out.push({ url, rel, type })\n }\n }\n return out\n}\n\n/** Splits on commas that are outside `<…>` and outside a quoted string. */\nfunction splitLinkEntries(value: string): string[] {\n const entries: string[] = []\n let depth = 0\n let quoted = false\n let start = 0\n for (let i = 0; i < value.length; i++) {\n const char = value.charAt(i)\n if (quoted) {\n if (char === '\"') quoted = false\n continue\n }\n if (char === '\"') quoted = true\n else if (char === '<') depth++\n else if (char === '>') depth = depth > 0 ? depth - 1 : 0\n else if (char === ',' && depth === 0) {\n entries.push(value.slice(start, i))\n start = i + 1\n }\n }\n entries.push(value.slice(start))\n return entries.map((entry) => entry.trim()).filter((entry) => entry.length > 0)\n}\n\n/** Comma/space-separated header token list, lowercased. */\nfunction headerTokens(value: string | null): string[] {\n if (value === null) return []\n return value\n .toLowerCase()\n .split(/[,\\s]+/)\n .map((token) => token.trim())\n .filter((token) => token.length > 0)\n}\n\n// ---------------------------------------------------------------------------\n// Scoring context\n// ---------------------------------------------------------------------------\n\n/** Everything the 19 checks read, computed exactly once. */\ninterface ScoreContext {\n readonly evidence: ArsEvidence\n readonly ruleset: ArsRuleset\n readonly agentCapture: ArsHttpCapture\n readonly browserCapture: ArsHttpCapture | null\n readonly agent: ArsRepresentation\n readonly browser: ArsRepresentation | null\n /** The representation that carries a tokenized document, if either does. */\n readonly structural: ArsRepresentation | null\n readonly classification: ArsClassification\n readonly profile: ArsFactProfile\n readonly facts: readonly MergedFact[]\n readonly agentFacts: readonly ExtractedFact[]\n readonly browserFacts: readonly ExtractedFact[]\n readonly structuralFacts: readonly ExtractedFact[]\n readonly policy: ArsPolicyReport\n readonly robots: RobotsFile | null\n readonly flags: ArsFlag[]\n}\n\ninterface CheckOutcome {\n readonly earned: number\n readonly evidence: ArsCheckEvidence[]\n readonly remedy?: string\n}\n\nconst YES = 'yes'\nconst NO = 'no'\nconst yesNo = (value: boolean): string => (value ? YES : NO)\n\nfunction measured(label: string, value: string): ArsCheckEvidence {\n return { label, value, basis: 'measured' }\n}\n\nfunction heuristic(label: string, value: string): ArsCheckEvidence {\n return { label, value, basis: 'heuristic' }\n}\n\n// ---------------------------------------------------------------------------\n// D1 — Retrievability\n// ---------------------------------------------------------------------------\n\nfunction checkReachable(context: ScoreContext): CheckOutcome {\n const { agentCapture, browserCapture, ruleset } = context\n const split = SUBPOINTS.reachable\n const status2xx = agentCapture.status >= 200 && agentCapture.status < 300\n const hops = agentCapture.redirects.length\n const withinLimit = hops <= ruleset.maxRedirects\n const sameFinalUrl = browserCapture !== null && browserCapture.finalUrl === agentCapture.finalUrl\n\n const earned =\n (status2xx ? split.status2xx : 0) +\n (withinLimit ? split.withinRedirectLimit : 0) +\n (sameFinalUrl ? split.noAcceptConditionalRedirect : 0)\n\n const evidence = [\n measured('HTTP status on the agent path', String(agentCapture.status)),\n measured('Redirect hops', `${hops} (limit ${ruleset.maxRedirects})`),\n measured(\n 'Both probes resolved to the same URL',\n browserCapture === null\n ? 'not comparable — no browser-control capture in this bundle'\n : yesNo(sameFinalUrl),\n ),\n ]\n return sameFinalUrl\n ? { earned, evidence }\n : {\n earned,\n evidence,\n remedy:\n 'Serve the same URL to both Accept headers. An Accept-conditional redirect sends the agent somewhere the browser never goes, and caches key on the URL.',\n }\n}\n\nfunction checkRobotsPolicy(context: ScoreContext): CheckOutcome {\n const { policy, robots } = context\n const split = SUBPOINTS.robotsPolicy\n const decision = policy.audiences.assistant\n const parsesClean = robots === null || robots.malformedLines === 0\n const noOrphanRules = robots === null || robots.orphanRules === 0\n\n const evidence = [\n measured('robots.txt', policy.robotsTxtStatus),\n measured(\n 'Assistant audience',\n decision.matchedGroup === null\n ? `${decision.decision} (no matching group)`\n : `${decision.decision} via User-agent: ${decision.matchedGroup}${\n decision.matchedRule === null ? '' : ` / ${decision.matchedRule}`\n }`,\n ),\n measured('Malformed lines', robots === null ? 'n/a' : String(robots.malformedLines)),\n measured(\n 'Rules before any User-agent line',\n robots === null ? 'n/a' : String(robots.orphanRules),\n ),\n measured('Sitemap: declared', yesNo(policy.sitemapDeclared)),\n measured(\n 'Training-crawler policy (never scored)',\n policy.trainingOptOut ? 'blocked — neutral, no effect on this score' : 'allowed',\n ),\n ]\n\n // §3.7: an accidental or ambiguous assistant disallow — a blanket group, a\n // malformed file — is SCORED, with D1.2 at zero and a `robots-contradiction`\n // warning. It is not an opt-out, because consent has to be specific.\n if (decision.decision === 'disallow') {\n context.flags.push({\n id: 'robots-contradiction',\n severity: 'warn',\n basis: 'measured',\n message:\n 'robots.txt disallows assistant crawlers through a group that does not name one, so it reads as a blanket rule rather than a deliberate choice. Assistant traffic is blocked as a side effect.',\n evidence: [evidence[1] ?? measured('Assistant audience', decision.decision)],\n })\n return {\n earned: 0,\n evidence,\n remedy:\n 'Name the assistant crawlers you mean to allow or block in their own robots.txt group. A blanket disallow blocks assistant fetches that users triggered on purpose.',\n }\n }\n\n const earned =\n split.assistantAllowed +\n (parsesClean ? split.parsesClean : 0) +\n (noOrphanRules ? split.noOrphanRules : 0) +\n (policy.sitemapDeclared ? split.sitemapDeclared : 0)\n\n return {\n earned,\n evidence,\n remedy: policy.sitemapDeclared\n ? undefined\n : 'Add a `Sitemap:` line to robots.txt. It is the one place an agent looks to find the rest of the site.',\n }\n}\n\nfunction checkRenderIndependence(context: ScoreContext): CheckOutcome {\n const { structural, structuralFacts, profile } = context\n const split = SUBPOINTS.renderIndependence\n const coreSize = profile.core.length\n\n if (structural === null || structural.doc === null) {\n return {\n earned: 0,\n evidence: [heuristic('HTML representation', 'none in this bundle — not evaluated')],\n }\n }\n\n const found = new Set<ArsFactKind>()\n for (const fact of structuralFacts) if (profile.core.includes(fact.kind)) found.add(fact.kind)\n const ratio = coreSize === 0 ? 0 : idiv(100 * found.size, coreSize)\n\n let noscriptText = ''\n for (const element of structural.doc.elements) {\n if (element.tag !== 'noscript') continue\n noscriptText = elementText(structural.doc, element.index).trim()\n if (noscriptText.length > 0) break\n }\n const hasNoscript = noscriptText.length > 0\n\n const banded = atLeast(split.band, ratio)\n const earned = Math.max(banded, hasNoscript ? split.noscriptFloor : 0)\n const full = atLeast(split.band, 100)\n\n if (ratio < 50) {\n context.flags.push({\n id: 'render-dependent',\n severity: 'info',\n basis: 'heuristic',\n message: `${found.size} of ${coreSize} core facts for this page kind were present in the HTML without running JavaScript. A caller that does not execute scripts sees the rest as missing.`,\n evidence: [heuristic('Core facts in the served HTML', `${found.size}/${coreSize}`)],\n })\n }\n\n return {\n earned,\n evidence: [\n heuristic('Core facts present without JavaScript', `${found.size}/${coreSize}`),\n heuristic('<noscript> fallback with content', yesNo(hasNoscript)),\n heuristic(\n 'Basis',\n 'inferred — ARS never executes JavaScript, so this measures the served HTML, not what a browser would render',\n ),\n ],\n remedy:\n earned === full\n ? undefined\n : 'Render the core facts for this page kind into the HTML the server sends. Agents do not run your JavaScript.',\n }\n}\n\n// ---------------------------------------------------------------------------\n// D2 — Machine representation\n// ---------------------------------------------------------------------------\n\n/** Media types that count as a machine representation for D2.1 (§3.4). */\nconst MACHINE_KINDS: ReadonlySet<ArsRepresentation['kind']> = new Set(['markdown', 'text', 'json'])\n\nfunction checkNegotiatedResponse(context: ScoreContext): CheckOutcome {\n const { agent } = context\n const typeIsMachine = MACHINE_KINDS.has(agent.kind)\n const bodyIsHtml = agent.looksLikeHtml\n const earned = typeIsMachine && !bodyIsHtml ? SUBPOINTS.negotiatedResponse.full : 0\n\n return {\n earned,\n evidence: [\n measured('Content-Type on the agent probe', agent.contentType ?? 'absent'),\n measured('Body is HTML', yesNo(bodyIsHtml)),\n measured(\n 'Request Accept header',\n context.evidence.probes.agent.requestHeaders['accept'] ??\n context.evidence.probes.agent.requestHeaders['Accept'] ??\n 'not recorded',\n ),\n ],\n remedy:\n earned > 0\n ? undefined\n : typeIsMachine\n ? 'The response declared a machine media type but the body is HTML. Send the representation the Content-Type promises.'\n : 'Return a machine representation — Markdown, plain text or JSON — when the request Accept header asks for one, with a matching Content-Type.',\n }\n}\n\nfunction checkDeclaredAlternates(context: ScoreContext): CheckOutcome {\n const { agentCapture, browserCapture, structural } = context\n const links = parseLinkHeaders([\n ...headerAll(agentCapture.headers, 'link'),\n ...(browserCapture === null ? [] : headerAll(browserCapture.headers, 'link')),\n ])\n // An alternate with no `type` is a language variant (`hreflang`), not a second\n // representation. Every international site declares those, and paying 4 points\n // for them would make the check meaningless.\n const headerAlternates = links.filter(\n (link) => link.rel.includes('alternate') && link.type !== null,\n )\n\n const documentAlternates: string[] = []\n if (structural !== null && structural.doc !== null) {\n for (const link of structural.doc.links) {\n if (!link.rel.includes('alternate')) continue\n if (link.type === null || link.href === null) continue\n documentAlternates.push(`${link.type} → ${link.href}`)\n }\n }\n\n const total = headerAlternates.length + documentAlternates.length\n return {\n earned: total > 0 ? SUBPOINTS.declaredAlternates.full : 0,\n evidence: [\n measured(\n 'Link: rel=\"alternate\" (typed)',\n headerAlternates.length === 0\n ? 'none'\n : headerAlternates.map((link) => `${link.type ?? '?'} → ${link.url}`).join(', '),\n ),\n measured(\n '<link rel=\"alternate\"> (typed)',\n documentAlternates.length === 0 ? 'none' : documentAlternates.join(', '),\n ),\n ],\n remedy:\n total > 0\n ? undefined\n : 'Declare the machine representation: `Link: <…>; rel=\"alternate\"; type=\"text/markdown\"` or a `<link rel=\"alternate\">` in the HTML. An endpoint an agent cannot find is an endpoint that does not exist.',\n }\n}\n\nfunction checkVaryAccept(context: ScoreContext, negotiated: number): CheckOutcome {\n const { agentCapture, browserCapture } = context\n const agentVary = headerTokens(header(agentCapture.headers, 'vary'))\n const browserVary =\n browserCapture === null ? [] : headerTokens(header(browserCapture.headers, 'vary'))\n const declared = agentVary.includes('accept') || browserVary.includes('accept')\n\n const evidence = [\n measured('Vary on the agent response', header(agentCapture.headers, 'vary') ?? 'absent'),\n measured(\n 'Vary on the browser response',\n browserCapture === null\n ? 'no browser capture'\n : (header(browserCapture.headers, 'vary') ?? 'absent'),\n ),\n ]\n\n // Gated on D2.1: `Vary: Accept` on a response that does not vary by Accept is\n // a claim about caching that is not true. Fixture 035 pins it.\n if (negotiated === 0) {\n return {\n earned: 0,\n evidence: [\n ...evidence,\n measured(\n 'Scored',\n 'no — this check is 0 unless a machine representation was served (D2.1)',\n ),\n ],\n }\n }\n\n if (!declared) {\n context.flags.push({\n id: 'vary-missing',\n severity: 'warn',\n basis: 'measured',\n message:\n 'The same URL returns different representations by Accept but does not send `Vary: Accept`. A shared cache can serve the Markdown to a browser, or the HTML to an agent.',\n evidence,\n })\n }\n\n return {\n earned: declared ? SUBPOINTS.varyAccept.full : 0,\n evidence,\n remedy: declared\n ? undefined\n : 'Send `Vary: Accept` on every response from a URL that negotiates on Accept.',\n }\n}\n\n/**\n * The kinds D2.4 compares. Explicitly four, and never description or free text\n * (§3.8): a prose difference between a Markdown summary and an HTML page is a\n * rendering difference, and calling it a substance divergence would be an\n * accusation we cannot support.\n */\nconst PARITY_KINDS: readonly ArsFactKind[] = ['price', 'currency', 'availability', 'title']\n\n/**\n * Two readings of one side's facts: the value it would PUBLISH for each kind\n * (the unqualified observation with the lowest byte offset, ties broken\n * lexicographically — the same choice `mergeFacts` makes for the published fact\n * set), and EVERY unqualified value it stated.\n *\n * Qualified values — ranges, \"from $9\" — never enter either map (§3.11).\n */\ninterface FactView {\n readonly representative: Map<ArsFactKind, string>\n readonly observed: Map<ArsFactKind, Set<string>>\n}\n\nfunction factView(facts: readonly ExtractedFact[]): FactView {\n const best = new Map<ArsFactKind, ExtractedFact>()\n const observed = new Map<ArsFactKind, Set<string>>()\n for (const fact of facts) {\n if (fact.qualified) continue\n const seen = observed.get(fact.kind)\n if (seen === undefined) observed.set(fact.kind, new Set([fact.normalized]))\n else seen.add(fact.normalized)\n\n const current = best.get(fact.kind)\n if (current === undefined) {\n best.set(fact.kind, fact)\n continue\n }\n if (fact.offset < current.offset) best.set(fact.kind, fact)\n else if (fact.offset === current.offset && fact.normalized < current.normalized)\n best.set(fact.kind, fact)\n }\n const representative = new Map<ArsFactKind, string>()\n for (const [kind, fact] of best) representative.set(kind, fact.normalized)\n return { representative, observed }\n}\n\n/**\n * The comparison rule for D2.4 and D5.3, and it is ASYMMETRIC on purpose:\n * **the value the left side would publish must appear somewhere among the values\n * the right side stated.**\n *\n * Both symmetric rules are wrong, and each is wrong in a way that matters:\n *\n * - Requiring the two REPRESENTATIVES to be equal produces false accusations on\n * ordinary pages. `tooling/fixtures/demo-pdp-before.html` names a backordered\n * variant above the line that says the product is in stock; its JSON-LD says\n * `InStock`, and both statements are true. Flagging that as a\n * structured-data divergence would be an accusation the evidence does not\n * support, and ARS reports observations rather than charges (§3.8).\n * - Accepting ANY shared value lets a real divergence hide behind an incidental\n * match: \"Free shipping over $50\" appears in both representations, so a page\n * whose headline price differs would still certify clean.\n *\n * The asymmetric rule catches the second and not the first, which is the\n * conservative direction: a missed divergence costs a merchant nothing, and a\n * false one is published on a scanner page next to their name.\n */\nfunction divergentKinds(\n left: FactView,\n right: FactView,\n kinds: readonly ArsFactKind[],\n): { compared: ArsFactKind[]; divergent: { kind: ArsFactKind; left: string; right: string }[] } {\n const compared: ArsFactKind[] = []\n const divergent: { kind: ArsFactKind; left: string; right: string }[] = []\n for (const kind of kinds) {\n const claim = left.representative.get(kind)\n const stated = right.observed.get(kind)\n if (claim === undefined || stated === undefined || stated.size === 0) continue\n compared.push(kind)\n if (!stated.has(claim)) {\n divergent.push({ kind, left: claim, right: [...stated].sort().join(' | ') })\n }\n }\n return { compared, divergent }\n}\n\nfunction checkSubstanceParity(context: ScoreContext, negotiated: number): CheckOutcome {\n const { agentFacts, browserFacts, browser, evidence: bundle } = context\n\n if (negotiated === 0 || browser === null) {\n return {\n earned: 0,\n evidence: [\n heuristic(\n 'Comparable',\n negotiated === 0\n ? 'no — there is one representation, so there is nothing to compare (this is the designed 84-point ceiling for a page with no content negotiation)'\n : 'no — no browser-control capture in this bundle',\n ),\n ],\n }\n }\n\n const agentValues = factView(agentFacts)\n const browserValues = factView(browserFacts)\n const { compared, divergent } = divergentKinds(agentValues, browserValues, PARITY_KINDS)\n\n const evidenceLines = [\n heuristic(\n 'Compared facts',\n compared.length === 0 ? 'none present in both representations' : compared.join(', '),\n ),\n heuristic(\n 'Values',\n divergent.length === 0\n ? 'agree'\n : divergent\n .map((entry) => `${entry.kind}: agent ${entry.left} / HTML ${entry.right}`)\n .join('; '),\n ),\n ]\n\n if (compared.length === 0) {\n return {\n earned: 0,\n evidence: [\n ...evidenceLines,\n heuristic(\n 'Scored',\n 'no — a comparison needs at least one comparable fact in both representations',\n ),\n ],\n remedy:\n 'State the same core facts in both representations. ARS could not compare them, so it could not award the parity points.',\n }\n }\n\n if (divergent.length === 0)\n return { earned: SUBPOINTS.substanceParity.full, evidence: evidenceLines }\n\n // §3.8: divergence must REPRODUCE on a third confirming probe taken ≥30s later\n // before the flag is set. Inventory and price genuinely change between two\n // sequential requests, and a one-shot difference is not evidence of anything.\n const confirm = bundle.probes.parityConfirm\n const confirmCapture = confirm !== null && confirm.result.ok ? confirm.result.capture : null\n const confirmRep = confirmCapture === null ? null : buildRepresentation(confirmCapture)\n if (confirmRep === null) {\n return {\n earned: 0,\n evidence: [\n ...evidenceLines,\n heuristic('Confirming probe', 'absent — divergence observed once and NOT flagged'),\n ],\n remedy:\n 'The two representations reported different values for a core fact. ARS did not flag it, because a single observation cannot distinguish a divergence from an inventory change.',\n }\n }\n\n const confirmFacts = extractFacts(confirmRep, {\n profile: context.profile,\n ruleset: context.ruleset,\n baseUrl: confirmRep.finalUrl,\n origin: bundle.target.origin,\n currencyHint: currencyHintOf(context.structural, context.agent),\n })\n const confirmValues = factView(confirmFacts)\n const reproduced = divergentKinds(\n confirmValues,\n browserValues,\n divergent.map((entry) => entry.kind),\n )\n\n if (reproduced.divergent.length === 0) {\n return {\n earned: SUBPOINTS.substanceParity.full,\n evidence: [\n ...evidenceLines,\n heuristic(\n 'Confirming probe',\n 'the difference did not reproduce — treated as a value that changed between requests',\n ),\n ],\n }\n }\n\n context.flags.push({\n id: 'substance-divergence',\n severity: 'warn',\n basis: 'heuristic',\n message: reproduced.divergent\n .map(\n (entry) =>\n `The agent representation reported ${entry.kind} ${entry.left}; the HTML representation reported ${entry.right} at capture time, on two captures taken apart.`,\n )\n .join(' '),\n evidence: evidenceLines,\n })\n\n return {\n earned: 0,\n evidence: [...evidenceLines, heuristic('Confirming probe', 'the difference reproduced')],\n remedy:\n 'Serve the same values in both representations. ARS reports what each one said; it does not assert which is correct.',\n }\n}\n\n// ---------------------------------------------------------------------------\n// D3 — Fact coverage\n// ---------------------------------------------------------------------------\n\ninterface CoverageMath {\n readonly coreFound: number\n readonly extendedFound: number\n readonly coveragePct: number\n readonly densityPct: number\n readonly factsPerKiB100: number\n}\n\n/** §3.6's fact weighting, verbatim, in quarter-units. */\nfunction coverageMath(context: ScoreContext): CoverageMath {\n const { facts, profile, ruleset, agent } = context\n const units = ruleset.thresholds['fact-coverage.fact-units'] ?? []\n const coreCorroboratedUnit = units[0] ?? 0\n const coreUnit = units[1] ?? 0\n const extendedCorroboratedUnit = units[2] ?? 0\n const extendedUnit = units[3] ?? 0\n const denominatorMultiplier =\n ruleset.thresholds['fact-coverage.core-denominator-multiplier']?.[0] ?? 0\n\n let coreUnits = 0\n let extendedUnits = 0\n let coreFound = 0\n let extendedFound = 0\n for (const fact of facts) {\n if (profile.core.includes(fact.kind)) {\n coreFound++\n coreUnits += fact.corroborated ? coreCorroboratedUnit : coreUnit\n } else if (profile.extended.includes(fact.kind)) {\n extendedFound++\n extendedUnits += fact.corroborated ? extendedCorroboratedUnit : extendedUnit\n }\n }\n\n const denominator = denominatorMultiplier * profile.core.length\n const coveragePct =\n denominator === 0\n ? 0\n : Math.min(100, divRoundHalfUp(100 * (coreUnits + extendedUnits), denominator))\n\n // The `max(1, bytes)` clamp is normative and replaces `max(1, bytes / 1024)`,\n // which let a 200-byte stub top the density band.\n const factsPerKiB100 = idiv(\n (coreFound * 100 + extendedFound * 25) * 1024,\n Math.max(1, agent.bytes),\n )\n const densityPct = atLeast(ruleset.thresholds['fact-coverage.density'], factsPerKiB100)\n\n return { coreFound, extendedFound, coveragePct, densityPct, factsPerKiB100 }\n}\n\nfunction checkCoreFacts(context: ScoreContext, math: CoverageMath): CheckOutcome {\n const weight = weightOf(context.ruleset, 'fact-coverage.core-facts')\n const earned = idiv(weight * math.coveragePct * math.densityPct + 5000, 10000)\n const missing = context.profile.core.filter(\n (kind) => !context.facts.some((fact) => fact.kind === kind),\n )\n\n return {\n earned,\n evidence: [\n heuristic(\n 'Core facts found',\n `${math.coreFound}/${context.profile.core.length}${missing.length === 0 ? '' : ` — missing ${missing.join(', ')}`}`,\n ),\n heuristic('Extended facts found', `${math.extendedFound}/${context.profile.extended.length}`),\n heuristic('Coverage', `${math.coveragePct}%`),\n heuristic(\n 'Density band',\n `${math.densityPct}% (${math.factsPerKiB100} hundredths of a fact per KiB)`,\n ),\n measured('Bytes the agent received', String(context.agent.bytes)),\n ],\n remedy:\n missing.length === 0\n ? undefined\n : `State ${missing.join(', ')} in the representation the agent receives. A fact only the HTML carries is a fact the caller never saw.`,\n }\n}\n\nfunction checkContextCost(context: ScoreContext): CheckOutcome {\n const table = context.ruleset.thresholds['fact-coverage.context-cost']\n const reference = context.profile.byteReference\n const ratio = reference === 0 ? 0 : idiv(100 * context.agent.bytes, reference)\n const earned = atMost(table, ratio)\n const full = atMost(table, 0)\n\n return {\n earned,\n evidence: [\n measured(\n 'Bytes the agent received',\n `${context.agent.bytes}${context.agent.truncated ? ' (truncated at the cap)' : ''}`,\n ),\n measured('Byte reference for this page kind', `${reference} (${context.profile.pageKind})`),\n measured('Ratio', `${ratio}% of the reference`),\n ],\n remedy:\n earned === full\n ? undefined\n : 'Serve a representation sized to the facts. The reference is what a page of this kind reasonably costs, not an absolute budget.',\n }\n}\n\n// ---------------------------------------------------------------------------\n// D4 — Fact position\n// ---------------------------------------------------------------------------\n\nfunction coreOffsets(context: ScoreContext): number[] {\n const offsets: number[] = []\n for (const fact of context.facts)\n if (context.profile.core.includes(fact.kind)) offsets.push(fact.offset)\n return offsets.sort((a, b) => a - b)\n}\n\nfunction checkFirstCoreFactOffset(context: ScoreContext, offsets: readonly number[]): CheckOutcome {\n const first = offsets[0]\n if (first === undefined) {\n return {\n earned: 0,\n evidence: [heuristic('First core fact', 'none found — nothing to position')],\n }\n }\n return {\n earned: atMost(context.ruleset.thresholds['fact-position.first-core-fact-offset'], first),\n evidence: [\n measured('Byte offset of the first core fact', String(first)),\n heuristic(\n 'Which fact',\n context.facts.find((fact) => fact.offset === first)?.kind ?? 'unknown',\n ),\n ],\n remedy:\n first <= 512\n ? undefined\n : 'Move the core facts to the top of the representation. A caller that stops reading early stops before them.',\n }\n}\n\nfunction checkFrontWindow(context: ScoreContext, offsets: readonly number[]): CheckOutcome {\n const windowRule = context.ruleset.thresholds['fact-position.front-window-size'] ?? []\n const floor = windowRule[0] ?? 0\n const divisor = windowRule[1] ?? 1\n const size = Math.max(floor, idiv(context.agent.bytes, divisor))\n\n if (offsets.length === 0) {\n return {\n earned: 0,\n evidence: [\n measured('Front window', `${size} bytes`),\n heuristic('Core facts inside it', 'none found — nothing to position'),\n ],\n }\n }\n\n const inside = offsets.filter((offset) => offset < size).length\n // The denominator is the core facts that are PRESENT, not the profile size:\n // absence is D3.1's job, and charging the same absence twice would make the\n // 100 points non-orthogonal. The evidence prints both numbers so a reader can\n // see which question was asked.\n const pct = idiv(100 * inside, offsets.length)\n\n return {\n earned: atLeast(context.ruleset.thresholds['fact-position.front-window'], pct),\n evidence: [\n measured('Front window', `${size} bytes (max(${floor}, bytes/${divisor}))`),\n heuristic('Core facts inside it', `${inside}/${offsets.length} found (${pct}%)`),\n heuristic('Core facts in this page kind', String(context.profile.core.length)),\n ],\n remedy:\n pct >= 90\n ? undefined\n : 'Front-load the core facts. Everything after the window costs the caller a full read.',\n }\n}\n\n// ---------------------------------------------------------------------------\n// D5 — Structured data\n// ---------------------------------------------------------------------------\n\nfunction checkStructuredDataPresent(context: ScoreContext): CheckOutcome {\n const { structural } = context\n const split = SUBPOINTS.structuredDataPresent\n if (structural === null) {\n return {\n earned: 0,\n evidence: [measured('HTML representation', 'none in this bundle — not evaluated')],\n }\n }\n\n const { blocks, parsed } = structural.jsonLd\n let microdata = 0\n let rdfa = 0\n if (structural.doc !== null) {\n for (const element of structural.doc.elements) {\n if (attr(element, 'itemtype') !== null) microdata++\n if (attr(element, 'typeof') !== null) rdfa++\n }\n }\n\n const jsonLdScore =\n blocks === 0 ? null : parsed === blocks ? split.clean : parsed > 0 ? split.partial : 0\n const otherScore = microdata > 0 || rdfa > 0 ? split.clean : null\n const earned = Math.max(jsonLdScore ?? 0, otherScore ?? 0)\n\n return {\n earned,\n evidence: [\n measured('JSON-LD blocks', `${parsed} of ${blocks} parsed`),\n measured('Microdata itemtype scopes', String(microdata)),\n measured('RDFa typeof scopes', String(rdfa)),\n ],\n remedy:\n earned === split.clean\n ? undefined\n : blocks > parsed\n ? 'One or more JSON-LD blocks did not parse. A block that does not parse is not structured data.'\n : 'Add JSON-LD for this page. It is the one machine representation every consumer already reads.',\n }\n}\n\n/**\n * The JSON-LD node D5.2 scores against: the node whose `@type` decided the page\n * kind, then any node with a recognised type. Scoring the first node in the\n * document would mark a page incomplete because its `BreadcrumbList` has no\n * `offers.price` (§ `nodeForKind` in ./classify).\n */\nfunction scoredNode(context: ScoreContext): JsonLdNode | null {\n const nodes = context.structural?.jsonLd.nodes ?? []\n const forKind = nodeForKind(nodes, context.profile.pageKind)\n if (forKind !== null) return forKind\n for (const node of nodes) if (node.types.some(isRecognisedType)) return node\n return null\n}\n\nfunction checkRequiredProperties(context: ScoreContext): CheckOutcome {\n const split = SUBPOINTS.requiredProperties\n const required = context.ruleset.requiredProperties[context.profile.pageKind] ?? []\n const node = scoredNode(context)\n\n if (node === null) {\n return {\n earned: 0,\n evidence: [\n measured('Recognised schema.org type', 'none'),\n measured('Required properties for this page kind', required.join(', ') || 'none'),\n measured(\n 'Scope',\n 'JSON-LD only in 0.1 — microdata satisfies D5.1 but is not walked for required properties',\n ),\n ],\n remedy:\n 'Declare a schema.org type in JSON-LD. Choosing no type does not avoid this check — an unrecognised page still scores against \"any recognised type present\".',\n }\n }\n\n const satisfied = required.filter((path) => hasPath(node, path))\n const missing = required.filter((path) => !hasPath(node, path))\n const completeness =\n required.length === 0\n ? split.completeness\n : divRoundHalfUp(split.completeness * satisfied.length, required.length)\n\n return {\n earned: split.recognisedType + completeness,\n evidence: [\n measured('Scored node @type', node.types.join(', ')),\n measured(\n 'Required properties',\n `${satisfied.length}/${required.length}${missing.length === 0 ? '' : ` — missing ${missing.join(', ')}`}`,\n ),\n measured('Table', `ruleset.requiredProperties.${context.profile.pageKind}`),\n ],\n remedy:\n missing.length === 0\n ? undefined\n : `Add ${missing.join(', ')} to the ${node.types[0] ?? 'top-level'} node.`,\n }\n}\n\nfunction checkTextAgreement(context: ScoreContext): CheckOutcome {\n const { structuralFacts } = context\n const fromJsonLd = factView(structuralFacts.filter((fact) => fact.source === 'json-ld'))\n const fromPage = factView(structuralFacts.filter((fact) => fact.source !== 'json-ld'))\n const { compared, divergent } = divergentKinds(fromJsonLd, fromPage, PARITY_KINDS)\n\n const evidenceLines = [\n heuristic(\n 'Compared facts',\n compared.length === 0\n ? 'none stated both in structured data and on the page'\n : compared.join(', '),\n ),\n heuristic(\n 'Values',\n divergent.length === 0\n ? 'agree'\n : divergent\n .map((entry) => `${entry.kind}: structured data ${entry.left} / page ${entry.right}`)\n .join('; '),\n ),\n ]\n\n if (compared.length === 0) {\n return {\n earned: 0,\n evidence: [...evidenceLines, heuristic('Scored', 'no — nothing was comparable')],\n remedy:\n 'State the core facts in both the structured data and the visible page, so the two can be checked against each other.',\n }\n }\n\n if (divergent.length > 0) {\n context.flags.push({\n id: 'structured-data-divergence',\n severity: 'warn',\n basis: 'heuristic',\n message: divergent\n .map(\n (entry) =>\n `The structured data reported ${entry.kind} ${entry.left}; the visible page reported ${entry.right}.`,\n )\n .join(' '),\n evidence: evidenceLines,\n })\n return {\n earned: 0,\n evidence: evidenceLines,\n remedy:\n 'Generate the structured data from the same source as the rendered page, so the two cannot drift.',\n }\n }\n\n return { earned: SUBPOINTS.textAgreement.full, evidence: evidenceLines }\n}\n\n// ---------------------------------------------------------------------------\n// D6 — Contract & discovery\n// ---------------------------------------------------------------------------\n\nfunction canonicalOf(\n capture: ArsHttpCapture | null,\n representation: ArsRepresentation | null,\n): string | null {\n if (capture !== null) {\n for (const link of parseLinkHeaders(headerAll(capture.headers, 'link'))) {\n if (link.rel.includes('canonical')) return link.url\n }\n }\n if (representation !== null && representation.doc !== null) {\n for (const link of representation.doc.links) {\n if (link.rel.includes('canonical') && link.href !== null) return link.href\n }\n }\n return null\n}\n\nfunction checkCanonical(context: ScoreContext): CheckOutcome {\n const split = SUBPOINTS.canonical\n const htmlCanonical =\n canonicalOf(context.browserCapture, context.browser) ??\n canonicalOf(context.agentCapture, context.agent)\n const agentCanonical = canonicalOf(context.agentCapture, context.agent)\n\n const present = htmlCanonical !== null\n const absolute = htmlCanonical !== null && /^https?:\\/\\//i.test(htmlCanonical)\n const consistent =\n htmlCanonical !== null && agentCanonical !== null && agentCanonical === htmlCanonical\n\n if (htmlCanonical !== null && agentCanonical !== null && agentCanonical !== htmlCanonical) {\n context.flags.push({\n id: 'canonical-mismatch',\n severity: 'warn',\n basis: 'measured',\n message: `The two representations of this URL declare different canonicals: ${agentCanonical} and ${htmlCanonical}.`,\n evidence: [\n measured('Agent probe canonical', agentCanonical),\n measured('HTML canonical', htmlCanonical),\n ],\n })\n }\n\n return {\n earned:\n (present ? split.present : 0) +\n (absolute ? split.absolute : 0) +\n (consistent ? split.consistentAcrossProbes : 0),\n evidence: [\n measured('Canonical (HTML)', htmlCanonical ?? 'absent'),\n measured('Canonical (agent representation)', agentCanonical ?? 'absent'),\n measured('Absolute', yesNo(absolute)),\n measured('Same across both probes', yesNo(consistent)),\n ],\n remedy: consistent\n ? undefined\n : agentCanonical === null\n ? 'Declare the canonical on the machine representation too — `Link: <https://…>; rel=\"canonical\"`. A representation with no canonical cannot be attributed to a page.'\n : 'Declare one canonical URL and use it in both representations.',\n }\n}\n\nfunction checkCacheValidators(context: ScoreContext): CheckOutcome {\n const split = SUBPOINTS.cacheValidators\n const cacheControl = header(context.agentCapture.headers, 'cache-control')\n const directives = headerTokens(cacheControl)\n const noStore = directives.includes('no-store')\n const maxAge = directives.some((token) => {\n const match = /^(?:max-age|s-maxage)=(\\d{1,10})$/.exec(token)\n return match !== null && Number(match[1]) > 0\n })\n const noCache = directives.includes('no-cache') || directives.includes('must-revalidate')\n const etag = header(context.agentCapture.headers, 'etag')\n const lastModified = header(context.agentCapture.headers, 'last-modified')\n const validator = etag !== null || lastModified !== null\n\n // \"Sane\" is: the response says how long it may be reused, or says to\n // revalidate — and revalidation only means anything with a validator.\n const sane = cacheControl !== null && !noStore && (maxAge || (noCache && validator))\n\n return {\n earned: (sane ? split.saneCacheControl : 0) + (validator ? split.validator : 0),\n evidence: [\n measured('Cache-Control', cacheControl ?? 'absent'),\n measured('ETag', etag ?? 'absent'),\n measured('Last-Modified', lastModified ?? 'absent'),\n ],\n remedy:\n sane && validator\n ? undefined\n : 'Send a `Cache-Control` a cache can act on, plus an `ETag` or `Last-Modified`. Repeat fetches are most of agent traffic.',\n }\n}\n\nfunction bodyOf(probe: ArsProbeRecord | null): string | null {\n if (probe === null || !probe.result.ok) return null\n const capture = probe.result.capture\n if (capture.status < 200 || capture.status >= 300) return null\n return typeof capture.body === 'string' ? capture.body : null\n}\n\nconst MARKDOWN_LINK = /\\[[^\\]\\n]{1,200}\\]\\(([^)\\s]{1,500})\\)/g\n\nfunction checkLlmsTxt(context: ScoreContext): CheckOutcome {\n const split = SUBPOINTS.llmsTxt\n const body = bodyOf(context.evidence.probes.llmsTxt)\n if (body === null || body.trim().length === 0) {\n return {\n earned: 0,\n evidence: [measured('/llms.txt', body === null ? 'absent or non-2xx' : 'empty')],\n remedy:\n 'Publish /llms.txt: an H1 title, a short summary, and links to the pages that matter. It is worth 2 points of 100, deliberately.',\n }\n }\n // The llms.txt convention: an H1 title, then Markdown links. Both halves are\n // checked because a file with a title and no links tells an agent nothing.\n const hasTitle = /^#\\s+\\S/m.test(body)\n MARKDOWN_LINK.lastIndex = 0\n const hasLinks = MARKDOWN_LINK.test(body)\n const specShaped = hasTitle && hasLinks\n\n return {\n earned: specShaped ? split.specShaped : split.present,\n evidence: [\n measured('/llms.txt', `${body.length} characters`),\n measured('H1 title', yesNo(hasTitle)),\n measured('Markdown links', yesNo(hasLinks)),\n ],\n remedy: specShaped ? undefined : 'Give /llms.txt an H1 title and at least one Markdown link.',\n }\n}\n\nfunction checkSitemap(context: ScoreContext): CheckOutcome {\n return {\n earned: context.policy.sitemapDeclared ? SUBPOINTS.sitemap.full : 0,\n evidence: [\n measured('Sitemap: in robots.txt', yesNo(context.policy.sitemapDeclared)),\n measured(\n 'Sitemaps declared',\n context.robots === null ? 'n/a' : context.robots.sitemaps.join(', ') || 'none',\n ),\n ],\n remedy: context.policy.sitemapDeclared ? undefined : 'Declare `Sitemap:` in robots.txt.',\n }\n}\n\n/**\n * Media types and URL shapes that count as a declared machine endpoint (§3.4\n * D6.5: UCP/ACP/MCP/OpenAPI/GraphQL/RSS/Atom/ICS/JSON feed).\n *\n * Credit comes from DECLARATION. ARS probes `/robots.txt`, `/llms.txt` and\n * `/.well-known/ucp` and nothing else — no guessing at `/sitemap.xml`, `/mcp` or\n * `/acp` — because an endpoint an agent cannot find is an endpoint that does not\n * exist. The three probed paths are the disclosed exception: they are published\n * conventions with published locations.\n */\nconst ENDPOINT_TYPES: readonly string[] = [\n 'application/rss+xml',\n 'application/atom+xml',\n 'application/feed+json',\n 'application/json',\n 'application/ld+json',\n 'application/vnd.api+json',\n 'application/schema+json',\n 'application/graphql',\n 'application/openapi+json',\n 'application/yaml',\n 'text/calendar',\n]\nconst ENDPOINT_RELS: readonly string[] = [\n 'service-desc',\n 'service-doc',\n 'api',\n 'describedby',\n 'ucp',\n 'mcp',\n]\nconst ENDPOINT_PATH_MARKERS: readonly string[] = [\n '/api',\n '/mcp',\n '/graphql',\n '/openapi',\n '/.well-known/',\n '.json',\n '.ics',\n '.rss',\n '.atom',\n]\n\nfunction checkMachineEndpoint(context: ScoreContext): CheckOutcome {\n const declarations: string[] = []\n\n const links = parseLinkHeaders([\n ...headerAll(context.agentCapture.headers, 'link'),\n ...(context.browserCapture === null ? [] : headerAll(context.browserCapture.headers, 'link')),\n ])\n for (const link of links) {\n if (link.rel.some((rel) => ENDPOINT_RELS.includes(rel)))\n declarations.push(`Link rel=${link.rel.join(' ')} → ${link.url}`)\n else if (link.type !== null && ENDPOINT_TYPES.includes(link.type))\n declarations.push(`Link type=${link.type} → ${link.url}`)\n }\n\n if (context.structural !== null && context.structural.doc !== null) {\n for (const link of context.structural.doc.links) {\n if (link.href === null) continue\n if (link.rel.some((rel) => ENDPOINT_RELS.includes(rel)))\n declarations.push(`<link rel=\"${link.rel.join(' ')}\"> → ${link.href}`)\n else if (link.type !== null && ENDPOINT_TYPES.includes(link.type))\n declarations.push(`<link type=\"${link.type}\"> → ${link.href}`)\n }\n }\n\n const llms = bodyOf(context.evidence.probes.llmsTxt)\n if (llms !== null) {\n MARKDOWN_LINK.lastIndex = 0\n let match: RegExpExecArray | null\n while ((match = MARKDOWN_LINK.exec(llms)) !== null) {\n const url = (match[1] ?? '').toLowerCase()\n if (ENDPOINT_PATH_MARKERS.some((marker) => url.includes(marker)))\n declarations.push(`llms.txt → ${match?.[1] ?? url}`)\n }\n }\n\n const ucp = bodyOf(context.evidence.probes.wellKnownUcp)\n if (ucp !== null && ucp.trim().length > 0) declarations.push('/.well-known/ucp')\n\n return {\n earned: declarations.length > 0 ? SUBPOINTS.machineEndpoint.full : 0,\n evidence: [\n measured(\n 'Declared machine endpoints',\n declarations.length === 0 ? 'none' : declarations.join('; '),\n ),\n measured('Probed paths', '/robots.txt, /llms.txt, /.well-known/ucp — ARS probes no others'),\n ],\n remedy:\n declarations.length > 0\n ? undefined\n : 'Declare one machine endpoint — a feed, an OpenAPI document, /.well-known/ucp — with a `Link` header or a `<link>`. ARS does not guess at paths.',\n }\n}\n\n// ---------------------------------------------------------------------------\n// Assembly\n// ---------------------------------------------------------------------------\n\nfunction weightOf(ruleset: ArsRuleset, id: ArsCheckId): number {\n return ruleset.weights[id] ?? 0\n}\n\nfunction buildCheck(ruleset: ArsRuleset, id: ArsCheckId, outcome: CheckOutcome): ArsCheck {\n const meta = CHECK_META[id]\n const weight = weightOf(ruleset, id)\n // Structural guarantee: `earned` is an integer in `[0, weight]`. Every branch\n // above already produces one; the clamp is what makes it impossible for a\n // future check to publish a number outside its own weight. Fixture 052 asserts\n // the property over the whole corpus.\n const earned = Math.max(0, Math.min(weight, outcome.earned))\n const check: ArsCheck = {\n id,\n label: meta.label,\n basis: meta.basis,\n weight,\n earned,\n evidence: outcome.evidence,\n }\n return outcome.remedy === undefined || earned === weight\n ? check\n : { ...check, remedy: outcome.remedy }\n}\n\nconst DIMENSION_ORDER: readonly ArsDimensionId[] = [\n 'retrievability',\n 'machine-representation',\n 'fact-coverage',\n 'fact-position',\n 'structured-data',\n 'contract-discovery',\n]\n\nfunction buildDimensions(checks: readonly ArsCheck[]): ArsDimension[] {\n return DIMENSION_ORDER.map((id) => {\n const own = checks.filter((check) => CHECK_META[check.id].dimension === id)\n return {\n id,\n label: DIMENSION_META[id].label,\n weight: DIMENSION_META[id].weight,\n earned: own.reduce((sum, check) => sum + check.earned, 0),\n basis: own.some((check) => check.basis === 'heuristic')\n ? ('heuristic' as ArsBasis)\n : ('measured' as ArsBasis),\n checks: own,\n }\n })\n}\n\n/** Pinned flag order, so two runs over the same evidence emit the same array. */\nconst FLAG_ORDER: readonly ArsFlagId[] = [\n 'substance-divergence',\n 'structured-data-divergence',\n 'robots-contradiction',\n 'paywalled',\n 'render-dependent',\n 'scanner-blocked',\n 'training-opt-out',\n 'assistant-opt-out',\n 'vary-missing',\n 'canonical-mismatch',\n 'body-truncated',\n 'vantage-variance',\n]\n\nfunction sortFlags(flags: readonly ArsFlag[]): ArsFlag[] {\n return [...flags].sort((a, b) => FLAG_ORDER.indexOf(a.id) - FLAG_ORDER.indexOf(b.id))\n}\n\n/** The band a score falls in. Bands headline; the integer is secondary (§3.6). */\nexport function bandFor(score: number, ruleset: ArsRuleset = DEFAULT_RULESET): ArsBand | null {\n for (const band of ruleset.bands) if (score >= band.min && score <= band.max) return band\n return null\n}\n\n// ---------------------------------------------------------------------------\n// Evidence plumbing\n// ---------------------------------------------------------------------------\n\nfunction captureOf(probe: ArsProbeRecord | null): ArsHttpCapture | null {\n return probe !== null && probe.result.ok ? probe.result.capture : null\n}\n\n/**\n * The currency the page prices in, read from structured data and Open Graph.\n * The SAME hint is used for both representations, deliberately: a hint is a\n * property of the page, and letting the two representations resolve `$` to\n * different currencies would manufacture a substance divergence out of nothing.\n */\nfunction currencyHintOf(\n structural: ArsRepresentation | null,\n agent: ArsRepresentation,\n): string | undefined {\n for (const representation of [structural, agent]) {\n if (representation === null) continue\n for (const node of representation.jsonLd.nodes) {\n for (const path of ['offers.priceCurrency', 'priceCurrency']) {\n const raw = readPath(node, path)\n if (raw !== null && /^[A-Za-z]{3}$/.test(raw.trim())) return raw.trim().toUpperCase()\n }\n }\n if (representation.doc === null) continue\n for (const meta of representation.doc.metas) {\n const key = meta.property ?? meta.name\n if (key !== 'og:price:currency' && key !== 'product:price:currency') continue\n const value = meta.content\n if (value !== null && /^[A-Za-z]{3}$/.test(value.trim())) return value.trim().toUpperCase()\n }\n }\n return undefined\n}\n\nfunction pathOf(url: string, fallback: string): string {\n try {\n return new URL(url).pathname\n } catch {\n return fallback\n }\n}\n\n/** robots.txt status and parse, from the probe record alone. */\nfunction readRobots(probe: ArsProbeRecord | null): {\n status: ArsPolicyReport['robotsTxtStatus']\n robots: RobotsFile | null\n} {\n if (probe === null) return { status: 'missing', robots: null }\n if (!probe.result.ok) return { status: 'error', robots: null }\n const capture = probe.result.capture\n if (capture.status >= 500) return { status: 'error', robots: null }\n if (capture.status >= 400) return { status: 'missing', robots: null }\n const body = typeof capture.body === 'string' ? capture.body : null\n if (body === null) return { status: 'missing', robots: null }\n const robots = parseRobots(body)\n const empty = robots.groups.length === 0 && robots.sitemaps.length === 0\n return { status: empty && robots.malformedLines > 0 ? 'unparseable' : 'ok', robots }\n}\n\n/** Declared paywalls only (§3.8). Undeclared soft paywalls need impersonation, which we refuse. */\nfunction detectPaywall(context: {\n structural: ArsRepresentation | null\n agentCapture: ArsHttpCapture\n}): string | null {\n if (context.agentCapture.status === 402) return 'HTTP 402'\n if (header(context.agentCapture.headers, 'www-authenticate') !== null) return 'WWW-Authenticate'\n for (const node of context.structural?.jsonLd.nodes ?? []) {\n const value = node.value['isAccessibleForFree']\n if (value === false || value === 'False' || value === 'false')\n return 'isAccessibleForFree: false'\n }\n return null\n}\n\n// ---------------------------------------------------------------------------\n// Non-grades\n// ---------------------------------------------------------------------------\n\n/**\n * The result shape for the three non-grades (§3.6). `score` is null and there is\n * no letter — an opt-out is a choice and an unscored target is a missing\n * observation, and neither is an F.\n *\n * The six dimensions are still present with their weights, because §3.9 says\n * `dimensions` always has 6 entries summing to 100, but every check reports\n * `earned: 0` with an evidence line naming the reason. A non-grade is a\n * statement that we did not score; publishing sub-scores next to it would be\n * scoring by another name.\n */\nfunction nonGrade(\n evidence: ArsEvidence,\n ruleset: ArsRuleset,\n outcome: ArsOutcome,\n reason: string,\n policy: ArsPolicyReport,\n flags: readonly ArsFlag[],\n): ArsResult {\n const agentCapture = captureOf(evidence.probes.agent)\n const browserCapture = captureOf(evidence.probes.browser)\n const checks = (Object.keys(CHECK_META) as ArsCheckId[]).map((id) =>\n buildCheck(ruleset, id, {\n earned: 0,\n evidence: [{ label: 'Not evaluated', value: reason, basis: CHECK_META[id].basis }],\n }),\n )\n const htmlBytes = browserCapture?.bytes ?? agentCapture?.bytes ?? 0\n const perToken = ruleset.thresholds['cost.approx-bytes-per-token']?.[0] ?? 4\n\n return {\n spec: 'ars',\n specVersion: ARS_SPEC_VERSION,\n rulesetHash: rulesetHash(ruleset),\n corpusHash: ARS_CORPUS_HASH,\n evidenceHash: evidenceHash(evidence),\n vantage: evidence.vantage,\n target: {\n url: evidence.target.url,\n finalUrl: agentCapture?.finalUrl ?? evidence.target.url,\n origin: evidence.target.origin,\n },\n outcome,\n score: null,\n grade: null,\n bandLabel: null,\n pageKind: 'unknown',\n pageKindBasis: 'heuristic',\n pageKindConfidence: 'low',\n factProfile: profileFor('unknown'),\n facts: [],\n dimensions: buildDimensions(checks),\n flags: sortFlags(flags),\n policy,\n cost: {\n htmlBytes,\n negotiatedBytes: null,\n approxHtmlTokens: idiv(htmlBytes, perToken),\n approxNegotiatedTokens: null,\n reductionRatio: null,\n firstCoreFactOffset: null,\n truncated: (agentCapture?.truncated ?? false) || (browserCapture?.truncated ?? false),\n },\n recommendations: [],\n measuredWeight: measuredWeightOf(ruleset),\n heuristicWeight: heuristicWeightOf(ruleset),\n }\n}\n\nfunction measuredWeightOf(ruleset: ArsRuleset): number {\n let total = 0\n for (const id of Object.keys(CHECK_META) as ArsCheckId[]) {\n if (CHECK_META[id].basis === 'measured') total += weightOf(ruleset, id)\n }\n return total\n}\n\nfunction heuristicWeightOf(ruleset: ArsRuleset): number {\n let total = 0\n for (const id of Object.keys(CHECK_META) as ArsCheckId[]) {\n if (CHECK_META[id].basis === 'heuristic') total += weightOf(ruleset, id)\n }\n return total\n}\n\n/** Probe error → the reason ARS publishes. `detail` carries the probe's own word for it. */\nfunction unscoredReasonFor(error: string): { reason: ArsUnscoredReason; detail?: string } {\n switch (error) {\n case 'challenge':\n return { reason: 'blocked-at-edge', detail: 'challenge' }\n case 'non-2xx':\n return { reason: 'non-2xx' }\n case 'too-many-redirects':\n return { reason: 'too-many-redirects' }\n case 'timeout':\n return { reason: 'unreachable', detail: 'timeout' }\n case 'blocked-redirect':\n return { reason: 'unreachable', detail: 'blocked-redirect' }\n case 'policy-rejected':\n return { reason: 'unreachable', detail: 'policy-rejected' }\n default:\n return { reason: 'unreachable' }\n }\n}\n\n// ---------------------------------------------------------------------------\n// score()\n// ---------------------------------------------------------------------------\n\n/**\n * The entire pure surface. No network. No clock. No randomness. No LLM.\n *\n * GATE ORDER, and why it is this order:\n * 1. `robots-disallow-scanner` — a statement about OUR conduct. If we were not\n * allowed to fetch, nothing else about the evidence should be reported.\n * Only `vantage: 'public'` is gated; an owner can consent for their own\n * origin (§3.7), and a merchant scanning their own store getting `unscored`\n * because they block unknown tokens is a product regression dressed as rigour.\n * 2. `robots-unavailable` — a persistent 5xx means we could not learn the policy.\n * 3. `opt-out` — the site's own decision, reported before any failure of ours,\n * because it is a choice and not a failure.\n * 4. Fetch failures, then a bundle with no body, then a truncated body.\n */\nexport function score(evidence: ArsEvidence, ruleset: ArsRuleset = DEFAULT_RULESET): ArsResult {\n const flags: ArsFlag[] = []\n const targetPath = pathOf(evidence.target.url, '/')\n const { status: robotsStatus, robots } = readRobots(evidence.probes.robotsTxt)\n const policy = buildPolicyReport(robots, robotsStatus, ruleset, targetPath)\n\n if (policy.trainingOptOut) {\n flags.push({\n id: 'training-opt-out',\n severity: 'info',\n basis: 'measured',\n message:\n 'This site blocks model-training crawlers while allowing assistant fetches. That is neutral in ARS: it never lowers the score.',\n evidence: [\n measured('Training audience', policy.audiences.training.matchedRule ?? 'disallowed'),\n measured('Effect on this score', 'none'),\n ],\n })\n }\n\n // 1 — we obey our own token, and say so.\n if (evidence.vantage === 'public' && robots !== null) {\n const scannerDecision = decideScannerToken(robots, targetPath)\n if (scannerDecision) {\n flags.push({\n id: 'scanner-blocked',\n severity: 'info',\n basis: 'measured',\n message:\n 'robots.txt disallows the rebilder-ars scanner. We obeyed it and did not score this page.',\n evidence: [measured('Matched rule', scannerDecision)],\n })\n return nonGrade(\n evidence,\n ruleset,\n { kind: 'unscored', reason: 'robots-disallow-scanner' },\n 'robots.txt disallows the rebilder-ars token',\n policy,\n flags,\n )\n }\n }\n\n // 2 — a policy we could not read is not a policy we may assume.\n if (robotsStatus === 'error') {\n return nonGrade(\n evidence,\n ruleset,\n { kind: 'unscored', reason: 'robots-unavailable' },\n 'robots.txt returned a persistent error',\n policy,\n flags,\n )\n }\n\n // 3 — a deliberate, well-formed opt-out. Not a failure, not ranked, no letter.\n if (policy.deliberateOptOut) {\n flags.push({\n id: 'assistant-opt-out',\n severity: 'info',\n basis: 'measured',\n message:\n 'This site names assistant crawlers in robots.txt and disallows them. ARS records the choice and does not grade the page.',\n evidence: [\n measured('Matched group', policy.audiences.assistant.matchedGroup ?? '(named group)'),\n measured('Matched rule', policy.audiences.assistant.matchedRule ?? 'Disallow'),\n ],\n })\n return nonGrade(\n evidence,\n ruleset,\n { kind: 'opt-out', audience: 'assistant' satisfies ArsAudience, wellFormed: true },\n 'the site opted out of assistant crawling',\n policy,\n flags,\n )\n }\n\n // 4 — fetch failures.\n const agentProbe = evidence.probes.agent\n if (!agentProbe.result.ok) {\n const { reason, detail } = unscoredReasonFor(agentProbe.result.error)\n if (reason === 'blocked-at-edge') {\n flags.push({\n id: 'scanner-blocked',\n severity: 'warn',\n basis: 'measured',\n message:\n 'The origin answered the agent probe with a challenge or a block. ARS reports the evidence and does not grade the page.',\n evidence: [measured('Probe error', agentProbe.result.error)],\n })\n }\n const outcome: ArsOutcome =\n detail === undefined ? { kind: 'unscored', reason } : { kind: 'unscored', reason, detail }\n return nonGrade(\n evidence,\n ruleset,\n outcome,\n `the agent probe failed: ${agentProbe.result.error}`,\n policy,\n flags,\n )\n }\n\n const agentCapture = agentProbe.result.capture\n if (agentCapture.status === 403 || agentCapture.status === 401 || agentCapture.status === 429) {\n flags.push({\n id: 'scanner-blocked',\n severity: 'warn',\n basis: 'measured',\n message: `The origin answered the agent probe with HTTP ${agentCapture.status}. ARS reports the evidence and does not grade the page.`,\n evidence: [measured('HTTP status', String(agentCapture.status))],\n })\n return nonGrade(\n evidence,\n ruleset,\n { kind: 'unscored', reason: 'blocked-at-edge', detail: `HTTP ${agentCapture.status}` },\n `the origin answered with HTTP ${agentCapture.status}`,\n policy,\n flags,\n )\n }\n if (agentCapture.status < 200 || agentCapture.status >= 300) {\n return nonGrade(\n evidence,\n ruleset,\n { kind: 'unscored', reason: 'non-2xx', detail: `HTTP ${agentCapture.status}` },\n `the origin answered with HTTP ${agentCapture.status}`,\n policy,\n flags,\n )\n }\n if (agentCapture.redirects.length > ruleset.maxRedirects) {\n return nonGrade(\n evidence,\n ruleset,\n {\n kind: 'unscored',\n reason: 'too-many-redirects',\n detail: `${agentCapture.redirects.length} hops`,\n },\n `the agent path took ${agentCapture.redirects.length} redirect hops`,\n policy,\n flags,\n )\n }\n\n const browserCapture = captureOf(evidence.probes.browser)\n if (agentCapture.truncated || (browserCapture?.truncated ?? false)) {\n flags.push({\n id: 'body-truncated',\n severity: 'warn',\n basis: 'measured',\n message: `A response exceeded the ${ruleset.maxBodyBytes}-byte body cap and was truncated. The fact set and the byte count would both be wrong, so the page is not scored.`,\n evidence: [\n measured('Body cap', `${ruleset.maxBodyBytes} bytes`),\n measured('Bytes read', `≥ ${agentCapture.bytes}`),\n ],\n })\n return nonGrade(\n evidence,\n ruleset,\n { kind: 'unscored', reason: 'truncated-evidence' },\n 'the response exceeded the body cap and was truncated',\n policy,\n flags,\n )\n }\n\n const agent = buildRepresentation(agentCapture)\n if (agent === null) {\n return nonGrade(\n evidence,\n ruleset,\n {\n kind: 'unscored',\n reason: 'evidence-incomplete',\n detail: 'the bundle carries no response body',\n },\n 'the evidence bundle carries hashes but no body, so it cannot be re-scored',\n policy,\n flags,\n )\n }\n const browser = browserCapture === null ? null : buildRepresentation(browserCapture)\n const structural =\n browser !== null && browser.doc !== null ? browser : agent.doc !== null ? agent : browser\n\n // ── classification (pass 1) ──────────────────────────────────────────────\n const classification = classify(pass1Signals(structural ?? agent, evidence.target.url))\n const profile = profileFor(classification.pageKind)\n\n // ── extraction (pass 2) ──────────────────────────────────────────────────\n const currencyHint = currencyHintOf(structural, agent)\n const extractContext = {\n profile,\n ruleset,\n baseUrl: agentCapture.finalUrl,\n origin: evidence.target.origin,\n currencyHint,\n }\n const agentFacts = extractFacts(agent, extractContext)\n const browserFacts =\n browser === null || browser === agent\n ? []\n : extractFacts(browser, { ...extractContext, baseUrl: browser.finalUrl })\n const structuralFacts =\n structural === agent ? agentFacts : structural === browser ? browserFacts : []\n const facts = mergeFacts(agentFacts, structuralFacts)\n\n const context: ScoreContext = {\n evidence,\n ruleset,\n agentCapture,\n browserCapture,\n agent,\n browser,\n structural,\n classification,\n profile,\n facts,\n agentFacts,\n browserFacts,\n structuralFacts,\n policy,\n robots,\n flags,\n }\n\n const paywall = detectPaywall(context)\n if (paywall !== null) {\n flags.push({\n id: 'paywalled',\n severity: 'info',\n basis: 'measured',\n message: `This page declares a paywall (${paywall}). ARS scores the portion it was served and does not attempt to reach the gated part.`,\n evidence: [measured('Paywall signal', paywall)],\n })\n }\n\n // ── the 19 checks ────────────────────────────────────────────────────────\n const math = coverageMath(context)\n const offsets = coreOffsets(context)\n const negotiated = checkNegotiatedResponse(context)\n\n const checks: ArsCheck[] = [\n buildCheck(ruleset, 'retrievability.reachable', checkReachable(context)),\n buildCheck(ruleset, 'retrievability.robots-policy', checkRobotsPolicy(context)),\n buildCheck(ruleset, 'retrievability.render-independence', checkRenderIndependence(context)),\n buildCheck(ruleset, 'machine-representation.negotiated-response', negotiated),\n buildCheck(\n ruleset,\n 'machine-representation.declared-alternates',\n checkDeclaredAlternates(context),\n ),\n buildCheck(\n ruleset,\n 'machine-representation.vary-accept',\n checkVaryAccept(context, negotiated.earned),\n ),\n buildCheck(\n ruleset,\n 'machine-representation.substance-parity',\n checkSubstanceParity(context, negotiated.earned),\n ),\n buildCheck(ruleset, 'fact-coverage.core-facts', checkCoreFacts(context, math)),\n buildCheck(ruleset, 'fact-coverage.context-cost', checkContextCost(context)),\n buildCheck(\n ruleset,\n 'fact-position.first-core-fact-offset',\n checkFirstCoreFactOffset(context, offsets),\n ),\n buildCheck(ruleset, 'fact-position.front-window', checkFrontWindow(context, offsets)),\n buildCheck(ruleset, 'structured-data.present', checkStructuredDataPresent(context)),\n buildCheck(ruleset, 'structured-data.required-properties', checkRequiredProperties(context)),\n buildCheck(ruleset, 'structured-data.text-agreement', checkTextAgreement(context)),\n buildCheck(ruleset, 'contract-discovery.canonical', checkCanonical(context)),\n buildCheck(ruleset, 'contract-discovery.cache-validators', checkCacheValidators(context)),\n buildCheck(ruleset, 'contract-discovery.llms-txt', checkLlmsTxt(context)),\n buildCheck(ruleset, 'contract-discovery.sitemap', checkSitemap(context)),\n buildCheck(ruleset, 'contract-discovery.machine-endpoint', checkMachineEndpoint(context)),\n ]\n\n const dimensions = buildDimensions(checks)\n const total = dimensions.reduce((sum, dimension) => sum + dimension.earned, 0)\n const band = bandFor(total, ruleset)\n const grade: ArsGrade = band?.grade ?? 'F'\n\n const perToken = ruleset.thresholds['cost.approx-bytes-per-token']?.[0] ?? 4\n const htmlBytes = structural?.bytes ?? agent.bytes\n const negotiatedBytes = negotiated.earned > 0 ? agent.bytes : null\n const cost: ArsCostReport = {\n htmlBytes,\n negotiatedBytes,\n approxHtmlTokens: idiv(htmlBytes, perToken),\n approxNegotiatedTokens: negotiatedBytes === null ? null : idiv(negotiatedBytes, perToken),\n // Integer PERCENT of HTML bytes the machine representation eliminates:\n // 94 means \"94% fewer bytes\". §3.9 types this as a number and does not fix\n // its unit; a multiple (`4.2×`) would be a float, and this is the same\n // information with no rounding for two implementations to disagree about.\n reductionRatio:\n negotiatedBytes === null || htmlBytes === 0\n ? null\n : Math.max(0, 100 - idiv(100 * negotiatedBytes, htmlBytes)),\n firstCoreFactOffset: offsets[0] ?? null,\n truncated: agent.truncated || (browser?.truncated ?? false),\n }\n\n const published: ArsFactObservation[] = facts.map((fact) => ({\n kind: fact.kind,\n normalized: fact.normalized,\n source: fact.source,\n offset: fact.offset,\n corroborated: fact.corroborated,\n }))\n\n return {\n spec: 'ars',\n specVersion: ARS_SPEC_VERSION,\n rulesetHash: rulesetHash(ruleset),\n corpusHash: ARS_CORPUS_HASH,\n evidenceHash: evidenceHash(evidence),\n vantage: evidence.vantage,\n target: {\n url: evidence.target.url,\n finalUrl: agentCapture.finalUrl,\n origin: evidence.target.origin,\n },\n outcome: { kind: 'scored', grade, score: total },\n score: total,\n grade,\n bandLabel: band?.label ?? null,\n pageKind: classification.pageKind,\n pageKindBasis: 'heuristic',\n pageKindConfidence: classification.confidence,\n factProfile: profile,\n facts: published,\n dimensions,\n flags: sortFlags(flags),\n policy,\n cost,\n recommendations: recommend({ dimensions, score: total }),\n measuredWeight: measuredWeightOf(ruleset),\n heuristicWeight: heuristicWeightOf(ruleset),\n }\n}\n\n/**\n * The product token the probe sends (§3.3). This is the ONLY place in the scorer\n * where our own identity is an input to a decision, and the decision it drives is\n * to score nothing.\n */\nconst SCANNER_TOKEN = 'rebilder-ars'\n\n/**\n * Does robots.txt disallow the ARS scanner itself? Returns the matched rule when\n * it does, so the result can print the line rather than assert a verdict.\n *\n * Only a group that NAMES `rebilder-ars` counts. A blanket `User-agent: *`\n * disallow is not a decision about us: it is the accidental case (§3.7), which is\n * scored with `robots-contradiction`, not silently exempted. Rule selection is\n * RFC 9309 longest-match with ties to Allow, via `./extract`'s `pathMatches` —\n * the same matcher `decideRobots` uses, so the scanner gate and the audience\n * decision can never disagree about what a pattern means.\n */\nfunction decideScannerToken(robots: RobotsFile, path: string): string | null {\n for (const group of robots.groups) {\n if (!group.agents.some((agent) => agent === SCANNER_TOKEN)) continue\n let best: { field: 'allow' | 'disallow'; value: string } | null = null\n for (const value of group.allow) {\n if (!pathMatches(value, path)) continue\n if (best === null || value.length > best.value.length) best = { field: 'allow', value }\n }\n for (const value of group.disallow) {\n if (!pathMatches(value, path)) continue\n if (best === null || value.length > best.value.length) best = { field: 'disallow', value }\n }\n if (best !== null && best.field === 'disallow') {\n return `User-agent: ${SCANNER_TOKEN} / Disallow: ${best.value}`\n }\n }\n return null\n}\n"]}
1
+ {"version":3,"sources":["../src/types.ts","../src/profiles.ts","../src/ruleset.ts","../src/html.ts","../src/parse-money.ts","../src/extract.ts","../src/classify.ts","../src/recommend.ts","../src/score.ts","../src/probe/headers.ts","../src/robots-policy.ts"],"names":["child","deepFreeze","a","b","score"],"mappings":";;;AAuCO,IAAM,gBAAA,GAAmB;;;AC8BzB,IAAM,eAAA,GAAkB;AAAA,EAC7B,OAAA,EAAS;AAAA,IACP,QAAA,EAAU,SAAA;AAAA,IACV,IAAA,EAAM,CAAC,OAAA,EAAS,OAAA,EAAS,YAAY,cAAc,CAAA;AAAA,IACnD,UAAU,CAAC,OAAA,EAAS,KAAA,EAAO,UAAA,EAAY,WAAW,aAAa,CAAA;AAAA,IAC/D,e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C,KAAA,CAAM,MAAA,CAAO,IAAA,CAAK,CAAC,UAAU,KAAA,CAAM,WAAA,EAAY,KAAM,gBAAgB,CAAA,EAAG;AAC7E,IAAA,IAAI,IAAA,GAA8D,IAAA;AAClE,IAAA,KAAA,MAAW,KAAA,IAAS,MAAM,KAAA,EAAO;AAC/B,MAAA,IAAI,CAAC,WAAA,CAAY,KAAA,EAAO,IAAI,CAAA,EAAG;AAC/B,MAAA,IAAI,IAAA,KAAS,IAAA,IAAQ,KAAA,CAAM,MAAA,GAAS,IAAA,CAAK,KAAA,CAAM,MAAA,EAAQ,IAAA,GAAO,EAAE,KAAA,EAAO,OAAA,EAAS,KAAA,EAAM;AAAA,IACxF;AACA,IAAA,KAAA,MAAW,KAAA,IAAS,MAAM,QAAA,EAAU;AAClC,MAAA,IAAI,CAAC,WAAA,CAAY,KAAA,EAAO,IAAI,CAAA,EAAG;AAC/B,MAAA,IAAI,IAAA,KAAS,IAAA,IAAQ,KAAA,CAAM,MAAA,GAAS,IAAA,CAAK,KAAA,CAAM,MAAA,EAAQ,IAAA,GAAO,EAAE,KAAA,EAAO,UAAA,EAAY,KAAA,EAAM;AAAA,IAC3F;AACA,IAAA,IAAI,IAAA,KAAS,IAAA,IAAQ,IAAA,CAAK,KAAA,KAAU,UAAA,EAAY;AAC9C,MAAA,OAAO,CAAA,YAAA,EAAe,gBAAgB,CAAA,aAAA,EAAgB,IAAA,CAAK,KAAK,CAAA,CAAA;AAAA,IAClE;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT","file":"index.cjs","sourcesContent":["/**\n * types.ts — the public contract of the Agent Readability Score, ARS 0.2.\n *\n * Transcribed from `docs/design/universal-gateway-and-public-surfaces.md` §3.9,\n * which is the decided contract. Where §3.9 abbreviates (it writes `id: string`\n * for a check id whose format it then demonstrates), this file fills the gap\n * consistently with the §3.4 dimension table and the §3.6 scoring tables. Two\n * deliberate narrowings and one addition are marked NARROWED / ADDED below;\n * nothing else departs from the design.\n *\n * WHY THE TYPES MATTER MORE THAN USUAL HERE. ARS is published as a standard\n * (`docs/spec/ars-0.2.md`, rendered at `/spec/ars`), and its determinism\n * guarantee is stated as: *for a given `evidenceHash`, `rulesetHash` and\n * `corpusHash`, `score()` returns a byte-identical `ArsResult` in any conformant\n * implementation, in any language.* A second implementation in Go or Python\n * reproduces `expected.json` from the conformance corpus, and these types are\n * the schema of that file. A field added casually here is a field an outside\n * team has to reverse-engineer.\n *\n * SHAPE OF THE SYSTEM. The impure half (`./probe`) produces exactly one thing:\n * an `ArsEvidence` bundle. The pure half (`.`) consumes exactly that, plus an\n * `ArsRuleset`, and produces an `ArsResult`. There is no third input — no\n * clock, no network, no randomness, no LLM. The ESLint rule in\n * `eslint.config.mjs` enforces that at build time.\n */\n\n/**\n * The spec version this package implements. See §3.1 for the versioning rules.\n *\n * THIS IS THE SECOND PLACE THE VERSION IS WRITTEN — `DEFAULT_RULESET.version` is\n * the first — and the two are asserted equal in `tests/score.test.ts` for the\n * same reason `SUBPOINTS` is asserted against `WEIGHTS`: they disagreed once,\n * during the 0.2 rebalance, and the visible symptom was every result printing\n * `specVersion: '0.1.0'` next to a 0.2 `rulesetHash`. A score whose two identity\n * fields name different versions is worse than one that names neither.\n *\n * It cannot simply be re-exported from the ruleset: `types.ts` is the bottom of\n * the import graph and `ruleset.ts` imports from it.\n */\nexport const ARS_SPEC_VERSION = '0.2.0' as const\n\n/**\n * Where the scan was taken from.\n * - `public` — an anonymous third-party scan. The only vantage that is robots-gated.\n * - `authenticated` — a signed-in Rebilder user scanning a domain they have verified.\n * - `self` — the site's own operator (Console, or the CLI run against their own\n * origin). Bypasses the `rebilder-ars` token check, because the owner can\n * consent for their own origin (§3.7).\n */\nexport type ArsVantage = 'public' | 'authenticated' | 'self'\n\n/**\n * Whether a check's earned points come from an observation or from an inference.\n * Published per check, and the total heuristic weight is capped at 40 of 100\n * (37 in 0.2) and printed. See §5.1.\n */\nexport type ArsBasis = 'measured' | 'heuristic'\n\nexport type ArsGrade = 'A' | 'B' | 'C' | 'D' | 'F'\n\n/**\n * The three crawler audiences (§3.7). `training` is strictly neutral: blocking\n * training crawlers while allowing assistants scores identically to a fully open\n * site (conformance fixtures 021 and 022 exist to prove exactly that).\n */\nexport type ArsAudience = 'assistant' | 'training' | 'search'\n\nexport type ArsUnscoredReason =\n | 'blocked-at-edge'\n | 'unreachable'\n | 'non-2xx'\n | 'too-many-redirects'\n | 'robots-disallow-scanner'\n | 'robots-unavailable'\n | 'truncated-evidence'\n | 'evidence-incomplete'\n\n/**\n * The three outcomes. Two of them carry no letter grade at all: a deliberate\n * opt-out is a choice, not a failure, and an unscored target is a missing\n * observation, not a bad one. Neither is ever ranked or listed (§3.6).\n */\nexport type ArsOutcome =\n | { kind: 'scored'; grade: ArsGrade; score: number }\n | { kind: 'opt-out'; audience: ArsAudience; wellFormed: true }\n | { kind: 'unscored'; reason: ArsUnscoredReason; detail?: string }\n\n/* ── evidence: the impure half's output, the pure half's only input ───────── */\n\nexport interface ArsHttpCapture {\n requestedUrl: string\n finalUrl: string\n redirects: { status: number; location: string }[]\n status: number\n /**\n * Lowercased header names → all values. An array, not a string, because\n * `Link` is routinely sent multiple times and is scored (D2.2, D6.5).\n * Volatile headers (`date`, `age`, `set-cookie`, `x-request-id`, `cf-ray`,\n * `report-to`) are excluded before hashing — without that exclusion the\n * evidence hash changes on every scan of every real site and replay dies.\n */\n headers: Record<string, string[]>\n /**\n * Decoded byte length. NORMATIVE MEASUREMENT — bodies are decoded per the\n * `Content-Type` charset (default UTF-8) and this is the UTF-8 byte length of\n * the result, so a Go implementation reproduces D3.2 and D4 offsets exactly.\n */\n bytes: number\n /** SHA-256 of the raw decoded body, hex. Published; the body is not. */\n bodySha256: string\n /** Present in-process and for a verified owner. NEVER in a published bundle. */\n body?: string\n /**\n * True when the 2 MiB body cap was hit. Surfaced in the UI and the byte figure\n * rendered as \"≥ N bytes\": silently scoring a truncated body makes the worst\n * sites score best on the one number the product is built on (§3.3).\n */\n truncated: boolean\n}\n\nexport type ArsProbeError =\n | 'timeout'\n | 'unreachable'\n | 'non-2xx'\n | 'blocked-redirect'\n | 'too-many-redirects'\n | 'challenge'\n | 'policy-rejected'\n\nexport interface ArsProbeRecord {\n requestHeaders: Record<string, string>\n result:\n | { ok: true; capture: ArsHttpCapture }\n | { ok: false; error: ArsProbeError; detail?: string }\n}\n\nexport interface ArsEvidence {\n evidenceVersion: '0.1.0'\n target: { url: string; origin: string }\n /**\n * `agent` and `browser` differ ONLY in the `Accept` header — same User-Agent,\n * same everything else. That is what makes the D2.4 parity check meaningful\n * and what stops a correctly installed gateway (which negotiates on `Accept`,\n * not on UA) from being scored as a cloaker (§3.3).\n */\n probes: {\n agent: ArsProbeRecord\n browser: ArsProbeRecord\n /** Third probe, ≥30s later, taken only when divergence was detected (§3.8). */\n parityConfirm: ArsProbeRecord | null\n robotsTxt: ArsProbeRecord | null\n llmsTxt: ArsProbeRecord | null\n wellKnownUcp: ArsProbeRecord | null\n }\n vantage: ArsVantage\n /** Wall clock. EXCLUDED from evidenceHash — never an input to scoring. */\n capturedAt: string\n}\n\n/* ── facts ───────────────────────────────────────────────────────────────── */\n\n/**\n * A closed set of 8. Every kind has exactly one complete profile (see\n * `./profiles`); a property test asserts the mapping is total. `unknown` is not\n * an easy exit — it still scores D5.2 against \"any recognised schema.org type\n * present\", so hiding your page kind costs points and gains nothing (§3.5).\n */\nexport type ArsPageKind =\n | 'product'\n | 'collection'\n | 'article'\n | 'place'\n | 'service'\n | 'faq'\n | 'document'\n | 'unknown'\n\n/**\n * Every fact name any profile may reference. Conformance fixture `058` asserts\n * that every name in every profile is a member of this union — the union is the\n * vocabulary, and a profile naming a fact outside it is a spec bug.\n */\nexport type ArsFactKind =\n | 'title'\n | 'description'\n | 'updated'\n | 'published'\n | 'price'\n | 'currency'\n | 'availability'\n | 'brand'\n | 'sku'\n | 'shipping'\n | 'returns'\n | 'org-name'\n | 'address'\n | 'hours'\n | 'phone'\n | 'email'\n | 'service-area'\n | 'author'\n | 'section'\n | 'authority'\n | 'primary-action-url'\n | 'eligibility'\n | 'duration'\n | 'question-answer'\n | 'item-count'\n | 'item-link'\n\nexport interface ArsFactProfile {\n pageKind: ArsPageKind\n core: readonly ArsFactKind[]\n extended: readonly ArsFactKind[]\n /**\n * Byte reference for D3.2, in bytes. Varies by kind; weights never do. This\n * is the mechanism that stops long-form content (articles, docs) being\n * structurally capped around C — the defect in every design that used\n * absolute byte bands (§3.5).\n */\n byteReference: number\n}\n\nexport interface ArsFactObservation {\n kind: ArsFactKind\n /** Normalised (money → minor units + ISO currency; dates → ISO 8601). */\n normalized: string\n source: 'json-ld' | 'microdata' | 'meta' | 'html-text' | 'negotiated'\n /**\n * UTF-8 byte offset of the first occurrence in the decoded body. A measured\n * offset of a heuristic fact — the offset itself is not a guess, which is why\n * D4 reports it as evidence even though D4's checks are heuristic.\n */\n offset: number\n /** Observed in ≥2 sources (e.g. JSON-LD and visible text). §3.6. */\n corroborated: boolean\n}\n\n/* ── scoring ─────────────────────────────────────────────────────────────── */\n\nexport type ArsDimensionId =\n | 'retrievability'\n | 'machine-representation'\n | 'fact-coverage'\n | 'fact-position'\n | 'structured-data'\n | 'contract-discovery'\n | 'evidence-density'\n\n/**\n * Every check id in ARS 0.2, in dimension order, matching the §5.1 table row for\n * row. The `<dimension>.<check>` shape is normative: the prefix IS the\n * `ArsDimensionId`, so a check's dimension is derivable from its id and the two\n * can never disagree. §3.9 demonstrates the format with\n * `'retrievability.render-independence'` and leaves the rest implied; this is\n * that list, written out.\n *\n * NARROWED vs §3.9: `ArsCheck['id']` is this union rather than `string`. These\n * ids are published in the spec and appear in every `expected.json`; an\n * unconstrained string in a frozen contract is a typo waiting to ship.\n */\nexport type ArsCheckId =\n // D1 Retrievability — 20\n | 'retrievability.reachable' // D1.1, 8, measured\n | 'retrievability.robots-policy' // D1.2, 6, measured\n | 'retrievability.render-independence' // D1.3, 6, heuristic\n // D2 Machine representation — 20\n | 'machine-representation.negotiated-response' // D2.1, 10, measured\n | 'machine-representation.declared-alternates' // D2.2, 4, measured\n | 'machine-representation.vary-accept' // D2.3, 3, measured\n | 'machine-representation.substance-parity' // D2.4, 3, heuristic\n // D3 Fact coverage — 20\n | 'fact-coverage.core-facts' // D3.1, 14, heuristic\n | 'fact-coverage.context-cost' // D3.2, 6, measured\n // D4 Fact position — 10\n | 'fact-position.first-core-fact-offset' // D4.1, 5, heuristic\n | 'fact-position.front-window' // D4.2, 5, heuristic\n // D5 Structured data — 15\n | 'structured-data.present' // D5.1, 5, measured\n | 'structured-data.required-properties' // D5.2, 7, measured\n | 'structured-data.text-agreement' // D5.3, 3, heuristic\n // D6 Contract & discovery — 15\n | 'contract-discovery.canonical' // D6.1, 4, measured\n | 'contract-discovery.cache-validators' // D6.2, 3, measured\n | 'contract-discovery.llms-txt' // D6.3, 2, measured\n | 'contract-discovery.sitemap' // D6.4, 2, measured\n | 'contract-discovery.machine-endpoint' // D6.5, 2, measured\n // D7 Evidence density — 8\n | 'evidence-density.quantities' // D7.1, 4, measured\n | 'evidence-density.definitions' // D7.2, 2, heuristic\n | 'evidence-density.comparisons' // D7.3, 2, measured\n\nexport interface ArsCheckEvidence {\n label: string\n value: string\n basis: ArsBasis\n}\n\nexport interface ArsCheck {\n /** e.g. 'retrievability.render-independence'. */\n id: ArsCheckId\n label: string\n basis: ArsBasis\n weight: number\n /** Integer, 0..weight. No floating point anywhere in the scoring path (§3.6). */\n earned: number\n evidence: ArsCheckEvidence[]\n remedy?: string\n}\n\nexport interface ArsDimension {\n id: ArsDimensionId\n label: string\n weight: number\n earned: number\n /** 'heuristic' if ANY constituent check is heuristic. */\n basis: ArsBasis\n checks: ArsCheck[]\n}\n\nexport type ArsFlagId =\n | 'substance-divergence'\n | 'structured-data-divergence'\n | 'robots-contradiction'\n | 'paywalled'\n | 'render-dependent'\n | 'scanner-blocked'\n | 'training-opt-out'\n | 'assistant-opt-out'\n | 'vary-missing'\n | 'canonical-mismatch'\n | 'body-truncated'\n | 'vantage-variance'\n\nexport interface ArsFlag {\n id: ArsFlagId\n /**\n * No 'critical'. No check publicly accuses anyone: a divergence flag reports\n * *\"the agent representation reported price X; the HTML representation\n * reported price Y at capture time\"*, which is an observation, not a charge of\n * cloaking (§3.8).\n */\n severity: 'info' | 'warn'\n basis: ArsBasis\n message: string\n evidence: ArsCheckEvidence[]\n}\n\nexport interface ArsAudienceDecision {\n decision: 'allow' | 'disallow' | 'unspecified'\n matchedGroup: string | null\n matchedRule: string | null\n}\n\nexport interface ArsPolicyReport {\n robotsTxtStatus: 'ok' | 'missing' | 'error' | 'unparseable'\n audiences: Record<ArsAudience, ArsAudienceDecision>\n deliberateOptOut: boolean\n /** NEUTRAL. Never lowers the score. */\n trainingOptOut: boolean\n sitemapDeclared: boolean\n}\n\nexport interface ArsCostReport {\n htmlBytes: number\n negotiatedBytes: number | null\n /** HEURISTIC (chars/4). Always rendered with ≈ and an \"est.\" chip. */\n approxHtmlTokens: number\n approxNegotiatedTokens: number | null\n reductionRatio: number | null\n firstCoreFactOffset: number | null\n truncated: boolean\n}\n\nexport interface ArsRecommendation {\n id: string\n title: string\n /**\n * Points recoverable, after dependency dedup: a recommendation counts only\n * checks not claimed by a higher-ranked recommendation, plus the checks it\n * uniquely unlocks. Sums per dimension are capped at the dimension weight, and\n * a property test asserts `Σ pointsAvailable ≤ 100 − score` (§3.9). Merchants\n * act on this surface, so the arithmetic is specified rather than implied.\n */\n pointsAvailable: number\n effort: 'config' | 'template' | 'engineering'\n detail: string\n /** Check ids this closes. */\n checks: ArsCheckId[]\n /** Check ids it unlocks (e.g. D2.1 unlocks D2.3, which is gated on it). */\n unlocks: ArsCheckId[]\n}\n\nexport interface ArsResult {\n spec: 'ars'\n specVersion: string\n /** SHA-256 of RFC 8785 canonical JSON of the frozen ruleset. */\n rulesetHash: string\n /** SHA-256 over the conformance corpus; pins observable behaviour. */\n corpusHash: string\n evidenceHash: string\n vantage: ArsVantage\n target: { url: string; finalUrl: string; origin: string }\n\n outcome: ArsOutcome\n score: number | null\n grade: ArsGrade | null\n bandLabel: string | null\n\n pageKind: ArsPageKind\n pageKindBasis: ArsBasis // always 'heuristic' in 0.1\n pageKindConfidence: 'high' | 'medium' | 'low'\n factProfile: ArsFactProfile\n facts: ArsFactObservation[]\n\n /** Always 6 entries, weights always summing to 100. */\n dimensions: ArsDimension[]\n flags: ArsFlag[]\n policy: ArsPolicyReport\n cost: ArsCostReport\n recommendations: ArsRecommendation[]\n\n measuredWeight: number // 64 in 0.1\n heuristicWeight: number // 36 in 0.1; ceiling 40, enforced by fixture 053\n}\n\nexport interface ArsBand {\n grade: ArsGrade\n min: number\n max: number\n label: string\n /** Descriptive only. Never predictive of third-party AI behaviour (§3.6). */\n meaning: string\n}\n\n/**\n * The frozen, hashed ruleset. Everything a second implementation needs to\n * reproduce a score, and nothing that varies between runs.\n *\n * ADDED vs §3.9: `timeoutMs`. §3.9's listing stops at `maxRedirects`, but §5.2\n * pins the probe timeout at 5 000ms in the same breath as the body cap and the\n * redirect limit, and the same argument applies to all three — two\n * implementations with different timeouts disagree about which pages are\n * scoreable at all, which is a score difference wearing a disguise.\n */\nexport interface ArsRuleset {\n version: string\n /** Check id → points. Must sum to exactly 100. Frozen per version. */\n weights: Readonly<Record<string, number>>\n /**\n * The §3.6 numeric bands, as flat integer arrays. Each key documents its own\n * encoding in `./ruleset`; all of them are `[threshold, value]` pairs so that a\n * second implementation reads one shape, not five.\n */\n thresholds: Readonly<Record<string, readonly number[]>>\n /** Robots `User-agent:` tokens per audience. Matched case-insensitively. */\n audienceTokens: Readonly<Record<ArsAudience, readonly string[]>>\n /** Hand-curated required properties per page kind. Provenance in the spec. */\n requiredProperties: Readonly<Record<ArsPageKind, readonly string[]>>\n /** Anchor/action phrases that qualify a link as `primary-action-url` (§3.5). */\n actionLexicon: readonly string[]\n maxBodyBytes: number // 2 MiB, normative\n maxRedirects: number // 3, normative\n timeoutMs: number // 5_000, normative (see the ADDED note above)\n profiles: readonly ArsFactProfile[] // total over ArsPageKind\n bands: readonly ArsBand[]\n}\n","/**\n * profiles.ts — the eight page-kind fact profiles. Design §3.5, table verbatim.\n *\n * THE ONE IDEA IN THIS FILE. ARS uses fixed weights for every page kind. What\n * varies is *what counts as a fact* and *what a page of that kind reasonably\n * costs*:\n *\n * > ARS does not measure how much you say. It measures whether the facts a\n * > caller needs **for this kind of page** are present, findable, and cheap\n * > **relative to what that kind of page costs**.\n *\n * Per-vertical *weights* would be the wrong design — it makes an 88 mean\n * different things on different pages and invites site-type shopping. A\n * per-vertical *fact set* and *byte reference* are not weights: an article that\n * spends 38 KB saying something is not penalised against a 40 KB reference,\n * while a product page that spends 38 KB to state four facts is. The byte\n * reference is specifically what stops long-form content being structurally\n * capped around C, which every source design that used absolute byte bands did.\n *\n * The set is CLOSED at eight, and every kind has a complete profile — there is\n * no \"no profile\" path. Conformance fixture `058-profiles-total-and-typed`\n * asserts both halves of that: the mapping is total over `ArsPageKind`, and\n * every fact name is a member of `ArsFactKind`. `PROFILE_BY_KIND` is typed as a\n * total `Record`, so the first half is also a compile error.\n *\n * `unknown` is deliberately not an easy exit. It carries the smallest core set,\n * but it still scores D5.2 against \"any recognised schema.org type present\",\n * which requires having a type at all. Hiding your page kind costs up to 7\n * points and gains nothing on coverage.\n *\n * ── Definitions of the fact terms the source designs left undefined (§3.5) ──\n *\n * `primary-action-url` — a same-origin-or-declared URL reachable from an\n * `<a href>`, a `<form action>`, or JSON-LD `potentialAction.target`, whose\n * anchor text or `name` matches the ruleset's action lexicon (`book`, `apply`,\n * `contact`, `buy`, `subscribe`, `start`, `request`, `download`, `sign up`,\n * `get a quote` and their pinned synonyms). The lexicon is pinned in\n * `DEFAULT_RULESET.actionLexicon`, not inferred per page.\n *\n * `authority` — an organisation or person named as the publisher of the content,\n * extracted from JSON-LD `publisher`/`author`, `<meta name=\"author\">`, or a\n * `rel=\"publisher\"` link.\n *\n * `org-name` — JSON-LD `Organization.name` / `LocalBusiness.name`,\n * `og:site_name`, or `<meta itemprop=\"name\">` on an org-typed scope.\n *\n * `item-count` / `item-link` — for `collection`: the number of distinct item\n * links inside the largest repeated-structure block, and whether those links\n * resolve to same-origin URLs. Counted from the largest repeated block\n * specifically so that a nav menu is not mistaken for a product grid.\n *\n * `question-answer` — a `FAQPage`/`Question` JSON-LD pair, or a `<dt>/<dd>`, a\n * `<details><summary>`, or a heading-followed-by-paragraph pair. Counted ONCE\n * as present, not per item: a page with 40 questions is not four times better\n * than a page with 10.\n *\n * `price` is satisfied by an explicit \"no published price\" signal as well as by\n * a number. We score honesty, not disclosure — a service page that says\n * \"pricing on request\" has told the agent what it needs to know.\n */\n\nimport type { ArsFactProfile, ArsPageKind } from './types'\n\n/**\n * The §3.5 table, one entry per `ArsPageKind`. Core facts score at full weight,\n * extended facts at ¼ credit (the single definition — the source designs used\n * ¼, ½ and \"half credit\" in three different places). Byte references are the\n * D3.2 denominator, in bytes.\n */\nexport const PROFILE_BY_KIND = {\n product: {\n pageKind: 'product',\n core: ['title', 'price', 'currency', 'availability'],\n extended: ['brand', 'sku', 'shipping', 'returns', 'description'],\n byteReference: 8 * 1024,\n },\n collection: {\n pageKind: 'collection',\n core: ['title', 'item-count', 'item-link'],\n extended: ['price', 'availability', 'description'],\n byteReference: 16 * 1024,\n },\n article: {\n pageKind: 'article',\n core: ['title', 'author', 'published'],\n extended: ['updated', 'section', 'description'],\n byteReference: 40 * 1024,\n },\n place: {\n pageKind: 'place',\n core: ['org-name', 'address', 'hours', 'phone'],\n extended: ['email', 'service-area', 'primary-action-url', 'description'],\n byteReference: 8 * 1024,\n },\n service: {\n pageKind: 'service',\n core: ['title', 'price', 'primary-action-url'],\n extended: ['duration', 'eligibility', 'service-area', 'description', 'updated'],\n byteReference: 8 * 1024,\n },\n faq: {\n pageKind: 'faq',\n core: ['title', 'question-answer'],\n extended: ['updated', 'description'],\n byteReference: 16 * 1024,\n },\n document: {\n pageKind: 'document',\n core: ['title', 'updated', 'authority'],\n extended: ['description', 'primary-action-url', 'section'],\n byteReference: 24 * 1024,\n },\n unknown: {\n pageKind: 'unknown',\n core: ['title', 'description', 'primary-action-url'],\n extended: ['updated', 'org-name'],\n byteReference: 16 * 1024,\n },\n} as const satisfies Record<ArsPageKind, ArsFactProfile>\n\n/**\n * The same eight profiles as the array `ArsRuleset.profiles` expects, in\n * declaration order (which is the order they appear in the §3.5 table, and is\n * therefore the order the spec renders them in).\n *\n * Runtime immutability: `as const` above makes every profile deeply readonly to\n * TypeScript, and `DEFAULT_RULESET` deep-freezes these exact objects at module\n * load, so a consumer cannot mutate a shared profile and silently change every\n * subsequent score.\n */\nexport const PROFILES: readonly ArsFactProfile[] = Object.freeze(Object.values(PROFILE_BY_KIND))\n\n/** Total by construction — `PROFILE_BY_KIND` is typed as a total Record. */\nexport function profileFor(pageKind: ArsPageKind): ArsFactProfile {\n return PROFILE_BY_KIND[pageKind]\n}\n","/**\n * ruleset.ts — `DEFAULT_RULESET`, the frozen ARS 0.2 ruleset.\n *\n * WHAT THIS FILE IS. Every number a second implementation needs in order to\n * reproduce a score, and nothing that varies between runs. `rulesetHash()` is\n * the SHA-256 of the RFC 8785 canonical JSON of this object, it is printed on\n * every result, and the determinism guarantee is stated in terms of it: a\n * number without `rulesetHash`, `corpusHash` and `evidenceHash` is not an ARS\n * score. That makes this file a published artifact, not configuration.\n *\n * CONSEQUENCE: editing a number here is a spec version change, not a code\n * change. Per §3.1, any edit that moves a conformance `expected.json` is at\n * minimum a MINOR — and MINOR means scores stop being comparable and every\n * published surface re-scores in a batch. The CI gate on PATCH releases exists\n * precisely so that \"just tweaking a threshold\" cannot happen quietly.\n *\n * WHY THE BODY CAP, REDIRECT LIMIT AND TIMEOUT LIVE HERE rather than in the\n * probe: two implementations with different caps produce different scores. A\n * 3 MiB cap turns a `truncated-evidence` non-grade into an F, and a 10s timeout\n * scores pages a 5s timeout reports as unreachable. They are inputs to the\n * score, so they are inputs to the hash.\n *\n * SHAPE. Everything is `as const satisfies <contract>`: the `satisfies` clause\n * proves the object matches the published type (and, for the tables keyed by\n * `ArsCheckId` / `ArsPageKind`, that it is TOTAL), while `as const` keeps the\n * literal types so callers get `number`, not `number | undefined`, from a known\n * key. `deepFreeze` then makes it immutable at runtime as well — a mutated\n * shared ruleset would corrupt every subsequent score in the process, silently.\n */\n\nimport { PROFILES } from './profiles'\nimport type {\n ArsBand,\n ArsBasis,\n ArsCheckId,\n ArsDimensionId,\n ArsPageKind,\n ArsRuleset,\n} from './types'\n\n// ---------------------------------------------------------------------------\n// Deep freeze\n// ---------------------------------------------------------------------------\n\n/**\n * Recursively freezes a plain data structure. Used once, on `DEFAULT_RULESET`.\n * `as const` is a compile-time guarantee only; this is the runtime half.\n */\nfunction deepFreeze<T>(value: T): T {\n if (typeof value !== 'object' || value === null) return value\n for (const child of Object.values(value as Record<string, unknown>)) deepFreeze(child)\n return Object.freeze(value)\n}\n\n// ---------------------------------------------------------------------------\n// Check weights — the §3.4 table, row for row\n// ---------------------------------------------------------------------------\n\n/**\n * Check id → points. Sums to exactly 100 across 22 checks.\n *\n * NO CONDITIONAL WEIGHTS. NO REDISTRIBUTION. NO HEURISTIC GATES OVER MEASURED\n * POINTS. Redistribution is a gaming vector (make the dimension you are bad at\n * inapplicable and the rest inflate), and a heuristic that can zero measured\n * points makes those points heuristic. So D2.4 and D5.3 are scored checks, not\n * gates: a parity failure loses its own 3 points and raises a `warn`, and does\n * not touch D2's other measured points. That is what makes \"measured 63 /\n * heuristic 37\" an honest figure rather than a presentational one, and fixture\n * `053` re-derives the heuristic-*controlled* weight to prove it.\n *\n * `satisfies Record<ArsCheckId, number>` makes the table total: a check id\n * added to the union without a weight here is a compile error.\n */\nconst WEIGHTS = {\n // D1 Retrievability — 28\n 'retrievability.reachable': 11,\n 'retrievability.robots-policy': 10,\n 'retrievability.render-independence': 7,\n // D2 Machine representation — 18\n 'machine-representation.negotiated-response': 9,\n 'machine-representation.declared-alternates': 3,\n 'machine-representation.vary-accept': 3,\n 'machine-representation.substance-parity': 3,\n // D3 Fact coverage — 20\n 'fact-coverage.core-facts': 14,\n 'fact-coverage.context-cost': 6,\n // D4 Fact position — 10\n 'fact-position.first-core-fact-offset': 5,\n 'fact-position.front-window': 5,\n // D5 Structured data — 6\n 'structured-data.present': 2,\n 'structured-data.required-properties': 3,\n 'structured-data.text-agreement': 1,\n // D6 Contract & discovery — 10\n 'contract-discovery.canonical': 4,\n 'contract-discovery.cache-validators': 2,\n 'contract-discovery.llms-txt': 1,\n 'contract-discovery.sitemap': 1,\n 'contract-discovery.machine-endpoint': 2,\n // D7 Evidence density — 8\n 'evidence-density.quantities': 4,\n 'evidence-density.definitions': 2,\n 'evidence-density.comparisons': 2,\n} as const satisfies Record<ArsCheckId, number>\n\n/** Descriptive metadata per check: which dimension it belongs to, its published label, its basis. */\nexport interface ArsCheckMeta {\n dimension: ArsDimensionId\n label: string\n basis: ArsBasis\n}\n\n/**\n * The published catalogue of checks. `dimension` is redundant with the check id\n * prefix by construction — the id shape `<dimension>.<check>` is normative — and\n * is spelled out anyway so consumers never parse an id string to group results.\n *\n * `basis` is spec data (it appears in every `expected.json` and is printed next\n * to every check in the UI) but it is not part of `ArsRuleset` in §3.9, so it is\n * exported here rather than folded into the hashed object. A second\n * implementation reads it from the published §3.4 table.\n */\nexport const CHECK_META = {\n 'retrievability.reachable': {\n dimension: 'retrievability',\n label: 'Reachable on the agent path',\n basis: 'measured',\n },\n 'retrievability.robots-policy': {\n dimension: 'retrievability',\n label: 'Robots policy for assistants',\n basis: 'measured',\n },\n 'retrievability.render-independence': {\n dimension: 'retrievability',\n label: 'Core facts present without JavaScript',\n basis: 'heuristic',\n },\n 'machine-representation.negotiated-response': {\n dimension: 'machine-representation',\n label: 'Machine representation on Accept negotiation',\n basis: 'measured',\n },\n 'machine-representation.declared-alternates': {\n dimension: 'machine-representation',\n label: 'Declared alternate representations',\n basis: 'measured',\n },\n 'machine-representation.vary-accept': {\n dimension: 'machine-representation',\n label: 'Vary: Accept declared correctly',\n basis: 'measured',\n },\n 'machine-representation.substance-parity': {\n dimension: 'machine-representation',\n label: 'Same substance across representations',\n basis: 'heuristic',\n },\n 'fact-coverage.core-facts': {\n dimension: 'fact-coverage',\n label: 'Core facts for this page kind',\n basis: 'heuristic',\n },\n 'fact-coverage.context-cost': {\n dimension: 'fact-coverage',\n label: 'Context cost relative to this page kind',\n basis: 'measured',\n },\n 'fact-position.first-core-fact-offset': {\n dimension: 'fact-position',\n label: 'Byte offset of the first core fact',\n basis: 'heuristic',\n },\n 'fact-position.front-window': {\n dimension: 'fact-position',\n label: 'Core facts inside the front window',\n basis: 'heuristic',\n },\n 'structured-data.present': {\n dimension: 'structured-data',\n label: 'Structured data present and parsing',\n basis: 'measured',\n },\n 'structured-data.required-properties': {\n dimension: 'structured-data',\n label: 'Recognised type with its required properties',\n basis: 'measured',\n },\n 'structured-data.text-agreement': {\n dimension: 'structured-data',\n label: 'Structured data agrees with visible text',\n basis: 'heuristic',\n },\n 'contract-discovery.canonical': {\n dimension: 'contract-discovery',\n label: 'Canonical URL present and self-consistent',\n basis: 'measured',\n },\n 'contract-discovery.cache-validators': {\n dimension: 'contract-discovery',\n label: 'Cache validators',\n basis: 'measured',\n },\n 'contract-discovery.llms-txt': {\n dimension: 'contract-discovery',\n label: 'llms.txt present and spec-shaped',\n basis: 'measured',\n },\n 'contract-discovery.sitemap': {\n dimension: 'contract-discovery',\n label: 'Sitemap declared in robots.txt',\n basis: 'measured',\n },\n 'contract-discovery.machine-endpoint': {\n dimension: 'contract-discovery',\n label: 'Declared machine endpoint',\n basis: 'measured',\n },\n 'evidence-density.quantities': {\n dimension: 'evidence-density',\n label: 'Quantities an answer can quote',\n basis: 'measured',\n },\n 'evidence-density.definitions': {\n dimension: 'evidence-density',\n label: 'Labelled term and value pairs',\n basis: 'heuristic',\n },\n 'evidence-density.comparisons': {\n dimension: 'evidence-density',\n label: 'Comparable rows',\n basis: 'measured',\n },\n} as const satisfies Record<ArsCheckId, ArsCheckMeta>\n\n/**\n * The six dimensions and their frozen weights (§3.4): 20 · 20 · 20 · 10 · 15 ·\n * 15 = 100, identical for every page kind. Each weight is the sum of its\n * checks' weights in `WEIGHTS`; both are written out because both are published,\n * and conformance fixture `052` asserts they agree and that the total is 100.\n */\nexport const DIMENSION_META = {\n retrievability: { label: 'Retrievability', weight: 28 },\n 'machine-representation': { label: 'Machine representation', weight: 18 },\n 'fact-coverage': { label: 'Fact coverage', weight: 20 },\n 'fact-position': { label: 'Fact position', weight: 10 },\n 'structured-data': { label: 'Structured data', weight: 6 },\n 'contract-discovery': { label: 'Contract & discovery', weight: 10 },\n 'evidence-density': { label: 'Evidence density', weight: 8 },\n} as const satisfies Record<ArsDimensionId, { label: string; weight: number }>\n\n/**\n * Published totals (§3.4). Heuristic weight has a spec ceiling of 40; fixture\n * `053` enforces it, and the ceiling is what shaped D7's basis split rather\n * than the other way round. Labelling `definitions` measured would have bought\n * three points of headroom and made \"measured 63\" a presentational number\n * instead of an honest one, which is the exact failure the ceiling exists to\n * prevent.\n */\nexport const ARS_MEASURED_WEIGHT = 63\nexport const ARS_HEURISTIC_WEIGHT = 37\nexport const ARS_HEURISTIC_WEIGHT_CEILING = 40\n\n// ---------------------------------------------------------------------------\n// Thresholds — the §3.6 scoring tables, as integer pairs\n// ---------------------------------------------------------------------------\n\n/**\n * All numeric bands from §3.6, encoded as flat `[threshold, value]` pairs so a\n * second implementation reads one shape rather than five. Integer arithmetic\n * only: no floating point anywhere in the scoring path, because cross-language\n * conformance is impossible with float rounding drift. All values are\n * non-negative, so rounding is unambiguous half-up via\n * `(numerator + denominator / 2) / denominator` in integer division.\n *\n * Two encodings, each stated per key:\n * AT-LEAST — descending pairs; the first pair whose `threshold <= input` wins.\n * AT-MOST — ascending pairs; the first pair whose `input <= threshold` wins;\n * no match scores 0.\n */\nconst THRESHOLDS = {\n /**\n * D3.1 fact weighting, in quarter-units (§3.6), as\n * `[corroboratedCore, uncorroboratedCore, corroboratedExtended, uncorroboratedExtended]`:\n * coreUnits = 4 × corroborated core + 2 × uncorroborated core\n * extendedUnits = 1 × corroborated extended + 0 × uncorroborated extended\n * \"Extended = ¼ credit\" is the single definition of extended credit.\n */\n 'fact-coverage.fact-units': [4, 2, 1, 0],\n /**\n * D3.1 denominator multiplier: `denominator = 4 × coreSize`, i.e. full credit\n * is every core fact corroborated. `coveragePct` is then\n * `min(100, (100 × (coreUnits + extendedUnits) + denominator / 2) / denominator)`.\n */\n 'fact-coverage.core-denominator-multiplier': [4],\n /**\n * D3.1 density band. AT-LEAST over\n * `factsPerKiB100 = (coreFound × 100 + extendedFound × 25) × 1024 / max(1, bytes)`.\n * The `max(1, bytes)` clamp is normative and replaces `max(1, bytes / 1024)`,\n * which let a 200-byte stub top the band. Density saturates at ≥2 facts/KiB so\n * that keyword stuffing is pointless — fixtures `031` and `032` must score\n * identically.\n * Earned = `(14 × coveragePct × densityPct + 5000) / 10000`.\n */\n 'fact-coverage.density': [200, 100, 100, 85, 50, 70, 20, 50, 5, 30, 0, 15],\n /**\n * D3.2 context cost, 6 pts. AT-MOST over\n * `ratio = 100 × bytes / byteReference[pageKind]`; above the last threshold, 0.\n */\n 'fact-coverage.context-cost': [100, 6, 200, 5, 500, 3, 1500, 1],\n /**\n * D7.1 quantities, 4 pts. AT-LEAST over the count of DISTINCT quantity tokens\n * in the agent's counted text: a currency amount, a percentage, a number\n * carrying a unit, or an ISO date. Distinct, because a price repeated in a\n * header, a buy box and a footer is one fact stated three times, and counting\n * it three times would reward the repetition this score exists to discourage.\n * Saturates at 12 so a specification table cannot outscore a page that simply\n * states its facts.\n */\n 'evidence-density.quantities': [12, 4, 6, 3, 3, 2, 1, 1],\n /**\n * D7.2 definitions, 2 pts. AT-LEAST over the count of `term: value` pairs the\n * agent can read as a labelled fact, counting markdown bold-label lines,\n * list items with a leading label, and HTML definition lists.\n */\n 'evidence-density.definitions': [6, 2, 2, 1],\n /**\n * D7.3 comparisons, 2 pts. AT-LEAST over the number of comparable ROWS: a\n * table with at least two data columns contributes its data-row count, minus\n * the header. One row is not a comparison, so the band starts at two; three\n * options laid side by side is a full comparison and pays out. Calibrated\n * against fixture `060`, where a three-row size table is exactly the shape\n * this check exists to reward, and `063`, where one row is not.\n */\n 'evidence-density.comparisons': [3, 2, 2, 1],\n /** D4.1 first-core-fact byte offset, 5 pts. AT-MOST over the offset in bytes; else 0. */\n 'fact-position.first-core-fact-offset': [512, 5, 2048, 4, 8192, 2, 32768, 1],\n /**\n * D4.2 front window, 5 pts. AT-LEAST over the percentage of core facts whose\n * offset falls inside the window; below the last threshold, 0.\n */\n 'fact-position.front-window': [90, 5, 70, 4, 50, 3, 25, 1],\n /**\n * D4.2 window size: `max(2048, bytes / 5)`, as `[floor, divisor]`. ONE\n * expression, integer division — the `0.2 × bytes` form is deleted, because\n * two implementations rounding a float disagree at the boundary.\n */\n 'fact-position.front-window-size': [2048, 5],\n /**\n * Approximate token estimate, as `[bytesPerToken]`. HEURISTIC: decoded UTF-8\n * bytes are the normative measurement and approximate tokens are always\n * rendered with `≈` and an \"est.\" chip. chars/4 is not a token count and the\n * spec says so.\n */\n 'cost.approx-bytes-per-token': [4],\n} as const satisfies Readonly<Record<string, readonly number[]>>\n\n// ---------------------------------------------------------------------------\n// Crawler audiences (§3.7)\n// ---------------------------------------------------------------------------\n\n/**\n * Robots `User-agent:` product tokens per audience, in their published casing.\n * Matching is case-insensitive (RFC 9309 §2.2.1) — the casing here is for the\n * rendered spec table.\n *\n * The `training` list exists so it can be treated NEUTRALLY. Blocking training\n * crawlers while allowing assistants scores identically to a fully open site,\n * and fixtures `021`/`022` exist solely to prove it, because it is the first\n * thing a hostile reviewer tests. `search` is reported only, and feeds the\n * `robots-contradiction` input; it never scores.\n *\n * This list is versioned data, not a heuristic: adding a token changes scores\n * for sites that named it, so additions land as a MINOR.\n */\nconst AUDIENCE_TOKENS = {\n /** User-triggered assistant fetches. THE audience ARS scores. */\n assistant: [\n 'ChatGPT-User',\n 'Claude-User',\n 'Claude-SearchBot',\n 'DuckAssistBot',\n 'Meta-ExternalFetcher',\n 'MistralAI-User',\n 'OAI-SearchBot',\n 'Perplexity-User',\n ],\n /** Corpus/model-training crawlers. STRICTLY NEUTRAL — never lowers the score. */\n training: [\n 'AI2Bot',\n 'Applebot-Extended',\n 'Bytespider',\n 'CCBot',\n 'ClaudeBot',\n 'Diffbot',\n 'FacebookBot',\n 'Google-Extended',\n 'GPTBot',\n 'Meta-ExternalAgent',\n 'PanguBot',\n 'Timpibot',\n 'anthropic-ai',\n 'cohere-ai',\n 'omgili',\n ],\n /** Classic search indexers. Reported only. */\n search: ['Applebot', 'Baiduspider', 'Bingbot', 'DuckDuckBot', 'Googlebot', 'Slurp', 'YandexBot'],\n} as const satisfies Record<'assistant' | 'training' | 'search', readonly string[]>\n\n// ---------------------------------------------------------------------------\n// D5.2 required properties (§3.6)\n// ---------------------------------------------------------------------------\n\n/**\n * The hand-curated required-property table, per page kind.\n *\n * PROVENANCE, stated because D5.2 is 7 points and merchants will ask where the\n * list came from: it is NOT \"schema.org validity\" — schema.org defines no\n * required properties at all — and it is NOT Google's rich-results guidelines by\n * reference, which change without a version and would make ARS scores move\n * without an ARS release. It is the CORE FACT SET of each page kind (see\n * `./profiles`) expressed in schema.org vocabulary, plus the properties without\n * which those facts are not actionable — a price with no `priceCurrency` cannot\n * be used by a buying agent, so `product` and `service` require both. The table\n * is bounded because it covers 8 kinds, not the full vocabulary, and it is\n * published in the spec next to this rationale.\n *\n * NOTATION: a dot is a property path from the top-level node; traversal enters\n * array members (`offers.price` matches `offers[0].price`). Alias handling\n * (`openingHours` vs `openingHoursSpecification`, `Article.headline` vs `name`)\n * belongs to the extractor, not to this table.\n *\n * `unknown` requires only `name`, deliberately: §3.5 scores `unknown` against\n * \"any recognised schema.org type present\", which requires having a type but\n * cannot require properties of a kind we did not identify.\n */\nconst REQUIRED_PROPERTIES = {\n product: ['name', 'offers.price', 'offers.priceCurrency', 'offers.availability'],\n collection: ['name', 'numberOfItems', 'itemListElement'],\n article: ['headline', 'author', 'datePublished'],\n place: ['name', 'address', 'openingHours', 'telephone'],\n service: ['name', 'offers.price', 'offers.priceCurrency', 'potentialAction.target'],\n faq: ['name', 'mainEntity', 'mainEntity.acceptedAnswer'],\n document: ['name', 'dateModified', 'publisher'],\n unknown: ['name'],\n} as const satisfies Record<ArsPageKind, readonly string[]>\n\n// ---------------------------------------------------------------------------\n// Action lexicon (§3.5)\n// ---------------------------------------------------------------------------\n\n/**\n * Phrases that qualify a link, form or `potentialAction` as the page's\n * `primary-action-url`. Matched case-insensitively against normalised anchor\n * text / `name`, whitespace collapsed.\n *\n * PINNED, not inferred. §3.5 names ten stems — `book`, `apply`, `contact`,\n * `buy`, `subscribe`, `start`, `request`, `download`, `sign up`, `get a quote` —\n * \"and their pinned synonyms\"; this is that list. A lexicon that grew per page\n * (or per LLM call) would make `primary-action-url` non-deterministic, and\n * `primary-action-url` is a core fact for `service` and `unknown`, so it would\n * take the whole score with it. Sorted for readability; order is not\n * significant.\n */\nconst ACTION_LEXICON = [\n 'add to bag',\n 'add to basket',\n 'add to cart',\n 'apply',\n 'apply now',\n 'book',\n 'book now',\n 'buy',\n 'buy now',\n 'call now',\n 'checkout',\n 'contact',\n 'contact us',\n 'donate',\n 'download',\n 'email us',\n 'enroll',\n 'get a quote',\n 'get quote',\n 'get started',\n 'join',\n 'make an appointment',\n 'order',\n 'order now',\n 'purchase',\n 'register',\n 'request',\n 'request a demo',\n 'request a quote',\n 'reserve',\n 'schedule',\n 'sign up',\n 'signup',\n 'start',\n 'start free trial',\n 'subscribe',\n] as const satisfies readonly string[]\n\n// ---------------------------------------------------------------------------\n// Bands (§3.6)\n// ---------------------------------------------------------------------------\n\n/**\n * The five grade bands. Bands headline, integers are secondary, and there are no\n * decimals ever: ARS is ORDINAL, and \"you gave me 81 and my competitor 83\" is a\n * conversation about noise.\n *\n * The `meaning` strings are DESCRIPTIVE ONLY, and the phrasing is load-bearing.\n * Three labels from the source designs are deliberately gone: *\"expect wrong or\n * missing details in AI answers about this page\"* is a predictive assertion\n * about third-party AI output that ARS does not measure; *\"effectively closed to\n * agents\"* is falsifiable and wrong for a site at 39 serving clean HTML; *\"and\n * can trust it\"* asserts veracity, and ARS measures format, not truth. Two lines\n * print on every surface that shows a grade:\n *\n * ARS measures format and retrievability. It does not measure whether the\n * facts are true, or whether any assistant cites this page.\n */\nconst BANDS = [\n {\n grade: 'A',\n min: 90,\n max: 100,\n label: 'Agent-native',\n meaning:\n 'Facts are in a machine representation, complete for this page kind, front-loaded, and cheap to fetch.',\n },\n {\n grade: 'B',\n min: 75,\n max: 89,\n label: 'Agent-friendly',\n meaning:\n 'All core facts are present and findable; the agent pays more bytes than it needs, or one signal is missing.',\n },\n {\n grade: 'C',\n min: 60,\n max: 74,\n label: 'Readable with effort',\n meaning: 'Core facts are extractable from HTML, at high cost.',\n },\n {\n grade: 'D',\n min: 40,\n max: 59,\n label: 'Partial',\n meaning: 'Some core facts for this page kind were not found in the fetched response.',\n },\n {\n grade: 'F',\n min: 0,\n max: 39,\n label: 'Not extractable',\n meaning: 'Few or no core facts for this page kind were found in the fetched response.',\n },\n] as const satisfies readonly ArsBand[]\n\n// ---------------------------------------------------------------------------\n// The ruleset\n// ---------------------------------------------------------------------------\n\n/**\n * ARS 0.2's frozen ruleset.\n *\n * DESIGNED CEILINGS, printed in the spec (§8) as intentional rather than\n * discovered, and stated here in 0.2's numbers: no content negotiation loses\n * D2.1 (9) + D2.3 (3, gated on D2.1) + D2.4 (3, nothing comparable) → max 85,\n * capped at B. No valid structured data loses all of D5 (6) → max 94, so an A is\n * still reachable. Reaching an A therefore requires a machine representation and\n * NO LONGER requires structured data — 0.1 required both, and 0.2 does not.\n * Provable from these numbers alone, which is why the whole ruleset is published\n * rather than described.\n */\nexport const DEFAULT_RULESET = deepFreeze({\n version: '0.2.0',\n weights: WEIGHTS,\n thresholds: THRESHOLDS,\n audienceTokens: AUDIENCE_TOKENS,\n requiredProperties: REQUIRED_PROPERTIES,\n actionLexicon: ACTION_LEXICON,\n /** 2 MiB decoded. Streamed and aborted at the cap; `await response.text()` is forbidden. */\n maxBodyBytes: 2 * 1024 * 1024,\n /** 3 hops. Every hop re-resolves DNS and re-validates (§5.2). */\n maxRedirects: 3,\n /** 5s per request. See the ADDED note on `ArsRuleset` in ./types. */\n timeoutMs: 5_000,\n profiles: PROFILES,\n bands: BANDS,\n} as const satisfies ArsRuleset)\n","/**\n * html.ts — a tolerant, NON-EXECUTING HTML tokenizer, hand-rolled.\n *\n * WHY NOT parse5, cheerio, jsdom, or htmlparser2 (design §3.2, stated as a\n * normative reason rather than a preference): **a third-party parser version is\n * an unversioned input to a deterministic score.** ARS publishes the guarantee\n * that for a given `evidenceHash`, `rulesetHash` and `corpusHash`, `score()`\n * returns a byte-identical result in any conformant implementation, in any\n * language. A dependency that changes how a malformed `<div` is recovered\n * changes scores on a `pnpm update`, with no ARS version bump, no conformance\n * diff, and nothing in the release notes. It would also put a transitive\n * dependency tree into a package whose whole claim is that it has none.\n *\n * The second reason is the same one that rules out a cascade engine: this\n * tokenizer's recovery rules ARE the spec. They are written here, in ~600 lines,\n * where a second implementation in Go can read them.\n *\n * NON-EXECUTING is literal and load-bearing. `<script>` and `<style>` contents\n * are captured as opaque raw text and never evaluated, never fed to a JS engine,\n * never resolved. The probe fetches attacker-controlled bytes from arbitrary\n * origins; the only safe posture is that those bytes are data all the way down.\n *\n * WHAT IT EXTRACTS\n * - every start/end tag, with attributes (lowercased names, entity-decoded values)\n * - every text node, with its **UTF-8 byte offset** into the source\n * - `<script type=\"application/ld+json\">` contents, verbatim\n * - `<meta>` tags (name / property / http-equiv / itemprop / charset / content)\n * - `<link>` tags, including the multi-value `rel` token list\n *\n * BYTE OFFSETS ARE LOAD-BEARING. D4 scores the byte offset of the first core\n * fact (`≤512B → 5 · ≤2KiB → 4 · ≤8KiB → 2 · ≤32KiB → 1`) and the fraction of\n * core facts inside a `max(2048, bytes / 5)` front window. `ArsHttpCapture.bytes`\n * is defined as the *decoded UTF-8 byte length*, so offsets here are UTF-8 byte\n * offsets, NOT JavaScript string indices. On a page with any multibyte character\n * before the price — a `€`, a `—`, a CJK product name — those two numbers differ,\n * and a Go implementation counting real bytes would disagree with us. See\n * `Utf8Cursor`.\n *\n * TEXT EXTRACTION (normative, §3.6). Counted text is every text node except:\n * `<script>`, `<style>`, `<template>`, elements carrying the `hidden`\n * attribute, and elements carrying inline `style=\"display:none\"`.\n * **No CSS resolution** — a cascade engine would not be deterministic across\n * implementations, so a class that hides an element in a stylesheet does not\n * hide it here, and the spec says so rather than pretending otherwise.\n *\n * ONE READING DECISION, FLAGGED. §3.6 writes the rule as \"except `<script>`\n * (excluding `application/ld+json`)\", which can be read either way. We implement:\n * **JSON-LD script contents are NOT counted text**; they are surfaced separately\n * as `HtmlDocument.jsonLd`. The other reading breaks two mechanisms that the rest\n * of the spec depends on — D5.3 checks that structured data agrees with *visible*\n * text, and \"corroborated\" means observed in ≥2 sources (e.g. JSON-LD *and*\n * visible text). If JSON-LD were visible text, both would be satisfied by a\n * single JSON-LD block, trivially and always. Every text node reports\n * `excludedBy`, so the distinction is visible to callers rather than baked in.\n *\n * TOLERANCE CONTRACT: `tokenizeHtml` never throws, for any input string —\n * unterminated tags, unterminated comments, stray `<`, lone surrogates, 100k\n * nested `<div>`s, binary noise. Conformance fixture `057-tokenizer-fuzz` and\n * `tests/html.test.ts` both assert it. A scanner that can be crashed by the page\n * it is scanning is a denial-of-service endpoint.\n */\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/** Why a text node is not counted text. `null` means it is counted. */\nexport type HtmlExclusionReason =\n | 'script'\n | 'script-ld-json'\n | 'style'\n | 'template'\n | 'hidden-attribute'\n | 'inline-display-none'\n\nexport interface HtmlElement {\n /** Index into `HtmlDocument.elements`; ascending in source order. */\n index: number\n /** Lowercased tag name. */\n tag: string\n /** Lowercased attribute names → entity-decoded values. First occurrence wins (HTML5). */\n attrs: Readonly<Record<string, string>>\n /** UTF-8 byte offset of the `<` that opens this tag. */\n offset: number\n /** Index of the enclosing open element, or -1 at document level. */\n parent: number\n /** Nesting depth; 0 at document level. */\n depth: number\n /**\n * Effective exclusion for text inside this element — its own reason, or the\n * nearest ancestor's. `null` when text inside it counts.\n */\n excludedBy: HtmlExclusionReason | null\n}\n\nexport interface HtmlText {\n /** Entity-decoded text (raw, undecoded inside `<script>`/`<style>`). */\n text: string\n /** UTF-8 byte offset of the first character of the RAW source text. */\n offset: number\n /** UTF-8 byte length of the RAW source text. */\n bytes: number\n /** Index of the innermost enclosing element, or -1 at document level. */\n parent: number\n /** `null` when this node is counted text; otherwise why it is not. */\n excludedBy: HtmlExclusionReason | null\n}\n\nexport interface HtmlJsonLd {\n /** Script contents, verbatim. Not entity-decoded: `<script>` is a raw-text element. */\n text: string\n /** UTF-8 byte offset of the first character of the contents. */\n offset: number\n /** Index of the `<script>` element in `HtmlDocument.elements`. */\n element: number\n}\n\nexport interface HtmlMeta {\n /** Lowercased `name`, or null. */\n name: string | null\n /** Lowercased `property` (Open Graph), or null. */\n property: string | null\n /** Lowercased `http-equiv`, or null. */\n httpEquiv: string | null\n /** Lowercased `itemprop`, or null. */\n itemprop: string | null\n /** Lowercased `charset`, or null. */\n charset: string | null\n /** `content`, decoded, case preserved. */\n content: string | null\n element: number\n offset: number\n}\n\nexport interface HtmlLink {\n /**\n * `rel` as a token list, lowercased, source order, duplicates removed.\n * `rel=\"alternate canonical\"` is one link declaring two relations, and D2.2\n * (declared alternates) and D6.1 (canonical) both read it — collapsing it to a\n * string would lose one of them.\n */\n rel: readonly string[]\n href: string | null\n /** Lowercased `type`, or null. */\n type: string | null\n /** Lowercased `hreflang`, or null. */\n hreflang: string | null\n title: string | null\n element: number\n offset: number\n}\n\nexport interface HtmlDocument {\n readonly elements: readonly HtmlElement[]\n readonly texts: readonly HtmlText[]\n readonly jsonLd: readonly HtmlJsonLd[]\n readonly metas: readonly HtmlMeta[]\n readonly links: readonly HtmlLink[]\n /** Total UTF-8 byte length of the source. */\n readonly bytes: number\n}\n\n// ---------------------------------------------------------------------------\n// UTF-8 offsets\n// ---------------------------------------------------------------------------\n\n/**\n * Maps JavaScript string indices to UTF-8 byte offsets in one forward pass.\n *\n * The tokenizer advances monotonically, so `at()` is amortised O(1); a\n * non-monotonic call restarts from zero rather than returning a wrong number,\n * because a silently wrong offset is a silently wrong D4 score.\n *\n * Surrogate handling matches `TextEncoder`: a well-formed pair costs 4 bytes,\n * and a LONE surrogate costs 3 — WHATWG encoding replaces it with U+FFFD, so\n * that is what its byte cost actually is on the wire.\n */\nclass Utf8Cursor {\n private charIndex = 0\n private byteIndex = 0\n\n constructor(private readonly source: string) {}\n\n at(target: number): number {\n if (target < this.charIndex) {\n this.charIndex = 0\n this.byteIndex = 0\n }\n const limit = Math.min(target, this.source.length)\n while (this.charIndex < limit) {\n const code = this.source.charCodeAt(this.charIndex)\n if (code < 0x80) {\n this.byteIndex += 1\n this.charIndex += 1\n } else if (code < 0x800) {\n this.byteIndex += 2\n this.charIndex += 1\n } else if (code >= 0xd800 && code <= 0xdbff) {\n const next =\n this.charIndex + 1 < this.source.length ? this.source.charCodeAt(this.charIndex + 1) : 0\n if (next >= 0xdc00 && next <= 0xdfff && this.charIndex + 1 < limit) {\n this.byteIndex += 4\n this.charIndex += 2\n } else {\n // Lone high surrogate, or a pair straddling `limit`: 3 bytes for U+FFFD.\n this.byteIndex += 3\n this.charIndex += 1\n }\n } else {\n this.byteIndex += 3\n this.charIndex += 1\n }\n }\n return this.byteIndex\n }\n}\n\n// ---------------------------------------------------------------------------\n// Entity decoding\n// ---------------------------------------------------------------------------\n\n/**\n * Pinned named character references.\n *\n * The full HTML5 named-reference table is ~2 200 entries. This is the subset\n * that appears in the parts of a page ARS reads — money symbols, typography,\n * and the five XML entities — and it is PINNED per spec version for the same\n * reason the tokenizer is hand-rolled: growing the table changes extracted text,\n * which changes facts, which changes scores. Additions land as a MINOR.\n *\n * A named reference outside this table is left verbatim, which is also the only\n * safe failure: `&hearts;` surviving as literal text costs nothing, whereas\n * guessing would be non-deterministic.\n */\nconst NAMED_ENTITIES: Readonly<Record<string, string>> = {\n amp: '&',\n lt: '<',\n gt: '>',\n quot: '\"',\n apos: \"'\",\n nbsp: '\\u00a0',\n ensp: '\\u2002',\n emsp: '\\u2003',\n thinsp: '\\u2009',\n shy: '\\u00ad',\n zwnj: '\\u200c',\n zwj: '\\u200d',\n // Currency\n cent: '¢',\n pound: '£',\n curren: '¤',\n yen: '¥',\n euro: '€',\n dollar: '$',\n // Typography\n ndash: '–',\n mdash: '—',\n hellip: '…',\n lsquo: '‘',\n rsquo: '’',\n sbquo: '‚',\n ldquo: '“',\n rdquo: '”',\n bdquo: '„',\n laquo: '«',\n raquo: '»',\n lsaquo: '‹',\n rsaquo: '›',\n bull: '•',\n middot: '·',\n dagger: '†',\n Dagger: '‡',\n prime: '′',\n Prime: '″',\n // Marks and math\n copy: '©',\n reg: '®',\n trade: '™',\n sect: '§',\n para: '¶',\n deg: '°',\n plusmn: '±',\n times: '×',\n divide: '÷',\n minus: '−',\n permil: '‰',\n frac12: '½',\n frac14: '¼',\n frac34: '¾',\n sup2: '²',\n sup3: '³',\n le: '≤',\n ge: '≥',\n ne: '≠',\n // Directionality (invisible, but they do occupy bytes)\n lrm: '\\u200e',\n rlm: '\\u200f',\n}\n\n/**\n * The HTML spec's windows-1252 override for numeric references in 0x80–0x9F.\n * `&#146;` is a right single quote on real pages, not a C1 control, and\n * decoding it as one would corrupt product titles.\n */\nconst C1_REPLACEMENTS: Readonly<Record<number, number>> = {\n 0x80: 0x20ac,\n 0x82: 0x201a,\n 0x83: 0x0192,\n 0x84: 0x201e,\n 0x85: 0x2026,\n 0x86: 0x2020,\n 0x87: 0x2021,\n 0x88: 0x02c6,\n 0x89: 0x2030,\n 0x8a: 0x0160,\n 0x8b: 0x2039,\n 0x8c: 0x0152,\n 0x8e: 0x017d,\n 0x91: 0x2018,\n 0x92: 0x2019,\n 0x93: 0x201c,\n 0x94: 0x201d,\n 0x95: 0x2022,\n 0x96: 0x2013,\n 0x97: 0x2014,\n 0x98: 0x02dc,\n 0x99: 0x2122,\n 0x9a: 0x0161,\n 0x9b: 0x203a,\n 0x9c: 0x0153,\n 0x9e: 0x017e,\n 0x9f: 0x0178,\n}\n\n/**\n * A trailing `;` is REQUIRED. HTML's legacy semicolon-less forms\n * (`&copy` inside `?a=1&copy=2`) are exactly the cases where decoding mangles a\n * URL, and every reference that matters on a page ARS reads is written properly.\n * Bounded name length keeps the match linear.\n */\nconst ENTITY_RE = /&(#[xX][0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z][a-zA-Z0-9]{0,31});/g\n\nfunction codePointToString(raw: number): string {\n const mapped = C1_REPLACEMENTS[raw]\n const code = mapped ?? raw\n // Null, surrogates and out-of-range all become U+FFFD, per the HTML spec.\n if (code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) return '\\ufffd'\n return String.fromCodePoint(code)\n}\n\n/** Decodes the pinned named references plus numeric references. Never throws. */\nexport function decodeEntities(text: string): string {\n if (!text.includes('&')) return text\n return text.replace(ENTITY_RE, (match, body: string) => {\n if (body.startsWith('#')) {\n const isHex = body[1] === 'x' || body[1] === 'X'\n const digits = isHex ? body.slice(2) : body.slice(1)\n const value = Number.parseInt(digits, isHex ? 16 : 10)\n return Number.isNaN(value) ? match : codePointToString(value)\n }\n return NAMED_ENTITIES[body] ?? match\n })\n}\n\n// ---------------------------------------------------------------------------\n// Element tables\n// ---------------------------------------------------------------------------\n\n/** Void elements: no contents, never pushed onto the open-element stack. */\nconst VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n])\n\n/** Raw-text elements: contents are opaque, entities are NOT decoded. */\nconst RAW_TEXT_ELEMENTS = new Set(['script', 'style'])\n\n/** RCDATA elements: contents are text, entities ARE decoded, tags are not. */\nconst RCDATA_ELEMENTS = new Set(['textarea', 'title'])\n\n/**\n * Optional-end-tag recovery, in the small form that matters here. A start tag\n * listed as a key implicitly closes any open element in its value set. Without\n * this, `<li>a<li>b` nests forever and `<dt>q<dd>a` puts the answer inside the\n * question — and `<dt>/<dd>` pairs are one of the recognised `question-answer`\n * shapes for the `faq` page kind, so getting it wrong costs real points.\n */\nconst IMPLIED_END_TAGS: Readonly<Record<string, readonly string[]>> = {\n li: ['li'],\n dt: ['dt', 'dd'],\n dd: ['dt', 'dd'],\n option: ['option'],\n optgroup: ['option', 'optgroup'],\n tr: ['td', 'th', 'tr'],\n td: ['td', 'th'],\n th: ['td', 'th'],\n tbody: ['td', 'th', 'tr', 'thead', 'tbody'],\n tfoot: ['td', 'th', 'tr', 'thead', 'tbody'],\n}\n\n/** Block-level start tags that implicitly close an open `<p>`. */\nconst CLOSES_OPEN_P = new Set([\n 'address',\n 'article',\n 'aside',\n 'blockquote',\n 'details',\n 'div',\n 'dl',\n 'fieldset',\n 'figcaption',\n 'figure',\n 'footer',\n 'form',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'header',\n 'hr',\n 'main',\n 'nav',\n 'ol',\n 'p',\n 'pre',\n 'section',\n 'table',\n 'ul',\n])\n\n/**\n * Cap on open-element depth. Beyond it, elements are still recorded but not\n * pushed, so a page with 200 000 nested `<div>`s costs memory proportional to\n * its bytes and nothing more. Real documents do not approach this.\n */\nconst MAX_DEPTH = 256\n\n// ---------------------------------------------------------------------------\n// Small helpers\n// ---------------------------------------------------------------------------\n\nfunction isAsciiAlpha(ch: string | undefined): boolean {\n if (ch === undefined) return false\n return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')\n}\n\nfunction isHtmlSpace(ch: string): boolean {\n return ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r' || ch === '\\f'\n}\n\n/**\n * Inline `display:none`, with whitespace stripped first so the test itself is a\n * plain substring match rather than a regex with a backtracking profile. Only\n * the element's own `style` attribute is consulted: NO CSS RESOLUTION (§3.6).\n */\nconst DISPLAY_NONE_RE = /(^|;)display:none(!important)?(;|$)/\n\nfunction hasInlineDisplayNone(style: string | undefined): boolean {\n if (style === undefined) return false\n return DISPLAY_NONE_RE.test(style.toLowerCase().replace(/\\s+/g, ''))\n}\n\n/** Reads an attribute, or null. Attribute names are lowercased by the tokenizer. */\nexport function attr(element: HtmlElement, name: string): string | null {\n return element.attrs[name] ?? null\n}\n\n// ---------------------------------------------------------------------------\n// Tag parsing\n// ---------------------------------------------------------------------------\n\ninterface ParsedTag {\n tag: string\n attrs: Record<string, string>\n selfClosing: boolean\n /** Index just past the closing `>` (or past the end of input if unterminated). */\n end: number\n}\n\n/**\n * Parses a start tag beginning at `start` (the `<`). Tolerant: an unterminated\n * tag consumes to end of input and returns what it read.\n */\nfunction parseStartTag(html: string, start: number): ParsedTag {\n let i = start + 1\n const nameStart = i\n while (i < html.length) {\n const ch = html[i] ?? ''\n if (isHtmlSpace(ch) || ch === '/' || ch === '>') break\n i++\n }\n const tag = html.slice(nameStart, i).toLowerCase()\n const attrs: Record<string, string> = {}\n let selfClosing = false\n\n while (i < html.length) {\n while (i < html.length && isHtmlSpace(html[i] ?? '')) i++\n if (i >= html.length) break\n const ch = html[i] ?? ''\n if (ch === '>') {\n i++\n return { tag, attrs, selfClosing, end: i }\n }\n if (ch === '/') {\n selfClosing = true\n i++\n continue\n }\n // Attribute name.\n const attrNameStart = i\n while (i < html.length) {\n const c = html[i] ?? ''\n if (isHtmlSpace(c) || c === '=' || c === '>' || c === '/') break\n i++\n }\n if (i === attrNameStart) {\n // Nothing consumed (e.g. a stray '='): skip a character so we always advance.\n i++\n continue\n }\n const attrName = html.slice(attrNameStart, i).toLowerCase()\n let value = ''\n while (i < html.length && isHtmlSpace(html[i] ?? '')) i++\n if (html[i] === '=') {\n i++\n while (i < html.length && isHtmlSpace(html[i] ?? '')) i++\n const quote = html[i]\n if (quote === '\"' || quote === \"'\") {\n i++\n const valueStart = i\n const close = html.indexOf(quote, i)\n if (close === -1) {\n value = html.slice(valueStart)\n i = html.length\n } else {\n value = html.slice(valueStart, close)\n i = close + 1\n }\n } else {\n const valueStart = i\n while (i < html.length) {\n const c = html[i] ?? ''\n if (isHtmlSpace(c) || c === '>') break\n i++\n }\n value = html.slice(valueStart, i)\n }\n }\n // First occurrence wins, per the HTML parsing spec.\n if (!(attrName in attrs)) attrs[attrName] = decodeEntities(value)\n }\n return { tag, attrs, selfClosing, end: i }\n}\n\n/** Locates the matching `</tag` for a raw-text or RCDATA element, case-insensitively. */\nfunction findRawTextEnd(html: string, from: number, tag: string): number {\n const needle = `</${tag}`\n const lower = html.toLowerCase()\n const at = lower.indexOf(needle, from)\n return at === -1 ? -1 : at\n}\n\n// ---------------------------------------------------------------------------\n// tokenizeHtml\n// ---------------------------------------------------------------------------\n\n/** The element's own exclusion reason, ignoring ancestors. */\nfunction ownExclusion(\n tag: string,\n attrs: Readonly<Record<string, string>>,\n): HtmlExclusionReason | null {\n if (tag === 'script') {\n const type = (attrs['type'] ?? '').toLowerCase().split(';')[0]?.trim() ?? ''\n return type === 'application/ld+json' ? 'script-ld-json' : 'script'\n }\n if (tag === 'style') return 'style'\n if (tag === 'template') return 'template'\n // `hidden` is a boolean attribute: its presence hides, whatever the value\n // (including `hidden=\"until-found\"`, which is still hidden until found).\n if ('hidden' in attrs) return 'hidden-attribute'\n if (hasInlineDisplayNone(attrs['style'])) return 'inline-display-none'\n return null\n}\n\n/**\n * Tokenizes `html` into the flat, offset-annotated structure ARS scores against.\n * Never throws. `html` is the DECODED response body; offsets are UTF-8 byte\n * offsets into that decoded body, matching `ArsHttpCapture.bytes`.\n */\nexport function tokenizeHtml(html: string): HtmlDocument {\n const elements: HtmlElement[] = []\n const texts: HtmlText[] = []\n const jsonLd: HtmlJsonLd[] = []\n const metas: HtmlMeta[] = []\n const links: HtmlLink[] = []\n const stack: number[] = []\n const cursor = new Utf8Cursor(html)\n\n const topIndex = (): number => stack[stack.length - 1] ?? -1\n const exclusionAt = (elementIndex: number): HtmlExclusionReason | null =>\n elementIndex >= 0 ? (elements[elementIndex]?.excludedBy ?? null) : null\n\n const emitText = (\n from: number,\n to: number,\n decode: boolean,\n override?: HtmlExclusionReason,\n ): void => {\n if (to <= from) return\n const raw = html.slice(from, to)\n const parent = topIndex()\n const offset = cursor.at(from)\n texts.push({\n text: decode ? decodeEntities(raw) : raw,\n offset,\n bytes: cursor.at(to) - offset,\n parent,\n excludedBy: override ?? exclusionAt(parent),\n })\n }\n\n const popTo = (tag: string): void => {\n for (let depth = stack.length - 1; depth >= 0; depth--) {\n const candidate = stack[depth]\n if (candidate === undefined) continue\n if (elements[candidate]?.tag === tag) {\n stack.length = depth\n return\n }\n }\n // No matching open element: a stray end tag. Ignore it, as browsers do.\n }\n\n const applyImpliedEndTags = (tag: string): void => {\n const closes = IMPLIED_END_TAGS[tag]\n if (closes !== undefined) {\n while (stack.length > 0) {\n const top = stack[stack.length - 1]\n const openTag = top === undefined ? undefined : elements[top]?.tag\n if (openTag === undefined || !closes.includes(openTag)) break\n stack.pop()\n }\n }\n if (CLOSES_OPEN_P.has(tag)) {\n const top = stack[stack.length - 1]\n if (top !== undefined && elements[top]?.tag === 'p') stack.pop()\n }\n }\n\n // `textStart` trails `i`: a `<` that turns out NOT to open markup stays inside\n // the current text run rather than splitting it. `a < b` is one text node, not\n // three — and since `countedText` joins nodes with a space, splitting it would\n // silently rewrite the page's own text before any fact is extracted from it.\n let i = 0\n let textStart = 0\n while (i < html.length) {\n const lt = html.indexOf('<', i)\n if (lt === -1) break\n\n const next = html[lt + 1]\n // A `<` opens markup only before `!`, `/`, or an ASCII letter. Anything else\n // — `3<4`, a stray `<` at end of input — is text.\n if (next !== '!' && next !== '/' && !isAsciiAlpha(next)) {\n i = lt + 1\n continue\n }\n emitText(textStart, lt, true)\n\n // --- Comments, doctypes, CDATA, bogus comments ---\n if (next === '!') {\n if (html.startsWith('<!--', lt)) {\n const close = html.indexOf('-->', lt + 4)\n i = close === -1 ? html.length : close + 3\n } else {\n const close = html.indexOf('>', lt + 2)\n i = close === -1 ? html.length : close + 1\n }\n textStart = i\n continue\n }\n\n // --- End tags ---\n if (next === '/') {\n const close = html.indexOf('>', lt + 2)\n const end = close === -1 ? html.length : close + 1\n const rawName = html.slice(lt + 2, close === -1 ? html.length : close).trim()\n const tag = rawName.toLowerCase()\n if (tag.length > 0) popTo(tag)\n i = end\n textStart = i\n continue\n }\n\n // --- Start tags ---\n const parsed = parseStartTag(html, lt)\n applyImpliedEndTags(parsed.tag)\n\n const parent = topIndex()\n const own = ownExclusion(parsed.tag, parsed.attrs)\n const element: HtmlElement = {\n index: elements.length,\n tag: parsed.tag,\n attrs: parsed.attrs,\n offset: cursor.at(lt),\n parent,\n depth: stack.length,\n excludedBy: exclusionAt(parent) ?? own,\n }\n elements.push(element)\n collectMetaOrLink(element, metas, links)\n i = parsed.end\n\n const isVoid = VOID_ELEMENTS.has(parsed.tag)\n const isRawText = RAW_TEXT_ELEMENTS.has(parsed.tag)\n const isRcdata = RCDATA_ELEMENTS.has(parsed.tag)\n\n if (isRawText || isRcdata) {\n // Contents are opaque: no nested tags, no stack push. Entities are decoded\n // for RCDATA (`<title>`, `<textarea>`) and NOT for raw text (`<script>`,\n // `<style>`) — a JSON-LD block must survive byte-for-byte.\n const contentStart = i\n const close = findRawTextEnd(html, contentStart, parsed.tag)\n const contentEnd = close === -1 ? html.length : close\n if (contentEnd > contentStart) {\n const wasTop = stack.length\n stack.push(element.index)\n emitText(contentStart, contentEnd, isRcdata, element.excludedBy ?? own ?? undefined)\n stack.length = wasTop\n if (own === 'script-ld-json') {\n jsonLd.push({\n text: html.slice(contentStart, contentEnd),\n offset: cursor.at(contentStart),\n element: element.index,\n })\n }\n }\n if (close === -1) {\n i = html.length\n } else {\n const gt = html.indexOf('>', close)\n i = gt === -1 ? html.length : gt + 1\n }\n textStart = i\n continue\n }\n\n if (!isVoid && !parsed.selfClosing && stack.length < MAX_DEPTH) stack.push(element.index)\n textStart = i\n }\n emitText(textStart, html.length, true)\n\n return {\n elements,\n texts,\n jsonLd,\n metas,\n links,\n bytes: cursor.at(html.length),\n }\n}\n\n/** Records `<meta>` and `<link>` elements into their typed side-tables. */\nfunction collectMetaOrLink(element: HtmlElement, metas: HtmlMeta[], links: HtmlLink[]): void {\n const lower = (value: string | undefined): string | null =>\n value === undefined ? null : value.toLowerCase()\n\n if (element.tag === 'meta') {\n metas.push({\n name: lower(element.attrs['name']),\n property: lower(element.attrs['property']),\n httpEquiv: lower(element.attrs['http-equiv']),\n itemprop: lower(element.attrs['itemprop']),\n charset: lower(element.attrs['charset']),\n content: element.attrs['content'] ?? null,\n element: element.index,\n offset: element.offset,\n })\n return\n }\n\n if (element.tag === 'link') {\n const rawRel = element.attrs['rel'] ?? ''\n const rel: string[] = []\n for (const token of rawRel.toLowerCase().split(/\\s+/)) {\n if (token.length > 0 && !rel.includes(token)) rel.push(token)\n }\n links.push({\n rel,\n href: element.attrs['href'] ?? null,\n type: lower(element.attrs['type']),\n hreflang: lower(element.attrs['hreflang']),\n title: element.attrs['title'] ?? null,\n element: element.index,\n offset: element.offset,\n })\n }\n}\n\n// ---------------------------------------------------------------------------\n// Text views\n// ---------------------------------------------------------------------------\n\n/**\n * Joins text nodes with a single space and collapses whitespace runs.\n *\n * A single space rather than an empty string: `<b>Blue</b><i>Shirt</i>` renders\n * as two words to a reader, and \"BlueShirt\" is not a title. Joining always,\n * rather than only across block boundaries, avoids needing a display-model —\n * which is the same reason there is no CSS resolution anywhere in this file.\n */\nfunction joinText(parts: readonly string[]): string {\n return parts.join(' ').replace(/\\s+/g, ' ').trim()\n}\n\n/** All counted text in the document, per the §3.6 normative extraction rule. */\nexport function countedText(doc: HtmlDocument): string {\n const parts: string[] = []\n for (const node of doc.texts) {\n if (node.excludedBy === null) parts.push(node.text)\n }\n return joinText(parts)\n}\n\n/**\n * Counted text inside one element's subtree — anchor text for\n * `primary-action-url`, a `<summary>`'s question, a heading. `includeExcluded`\n * opts into hidden subtrees, which the extractor needs for exactly one thing:\n * reporting hidden facts as evidence (fixture `037-hidden-text-facts`) without\n * letting them score.\n */\nexport function elementText(\n doc: HtmlDocument,\n elementIndex: number,\n includeExcluded = false,\n): string {\n const parts: string[] = []\n for (const node of doc.texts) {\n if (!includeExcluded && node.excludedBy !== null) continue\n if (isSelfOrDescendant(doc, node.parent, elementIndex)) parts.push(node.text)\n }\n return joinText(parts)\n}\n\n/** Walks `parent` links upward. Bounded by MAX_DEPTH + 1 so a cycle cannot hang. */\nfunction isSelfOrDescendant(doc: HtmlDocument, from: number, ancestor: number): boolean {\n let current = from\n for (let hops = 0; hops <= MAX_DEPTH + 1 && current >= 0; hops++) {\n if (current === ancestor) return true\n current = doc.elements[current]?.parent ?? -1\n }\n return false\n}\n","/**\n * parse-money.ts — text → `Money`, or `null` when ambiguous. Design §3.11.\n *\n * WHY THIS IS ITS OWN FILE, AND WHY IT IS BIG. `packages/render-md/src/money.ts`\n * only *formats* an already-structured `Money`. It cannot parse text, and the\n * claim that it could hid the largest single piece of extraction work in the\n * program. Price is a core fact for `product` and `service`, it is one of the\n * four values compared by the D2.4 substance-parity check, and it is the value a\n * buying agent acts on. Everything downstream of a wrong price is wrong.\n *\n * FAILS CLOSED, like `formatMoney`. Ambiguous input returns `null`, and a `null`\n * price is simply not a fact — it costs coverage points and nothing else. A\n * *wrong* price would be reported as truth on a public scanner page, and would\n * make a parity check accuse a merchant of divergence they did not commit.\n * Every rule below resolves in favour of `null`.\n *\n * WHY `Money` IS DECLARED HERE RATHER THAN IMPORTED. It is structurally\n * identical to `@rebilder/render-md`'s `Money`, and duplicating it is\n * deliberate: `tooling/check-package-graph.ts` forbids\n * `agent-readability → render-md` (and the reverse) in the `ars-boundary` rule.\n * The two packages point in opposite directions — gateway/render-md turn a\n * source of truth into output; the scorer turns a response into a judgment — so\n * a dependency either way is a design error before it is a size one. Four bytes\n * of duplicated interface is the cheap side of that trade.\n *\n * NO `String.prototype.normalize()`. Unicode normalisation is deterministic only\n * for a fixed Unicode version, and the Unicode version is a property of the\n * host's ICU build. That is the same class of unversioned input as a\n * third-party HTML parser, and the same answer applies: every character this\n * parser special-cases is listed here, in a pinned table.\n *\n * SUPPORTED FORMATS (§3.11 enumerates these; each has a test):\n * leading symbol `$1,499.00` `€49` `¥4,900`\n * trailing symbol `1.499,00 €` `49 zł`\n * ISO code prefix/suffix `USD 1499` `1499 USD`\n * comma and period as BOTH group and decimal separator, disambiguated by\n * position and by the minor-unit digits of the resolved currency\n * space / NBSP / narrow-NBSP / apostrophe group separators `1 499,00` `1'499.00`\n * zero-decimal currencies `¥4,900` → 4900, not 490000\n * ranges `$148.00 – $198.00` → the LOWER bound, `qualified: true`\n * qualifiers `From $9`, `$9+` → the stated bound, `qualified: true`\n *\n * `qualified: true` EXISTS FOR ONE REASON: qualified values are excluded from\n * the D2.4 parity comparison. \"From $9\" in markdown against \"$9 – $40\" in HTML is\n * the same page saying the same thing in two shapes, and flagging it as a\n * substance divergence would be a false accusation.\n */\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * Structural duplicate of `@rebilder/render-md`'s `Money` — same field names,\n * same semantics, deliberately not imported (see the file header).\n * `amount` is an INTEGER NUMBER OF MINOR UNITS: 4900 is $49.00 in USD and ¥4,900\n * in JPY, because JPY has no minor unit.\n */\nexport interface Money {\n amount: number\n currency: string\n}\n\n/**\n * What `parseMoneyText` returns: a `Money`, plus whether the source text stated\n * a bound rather than a price.\n */\nexport interface ParsedMoney extends Money {\n /** True for ranges (`$148 – $198`) and qualifiers (`From $9`, `$9+`). */\n qualified: boolean\n}\n\nexport interface MoneyHints {\n /**\n * ISO 4217 code the page is known to price in — from JSON-LD `priceCurrency`,\n * a `<meta itemprop=\"priceCurrency\">`, or the negotiated representation.\n * Does two jobs: it resolves symbols shared by several currencies (`$`, `¥`,\n * `kr`), and its minor-unit digit count disambiguates a lone separator\n * followed by three digits.\n */\n currency?: string\n}\n\n// ---------------------------------------------------------------------------\n// Currency tables\n// ---------------------------------------------------------------------------\n\n/**\n * ISO 4217 active alphabetic codes. Pinned: a bare three-letter token is\n * accepted as a currency ONLY if it is on this list, which is what stops\n * `50 OFF` parsing as 50 of some currency \"OFF\".\n *\n * Codes that are also English words do exist — `ALL` (Albanian lek), `TOP`\n * (Tongan paʻanga), `MAD`, `PEN`, `CUP`, `BOB`, `TRY`. They are handled by the\n * two structural rules rather than by a blocklist: a code must be immediately\n * adjacent to the number, and the text must contain exactly ONE number. `TRY 2\n * FOR 1` has two numbers and returns `null`.\n */\nconst ISO_4217 = new Set(\n (\n 'AED AFN ALL AMD ANG AOA ARS AUD AWG AZN BAM BBD BDT BGN BHD BIF BMD BND BOB BOV BRL BSD ' +\n 'BTN BWP BYN BZD CAD CDF CHE CHF CHW CLF CLP CNY COP COU CRC CUP CVE CZK DJF DKK DOP DZD ' +\n 'EGP ERN ETB EUR FJD FKP GBP GEL GHS GIP GMD GNF GTQ GYD HKD HNL HTG HUF IDR ILS INR IQD ' +\n 'IRR ISK JMD JOD JPY KES KGS KHR KMF KPW KRW KWD KYD KZT LAK LBP LKR LRD LSL LYD MAD MDL ' +\n 'MGA MKD MMK MNT MOP MRU MUR MVR MWK MXN MXV MYR MZN NAD NGN NIO NOK NPR NZD OMR PAB PEN ' +\n 'PGK PHP PKR PLN PYG QAR RON RSD RUB RWF SAR SBD SCR SDG SEK SGD SHP SLE SOS SRD SSP STN ' +\n 'SVC SYP SZL THB TJS TMT TND TOP TRY TTD TWD TZS UAH UGX USD USN UYI UYU UYW UZS VED VES ' +\n 'VND VUV WST XAF XAG XAU XCD XCG XDR XOF XPD XPF XPT YER ZAR ZMW ZWG'\n ).split(' '),\n)\n\n/**\n * Currencies with no minor unit — `amount` is already whole currency units.\n * Mirrors `render-md`'s table exactly (see the file header on why it is copied).\n */\nconst ZERO_DECIMAL = new Set([\n 'BIF',\n 'CLP',\n 'DJF',\n 'GNF',\n 'ISK',\n 'JPY',\n 'KMF',\n 'KRW',\n 'MGA',\n 'PYG',\n 'RWF',\n 'UGX',\n 'VND',\n 'VUV',\n 'XAF',\n 'XOF',\n 'XPF',\n])\n\n/** Currencies with three-digit minor units. Mirrors `render-md`'s table. */\nconst THREE_DECIMAL = new Set(['BHD', 'IQD', 'JOD', 'KWD', 'LYD', 'OMR', 'TND'])\n\n/** Minor-unit digit count for an ISO 4217 code. Unknown codes are treated as 2. */\nexport function minorUnitDigits(code: string): number {\n const upper = code.toUpperCase()\n if (ZERO_DECIMAL.has(upper)) return 0\n if (THREE_DECIMAL.has(upper)) return 3\n return 2\n}\n\ninterface SymbolEntry {\n /** Resolution when `hints.currency` says nothing useful. `null` = unresolvable alone. */\n fallback: string | null\n /** Codes this symbol may legitimately denote; `hints.currency` selects among them. */\n alternatives: readonly string[]\n}\n\n/**\n * Currency symbols, longest-first at match time so `CA$` beats `$`.\n *\n * `$`, `¥` and `kr` are shared. `$` and `¥` carry a pinned fallback (USD, JPY)\n * because a bare `$` on an unhinted page is overwhelmingly USD and `¥4,900` is\n * §3.11's own worked example of zero-decimal handling; `hints.currency`\n * overrides both. `kr` has NO fallback — SEK, NOK, DKK and ISK are genuinely\n * indistinguishable, and ISK is zero-decimal while the others are not, so\n * guessing would corrupt the amount and not merely the label.\n */\nconst SYMBOLS: Readonly<Record<string, SymbolEntry>> = {\n US$: { fallback: 'USD', alternatives: [] },\n CA$: { fallback: 'CAD', alternatives: [] },\n C$: { fallback: 'CAD', alternatives: [] },\n AU$: { fallback: 'AUD', alternatives: [] },\n A$: { fallback: 'AUD', alternatives: [] },\n NZ$: { fallback: 'NZD', alternatives: [] },\n HK$: { fallback: 'HKD', alternatives: [] },\n NT$: { fallback: 'TWD', alternatives: [] },\n S$: { fallback: 'SGD', alternatives: [] },\n R$: { fallback: 'BRL', alternatives: [] },\n MX$: { fallback: 'MXN', alternatives: [] },\n $: {\n fallback: 'USD',\n alternatives: [\n 'USD',\n 'CAD',\n 'AUD',\n 'NZD',\n 'SGD',\n 'HKD',\n 'MXN',\n 'TWD',\n 'BRL',\n 'ARS',\n 'CLP',\n 'COP',\n 'UYU',\n ],\n },\n '¥': { fallback: 'JPY', alternatives: ['JPY', 'CNY'] },\n kr: { fallback: null, alternatives: ['SEK', 'NOK', 'DKK', 'ISK'] },\n '€': { fallback: 'EUR', alternatives: [] },\n '£': { fallback: 'GBP', alternatives: [] },\n '₹': { fallback: 'INR', alternatives: [] },\n '₩': { fallback: 'KRW', alternatives: [] },\n '₽': { fallback: 'RUB', alternatives: [] },\n '₺': { fallback: 'TRY', alternatives: [] },\n '₪': { fallback: 'ILS', alternatives: [] },\n '₫': { fallback: 'VND', alternatives: [] },\n '₱': { fallback: 'PHP', alternatives: [] },\n '₴': { fallback: 'UAH', alternatives: [] },\n '₦': { fallback: 'NGN', alternatives: [] },\n '₡': { fallback: 'CRC', alternatives: [] },\n '₸': { fallback: 'KZT', alternatives: [] },\n '₾': { fallback: 'GEL', alternatives: [] },\n '฿': { fallback: 'THB', alternatives: [] },\n zł: { fallback: 'PLN', alternatives: [] },\n Kč: { fallback: 'CZK', alternatives: [] },\n}\n\n/** Symbols longest-first, so `CA$1.00` does not resolve through the bare `$` entry. */\nconst SYMBOLS_BY_LENGTH = Object.keys(SYMBOLS).sort((a, b) => b.length - a.length)\n\n// ---------------------------------------------------------------------------\n// Lexicons and limits\n// ---------------------------------------------------------------------------\n\n/**\n * Prefix qualifiers. Matched at the start of the text, case-insensitively, and\n * only when followed by a non-letter — so `fromage` is not `from`.\n */\nconst PREFIX_QUALIFIERS = [\n 'starting from',\n 'starting at',\n 'prices from',\n 'priced from',\n 'as little as',\n 'as much as',\n 'as low as',\n 'starts at',\n 'up to',\n 'from',\n] as const\n\n/** Suffix qualifiers, matched at the end of the text, case-insensitively. */\nconst SUFFIX_QUALIFIERS = ['and above', 'or more', 'or less', 'and up', '+'] as const\n\n/**\n * Range separators: em dash, en dash, Unicode hyphen, ASCII hyphen-minus. The\n * ASCII hyphen is included even though it is also a minus sign, because\n * `$148-$198` is a common real form; the \"exactly one separator in the whole\n * string\" rule below is what keeps `1-800-555-1212` and `2024-01-15` out.\n */\nconst RANGE_DASHES = ['\\u2014', '\\u2013', '\\u2010', '-'] as const\n\n/**\n * Whitespace normalised to a plain space before parsing: the ASCII controls,\n * NBSP, OGHAM SPACE MARK, the EN QUAD..HAIR SPACE block, NARROW NBSP, MEDIUM\n * MATHEMATICAL SPACE and IDEOGRAPHIC SPACE. NBSP and NARROW NBSP are the group\n * separators in fr-FR and ru-RU prices, which is why they are here as well as\n * in `GROUP_SPACERS`.\n */\nconst SPACE_RE = /[\\t\\n\\r\\f\\v\\u00a0\\u1680\\u2000-\\u200a\\u202f\\u205f\\u3000]/g\n\n/**\n * Characters that may separate digit groups in place of a comma or period: a\n * plain space (every exotic space has already been normalised to one) and the\n * de-CH apostrophe forms.\n */\nconst GROUP_SPACERS = [' ', \"'\", '\\u2019'] as const\n\n/**\n * Longest input accepted. A price does not occur inside 256 characters of prose,\n * and the cap also bounds the parser's work on adversarial input — the probe\n * fetches arbitrary bytes, and this function is called per fact candidate.\n */\nconst MAX_INPUT_LENGTH = 256\n\n/**\n * Digits allowed in a value before it is rejected. 15 significant digits is the\n * range in which `Number` is an exact integer; beyond it a price would round,\n * and a rounded price is a wrong price (Hard Rule 2).\n */\nconst MAX_SIGNIFICANT_DIGITS = 15\n\n/** A run of digits plus the characters that may appear inside a formatted number. */\nconst NUMBER_RUN_RE = /\\d[\\d.,'’ ]*/g\n\n// ---------------------------------------------------------------------------\n// Numeric parsing\n// ---------------------------------------------------------------------------\n\n/** True when every part is a plausible digit group: 1–3 leading digits, then exact 3s. */\nfunction isGroupedInteger(parts: readonly string[]): boolean {\n if (parts.length < 2) return false\n const first = parts[0] ?? ''\n // A grouped number never starts with 0: `0,500` is not five hundred.\n if (first.length < 1 || first.length > 3 || first.startsWith('0')) return false\n for (let i = 1; i < parts.length; i++) {\n if ((parts[i] ?? '').length !== 3) return false\n }\n return true\n}\n\n/**\n * Removes space/apostrophe group separators, or returns null if they are not in\n * valid group positions. `1 499,00` → `1499,00`; `12 34` → null.\n */\nfunction stripGroupSpacers(token: string): string | null {\n if (!GROUP_SPACERS.some((c) => token.includes(c))) return token\n\n // Split off a trailing decimal part first, so `1'499.00` keeps its `.00`.\n let head = token\n let tail = ''\n const lastDot = token.lastIndexOf('.')\n const lastComma = token.lastIndexOf(',')\n const lastSep = Math.max(lastDot, lastComma)\n if (lastSep > 0) {\n const after = token.slice(lastSep + 1)\n const afterIsDigits = after.length > 0 && !/\\D/.test(after)\n if (afterIsDigits) {\n head = token.slice(0, lastSep)\n tail = token.slice(lastSep)\n }\n }\n\n const parts: string[] = []\n let current = ''\n for (const ch of head) {\n if (GROUP_SPACERS.includes(ch as (typeof GROUP_SPACERS)[number])) {\n parts.push(current)\n current = ''\n } else if (ch >= '0' && ch <= '9') {\n current += ch\n } else {\n // A comma or period inside the head alongside spacers: two separator\n // systems in one number. Ambiguous.\n return null\n }\n }\n parts.push(current)\n if (!isGroupedInteger(parts)) return null\n return parts.join('') + tail\n}\n\n/**\n * Splits a `major`/`fraction` pair out of a token containing only digits, `.`\n * and `,`, or returns null when the two readings cannot be told apart.\n *\n * THE HARD CASE is a single separator followed by exactly three digits.\n * `1,500` is one thousand five hundred in en-US and one and a half in de-DE.\n * The resolver is the currency's minor-unit count, which is why\n * `hints.currency` matters:\n * 2 minor digits (USD, EUR) → a decimal separator cannot be followed by three\n * digits and still be minor units, so it is a GROUP separator → 1500.\n * 0 minor digits (JPY) → same conclusion → 4900, per §3.11's `¥4,900`.\n * 3 minor digits (KWD, BHD) → both readings are valid → AMBIGUOUS → null.\n */\nfunction splitMajorFraction(\n token: string,\n minorDigits: number,\n): { major: string; fraction: string } | null {\n const dots = token.split('.').length - 1\n const commas = token.split(',').length - 1\n\n if (dots === 0 && commas === 0) return { major: token, fraction: '' }\n\n if (dots > 0 && commas > 0) {\n // The LAST separator is the decimal point; the other groups.\n const decimal = token.lastIndexOf('.') > token.lastIndexOf(',') ? '.' : ','\n const group = decimal === '.' ? ',' : '.'\n const decimalAt = token.lastIndexOf(decimal)\n const head = token.slice(0, decimalAt)\n const fraction = token.slice(decimalAt + 1)\n if (fraction.length === 0 || head.includes(decimal)) return null\n if (!isGroupedInteger(head.split(group))) return null\n return { major: head.split(group).join(''), fraction }\n }\n\n const separator = dots > 0 ? '.' : ','\n const count = dots > 0 ? dots : commas\n const parts = token.split(separator)\n\n if (count > 1) {\n // Repeated separators can only be group separators.\n return isGroupedInteger(parts) ? { major: parts.join(''), fraction: '' } : null\n }\n\n const left = parts[0] ?? ''\n const right = parts[1] ?? ''\n if (left.length === 0 || right.length === 0) return null\n\n if (right.length === 3 && isGroupedInteger(parts)) {\n if (minorDigits === 3) return null // genuinely ambiguous; fail closed\n return { major: left + right, fraction: '' }\n }\n return { major: left, fraction: right }\n}\n\n/** Converts a validated major/fraction pair to integer minor units, or null. */\nfunction toMinorUnits(major: string, fraction: string, minorDigits: number): number | null {\n let frac = fraction\n if (frac.length > minorDigits) {\n // Extra precision is acceptable only when it is all zeros: `JPY 4900.00` is\n // 4900, but `USD 1.4990` states a sub-cent price we cannot represent.\n const extra = frac.slice(minorDigits)\n if (/[^0]/.test(extra)) return null\n frac = frac.slice(0, minorDigits)\n }\n frac = frac.padEnd(minorDigits, '0')\n const digits = (major + frac).replace(/^0+(?=\\d)/, '')\n if (digits.length > MAX_SIGNIFICANT_DIGITS) return null\n const value = Number.parseInt(digits, 10)\n return Number.isSafeInteger(value) ? value : null\n}\n\n// ---------------------------------------------------------------------------\n// Currency resolution\n// ---------------------------------------------------------------------------\n\ninterface CurrencyContext {\n /** Text before the number run, qualifiers already stripped. */\n before: string\n /** Text after the number run. */\n after: string\n}\n\n/** The ISO code immediately adjacent to the number, or null; `false` on conflict. */\nfunction adjacentIsoCode(ctx: CurrencyContext): string | null | false {\n const beforeMatch = /([A-Z]{3})\\s?$/.exec(ctx.before)\n const afterMatch = /^\\s?([A-Z]{3})(?![A-Za-z])/.exec(ctx.after)\n const codes: string[] = []\n for (const match of [beforeMatch, afterMatch]) {\n const code = match?.[1]\n if (code !== undefined && ISO_4217.has(code) && !codes.includes(code)) codes.push(code)\n }\n if (codes.length > 1) return false\n return codes[0] ?? null\n}\n\n/** Trailing minus sign, removed so `$-5.00` still sees its `$` as adjacent. */\nfunction stripTrailingSign(text: string): string {\n const trimmed = text.trimEnd()\n return /[-−]$/.test(trimmed) ? trimmed.slice(0, -1).trimEnd() : trimmed\n}\n\n/** The currency symbol immediately adjacent to the number, or null; `false` on conflict. */\nfunction adjacentSymbol(ctx: CurrencyContext): string | null | false {\n const before = stripTrailingSign(ctx.before)\n const after = ctx.after.trimStart()\n const found: string[] = []\n for (const symbol of SYMBOLS_BY_LENGTH) {\n if (before.endsWith(symbol) && !found.some((s) => s.endsWith(symbol))) found.push(symbol)\n }\n for (const symbol of SYMBOLS_BY_LENGTH) {\n if (after.startsWith(symbol) && !found.some((s) => s.startsWith(symbol))) found.push(symbol)\n }\n if (found.length > 1) return false\n return found[0] ?? null\n}\n\n/** Applies `hints.currency` to a symbol that denotes more than one currency. */\nfunction resolveSymbol(symbol: string, hint: string | undefined): string | null {\n const entry = SYMBOLS[symbol]\n if (entry === undefined) return null\n if (hint !== undefined) {\n const upper = hint.toUpperCase()\n if (upper === entry.fallback || entry.alternatives.includes(upper)) return upper\n }\n return entry.fallback\n}\n\n// ---------------------------------------------------------------------------\n// Text preparation\n// ---------------------------------------------------------------------------\n\ninterface Prepared {\n text: string\n qualified: boolean\n}\n\n/** Collapses every whitespace variant to a single plain space and trims. */\nfunction normalizeSpaces(text: string): string {\n return text.replace(SPACE_RE, ' ').replace(/ {2,}/g, ' ').trim()\n}\n\n/** Strips one leading and one trailing qualifier, recording that it was there. */\nfunction stripQualifiers(text: string): Prepared {\n let out = text\n let qualified = false\n\n const lower = out.toLowerCase()\n for (const phrase of PREFIX_QUALIFIERS) {\n if (!lower.startsWith(phrase)) continue\n const next = out.charAt(phrase.length)\n if (next !== '' && /[a-z]/i.test(next)) continue\n out = out.slice(phrase.length).trim()\n qualified = true\n break\n }\n\n const lowerEnd = out.toLowerCase()\n for (const phrase of SUFFIX_QUALIFIERS) {\n if (!lowerEnd.endsWith(phrase)) continue\n const prev = out.charAt(out.length - phrase.length - 1)\n if (/[a-z]/i.test(prev)) continue\n out = out.slice(0, out.length - phrase.length).trim()\n qualified = true\n break\n }\n\n return { text: out, qualified }\n}\n\n/**\n * Splits a range into its two operands, or returns null when the text is not a\n * range.\n *\n * The rule is EXACTLY ONE separator in the whole string, with digits on both\n * sides. `1-800-555-1212` has three and `2024-01-15` has two, so neither is a\n * range — and neither survives the one-number rule afterwards either.\n */\nfunction splitRange(text: string): [string, string] | null {\n let separatorIndex = -1\n let separatorLength = 0\n let count = 0\n\n for (const dash of RANGE_DASHES) {\n let at = text.indexOf(dash)\n while (at !== -1) {\n count++\n if (count === 1) {\n separatorIndex = at\n separatorLength = dash.length\n }\n at = text.indexOf(dash, at + dash.length)\n }\n }\n\n if (count === 0) {\n const word = / to /i.exec(text)\n if (word === null) return null\n separatorIndex = word.index\n separatorLength = word[0].length\n } else if (count > 1) {\n return null\n }\n\n const left = text.slice(0, separatorIndex).trim()\n const right = text.slice(separatorIndex + separatorLength).trim()\n if (!/\\d/.test(left) || !/\\d/.test(right)) return null\n return [left, right]\n}\n\n// ---------------------------------------------------------------------------\n// Single-operand parsing\n// ---------------------------------------------------------------------------\n\nfunction parseOperand(text: string, hints: MoneyHints | undefined): Money | null {\n if (text.includes('%')) return null // `20% off` is not a price\n\n // Exactly one number, or we cannot tell which one is the price.\n NUMBER_RUN_RE.lastIndex = 0\n const runs: { value: string; start: number; end: number }[] = []\n let match: RegExpExecArray | null\n while ((match = NUMBER_RUN_RE.exec(text)) !== null) {\n let value = match[0]\n // The run regex is greedy over separators; a run must end on a digit.\n while (value.length > 0 && !/\\d$/.test(value)) value = value.slice(0, -1)\n runs.push({ value, start: match.index, end: match.index + value.length })\n if (runs.length > 1) return null\n }\n const run = runs[0]\n if (run === undefined) return null\n\n const ctx: CurrencyContext = { before: text.slice(0, run.start), after: text.slice(run.end) }\n\n const isoCode = adjacentIsoCode(ctx)\n if (isoCode === false) return null\n const symbol = adjacentSymbol(ctx)\n if (symbol === false) return null\n\n let currency: string | null\n if (isoCode !== null && symbol !== null) {\n // Both present: they must agree. `$49.00 USD` is fine; `$49.00 EUR` is not.\n const fromSymbol = resolveSymbol(symbol, isoCode)\n if (fromSymbol !== isoCode) return null\n currency = isoCode\n } else if (isoCode !== null) {\n currency = isoCode\n } else if (symbol !== null) {\n currency = resolveSymbol(symbol, hints?.currency)\n } else {\n // No marker at all. `hints.currency` may supply one, but ONLY when the text\n // is a bare number: with a hint of USD, `1499` is a price and `4.5 stars`\n // is not, and the difference is the letters.\n const hint = hints?.currency?.toUpperCase()\n if (hint === undefined || !ISO_4217.has(hint)) return null\n if (/[A-Za-z]/.test(ctx.before + ctx.after)) return null\n currency = hint\n }\n if (currency === null || !ISO_4217.has(currency)) return null\n\n const negative = /[-−]\\s?$/.test(stripTrailingSymbol(ctx.before))\n\n const spaced = stripGroupSpacers(run.value)\n if (spaced === null) return null\n const split = splitMajorFraction(spaced, minorUnitDigits(currency))\n if (split === null) return null\n const magnitude = toMinorUnits(split.major, split.fraction, minorUnitDigits(currency))\n if (magnitude === null) return null\n\n return { amount: negative ? -magnitude : magnitude, currency }\n}\n\n/** Removes a trailing currency symbol so a sign in front of it is still visible. */\nfunction stripTrailingSymbol(before: string): string {\n const trimmed = before.trimEnd()\n for (const symbol of SYMBOLS_BY_LENGTH) {\n if (trimmed.endsWith(symbol)) return trimmed.slice(0, trimmed.length - symbol.length)\n }\n return trimmed\n}\n\n// ---------------------------------------------------------------------------\n// parseMoneyText\n// ---------------------------------------------------------------------------\n\n/**\n * Text → `Money`, or `null` when ambiguous. Fails closed, like `formatMoney`.\n *\n * Ranges and qualifiers return the lower bound with `qualified: true`, which\n * excludes them from the D2.4 parity comparison.\n */\nexport function parseMoneyText(text: string, hints?: MoneyHints): ParsedMoney | null {\n if (typeof text !== 'string' || text.length === 0 || text.length > MAX_INPUT_LENGTH) return null\n\n const normalized = normalizeSpaces(text)\n if (!/\\d/.test(normalized)) return null\n\n const prepared = stripQualifiers(normalized)\n const range = splitRange(prepared.text)\n\n if (range === null) {\n const single = parseOperand(prepared.text, hints)\n return single === null ? null : { ...single, qualified: prepared.qualified }\n }\n\n // A range. Only one end usually carries the currency — `$148 – 198` and\n // `148 to 198 USD` are both common — so each end is retried with the other's\n // currency before giving up. The result is the numerically LOWER end, always\n // `qualified`.\n const [leftText, rightText] = range\n let left = parseOperand(leftText, hints)\n const right = parseOperand(rightText, left === null ? hints : { currency: left.currency })\n if (left === null && right !== null) left = parseOperand(leftText, { currency: right.currency })\n\n if (left !== null && right !== null) {\n if (left.currency !== right.currency) return null\n const lower = right.amount < left.amount ? right : left\n return { ...lower, qualified: true }\n }\n const only = left ?? right\n return only === null ? null : { ...only, qualified: true }\n}\n","/**\n * extract.ts — pass 2 of the ARS pipeline: turn one fetched representation into\n * a set of normalised fact observations, scored against the resolved page-kind\n * profile (design §3.5, §3.6).\n *\n * WHAT A \"REPRESENTATION\" IS. The probe returns two captures that differ only in\n * their `Accept` header (§3.3). Each one is turned into an `ArsRepresentation`:\n * a decoded body, its byte length as the probe measured it, the tokenized\n * document when the bytes are HTML, the JSON-LD blocks, and the counted text.\n * Everything downstream reads a representation, never a raw capture, so the\n * markdown path and the HTML path go through the same scoring code.\n *\n * WHICH REPRESENTATION SCORES WHAT — the decision that makes the golden pair\n * (`001-pdp-gateway-md` vs `002-pdp-raw-html`) mean anything:\n *\n * D3 (coverage) and D4 (position) score the AGENT representation, because ARS\n * measures what a caller actually receives. A merchant whose markdown omits\n * `availability` loses coverage even though the HTML declares it — the agent\n * never saw it.\n *\n * D1.3 (render independence) and D5 (structured data) score the HTML\n * representation, because those checks are about the document a caller that\n * only reads HTML gets. JSON-LD does not live in markdown, and \"would this\n * page work without JavaScript\" is a question about HTML.\n *\n * CORROBORATION CROSSES THE TWO. §3.6 defines corroborated as \"observed in ≥2\n * sources (e.g. JSON-LD and visible text)\". A price stated in the negotiated\n * markdown *and* in the HTML's JSON-LD is observed in two sources and is\n * corroborated; that is the only reason a correctly installed gateway can reach\n * an A. But a fact observed ONLY in the HTML does not enter the scored fact set\n * at all — corroboration strengthens a fact the agent received, it never\n * conjures one it did not. See `mergeFacts`.\n *\n * VALUE FACTS vs PRESENCE FACTS. Some facts are compared by value (a price, a\n * title, a phone number); others are only ever \"declared or not\" (shipping,\n * returns, opening hours, question/answer shape). Presence facts normalise to\n * the literal string `declared` from EVERY source, deliberately: two sources\n * that describe the same shipping policy in different words must still\n * corroborate each other, and a free-text comparison would make that\n * non-deterministic. The split is pinned in `PRESENCE_FACTS` below and printed\n * in the spec, because it is the difference between \"we compared the values\" and\n * \"we compared whether you said anything\".\n *\n * EVERYTHING HERE IS PINNED DATA, NOT INFERENCE. The label lexicon, the\n * availability vocabulary, the no-published-price phrases, the schema.org\n * property aliases: all tables, all versioned. An extractor that guessed would\n * make `score()` non-reproducible in a second implementation, which is the one\n * property the whole package exists to provide.\n */\n\nimport { attr, countedText, elementText, tokenizeHtml } from './html'\nimport type { HtmlDocument } from './html'\nimport { parseMoneyText } from './parse-money'\nimport type {\n ArsAudience,\n ArsAudienceDecision,\n ArsFactKind,\n ArsFactObservation,\n ArsFactProfile,\n ArsHttpCapture,\n ArsPolicyReport,\n ArsRuleset,\n} from './types'\n\n// ---------------------------------------------------------------------------\n// UTF-8 offsets\n// ---------------------------------------------------------------------------\n\n/**\n * UTF-8 byte length of a JavaScript string, counting a lone surrogate as 3\n * bytes — the width WHATWG encoding gives U+FFFD, which is what a lone\n * surrogate actually costs on the wire. Matches `Utf8Cursor` in `./html`, which\n * is why offsets from the two files are in the same address space.\n */\nexport function utf8Length(text: string): number {\n let bytes = 0\n for (let i = 0; i < text.length; i++) {\n const code = text.charCodeAt(i)\n if (code < 0x80) bytes += 1\n else if (code < 0x800) bytes += 2\n else if (code >= 0xd800 && code <= 0xdbff) {\n const next = i + 1 < text.length ? text.charCodeAt(i + 1) : 0\n if (next >= 0xdc00 && next <= 0xdfff) {\n bytes += 4\n i++\n } else bytes += 3\n } else bytes += 3\n }\n return bytes\n}\n\n// ---------------------------------------------------------------------------\n// JSON-LD\n// ---------------------------------------------------------------------------\n\n/** A flattened JSON-LD node: one object with an `@type`, wherever it was nested. */\nexport interface JsonLdNode {\n /** `@type` values with any `http(s)://schema.org/` prefix stripped. Always ≥1 entry. */\n readonly types: readonly string[]\n readonly value: Readonly<Record<string, unknown>>\n /** UTF-8 byte offset of the block the node came from. */\n readonly offset: number\n}\n\n/** What `parseJsonLd` observed, including the blocks that failed — D5.1 scores both. */\nexport interface JsonLdReport {\n readonly nodes: readonly JsonLdNode[]\n readonly blocks: number\n readonly parsed: number\n}\n\nconst SCHEMA_PREFIX = /^https?:\\/\\/schema\\.org\\//\n\nfunction stripSchemaPrefix(type: string): string {\n return type.replace(SCHEMA_PREFIX, '')\n}\n\n/** Types from a node's `@type`, which may be a string or an array of strings. */\nfunction typesOf(value: Record<string, unknown>): string[] {\n const raw = value['@type']\n if (typeof raw === 'string') return [stripSchemaPrefix(raw)]\n if (Array.isArray(raw)) {\n const out: string[] = []\n for (const entry of raw) if (typeof entry === 'string') out.push(stripSchemaPrefix(entry))\n return out\n }\n return []\n}\n\n/** Depth cap on JSON-LD traversal. Deeper than any real graph; stops a hostile nesting bomb. */\nconst JSON_LD_MAX_DEPTH = 12\n\nfunction collectNodes(\n value: unknown,\n offset: number,\n depth: number,\n out: JsonLdNode[],\n seen: Set<object>,\n): void {\n if (depth > JSON_LD_MAX_DEPTH || value === null || typeof value !== 'object') return\n if (seen.has(value)) return\n seen.add(value)\n\n if (Array.isArray(value)) {\n for (const entry of value) collectNodes(entry, offset, depth + 1, out, seen)\n return\n }\n\n const record = value as Record<string, unknown>\n const types = typesOf(record)\n if (types.length > 0) out.push({ types, value: record, offset })\n\n for (const [key, child] of Object.entries(record)) {\n if (key === '@context') continue\n collectNodes(child, offset, depth + 1, out, seen)\n }\n}\n\n/**\n * Parses every JSON-LD block. A block that does not parse is counted and\n * dropped: D5.1 scores \"present **and parses**\", so fixture `033-invalid-jsonld`\n * needs the block count and the parsed count to differ.\n */\nexport function parseJsonLd(blocks: readonly { text: string; offset: number }[]): JsonLdReport {\n const nodes: JsonLdNode[] = []\n let parsed = 0\n for (const block of blocks) {\n let value: unknown\n try {\n value = JSON.parse(block.text) as unknown\n } catch {\n continue\n }\n parsed++\n collectNodes(value, block.offset, 0, nodes, new Set<object>())\n }\n return { nodes, blocks: blocks.length, parsed }\n}\n\n/**\n * Reads a dotted property path off a node, entering array members: `offers.price`\n * matches `offers[0].price`. Returns the first non-empty scalar found, or null.\n * The notation is the one `DEFAULT_RULESET.requiredProperties` is written in.\n */\nexport function readPath(node: JsonLdNode, path: string): string | null {\n const segments = path.split('.')\n let frontier: unknown[] = [node.value]\n for (const segment of segments) {\n const next: unknown[] = []\n for (const current of frontier) {\n if (current === null || typeof current !== 'object') continue\n if (Array.isArray(current)) {\n for (const entry of current) {\n if (entry !== null && typeof entry === 'object' && !Array.isArray(entry)) {\n const child = (entry as Record<string, unknown>)[segment]\n if (child !== undefined) next.push(child)\n }\n }\n continue\n }\n const child = (current as Record<string, unknown>)[segment]\n if (child !== undefined) next.push(child)\n }\n frontier = next\n if (frontier.length === 0) return null\n }\n for (const found of frontier) {\n const scalar = scalarOf(found)\n if (scalar !== null) return scalar\n }\n return null\n}\n\n/**\n * A scalar reading of a JSON-LD value. Objects yield their `name`, `@id` or\n * `value` — `brand: {\"@type\":\"Brand\",\"name\":\"X\"}` is the common real shape and\n * refusing to read it would cost merchants points for correct markup.\n */\nfunction scalarOf(value: unknown): string | null {\n if (typeof value === 'string') return value.trim().length > 0 ? value.trim() : null\n if (typeof value === 'number' && Number.isFinite(value)) return String(value)\n if (typeof value === 'boolean') return String(value)\n if (Array.isArray(value)) {\n for (const entry of value) {\n const scalar = scalarOf(entry)\n if (scalar !== null) return scalar\n }\n return null\n }\n if (value !== null && typeof value === 'object') {\n const record = value as Record<string, unknown>\n for (const key of ['name', 'value', '@id', 'url', 'headline']) {\n const scalar = scalarOf(record[key])\n if (scalar !== null) return scalar\n }\n }\n return null\n}\n\n/** True when the path resolves to anything at all — what D5.2 counts. */\nexport function hasPath(node: JsonLdNode, path: string): boolean {\n return readPath(node, path) !== null\n}\n\n// ---------------------------------------------------------------------------\n// Representations\n// ---------------------------------------------------------------------------\n\nexport type ArsRepresentationKind = 'html' | 'markdown' | 'text' | 'json' | 'other'\n\nexport interface ArsRepresentation {\n /** Classified from the `Content-Type` header alone. See `looksLikeHtml` for the body's opinion. */\n readonly kind: ArsRepresentationKind\n /** Lowercased media type without parameters, or null when the header is absent. */\n readonly contentType: string | null\n /** The decoded body. */\n readonly body: string\n /** Byte length AS THE PROBE MEASURED IT (`ArsHttpCapture.bytes`), not recomputed. */\n readonly bytes: number\n /** Tokenized document, present whenever the bytes are HTML however they are labelled. */\n readonly doc: HtmlDocument | null\n readonly jsonLd: JsonLdReport\n /** Counted text (§3.6) for HTML; the body itself for every other kind. */\n readonly text: string\n /** The body's own opinion, independent of the header. D2.1 scores the disagreement. */\n readonly looksLikeHtml: boolean\n readonly truncated: boolean\n readonly finalUrl: string\n readonly headers: Readonly<Record<string, readonly string[]>>\n}\n\n/** First value of a header, or null. Header names are lowercased by the probe. */\nexport function header(\n headers: Readonly<Record<string, readonly string[]>>,\n name: string,\n): string | null {\n const values = headers[name]\n return values !== undefined && values.length > 0 ? (values[0] ?? null) : null\n}\n\n/** All values of a header, in order. `Link` is routinely repeated and is scored twice over. */\nexport function headerAll(\n headers: Readonly<Record<string, readonly string[]>>,\n name: string,\n): readonly string[] {\n return headers[name] ?? []\n}\n\n/** Media type without parameters, lowercased. */\nexport function mediaType(contentType: string | null): string | null {\n if (contentType === null) return null\n const semi = contentType.indexOf(';')\n const value = (semi === -1 ? contentType : contentType.slice(0, semi)).trim().toLowerCase()\n return value.length > 0 ? value : null\n}\n\nfunction classifyMediaType(type: string | null): ArsRepresentationKind {\n if (type === null) return 'other'\n if (type === 'text/html' || type === 'application/xhtml+xml') return 'html'\n if (type === 'text/markdown' || type === 'text/x-markdown') return 'markdown'\n if (type === 'text/plain') return 'text'\n if (type === 'application/json' || type === 'application/ld+json' || type.endsWith('+json')) {\n return 'json'\n }\n return 'other'\n}\n\n/**\n * Does the body look like HTML regardless of what the header claims? Bounded to\n * the first 1 KiB so the test is O(1) on a 2 MiB body. Fixture\n * `036-negotiation-wrong-content-type` is exactly the case where the header and\n * this function disagree, and D2.1 pays for it.\n */\nfunction bodyLooksLikeHtml(body: string): boolean {\n const head = body.slice(0, 1024).trimStart().toLowerCase()\n return head.startsWith('<!doctype html') || head.startsWith('<html') || head.startsWith('<?xml')\n ? true\n : head.includes('<html') || head.includes('<head>') || head.includes('<body')\n}\n\n/**\n * Builds a representation from a capture. Returns null when the body is absent:\n * `ArsHttpCapture.body` is optional because a PUBLISHED evidence bundle carries\n * the hash and not the bytes (§3.9), and a bundle without bytes cannot be\n * re-scored — `score()` reports `unscored / evidence-incomplete` rather than\n * inventing a zero.\n */\nexport function buildRepresentation(capture: ArsHttpCapture): ArsRepresentation | null {\n if (typeof capture.body !== 'string') return null\n const contentType = mediaType(header(capture.headers, 'content-type'))\n const declared = classifyMediaType(contentType)\n const looksLikeHtml = bodyLooksLikeHtml(capture.body)\n\n // Tokenize whenever the BYTES are HTML, whatever the header says. A merchant\n // with a mislabelled content type already loses 10 points on D2.1; taking\n // their fact coverage as well would charge them twice for one mistake.\n const doc = declared === 'html' || looksLikeHtml ? tokenizeHtml(capture.body) : null\n\n const jsonLd =\n doc !== null\n ? parseJsonLd(doc.jsonLd.map((block) => ({ text: block.text, offset: block.offset })))\n : declared === 'json'\n ? parseJsonLd([{ text: capture.body, offset: 0 }])\n : { nodes: [], blocks: 0, parsed: 0 }\n\n return {\n kind: declared,\n contentType,\n body: capture.body,\n bytes: capture.bytes,\n doc,\n jsonLd,\n text: doc !== null ? countedText(doc) : capture.body,\n looksLikeHtml,\n truncated: capture.truncated,\n finalUrl: capture.finalUrl,\n headers: capture.headers,\n }\n}\n\n// ---------------------------------------------------------------------------\n// Facts — the internal shape\n// ---------------------------------------------------------------------------\n\nexport type ArsFactSource = ArsFactObservation['source']\n\n/**\n * One observation before merging. `qualified` and `element` are internal:\n * `ArsFactObservation` (§3.9) carries neither, and this file exists to keep the\n * published shape exactly as the design wrote it.\n */\nexport interface ExtractedFact {\n readonly kind: ArsFactKind\n readonly normalized: string\n readonly source: ArsFactSource\n readonly offset: number\n /** True for ranges and qualifiers. Excluded from the D2.4 parity comparison (§3.11). */\n readonly qualified: boolean\n}\n\n/** A merged fact: the published observation plus what merging learned. */\nexport interface MergedFact extends ArsFactObservation {\n readonly qualified: boolean\n /** Distinct sources that reported THIS value. `corroborated` is `length >= 2`. */\n readonly sources: readonly ArsFactSource[]\n}\n\n/**\n * Source precedence, used only to break an offset tie. Declaration order is the\n * order of the union in §3.9, so a second implementation reads it off the\n * published type rather than out of this file.\n */\nconst SOURCE_ORDER: readonly ArsFactSource[] = [\n 'json-ld',\n 'microdata',\n 'meta',\n 'html-text',\n 'negotiated',\n]\n\n/**\n * Facts that are only ever \"declared or not\". Every source normalises them to\n * the literal `declared`, so two sources that word the same shipping policy\n * differently still corroborate one another. See the file header.\n */\nconst PRESENCE_FACTS: ReadonlySet<ArsFactKind> = new Set<ArsFactKind>([\n 'shipping',\n 'returns',\n 'hours',\n 'service-area',\n 'eligibility',\n 'question-answer',\n 'item-link',\n])\n\nconst DECLARED = 'declared'\n\n/**\n * Merges observations into the published fact set.\n *\n * `primary` is the representation the agent received; `corroborating` is the\n * other one. A fact appears in the output only if the AGENT saw it. The\n * representative observation is the one with the lowest byte offset (ties broken\n * by `SOURCE_ORDER`, then lexicographically by value) — lowest offset, because\n * D4.1 scores the byte offset at which a fact first becomes available.\n * `corroborated` counts the distinct sources, across BOTH representations, that\n * reported the representative's exact normalised value; a source reporting a\n * different value corroborates nothing, which is what makes fixture\n * `034-jsonld-price-mismatch` fail to corroborate rather than agree.\n */\nexport function mergeFacts(\n primary: readonly ExtractedFact[],\n corroborating: readonly ExtractedFact[],\n): MergedFact[] {\n const byKind = new Map<ArsFactKind, ExtractedFact[]>()\n for (const fact of primary) {\n const list = byKind.get(fact.kind)\n if (list === undefined) byKind.set(fact.kind, [fact])\n else list.push(fact)\n }\n\n const merged: MergedFact[] = []\n for (const [kind, observations] of byKind) {\n const representative = observations.reduce((best, candidate) =>\n betterObservation(best, candidate),\n )\n const sources: ArsFactSource[] = []\n for (const fact of [...observations, ...corroborating]) {\n if (fact.kind !== kind) continue\n if (fact.normalized !== representative.normalized) continue\n if (!sources.includes(fact.source)) sources.push(fact.source)\n }\n merged.push({\n kind,\n normalized: representative.normalized,\n source: representative.source,\n offset: representative.offset,\n corroborated: sources.length >= 2,\n qualified: representative.qualified,\n sources,\n })\n }\n\n merged.sort((a, b) => (a.offset === b.offset ? cmp(a.kind, b.kind) : a.offset - b.offset))\n return merged\n}\n\nfunction betterObservation(a: ExtractedFact, b: ExtractedFact): ExtractedFact {\n if (a.offset !== b.offset) return a.offset < b.offset ? a : b\n const rank = SOURCE_ORDER.indexOf(a.source) - SOURCE_ORDER.indexOf(b.source)\n if (rank !== 0) return rank < 0 ? a : b\n return cmp(a.normalized, b.normalized) <= 0 ? a : b\n}\n\nfunction cmp(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0\n}\n\n// ---------------------------------------------------------------------------\n// Normalisation\n// ---------------------------------------------------------------------------\n\nconst TITLE_SEPARATORS = [' | ', ' — ', ' – ', ' · ', ' :: ', ' » ']\n\n/**\n * Collapse whitespace, cut at the first pinned separator, lowercase.\n *\n * The cut is what lets `<title>Alpine Trail Pack 28L — 420D Ripstop | Basecamp\n * Supply Co</title>` corroborate a JSON-LD `name` of `Alpine Trail Pack 28L`.\n * Without it, essentially no real page would ever have a corroborated title,\n * and `title` is a core fact for seven of the eight page kinds.\n */\nexport function normalizeTitle(text: string): string {\n const collapsed = text.replace(/\\s+/g, ' ').trim()\n let cut = collapsed\n for (const separator of TITLE_SEPARATORS) {\n const at = cut.indexOf(separator)\n if (at > 0) cut = cut.slice(0, at)\n }\n return cut.trim().toLowerCase()\n}\n\n/** Collapse whitespace + lowercase, capped so one long description cannot bloat a result. */\nconst MAX_NORMALIZED_TEXT = 200\n\nexport function normalizeText(text: string): string {\n return text.replace(/\\s+/g, ' ').trim().toLowerCase().slice(0, MAX_NORMALIZED_TEXT)\n}\n\n/**\n * Money → `<ISO> <minor units>`, e.g. `USD 14800`. Currency travels with the\n * amount so the D2.4 parity comparison cannot match 14800 JPY against 14800 USD,\n * and `currency` is still reported separately because it is its own core fact.\n */\nfunction normalizeMoney(amount: number, currency: string): string {\n return `${currency} ${amount}`\n}\n\n/** ISO 8601 date, day precision. Anything that is not a recognisable date is not a fact. */\nexport function normalizeDate(text: string): string | null {\n const trimmed = text.trim()\n const iso = /^(\\d{4})-(\\d{2})-(\\d{2})/.exec(trimmed)\n if (iso !== null) return `${iso[1]}-${iso[2]}-${iso[3]}`\n const slashes = /^(\\d{4})\\/(\\d{2})\\/(\\d{2})/.exec(trimmed)\n if (slashes !== null) return `${slashes[1]}-${slashes[2]}-${slashes[3]}`\n const named = /^(\\d{1,2}) ([A-Za-z]{3,9}) (\\d{4})$/.exec(trimmed)\n if (named !== null) {\n const month = MONTHS.indexOf((named[2] ?? '').slice(0, 3).toLowerCase())\n if (month >= 0) return `${named[3]}-${pad2(month + 1)}-${pad2(Number(named[1]))}`\n }\n const american = /^([A-Za-z]{3,9}) (\\d{1,2}), (\\d{4})$/.exec(trimmed)\n if (american !== null) {\n const month = MONTHS.indexOf((american[1] ?? '').slice(0, 3).toLowerCase())\n if (month >= 0) return `${american[3]}-${pad2(month + 1)}-${pad2(Number(american[2]))}`\n }\n return null\n}\n\nconst MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']\n\nfunction pad2(value: number): string {\n return value < 10 ? `0${value}` : String(value)\n}\n\n/**\n * The availability vocabulary, pinned. schema.org URLs, the bare enum names and\n * the visible-text phrases all collapse to one of six tokens, because \"In stock\"\n * on the page and `https://schema.org/InStock` in the JSON-LD are the same fact\n * and must corroborate.\n */\nconst AVAILABILITY_TOKENS: readonly (readonly [string, string])[] = [\n ['limitedavailability', 'limited'],\n ['onlineonly', 'instock'],\n ['instoreonly', 'instock'],\n ['presale', 'preorder'],\n ['preorder', 'preorder'],\n ['backorder', 'backorder'],\n ['discontinued', 'discontinued'],\n ['soldout', 'outofstock'],\n ['outofstock', 'outofstock'],\n ['instock', 'instock'],\n]\n\n/** Visible-text phrases, matched against normalised text. Longest first. */\nconst AVAILABILITY_PHRASES: readonly (readonly [string, string])[] = [\n ['limited availability', 'limited'],\n ['limited stock', 'limited'],\n ['currently unavailable', 'outofstock'],\n ['temporarily unavailable', 'outofstock'],\n ['out of stock', 'outofstock'],\n ['discontinued', 'discontinued'],\n ['back order', 'backorder'],\n ['backorder', 'backorder'],\n ['pre-order', 'preorder'],\n ['preorder', 'preorder'],\n ['sold out', 'outofstock'],\n ['in stock', 'instock'],\n ['available now', 'instock'],\n]\n\nexport function normalizeAvailability(value: string): string | null {\n const squashed = value.toLowerCase().replace(/[^a-z]/g, '')\n for (const [needle, token] of AVAILABILITY_TOKENS) {\n if (squashed.endsWith(needle) || squashed === needle) return token\n }\n return null\n}\n\n/**\n * \"We score honesty, not disclosure\" (§3.5): an explicit statement that there is\n * no published price satisfies the `price` core fact. The list is pinned and\n * deliberately short — it contains only phrases that state the absence of a\n * price, never phrases that merely fail to state one.\n */\nconst NO_PUBLISHED_PRICE: readonly string[] = [\n 'price on request',\n 'pricing on request',\n 'price on application',\n 'contact us for pricing',\n 'contact for pricing',\n 'contact us for a quote',\n 'no published price',\n 'pricing available on request',\n]\n\nconst UNPRICED = 'unpriced'\n\n/** Phone → `+` and digits. `(415) 555-0142` and `+1 415 555 0142` are one fact. */\nexport function normalizePhone(value: string): string | null {\n const trimmed = value.trim()\n const plus = trimmed.startsWith('+') || trimmed.startsWith('tel:+')\n const digits = trimmed.replace(/\\D/g, '')\n if (digits.length < 7 || digits.length > 15) return null\n return plus ? `+${digits}` : digits\n}\n\n// ---------------------------------------------------------------------------\n// Money tokens in free text\n// ---------------------------------------------------------------------------\n\n/**\n * Single-character currency symbols that may START a money span. Multi-character\n * markers (`R$`, `kr`, `CHF`) are reached through the ISO-code branch instead: a\n * scanner that treated `R` or `k` as a currency start would open a span on every\n * capital R on the page and hand `parseMoneyText` garbage to reject.\n */\nconst CURRENCY_SYMBOLS = '$€£¥₹₩₪₫₴₦₱฿₺'\nconst DIGITS = '0123456789'\n/** Comma, period, both apostrophes, plain space, NBSP, NARROW NBSP. */\nconst MONEY_SEPARATORS = \".,'’   \"\nconst MONEY_PREFIX_QUALIFIERS = [\n 'starting from',\n 'starting at',\n 'prices from',\n 'priced from',\n 'as little as',\n 'as low as',\n 'starts at',\n 'from',\n]\nconst RANGE_JOINERS = ['—', '–', '-', ' to ']\n\n/**\n * Finds money-shaped substrings and hands each to `parseMoneyText`.\n *\n * Written as a scanner rather than a regex on purpose: the pattern that would\n * express this correctly needs nested quantifiers over overlapping character\n * classes, which is both a backtracking hazard on attacker-supplied bytes and\n * much harder to reimplement in another language than twenty lines of loop.\n *\n * The window handed to the parser includes an immediately preceding qualifier\n * (`From $9`) and a following range operand (`$148 – $198`), because\n * `parseMoneyText` resolves both to the lower bound with `qualified: true`, and a\n * qualified price is excluded from D2.4 parity (§3.11). Slicing the bare token\n * would silently turn a range into an exact price.\n */\nexport function findMoneyPhrases(text: string): { phrase: string; index: number }[] {\n const found: { phrase: string; index: number }[] = []\n const limit = Math.min(text.length, MAX_SCAN_CHARS)\n let i = 0\n while (i < limit) {\n const spanEnd = readMoneySpan(text, i, limit)\n if (spanEnd === null) {\n i++\n continue\n }\n let start = i\n let end = spanEnd\n\n // Leading qualifier.\n const before = text.slice(Math.max(0, start - 20), start).toLowerCase()\n for (const qualifier of MONEY_PREFIX_QUALIFIERS) {\n if (before.trimEnd().endsWith(qualifier)) {\n start = Math.max(0, start - (before.length - before.trimEnd().length) - qualifier.length)\n break\n }\n }\n\n // Trailing range operand.\n for (const joiner of RANGE_JOINERS) {\n const after = text.slice(end, end + joiner.length + 2)\n const at = after.indexOf(joiner)\n if (at === -1 || at > 1) continue\n const secondStart = end + at + joiner.length\n const secondEnd = readMoneySpan(text, skipSpaces(text, secondStart, limit), limit)\n if (secondEnd !== null) end = secondEnd\n break\n }\n\n found.push({ phrase: text.slice(start, end), index: start })\n i = end\n }\n return found\n}\n\n/** Bounded scan window. A 2 MiB body is data, not a budget. */\nconst MAX_SCAN_CHARS = 400_000\n\nfunction skipSpaces(text: string, from: number, limit: number): number {\n let i = from\n while (i < limit && text.charAt(i) === ' ') i++\n return i\n}\n\n/**\n * Reads one money-shaped span starting at `from`, or null. A span is a currency\n * marker adjacent to a digit run, in either order; the marker is a symbol from\n * the pinned set or an uppercase three-letter token.\n */\nfunction readMoneySpan(text: string, from: number, limit: number): number | null {\n const char = text.charAt(from)\n if (CURRENCY_SYMBOLS.includes(char) && char !== '') {\n let i = from + 1\n if (text.charAt(i) === ' ') i++\n if (!DIGITS.includes(text.charAt(i))) return null\n return readNumberRun(text, i, limit)\n }\n if (DIGITS.includes(char)) {\n // Only start a span at the beginning of a number run.\n const previous = from > 0 ? text.charAt(from - 1) : ''\n if (DIGITS.includes(previous) || MONEY_SEPARATORS.includes(previous)) return null\n const end = readNumberRun(text, from, limit)\n let i = end\n if (text.charAt(i) === ' ') i++\n const symbol = text.charAt(i)\n if (CURRENCY_SYMBOLS.includes(symbol) && symbol !== '') return i + 1\n const code = text.slice(i, i + 3)\n if (/^[A-Z]{3}$/.test(code) && !/[A-Za-z]/.test(text.charAt(i + 3))) return i + 3\n return null\n }\n if (/[A-Z]/.test(char) && from + 3 <= limit) {\n const code = text.slice(from, from + 3)\n if (!/^[A-Z]{3}$/.test(code)) return null\n if (from > 0 && /[A-Za-z]/.test(text.charAt(from - 1))) return null\n let i = from + 3\n if (text.charAt(i) === ' ') i++\n if (!DIGITS.includes(text.charAt(i))) return null\n return readNumberRun(text, i, limit)\n }\n return null\n}\n\nfunction readNumberRun(text: string, from: number, limit: number): number {\n let i = from\n let end = from\n while (i < limit) {\n const char = text.charAt(i)\n if (DIGITS.includes(char)) {\n i++\n end = i\n continue\n }\n if (MONEY_SEPARATORS.includes(char) && char !== '') {\n i++\n continue\n }\n break\n }\n return end\n}\n\n// ---------------------------------------------------------------------------\n// Label lexicon — the key/value shape of markdown and of `<dt>`-style HTML\n// ---------------------------------------------------------------------------\n\n/**\n * Pinned label → fact mapping. This is how facts are read out of the negotiated\n * markdown representation, whose shape is `- **Price:** $148.00` (see\n * `@rebilder/render-md`), and out of definition-list HTML.\n *\n * Pinned rather than fuzzy-matched for the usual reason: a lexicon that grew per\n * page would make the same bytes score differently in two implementations.\n * Additions land as a MINOR.\n */\nconst LABEL_LEXICON: readonly (readonly [string, ArsFactKind])[] = [\n ['price', 'price'],\n ['cost', 'price'],\n ['currency', 'currency'],\n ['availability', 'availability'],\n ['stock', 'availability'],\n ['brand', 'brand'],\n ['manufacturer', 'brand'],\n ['sku', 'sku'],\n ['item number', 'sku'],\n ['product code', 'sku'],\n ['mpn', 'sku'],\n ['shipping', 'shipping'],\n ['delivery', 'shipping'],\n ['returns', 'returns'],\n ['return policy', 'returns'],\n ['refunds', 'returns'],\n ['description', 'description'],\n ['summary', 'description'],\n ['updated', 'updated'],\n ['last updated', 'updated'],\n ['modified', 'updated'],\n ['published', 'published'],\n ['date published', 'published'],\n ['author', 'author'],\n ['written by', 'author'],\n ['publisher', 'authority'],\n ['organization', 'org-name'],\n ['organisation', 'org-name'],\n ['company', 'org-name'],\n ['business', 'org-name'],\n ['address', 'address'],\n ['location', 'address'],\n ['phone', 'phone'],\n ['telephone', 'phone'],\n ['tel', 'phone'],\n ['email', 'email'],\n ['e-mail', 'email'],\n ['hours', 'hours'],\n ['opening hours', 'hours'],\n ['duration', 'duration'],\n ['length', 'duration'],\n ['eligibility', 'eligibility'],\n ['requirements', 'eligibility'],\n ['section', 'section'],\n ['category', 'section'],\n ['topic', 'section'],\n ['service area', 'service-area'],\n ['areas served', 'service-area'],\n ['items', 'item-count'],\n ['item count', 'item-count'],\n]\n\n/** Strips markdown list bullets, emphasis and heading marks from a label. */\nfunction normalizeLabel(raw: string): string {\n return raw\n .replace(/^[\\s>*\\-+#]+/, '')\n .replace(/[*_`]/g, '')\n .trim()\n .toLowerCase()\n}\n\ninterface LabelledValue {\n kind: ArsFactKind\n value: string\n index: number\n}\n\n/**\n * Reads `Label: value` lines. Handles the markdown emphasis form\n * (`- **Price:** $148.00`), the plain form (`Price: $148.00`) and nothing else —\n * a colon inside prose is not a label, which is why the label must be the first\n * thing on the line and no longer than `MAX_LABEL_CHARS`.\n */\nfunction readLabelledLines(text: string): LabelledValue[] {\n const out: LabelledValue[] = []\n let cursor = 0\n for (const line of text.split('\\n')) {\n const lineStart = cursor\n cursor += line.length + 1\n const colon = line.indexOf(':')\n if (colon === -1 || colon > MAX_LABEL_CHARS) continue\n const label = normalizeLabel(line.slice(0, colon))\n if (label.length === 0) continue\n const value = line\n .slice(colon + 1)\n .replace(/^[\\s*_`]+/, '')\n .trim()\n if (value.length === 0) continue\n for (const [needle, kind] of LABEL_LEXICON) {\n if (label !== needle) continue\n out.push({ kind, value, index: lineStart + colon + 1 })\n break\n }\n }\n return out\n}\n\nconst MAX_LABEL_CHARS = 32\n\n// ---------------------------------------------------------------------------\n// Extraction context\n// ---------------------------------------------------------------------------\n\nexport interface ExtractContext {\n readonly profile: ArsFactProfile\n readonly ruleset: ArsRuleset\n /** Absolute URL the capture resolved to, used as the base for relative links. */\n readonly baseUrl: string\n /** Origin of the target, for the same-origin test on `item-link`. */\n readonly origin: string\n /** ISO code from structured data, if any. Disambiguates `$` and a bare `1.500`. */\n readonly currencyHint: string | undefined\n}\n\n/** Facts the caller wants: the profile's core plus extended set, as one lookup. */\nfunction wanted(profile: ArsFactProfile): ReadonlySet<ArsFactKind> {\n return new Set<ArsFactKind>([...profile.core, ...profile.extended])\n}\n\n/**\n * Pass 2 (§3.5): extract against the RESOLVED profile. Only facts the profile\n * names are extracted, which is the mechanism that caps coverage at the profile\n * size and makes fixtures `031-keyword-stuffed` and `032-density-baseline` score\n * identically — a page can invent a hundred extra facts and none of them counts.\n */\nexport function extractFacts(\n representation: ArsRepresentation,\n context: ExtractContext,\n): ExtractedFact[] {\n const facts: ExtractedFact[] = []\n const want = wanted(context.profile)\n const push = (fact: ExtractedFact): void => {\n if (want.has(fact.kind)) facts.push(fact)\n }\n\n for (const node of representation.jsonLd.nodes) extractFromJsonLd(node, context, push)\n\n if (representation.doc !== null) {\n extractFromHtml(representation.doc, context, push)\n } else {\n extractFromPlainText(representation, context, push)\n }\n\n return facts\n}\n\n// ---------------------------------------------------------------------------\n// JSON-LD extraction\n// ---------------------------------------------------------------------------\n\n/**\n * Property aliases per fact, in precedence order. Written as paths so\n * `offers.price` reaches into an `Offer` and `offers.lowPrice` reaches into an\n * `AggregateOffer` — the shape Shopify actually emits.\n */\nconst JSON_LD_PATHS: readonly (readonly [ArsFactKind, readonly string[]])[] = [\n ['title', ['name', 'headline']],\n ['description', ['description', 'abstract']],\n ['price', ['offers.price', 'offers.lowPrice', 'offers.priceSpecification.price', 'price']],\n ['currency', ['offers.priceCurrency', 'offers.priceSpecification.priceCurrency', 'priceCurrency']],\n ['availability', ['offers.availability', 'availability']],\n ['brand', ['brand']],\n ['sku', ['sku', 'mpn', 'gtin13', 'gtin']],\n ['shipping', ['offers.shippingDetails', 'shippingDetails']],\n ['returns', ['offers.hasMerchantReturnPolicy', 'hasMerchantReturnPolicy']],\n ['org-name', ['name']],\n ['address', ['address']],\n ['hours', ['openingHours', 'openingHoursSpecification']],\n ['phone', ['telephone', 'contactPoint.telephone']],\n ['email', ['email', 'contactPoint.email']],\n ['service-area', ['areaServed', 'serviceArea']],\n ['author', ['author']],\n ['authority', ['publisher', 'author']],\n ['section', ['articleSection', 'genre']],\n ['published', ['datePublished', 'dateCreated']],\n ['updated', ['dateModified']],\n ['duration', ['duration', 'timeRequired']],\n ['eligibility', ['eligibleCustomerType', 'audience']],\n ['primary-action-url', ['potentialAction.target', 'potentialAction.url']],\n ['question-answer', ['mainEntity.acceptedAnswer']],\n ['item-count', ['numberOfItems']],\n ['item-link', ['itemListElement.url', 'itemListElement.item']],\n]\n\n/** Types whose `name` is an organisation name rather than a page title. */\nconst ORG_TYPES = new Set([\n 'Organization',\n 'LocalBusiness',\n 'Store',\n 'Restaurant',\n 'Corporation',\n 'NGO',\n 'GovernmentOrganization',\n 'EducationalOrganization',\n 'MedicalBusiness',\n 'ProfessionalService',\n 'FoodEstablishment',\n 'LodgingBusiness',\n 'AutomotiveBusiness',\n 'HealthAndBeautyBusiness',\n 'SportsActivityLocation',\n 'Place',\n])\n\nfunction extractFromJsonLd(\n node: JsonLdNode,\n context: ExtractContext,\n push: (fact: ExtractedFact) => void,\n): void {\n const isOrg = node.types.some((type) => ORG_TYPES.has(type))\n for (const [kind, paths] of JSON_LD_PATHS) {\n // `name` means two different things depending on the node's type; reading it\n // as both would let one string corroborate itself across two fact kinds.\n if (kind === 'title' && isOrg) continue\n if (kind === 'org-name' && !isOrg) continue\n\n for (const path of paths) {\n const raw = readPath(node, path)\n if (raw === null) continue\n const normalized = normalizeFactValue(kind, raw, context)\n if (normalized === null) continue\n push({ kind, normalized: normalized.value, source: 'json-ld', offset: node.offset, qualified: normalized.qualified })\n break\n }\n }\n}\n\ninterface NormalizedValue {\n value: string\n qualified: boolean\n}\n\n/** One normaliser, shared by every source, so the same fact from two places matches. */\nfunction normalizeFactValue(\n kind: ArsFactKind,\n raw: string,\n context: ExtractContext,\n): NormalizedValue | null {\n if (PRESENCE_FACTS.has(kind)) return { value: DECLARED, qualified: false }\n\n switch (kind) {\n case 'title':\n return raw.trim().length === 0 ? null : { value: normalizeTitle(raw), qualified: false }\n case 'price': {\n const lowered = raw.trim().toLowerCase()\n if (NO_PUBLISHED_PRICE.some((phrase) => lowered.includes(phrase))) {\n return { value: UNPRICED, qualified: false }\n }\n const money = parseMoneyText(raw, { currency: context.currencyHint })\n return money === null\n ? null\n : { value: normalizeMoney(money.amount, money.currency), qualified: money.qualified }\n }\n case 'currency': {\n const code = raw.trim().toUpperCase()\n return /^[A-Z]{3}$/.test(code) ? { value: code, qualified: false } : null\n }\n case 'availability': {\n const token = normalizeAvailability(raw)\n return token === null ? null : { value: token, qualified: false }\n }\n case 'phone': {\n const phone = normalizePhone(raw)\n return phone === null ? null : { value: phone, qualified: false }\n }\n case 'email': {\n const email = raw.trim().replace(/^mailto:/i, '').toLowerCase()\n return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email) ? { value: email, qualified: false } : null\n }\n case 'published':\n case 'updated': {\n const date = normalizeDate(raw)\n return date === null ? null : { value: date, qualified: false }\n }\n case 'duration': {\n const minutes = normalizeDuration(raw)\n return minutes === null ? null : { value: minutes, qualified: false }\n }\n case 'item-count': {\n const count = Number.parseInt(raw.replace(/[^0-9]/g, ''), 10)\n return Number.isFinite(count) && count > 0 ? { value: String(count), qualified: false } : null\n }\n case 'primary-action-url': {\n const absolute = absoluteUrl(raw, context.baseUrl)\n return absolute === null ? null : { value: absolute, qualified: false }\n }\n default:\n return raw.trim().length === 0 ? null : { value: normalizeText(raw), qualified: false }\n }\n}\n\n/** ISO 8601 durations and the two visible forms, normalised to whole minutes. */\nexport function normalizeDuration(raw: string): string | null {\n // LINEAR, verified.\n // safe-regex flags `\\d+` nested inside a quantified group structurally. It is\n // not ambiguous here: every `\\d+` is followed by a REQUIRED distinct literal\n // (D, H, M), so each group matches exactly one way or none, and the outer\n // quantifiers are `?` (max one repetition), not `*`/`+`. Catastrophic\n // backtracking needs many ways to split the same input; there are none.\n // Measured: 200k chars in <1 ms, growth linear. Input is also capped at\n // MAX_NORMALIZED_TEXT (200) upstream.\n // eslint-disable-next-line security/detect-unsafe-regex\n const iso = /^P(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?)?$/.exec(raw.trim().toUpperCase())\n if (iso !== null && (iso[1] ?? iso[2] ?? iso[3]) !== undefined) {\n const minutes = Number(iso[1] ?? 0) * 1440 + Number(iso[2] ?? 0) * 60 + Number(iso[3] ?? 0)\n return minutes > 0 ? String(minutes) : null\n }\n const spoken = /^(\\d{1,4})\\s?(min|mins|minute|minutes|h|hr|hrs|hour|hours)\\b/i.exec(raw.trim())\n if (spoken !== null) {\n const amount = Number(spoken[1])\n const unit = (spoken[2] ?? '').toLowerCase()\n const minutes = unit.startsWith('h') ? amount * 60 : amount\n return minutes > 0 ? String(minutes) : null\n }\n return null\n}\n\n/** Resolves a possibly relative URL. Returns null rather than throwing on garbage. */\nexport function absoluteUrl(href: string, base: string): string | null {\n try {\n return new URL(href, base).toString()\n } catch {\n return null\n }\n}\n\n// ---------------------------------------------------------------------------\n// HTML extraction\n// ---------------------------------------------------------------------------\n\n/** `<meta>` name/property → fact. Pinned; `og:` and the Twitter card are the whole set. */\nconst META_LEXICON: readonly (readonly [string, ArsFactKind])[] = [\n ['og:title', 'title'],\n ['twitter:title', 'title'],\n ['description', 'description'],\n ['og:description', 'description'],\n ['twitter:description', 'description'],\n ['og:price:amount', 'price'],\n ['product:price:amount', 'price'],\n ['og:price:currency', 'currency'],\n ['product:price:currency', 'currency'],\n ['og:availability', 'availability'],\n ['product:availability', 'availability'],\n ['product:brand', 'brand'],\n ['og:site_name', 'org-name'],\n ['author', 'author'],\n ['article:author', 'author'],\n ['article:published_time', 'published'],\n ['article:modified_time', 'updated'],\n ['article:section', 'section'],\n]\n\n/** `itemprop` → fact, for microdata. The same vocabulary as JSON-LD, one level flat. */\nconst ITEMPROP_LEXICON: readonly (readonly [string, ArsFactKind])[] = [\n ['name', 'title'],\n ['price', 'price'],\n ['pricecurrency', 'currency'],\n ['availability', 'availability'],\n ['brand', 'brand'],\n ['sku', 'sku'],\n ['description', 'description'],\n ['telephone', 'phone'],\n ['email', 'email'],\n ['address', 'address'],\n ['openinghours', 'hours'],\n ['author', 'author'],\n ['datepublished', 'published'],\n ['datemodified', 'updated'],\n ['articlesection', 'section'],\n]\n\nfunction extractFromHtml(\n doc: HtmlDocument,\n context: ExtractContext,\n push: (fact: ExtractedFact) => void,\n): void {\n // <title> and the first <h1>.\n for (const element of doc.elements) {\n if (element.tag !== 'title') continue\n const text = elementText(doc, element.index)\n const normalized = normalizeFactValue('title', text, context)\n if (normalized !== null) {\n push({ kind: 'title', normalized: normalized.value, source: 'html-text', offset: element.offset, qualified: false })\n }\n break\n }\n for (const element of doc.elements) {\n if (element.tag !== 'h1' || element.excludedBy !== null) continue\n const normalized = normalizeFactValue('title', elementText(doc, element.index), context)\n if (normalized !== null) {\n push({ kind: 'title', normalized: normalized.value, source: 'html-text', offset: element.offset, qualified: false })\n }\n break\n }\n\n // <meta>.\n for (const meta of doc.metas) {\n if (meta.content === null) continue\n const key = meta.property ?? meta.name\n if (key === null) continue\n for (const [needle, kind] of META_LEXICON) {\n if (key !== needle) continue\n const normalized = normalizeFactValue(kind, meta.content, context)\n if (normalized !== null) {\n push({ kind, normalized: normalized.value, source: 'meta', offset: meta.offset, qualified: normalized.qualified })\n }\n break\n }\n }\n\n // Microdata: itemprop, with content= preferred over text (schema.org's own advice).\n for (const element of doc.elements) {\n const itemprop = attr(element, 'itemprop')\n if (itemprop === null) continue\n const key = itemprop.toLowerCase()\n for (const [needle, kind] of ITEMPROP_LEXICON) {\n if (key !== needle) continue\n const raw =\n attr(element, 'content') ??\n attr(element, 'datetime') ??\n attr(element, 'href') ??\n elementText(doc, element.index)\n const normalized = normalizeFactValue(kind, raw, context)\n if (normalized !== null) {\n push({ kind, normalized: normalized.value, source: 'microdata', offset: element.offset, qualified: normalized.qualified })\n }\n break\n }\n }\n\n // Visible text: money, availability phrases, the no-published-price signal.\n extractVisibleText(doc, context, push)\n\n // Links and forms.\n extractLinks(doc, context, push)\n\n // Structural shapes: question/answer, opening hours, definition lists.\n extractStructures(doc, context, push)\n}\n\n/**\n * Facts read out of counted text. Every text node is visited individually so the\n * fact's offset is the offset of the node it was found in — a measured offset of\n * a heuristic fact, which is exactly how §3.9 describes `ArsFactObservation`.\n *\n * Hidden nodes (`hidden`, inline `display:none`, `<template>`) are skipped:\n * fixture `037-hidden-text-facts` asserts that facts stuffed into a hidden\n * element do not score.\n */\nfunction extractVisibleText(\n doc: HtmlDocument,\n context: ExtractContext,\n push: (fact: ExtractedFact) => void,\n): void {\n for (const node of doc.texts) {\n if (node.excludedBy !== null) continue\n const text = node.text\n if (text.trim().length === 0) continue\n\n for (const money of findMoneyPhrases(text)) {\n const parsed = parseMoneyText(money.phrase, { currency: context.currencyHint })\n if (parsed === null) continue\n push({\n kind: 'price',\n normalized: normalizeMoney(parsed.amount, parsed.currency),\n source: 'html-text',\n offset: node.offset,\n qualified: parsed.qualified,\n })\n push({\n kind: 'currency',\n normalized: parsed.currency,\n source: 'html-text',\n offset: node.offset,\n qualified: false,\n })\n }\n\n const lowered = text.toLowerCase()\n if (NO_PUBLISHED_PRICE.some((phrase) => lowered.includes(phrase))) {\n push({ kind: 'price', normalized: UNPRICED, source: 'html-text', offset: node.offset, qualified: false })\n }\n for (const [phrase, token] of AVAILABILITY_PHRASES) {\n if (!lowered.includes(phrase)) continue\n push({ kind: 'availability', normalized: token, source: 'html-text', offset: node.offset, qualified: false })\n break\n }\n for (const [kind, marker] of TEXT_PRESENCE_MARKERS) {\n if (!marker.some((phrase) => lowered.includes(phrase))) continue\n push({ kind, normalized: DECLARED, source: 'html-text', offset: node.offset, qualified: false })\n }\n const sku = /\\bsku[:\\s]+([A-Za-z0-9][A-Za-z0-9._-]{2,31})\\b/i.exec(text)\n if (sku !== null && sku[1] !== undefined) {\n push({ kind: 'sku', normalized: normalizeText(sku[1]), source: 'html-text', offset: node.offset, qualified: false })\n }\n }\n\n // Labelled lines inside HTML (`<dt>Price</dt><dd>$148</dd>` collapses to\n // \"Price $148\" in counted text, so this reads the whole document's text once).\n for (const labelled of readLabelledLines(countedText(doc))) {\n const normalized = normalizeFactValue(labelled.kind, labelled.value, context)\n if (normalized === null) continue\n push({\n kind: labelled.kind,\n normalized: normalized.value,\n source: 'html-text',\n offset: firstTextOffset(doc),\n qualified: normalized.qualified,\n })\n }\n}\n\n/** Presence facts detectable from prose, with their pinned phrase lists. */\nconst TEXT_PRESENCE_MARKERS: readonly (readonly [ArsFactKind, readonly string[]])[] = [\n ['shipping', ['free shipping', 'shipping', 'ships in', 'delivery', 'ships free']],\n ['returns', ['return policy', 'returns', 'money-back', 'money back', 'refund']],\n ['service-area', ['areas served', 'service area', 'we serve', 'serving']],\n ['eligibility', ['eligibility', 'who can apply', 'you must be', 'requirements']],\n]\n\nfunction firstTextOffset(doc: HtmlDocument): number {\n for (const node of doc.texts) {\n if (node.excludedBy === null && node.text.trim().length > 0) return node.offset\n }\n return 0\n}\n\nconst ACTION_MAX_TEXT_CHARS = 64\n\nfunction extractLinks(\n doc: HtmlDocument,\n context: ExtractContext,\n push: (fact: ExtractedFact) => void,\n): void {\n const lexicon = context.ruleset.actionLexicon\n for (const element of doc.elements) {\n if (element.excludedBy !== null) continue\n\n if (element.tag === 'a') {\n const href = attr(element, 'href')\n if (href === null) continue\n if (href.toLowerCase().startsWith('tel:')) {\n const phone = normalizePhone(href.slice(4))\n if (phone !== null) {\n push({ kind: 'phone', normalized: phone, source: 'html-text', offset: element.offset, qualified: false })\n }\n continue\n }\n if (href.toLowerCase().startsWith('mailto:')) {\n const normalized = normalizeFactValue('email', href, context)\n if (normalized !== null) {\n push({ kind: 'email', normalized: normalized.value, source: 'html-text', offset: element.offset, qualified: false })\n }\n continue\n }\n const text = elementText(doc, element.index).slice(0, ACTION_MAX_TEXT_CHARS)\n if (!matchesLexicon(text, lexicon)) continue\n const absolute = absoluteUrl(href, context.baseUrl)\n if (absolute === null) continue\n push({ kind: 'primary-action-url', normalized: absolute, source: 'html-text', offset: element.offset, qualified: false })\n continue\n }\n\n if (element.tag === 'form') {\n const action = attr(element, 'action')\n if (action === null) continue\n const text = elementText(doc, element.index).slice(0, ACTION_MAX_TEXT_CHARS)\n if (!matchesLexicon(text, lexicon)) continue\n const absolute = absoluteUrl(action, context.baseUrl)\n if (absolute === null) continue\n push({ kind: 'primary-action-url', normalized: absolute, source: 'html-text', offset: element.offset, qualified: false })\n }\n }\n\n const items = largestRepeatedLinkBlock(doc, context.origin)\n if (items.count > 0) {\n push({ kind: 'item-count', normalized: String(items.count), source: 'html-text', offset: items.offset, qualified: false })\n if (items.sameOrigin) {\n push({ kind: 'item-link', normalized: DECLARED, source: 'html-text', offset: items.offset, qualified: false })\n }\n }\n}\n\n/** Anchor text matches the action lexicon exactly, or begins with a lexicon phrase. */\nfunction matchesLexicon(text: string, lexicon: readonly string[]): boolean {\n const normalized = text.replace(/\\s+/g, ' ').trim().toLowerCase()\n if (normalized.length === 0) return false\n for (const phrase of lexicon) {\n if (normalized === phrase) return true\n if (normalized.startsWith(`${phrase} `)) return true\n }\n return false\n}\n\n/**\n * `item-count` / `item-link` for `collection` (§3.5): \"the number of distinct\n * item links inside the largest repeated-structure block, and whether those\n * links resolve to same-origin URLs.\"\n *\n * Made deterministic as: group every anchor by its GRANDPARENT element (the\n * container of the repeated item, e.g. `<ul>` for `<li><a>`), drop groups whose\n * container is inside `<nav>`, `<header>` or `<footer>`, and take the group with\n * the most distinct hrefs. The nav exclusion is the whole reason for the\n * \"largest repeated block\" phrasing — a site-wide menu is a repeated block of\n * links and is not a product grid.\n */\nfunction largestRepeatedLinkBlock(\n doc: HtmlDocument,\n origin: string,\n): { count: number; offset: number; sameOrigin: boolean } {\n const groups = new Map<number, { hrefs: Set<string>; sameOrigin: number; offset: number }>()\n for (const element of doc.elements) {\n if (element.tag !== 'a' || element.excludedBy !== null) continue\n const href = attr(element, 'href')\n if (href === null || href.startsWith('#')) continue\n const parent = element.parent >= 0 ? doc.elements[element.parent] : undefined\n const container = parent !== undefined && parent.parent >= 0 ? parent.parent : element.parent\n if (container < 0) continue\n if (isInsideChrome(doc, container)) continue\n\n const absolute = absoluteUrl(href, origin)\n if (absolute === null) continue\n const group = groups.get(container) ?? {\n hrefs: new Set<string>(),\n sameOrigin: 0,\n offset: doc.elements[container]?.offset ?? 0,\n }\n if (!group.hrefs.has(absolute)) {\n group.hrefs.add(absolute)\n if (absolute.startsWith(origin)) group.sameOrigin++\n }\n groups.set(container, group)\n }\n\n let best = { count: 0, offset: 0, sameOrigin: false }\n for (const [, group] of groups) {\n if (group.hrefs.size <= best.count) continue\n best = {\n count: group.hrefs.size,\n offset: group.offset,\n sameOrigin: group.sameOrigin * 2 >= group.hrefs.size,\n }\n }\n return best.count >= MIN_REPEATED_ITEMS ? best : { count: 0, offset: 0, sameOrigin: false }\n}\n\n/** Below this, a group of links is a paragraph with citations, not a listing. */\nconst MIN_REPEATED_ITEMS = 3\n\nconst CHROME_TAGS = new Set(['nav', 'header', 'footer'])\n\nfunction isInsideChrome(doc: HtmlDocument, from: number): boolean {\n let current = from\n for (let hops = 0; hops < 64 && current >= 0; hops++) {\n const element = doc.elements[current]\n if (element === undefined) return false\n if (CHROME_TAGS.has(element.tag)) return true\n if (element.attrs['role'] === 'navigation' || element.attrs['role'] === 'banner') return true\n current = element.parent\n }\n return false\n}\n\nconst DAY_NAMES = [\n 'monday',\n 'tuesday',\n 'wednesday',\n 'thursday',\n 'friday',\n 'saturday',\n 'sunday',\n 'mon',\n 'tue',\n 'wed',\n 'thu',\n 'fri',\n 'sat',\n 'sun',\n]\n\n/**\n * Day-name / `HH:MM` adjacency, the §3.5 pass-1 signal, reused here as the\n * visible-text source for `hours`. \"Adjacent\" is: a day name and a clock time\n * within 40 characters of each other in the same text node.\n */\nexport function hasOpeningHoursShape(text: string): boolean {\n const lowered = text.toLowerCase()\n for (const day of DAY_NAMES) {\n let at = lowered.indexOf(day)\n while (at !== -1) {\n const window = lowered.slice(at, at + 40)\n if (/\\d{1,2}[:.]\\d{2}/.test(window) || /\\d{1,2}\\s?(am|pm)/.test(window)) return true\n at = lowered.indexOf(day, at + day.length)\n }\n }\n return false\n}\n\nfunction extractStructures(\n doc: HtmlDocument,\n context: ExtractContext,\n push: (fact: ExtractedFact) => void,\n): void {\n for (const node of doc.texts) {\n if (node.excludedBy !== null) continue\n if (!hasOpeningHoursShape(node.text)) continue\n push({ kind: 'hours', normalized: DECLARED, source: 'html-text', offset: node.offset, qualified: false })\n break\n }\n\n for (const element of doc.elements) {\n if (element.excludedBy !== null) continue\n if (element.tag === 'address') {\n const normalized = normalizeFactValue('address', elementText(doc, element.index), context)\n if (normalized !== null) {\n push({ kind: 'address', normalized: normalized.value, source: 'html-text', offset: element.offset, qualified: false })\n }\n }\n }\n\n const qa = firstQuestionAnswer(doc)\n if (qa !== null) {\n push({ kind: 'question-answer', normalized: DECLARED, source: 'html-text', offset: qa, qualified: false })\n }\n}\n\nconst HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6'])\n\n/**\n * The §3.5 `question-answer` shapes: a `<dt>`/`<dd>` pair, a\n * `<details><summary>`, or a heading ending in `?` followed by a paragraph.\n * Counted ONCE as present, not per item — a page with 40 questions is not four\n * times better than a page with 10, and the offset returned is the first shape's.\n */\nfunction firstQuestionAnswer(doc: HtmlDocument): number | null {\n let sawDt = false\n let pendingQuestionHeading = false\n for (const element of doc.elements) {\n if (element.excludedBy !== null) continue\n if (element.tag === 'dt') {\n sawDt = true\n continue\n }\n if (element.tag === 'dd' && sawDt) return element.offset\n if (element.tag === 'details') {\n for (const child of doc.elements) {\n if (child.parent === element.index && child.tag === 'summary') return element.offset\n }\n continue\n }\n if (HEADING_TAGS.has(element.tag)) {\n pendingQuestionHeading = elementText(doc, element.index).trim().endsWith('?')\n continue\n }\n if (element.tag === 'p' && pendingQuestionHeading) return element.offset\n }\n return null\n}\n\n// ---------------------------------------------------------------------------\n// Plain-text / markdown extraction\n// ---------------------------------------------------------------------------\n\nconst MARKDOWN_LINK_RE = /\\[([^\\]\\n]{1,120})\\]\\(([^)\\s]{1,500})\\)/g\n\n/**\n * Extraction from a NEGOTIATED representation — markdown or plain text. Offsets\n * are UTF-8 byte offsets into the body, computed once per hit rather than by\n * scanning the whole body, so a 2 MiB markdown file does not become quadratic.\n *\n * The source is recorded as `negotiated` for everything found here, which is\n * what lets a fact stated in markdown corroborate the same fact in the HTML's\n * JSON-LD: two distinct sources, one value.\n */\nfunction extractFromPlainText(\n representation: ArsRepresentation,\n context: ExtractContext,\n push: (fact: ExtractedFact) => void,\n): void {\n const body = representation.body\n const offsetOf = (index: number): number => utf8Length(body.slice(0, index))\n\n // Title: the first ATX heading, with a wrapping markdown link unwrapped —\n // `render-md` emits `# [Alpine Trail Pack 28L](https://…)`.\n const heading = /^#{1,6}[ \\t]+(.+)$/m.exec(body)\n if (heading !== null && heading[1] !== undefined) {\n const linked = /^\\[([^\\]]+)\\]\\([^)]*\\)\\s*$/.exec(heading[1].trim())\n const raw = linked !== null && linked[1] !== undefined ? linked[1] : heading[1]\n const normalized = normalizeFactValue('title', raw, context)\n if (normalized !== null) {\n push({ kind: 'title', normalized: normalized.value, source: 'negotiated', offset: offsetOf(heading.index), qualified: false })\n }\n }\n\n for (const labelled of readLabelledLines(body)) {\n const normalized = normalizeFactValue(labelled.kind, labelled.value, context)\n if (normalized === null) continue\n push({ kind: labelled.kind, normalized: normalized.value, source: 'negotiated', offset: offsetOf(labelled.index), qualified: normalized.qualified })\n // A labelled price also states its currency.\n if (labelled.kind === 'price' && normalized.value !== UNPRICED) {\n const code = normalized.value.slice(0, 3)\n push({ kind: 'currency', normalized: code, source: 'negotiated', offset: offsetOf(labelled.index), qualified: false })\n }\n }\n\n for (const money of findMoneyPhrases(body)) {\n const parsed = parseMoneyText(money.phrase, { currency: context.currencyHint })\n if (parsed === null) continue\n push({ kind: 'price', normalized: normalizeMoney(parsed.amount, parsed.currency), source: 'negotiated', offset: offsetOf(money.index), qualified: parsed.qualified })\n push({ kind: 'currency', normalized: parsed.currency, source: 'negotiated', offset: offsetOf(money.index), qualified: false })\n }\n\n const lowered = body.toLowerCase()\n if (NO_PUBLISHED_PRICE.some((phrase) => lowered.includes(phrase))) {\n push({ kind: 'price', normalized: UNPRICED, source: 'negotiated', offset: 0, qualified: false })\n }\n for (const [phrase, token] of AVAILABILITY_PHRASES) {\n const at = lowered.indexOf(phrase)\n if (at === -1) continue\n push({ kind: 'availability', normalized: token, source: 'negotiated', offset: offsetOf(at), qualified: false })\n break\n }\n for (const [kind, markers] of TEXT_PRESENCE_MARKERS) {\n for (const phrase of markers) {\n const at = lowered.indexOf(phrase)\n if (at === -1) continue\n push({ kind, normalized: DECLARED, source: 'negotiated', offset: offsetOf(at), qualified: false })\n break\n }\n }\n if (hasOpeningHoursShape(body)) {\n push({ kind: 'hours', normalized: DECLARED, source: 'negotiated', offset: 0, qualified: false })\n }\n\n // Markdown links: the primary action, and the repeated-item block.\n const itemLinks = new Set<string>()\n let firstItemOffset = 0\n let match: RegExpExecArray | null\n MARKDOWN_LINK_RE.lastIndex = 0\n while ((match = MARKDOWN_LINK_RE.exec(body)) !== null) {\n const text = match[1] ?? ''\n const href = match[2] ?? ''\n const absolute = absoluteUrl(href, context.baseUrl)\n if (absolute === null) continue\n if (matchesLexicon(text, context.ruleset.actionLexicon)) {\n push({ kind: 'primary-action-url', normalized: absolute, source: 'negotiated', offset: offsetOf(match.index), qualified: false })\n }\n if (absolute.startsWith(context.origin) && !itemLinks.has(absolute)) {\n if (itemLinks.size === 0) firstItemOffset = offsetOf(match.index)\n itemLinks.add(absolute)\n }\n }\n if (itemLinks.size >= MIN_REPEATED_ITEMS) {\n push({ kind: 'item-count', normalized: String(itemLinks.size), source: 'negotiated', offset: firstItemOffset, qualified: false })\n push({ kind: 'item-link', normalized: DECLARED, source: 'negotiated', offset: firstItemOffset, qualified: false })\n }\n\n // A question/answer shape in markdown: a heading that ends in `?`.\n const question = /^#{1,6}[ \\t]+.*\\?[ \\t]*$/m.exec(body)\n if (question !== null) {\n push({ kind: 'question-answer', normalized: DECLARED, source: 'negotiated', offset: offsetOf(question.index), qualified: false })\n }\n}\n\n// ---------------------------------------------------------------------------\n// robots.txt\n// ---------------------------------------------------------------------------\n\nexport interface RobotsGroup {\n /** Lowercased user-agent tokens this group applies to. */\n readonly agents: readonly string[]\n readonly allow: readonly string[]\n readonly disallow: readonly string[]\n}\n\nexport interface RobotsFile {\n readonly groups: readonly RobotsGroup[]\n readonly sitemaps: readonly string[]\n /** Lines that are neither blank, a comment, nor a `field: value` pair. */\n readonly malformedLines: number\n /** Directives that appeared before any `User-agent:` line — the classic authoring bug. */\n readonly orphanRules: number\n}\n\n/**\n * RFC 9309 robots.txt, in the subset ARS reads. Deliberately small: we consume\n * `User-agent`, `Allow`, `Disallow` and `Sitemap`, count what we could not\n * parse, and ignore everything else. `Crawl-delay` is honoured by the PROBE, not\n * by the score — waiting longer is not worse markup.\n */\nexport function parseRobots(text: string): RobotsFile {\n /** Mutable while parsing; the exported shape is the readonly one. */\n interface MutableGroup {\n agents: string[]\n allow: string[]\n disallow: string[]\n }\n\n const groups: MutableGroup[] = []\n const sitemaps: string[] = []\n let malformedLines = 0\n let orphanRules = 0\n\n let current: MutableGroup | null = null\n /**\n * True while consecutive `User-agent:` lines are still accumulating into one\n * group. RFC 9309 §2.2.1: adjacent user-agent lines share the rules that\n * follow them; the first rule line closes the group to further agents.\n */\n let openingGroup = false\n\n for (const rawLine of text.split(/\\r?\\n/)) {\n const withoutComment = rawLine.split('#')[0] ?? ''\n const line = withoutComment.trim()\n if (line.length === 0) continue\n const colon = line.indexOf(':')\n if (colon <= 0) {\n malformedLines++\n continue\n }\n const field = line.slice(0, colon).trim().toLowerCase()\n const value = line.slice(colon + 1).trim()\n\n if (field === 'user-agent') {\n if (current === null || !openingGroup) {\n current = { agents: [], allow: [], disallow: [] }\n groups.push(current)\n openingGroup = true\n }\n current.agents.push(value.toLowerCase())\n continue\n }\n if (field === 'sitemap') {\n sitemaps.push(value)\n continue\n }\n if (field === 'allow' || field === 'disallow') {\n if (current === null) {\n orphanRules++\n continue\n }\n openingGroup = false\n if (field === 'allow') current.allow.push(value)\n else current.disallow.push(value)\n continue\n }\n if (field === 'crawl-delay' || field === 'host' || field === 'clean-param') continue\n malformedLines++\n }\n\n return { groups, sitemaps, malformedLines, orphanRules }\n}\n\n/**\n * RFC 9309 group selection: the most specific matching `User-agent` wins, `*` is\n * the fallback, and matching is case-insensitive. Returns the decision plus the\n * group and rule that produced it, because `ArsAudienceDecision` publishes both —\n * a merchant who disagrees with an `opt-out` verdict gets to see the line.\n */\nexport function decideRobots(\n robots: RobotsFile,\n tokens: readonly string[],\n path: string,\n): ArsAudienceDecision {\n let bestGroup: RobotsGroup | null = null\n let bestAgent: string | null = null\n let bestSpecificity = -1\n\n for (const group of robots.groups) {\n for (const agent of group.agents) {\n const specificity = agent === '*' ? 0 : matchesToken(agent, tokens) ? agent.length : -1\n if (specificity > bestSpecificity) {\n bestSpecificity = specificity\n bestGroup = group\n bestAgent = agent\n }\n }\n }\n\n if (bestGroup === null || bestAgent === null) {\n return { decision: 'unspecified', matchedGroup: null, matchedRule: null }\n }\n\n // Longest-match wins between Allow and Disallow; a tie goes to Allow (RFC 9309 §2.2.2).\n let bestRule: { field: 'allow' | 'disallow'; value: string } | null = null\n for (const value of bestGroup.allow) {\n if (!pathMatches(value, path)) continue\n if (bestRule === null || value.length > bestRule.value.length) {\n bestRule = { field: 'allow', value }\n }\n }\n for (const value of bestGroup.disallow) {\n if (!pathMatches(value, path)) continue\n if (bestRule === null || value.length > bestRule.value.length) {\n bestRule = { field: 'disallow', value }\n }\n }\n\n if (bestRule === null) {\n return { decision: 'allow', matchedGroup: bestAgent, matchedRule: null }\n }\n return {\n decision: bestRule.field === 'allow' ? 'allow' : 'disallow',\n matchedGroup: bestAgent,\n matchedRule: `${bestRule.field === 'allow' ? 'Allow' : 'Disallow'}: ${bestRule.value}`,\n }\n}\n\nfunction matchesToken(agent: string, tokens: readonly string[]): boolean {\n const lowered = agent.toLowerCase()\n return tokens.some((token) => token.toLowerCase() === lowered)\n}\n\n/**\n * Path matching with `*` and `$`, done as a bounded scan rather than a compiled\n * regex: a robots.txt is attacker-controlled input and\n * `new RegExp(pathFromTheInternet)` is a denial-of-service primitive.\n */\nexport function pathMatches(pattern: string, path: string): boolean {\n if (pattern === '') return false\n const anchored = pattern.endsWith('$')\n const body = anchored ? pattern.slice(0, -1) : pattern\n const segments = body.split('*')\n\n let cursor = 0\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i] ?? ''\n if (i === 0) {\n if (!path.startsWith(segment)) return false\n cursor = segment.length\n continue\n }\n if (segment === '') continue\n const at = path.indexOf(segment, cursor)\n if (at === -1) return false\n cursor = at + segment.length\n }\n if (anchored) {\n const last = segments[segments.length - 1] ?? ''\n return segments.length === 1 ? path === body : path.endsWith(last)\n }\n return true\n}\n\n/** Every audience decision plus the derived policy flags. Pure over a parsed robots file. */\nexport function buildPolicyReport(\n robots: RobotsFile | null,\n status: ArsPolicyReport['robotsTxtStatus'],\n ruleset: ArsRuleset,\n path: string,\n): ArsPolicyReport {\n const empty: ArsAudienceDecision = { decision: 'unspecified', matchedGroup: null, matchedRule: null }\n const audiences: Record<ArsAudience, ArsAudienceDecision> = {\n assistant: empty,\n training: empty,\n search: empty,\n }\n if (robots !== null) {\n for (const audience of ['assistant', 'training', 'search'] as const) {\n audiences[audience] = decideRobots(robots, ruleset.audienceTokens[audience], path)\n }\n }\n\n return {\n robotsTxtStatus: status,\n audiences,\n // A deliberate opt-out requires a group that NAMES an assistant token.\n // Consent has to be specific: a blanket `User-agent: *` disallow is the\n // accidental case (§3.7) and is scored, not excused.\n deliberateOptOut:\n robots !== null &&\n audiences.assistant.decision === 'disallow' &&\n audiences.assistant.matchedGroup !== '*' &&\n robots.malformedLines === 0 &&\n robots.orphanRules === 0,\n trainingOptOut: audiences.training.decision === 'disallow',\n sitemapDeclared: robots !== null && robots.sitemaps.length > 0,\n }\n}\n","/**\n * classify.ts — the two-pass page-kind classifier (design §3.5).\n *\n * THE CIRCULARITY THIS RESOLVES. Fact extraction needs a profile; the profile\n * comes from the page kind; the page kind looks like something you would infer\n * from the facts. Every source design had that loop and none of them cut it. The\n * decided answer is two passes with a hard wall between them:\n *\n * PASS 1 extracts a FIXED, KIND-INDEPENDENT probe set — JSON-LD `@type`,\n * microdata `itemtype`, RDFa `typeof`, `og:type`, URL path grammar,\n * currency-token presence, day-name/`HH:MM` adjacency, and `tel:` presence.\n * **Only pass-1 output may inform classification.** Nothing in this file reads\n * a profile, and `pass1Signals()` takes no page kind.\n *\n * PASS 2 (`./extract`) extracts against the resolved profile.\n *\n * Because pass 1 is fixed, two implementations classify the same bytes the same\n * way, and because it is small, a reader can check that it is fixed.\n *\n * PRECEDENCE, from §3.5: JSON-LD `@type` (through a pinned table) → microdata /\n * RDFa → `og:type` → URL path patterns → pass-1 structural signals. Ties are\n * broken by declared precedence, then lexicographically by `@type`.\n *\n * CONFIDENCE, AND WHY `unknown` IS NOT A PENALTY BOX. Below `medium` confidence\n * the kind is `unknown` — **we never guess into a vertical**, because guessing\n * `product` on an article scores that article against a fact set it has no\n * reason to carry, and the merchant cannot argue with a number. `unknown` is\n * also not an easy exit: it carries its own profile (title, description,\n * primary-action-url) and still scores D5.2 against \"any recognised schema.org\n * type present\", so hiding your page kind costs up to 7 points and gains nothing.\n *\n * THE TABLES BELOW ARE VERSIONED DATA. Adding a schema.org type or a URL pattern\n * changes the kind of some real page, which changes its profile, which changes\n * its score — so additions land as a MINOR, exactly like a ruleset edit. They\n * live here rather than in `DEFAULT_RULESET` because §3.9's `ArsRuleset` has no\n * field for them; that means they are NOT covered by `rulesetHash`, and the gap\n * is recorded in the package README as a known limitation of 0.1.\n */\n\nimport type { ArsRepresentation, JsonLdNode } from './extract'\nimport { absoluteUrl, findMoneyPhrases, hasOpeningHoursShape } from './extract'\nimport { attr } from './html'\nimport { parseMoneyText } from './parse-money'\nimport type { ArsPageKind } from './types'\n\n// ---------------------------------------------------------------------------\n// Pass 1 — the fixed, kind-independent probe set\n// ---------------------------------------------------------------------------\n\nexport interface ArsPass1Signals {\n /** `@type` values from every JSON-LD node, prefix-stripped, document order. */\n readonly jsonLdTypes: readonly string[]\n /** `itemtype` values, reduced to their final path segment. */\n readonly microdataTypes: readonly string[]\n /** RDFa `typeof` values, whitespace-split. */\n readonly rdfaTypes: readonly string[]\n /** `<meta property=\"og:type\">`, lowercased. */\n readonly ogType: string | null\n /** Lowercased, non-empty path segments of the target URL. */\n readonly pathSegments: readonly string[]\n /** At least one substring that `parseMoneyText` accepts. */\n readonly hasCurrencyToken: boolean\n /** A day name within 40 characters of a clock time. */\n readonly hasOpeningHours: boolean\n /** A `tel:` link, or a `telephone` property in structured data. */\n readonly hasTelephone: boolean\n}\n\n/**\n * Runs pass 1 over a representation. Takes the target URL rather than the\n * capture's final URL: the URL an operator typed is the one whose path grammar\n * describes their intent, and a redirect to a tracking URL should not reclassify\n * the page.\n */\nexport function pass1Signals(\n representation: ArsRepresentation,\n targetUrl: string,\n): ArsPass1Signals {\n const jsonLdTypes: string[] = []\n let hasTelephone = false\n for (const node of representation.jsonLd.nodes) {\n for (const type of node.types) jsonLdTypes.push(type)\n if (typeof node.value['telephone'] === 'string') hasTelephone = true\n }\n\n const microdataTypes: string[] = []\n const rdfaTypes: string[] = []\n if (representation.doc !== null) {\n for (const element of representation.doc.elements) {\n const itemtype = attr(element, 'itemtype')\n if (itemtype !== null) {\n for (const token of itemtype.split(/\\s+/)) {\n const segment = token.split('/').pop()\n if (segment !== undefined && segment.length > 0) microdataTypes.push(segment)\n }\n }\n const typeOf = attr(element, 'typeof')\n if (typeOf !== null) {\n for (const token of typeOf.split(/\\s+/)) {\n const segment = token.split(/[/:]/).pop()\n if (segment !== undefined && segment.length > 0) rdfaTypes.push(segment)\n }\n }\n if (element.tag === 'a') {\n const href = attr(element, 'href')\n if (href !== null && href.toLowerCase().startsWith('tel:')) hasTelephone = true\n }\n }\n }\n\n let ogType: string | null = null\n if (representation.doc !== null) {\n for (const meta of representation.doc.metas) {\n if (meta.property === 'og:type' && meta.content !== null) {\n ogType = meta.content.trim().toLowerCase()\n break\n }\n }\n }\n\n const text = representation.text\n let hasCurrencyToken = false\n for (const money of findMoneyPhrases(text)) {\n if (parseMoneyText(money.phrase) !== null) {\n hasCurrencyToken = true\n break\n }\n }\n if (!hasTelephone) hasTelephone = /\\btel:\\+?[0-9()\\-. ]{7,}/.test(text)\n\n return {\n jsonLdTypes,\n microdataTypes,\n rdfaTypes,\n ogType,\n pathSegments: pathSegmentsOf(targetUrl),\n hasCurrencyToken,\n hasOpeningHours: hasOpeningHoursShape(text),\n hasTelephone,\n }\n}\n\nfunction pathSegmentsOf(url: string): string[] {\n const absolute = absoluteUrl(url, 'https://invalid.example/')\n if (absolute === null) return []\n try {\n return new URL(absolute).pathname\n .toLowerCase()\n .split('/')\n .filter((segment) => segment.length > 0)\n } catch {\n return []\n }\n}\n\n// ---------------------------------------------------------------------------\n// The pinned type table\n// ---------------------------------------------------------------------------\n\n/**\n * schema.org type → ARS page kind. Sorted by kind for readability; lookup is\n * exact and case-sensitive, because schema.org type names are.\n *\n * A few placements are judgement calls and are stated rather than left implied:\n * - `Event` maps to `service`. A bookable event's core facts are title, price\n * and a primary action, which is the `service` profile exactly.\n * - `SoftwareApplication` maps to `product`: it carries `offers`, and an agent\n * asking about it wants a price and availability.\n * - `Organization` alone does NOT map to `place` — an org can be the publisher\n * of any page. Only `LocalBusiness` and its subtypes, which imply a physical\n * location with hours, do.\n */\nconst TYPE_TO_KIND: Readonly<Record<string, ArsPageKind>> = {\n // product\n Product: 'product',\n ProductGroup: 'product',\n ProductModel: 'product',\n IndividualProduct: 'product',\n SomeProducts: 'product',\n Vehicle: 'product',\n Car: 'product',\n Book: 'product',\n SoftwareApplication: 'product',\n MobileApplication: 'product',\n WebApplication: 'product',\n // collection\n CollectionPage: 'collection',\n ItemList: 'collection',\n OfferCatalog: 'collection',\n SearchResultsPage: 'collection',\n // article\n Article: 'article',\n NewsArticle: 'article',\n BlogPosting: 'article',\n TechArticle: 'article',\n ScholarlyArticle: 'article',\n ReportageNewsArticle: 'article',\n LiveBlogPosting: 'article',\n Blog: 'article',\n // place\n Place: 'place',\n LocalBusiness: 'place',\n Store: 'place',\n Restaurant: 'place',\n Hotel: 'place',\n LodgingBusiness: 'place',\n FoodEstablishment: 'place',\n CafeOrCoffeeShop: 'place',\n MedicalBusiness: 'place',\n MedicalClinic: 'place',\n Dentist: 'place',\n ProfessionalService: 'place',\n AutomotiveBusiness: 'place',\n HealthAndBeautyBusiness: 'place',\n HairSalon: 'place',\n SportsActivityLocation: 'place',\n ExerciseGym: 'place',\n // service\n Service: 'service',\n GovernmentService: 'service',\n FinancialProduct: 'service',\n LoanOrCredit: 'service',\n InsuranceAgency: 'service',\n Course: 'service',\n Event: 'service',\n BusinessEvent: 'service',\n EducationEvent: 'service',\n // faq\n FAQPage: 'faq',\n QAPage: 'faq',\n // document\n Dataset: 'document',\n DataCatalog: 'document',\n DigitalDocument: 'document',\n TextDigitalDocument: 'document',\n APIReference: 'document',\n WebAPI: 'document',\n Legislation: 'document',\n HowTo: 'document',\n Report: 'document',\n Manuscript: 'document',\n}\n\n/**\n * Types ARS recognises but which say nothing about the page kind. They matter\n * anyway: D5.2 scores `unknown` against *\"any recognised schema.org type\n * present\"*, so a page that declares `WebPage` has a recognised type and can\n * earn D5.2 while still classifying as `unknown`.\n */\nconst RECOGNISED_ONLY: ReadonlySet<string> = new Set([\n 'Thing',\n 'WebPage',\n 'WebSite',\n 'AboutPage',\n 'ContactPage',\n 'ProfilePage',\n 'ItemPage',\n 'Organization',\n 'Corporation',\n 'NGO',\n 'GovernmentOrganization',\n 'EducationalOrganization',\n 'Person',\n 'BreadcrumbList',\n 'Offer',\n 'AggregateOffer',\n 'PostalAddress',\n 'ImageObject',\n 'VideoObject',\n 'SiteNavigationElement',\n 'Brand',\n 'Review',\n 'AggregateRating',\n 'Question',\n 'Answer',\n 'MerchantReturnPolicy',\n 'OfferShippingDetails',\n 'SearchAction',\n 'ReadAction',\n 'OrderAction',\n])\n\n/** Is this a schema.org type ARS knows about at all? The D5.2 \"recognised\" test. */\nexport function isRecognisedType(type: string): boolean {\n return TYPE_TO_KIND[type] !== undefined || RECOGNISED_ONLY.has(type)\n}\n\n/** The kind a recognised type implies, or null when it implies none. */\nexport function kindForType(type: string): ArsPageKind | null {\n return TYPE_TO_KIND[type] ?? null\n}\n\n/**\n * The first node whose `@type` maps to `kind`. D5.2 scores required properties\n * against the node that decided the kind, not against whichever node came first —\n * a `BreadcrumbList` sitting above the `Product` must not be marked incomplete\n * for lacking `offers.price`.\n */\nexport function nodeForKind(\n nodes: readonly JsonLdNode[],\n kind: ArsPageKind,\n): JsonLdNode | null {\n for (const node of nodes) {\n for (const type of node.types) {\n if (kindForType(type) === kind) return node\n }\n }\n return null\n}\n\n// ---------------------------------------------------------------------------\n// og:type and URL grammar\n// ---------------------------------------------------------------------------\n\n/** Open Graph `og:type` → kind. The vocabulary is tiny and mostly commerce/article. */\nconst OG_TYPE_TO_KIND: Readonly<Record<string, ArsPageKind>> = {\n product: 'product',\n 'product.group': 'product',\n 'product.item': 'product',\n 'og:product': 'product',\n article: 'article',\n 'article:published_time': 'article',\n blog: 'article',\n book: 'product',\n place: 'place',\n business: 'place',\n 'business.business': 'place',\n restaurant: 'place',\n 'restaurant.restaurant': 'place',\n profile: 'unknown',\n website: 'unknown',\n}\n\n/**\n * URL path grammar, in precedence order. A pattern matches when any path segment\n * equals it, or when the first segment starts with it for the short forms.\n *\n * These are the conventional shapes of the platforms merchants actually run —\n * Shopify (`/products/`, `/collections/`), WordPress (`/blog/`, `/category/`),\n * documentation sites (`/docs/`, `/reference/`). A pattern earns `medium`\n * confidence and never `high`: a URL is a claim about a page, not the page.\n */\nconst PATH_PATTERNS: readonly (readonly [ArsPageKind, readonly string[]])[] = [\n ['product', ['products', 'product', 'p', 'item', 'items', 'dp', 'sku', 'buy']],\n ['collection', ['collections', 'collection', 'category', 'categories', 'catalog', 'c', 'shop']],\n ['article', ['blog', 'blogs', 'news', 'article', 'articles', 'post', 'posts', 'stories']],\n ['place', ['locations', 'location', 'stores', 'store-locator', 'branches', 'find-us', 'visit']],\n ['service', ['services', 'service', 'book', 'booking', 'appointments', 'pricing', 'plans']],\n ['faq', ['faq', 'faqs', 'questions', 'help']],\n ['document', ['docs', 'documentation', 'reference', 'guide', 'guides', 'manual', 'api', 'policies', 'legal', 'terms', 'privacy']],\n]\n\n// ---------------------------------------------------------------------------\n// The classifier\n// ---------------------------------------------------------------------------\n\nexport interface ArsClassification {\n readonly pageKind: ArsPageKind\n readonly confidence: 'high' | 'medium' | 'low'\n /** Which pass-1 signal decided it. Published as check evidence, not just logged. */\n readonly signal: string\n /** True when SOME recognised schema.org type was present, whatever the kind. */\n readonly hasRecognisedType: boolean\n}\n\n/**\n * Resolves the page kind from pass-1 signals and nothing else.\n *\n * The `low` → `unknown` collapse at the end is the \"never guess into a vertical\"\n * rule made mechanical: a lone currency token on a page with no type, no og:type\n * and no path grammar is not enough to call it a product, and a wrong vertical\n * is worse than no vertical because it scores the page against facts it was\n * never trying to state.\n */\nexport function classify(signals: ArsPass1Signals): ArsClassification {\n const hasRecognisedType =\n signals.jsonLdTypes.some(isRecognisedType) ||\n signals.microdataTypes.some(isRecognisedType) ||\n signals.rdfaTypes.some(isRecognisedType)\n\n // 1 — JSON-LD @type. Ties broken lexicographically by the type name (§3.5).\n const fromJsonLd = firstMappedType(signals.jsonLdTypes)\n if (fromJsonLd !== null) {\n return {\n pageKind: fromJsonLd.kind,\n confidence: 'high',\n signal: `json-ld @type ${fromJsonLd.type}`,\n hasRecognisedType,\n }\n }\n\n // 2 — microdata, then RDFa.\n const fromMicrodata = firstMappedType(signals.microdataTypes)\n if (fromMicrodata !== null) {\n return {\n pageKind: fromMicrodata.kind,\n confidence: 'high',\n signal: `microdata itemtype ${fromMicrodata.type}`,\n hasRecognisedType,\n }\n }\n const fromRdfa = firstMappedType(signals.rdfaTypes)\n if (fromRdfa !== null) {\n return {\n pageKind: fromRdfa.kind,\n confidence: 'high',\n signal: `rdfa typeof ${fromRdfa.type}`,\n hasRecognisedType,\n }\n }\n\n // 3 — og:type.\n if (signals.ogType !== null) {\n const kind = OG_TYPE_TO_KIND[signals.ogType]\n if (kind !== undefined && kind !== 'unknown') {\n return {\n pageKind: kind,\n confidence: 'medium',\n signal: `og:type ${signals.ogType}`,\n hasRecognisedType,\n }\n }\n }\n\n // 4 — URL path grammar.\n for (const [kind, patterns] of PATH_PATTERNS) {\n for (const segment of signals.pathSegments) {\n if (!patterns.includes(segment)) continue\n return {\n pageKind: kind,\n confidence: 'medium',\n signal: `url path segment /${segment}/`,\n hasRecognisedType,\n }\n }\n }\n\n // 5 — structural signals. Only ONE combination reaches `medium`: opening hours\n // AND a telephone number are two independent signals agreeing on `place`. A\n // lone currency token is `low`, which means `unknown`.\n if (signals.hasOpeningHours && signals.hasTelephone) {\n return {\n pageKind: 'place',\n confidence: 'medium',\n signal: 'opening-hours shape and telephone present',\n hasRecognisedType,\n }\n }\n\n return {\n pageKind: 'unknown',\n confidence: 'low',\n signal: signals.hasCurrencyToken\n ? 'currency token only — below medium confidence, not classified'\n : 'no classifying signal',\n hasRecognisedType,\n }\n}\n\n/**\n * First type that maps to a kind, preferring document order and breaking a\n * same-position tie lexicographically. Document order is the declared\n * precedence: a page that puts its `Product` node first has said which node is\n * the page.\n */\nfunction firstMappedType(\n types: readonly string[],\n): { type: string; kind: ArsPageKind } | null {\n const mapped: { type: string; kind: ArsPageKind }[] = []\n for (const type of types) {\n const kind = kindForType(type)\n if (kind !== null) mapped.push({ type, kind })\n }\n if (mapped.length === 0) return null\n\n const first = mapped[0]\n if (first === undefined) return null\n // Every type at the same document position (a node with `@type: [A, B]`) is\n // indistinguishable by order, so the lexicographically smaller name wins.\n let winner = first\n for (const candidate of mapped) {\n if (candidate.kind !== first.kind) break\n if (candidate.type < winner.type) winner = candidate\n }\n return winner\n}\n","/**\n * recommend.ts — what to fix, in what order, and what each fix is worth.\n *\n * WHY THIS FILE HAS A SPEC AT ALL. Recommendation arithmetic was undefined in\n * every source design, and it is the surface merchants actually act on: nobody\n * ships a change because a dimension moved, they ship it because a list said\n * \"this is worth 13 points\". A list that double-counts is a list that promises 30\n * points and delivers 16, and the second scan is where the product loses its\n * credibility. So §3.9's final paragraph pins the arithmetic and this file\n * implements exactly that:\n *\n * Recommendations are computed over a DEPENDENCY DAG. A recommendation's\n * `pointsAvailable` counts only the checks not already claimed by a\n * higher-ranked recommendation, plus the checks it uniquely UNLOCKS. Sums per\n * dimension are capped at the dimension weight. A property test asserts\n * `Σ pointsAvailable ≤ 100 − score`.\n *\n * WHAT \"UNLOCKS\" MEANS, PRECISELY. Two checks are gated on D2.1: D2.3\n * (`Vary: Accept` is meaningless on a response that does not vary) and D2.4\n * (substance parity has nothing to compare against). While D2.1 is at zero,\n * their points are not reachable by any other action, so they belong to the\n * recommendation that closes D2.1 — and to no other, which is what stops\n * \"declare Vary: Accept\" from also claiming them. Once D2.1 is earned, the gate\n * is open and D2.3 stands on its own. `unlocks` is therefore CONDITIONAL, not a\n * fixed edge list, and each template says when its edge exists.\n *\n * ORDER IS THE RANKING. The output array is in priority order: biggest raw\n * recovery first, ties broken by effort (a config change before an engineering\n * project) and then by id, so two runs over the same result produce the same\n * list. The dedup walks that same order, which is what \"higher-ranked\" means.\n *\n * NO POINTS ARE INVENTED. Every number is the gap between a check's `earned` and\n * its `weight` in the result being explained. A recommendation whose checks are\n * all already full does not appear at all — an empty list is the correct output\n * for a page at 100, and a list of platitudes would be worse than nothing.\n */\n\nimport type { ArsCheck, ArsCheckId, ArsDimension, ArsRecommendation, ArsResult } from './types'\n\n/** What `recommend()` needs from a result. Callers holding an `ArsResult` can pass it directly. */\nexport type ArsRecommendationInput = Pick<ArsResult, 'dimensions' | 'score'>\n\ninterface Template {\n readonly id: string\n readonly title: string\n readonly effort: ArsRecommendation['effort']\n readonly detail: string\n readonly checks: readonly ArsCheckId[]\n /**\n * Checks this recommendation makes reachable that nothing else can, given the\n * current state. Returns the empty list when the gate is already open.\n */\n readonly unlocks: (state: CheckState) => readonly ArsCheckId[]\n}\n\n/** Earned/weight for every check in the result, by id. */\ntype CheckState = ReadonlyMap<ArsCheckId, ArsCheck>\n\nconst NO_UNLOCKS = (): readonly ArsCheckId[] => []\n\n/**\n * The catalogue. One entry per action a site owner can actually take; the\n * `detail` is the instruction, not a restatement of the check name.\n *\n * Declaration order is the tie-break of last resort, so it is written in the\n * order the spec presents the dimensions rather than in any order of preference.\n */\nconst TEMPLATES: readonly Template[] = [\n {\n id: 'fix-robots-policy',\n title: 'Let assistant crawlers fetch this page',\n effort: 'config',\n detail:\n \"robots.txt currently blocks or ambiguously blocks the crawlers that fetch pages on a user's behalf. Name them in their own group and allow them. Blocking model-training crawlers is a separate decision and costs nothing in ARS.\",\n checks: ['retrievability.robots-policy'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'render-without-javascript',\n title: 'Put the core facts in the HTML the server sends',\n effort: 'engineering',\n detail:\n 'The facts for this page kind were not all present in the served HTML. Agents do not execute JavaScript: server-render the core facts, or ship them in a <noscript> block or structured data.',\n checks: ['retrievability.render-independence'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'serve-machine-representation',\n title: 'Serve a machine representation on Accept negotiation',\n effort: 'config',\n detail:\n 'Return Markdown, plain text or JSON with a matching Content-Type when the request asks for one, and keep the same URL. This is the single largest recoverable block in ARS, and it is also what makes Vary: Accept and the substance-parity check scoreable at all.',\n checks: ['machine-representation.negotiated-response'],\n unlocks: (state) =>\n earnedOf(state, 'machine-representation.negotiated-response') === 0\n ? ['machine-representation.vary-accept', 'machine-representation.substance-parity']\n : [],\n },\n {\n id: 'declare-alternates',\n title: 'Declare the alternate representation',\n effort: 'config',\n detail:\n 'Add `Link: <…>; rel=\"alternate\"; type=\"text/markdown\"` or a typed `<link rel=\"alternate\">`. An endpoint an agent cannot find is an endpoint that does not exist.',\n checks: ['machine-representation.declared-alternates'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'declare-vary-accept',\n title: 'Send Vary: Accept',\n effort: 'config',\n detail:\n 'A URL that returns different representations by Accept must say so, or a shared cache will hand the Markdown to a browser and the HTML to an agent.',\n checks: ['machine-representation.vary-accept'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'resolve-substance-divergence',\n title: 'Make both representations state the same values',\n effort: 'engineering',\n detail:\n 'The two representations reported different values for a core fact. Render both from one source of truth. ARS reports what each one said and does not assert which is correct.',\n checks: ['machine-representation.substance-parity'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'add-core-facts',\n title: 'State the missing core facts for this page kind',\n effort: 'template',\n detail:\n 'Coverage is scored against the fact set this kind of page is expected to carry, and only against that set — adding facts outside it earns nothing. A fact stated in two places (structured data and visible text) counts double.',\n checks: ['fact-coverage.core-facts'],\n unlocks: (state) =>\n // Position can only be scored once something is there to position. While\n // no core fact exists, D4's points are reachable through this and nothing\n // else; once one exists, \"front-load the core facts\" owns them.\n earnedOf(state, 'fact-position.first-core-fact-offset') === 0 &&\n earnedOf(state, 'fact-position.front-window') === 0\n ? ['fact-position.first-core-fact-offset', 'fact-position.front-window']\n : [],\n },\n {\n id: 'reduce-page-weight',\n title: 'Cut the bytes an agent has to read',\n effort: 'engineering',\n detail:\n 'Context cost is scored against what a page of this kind reasonably costs, not an absolute budget. The cheapest fix is usually to serve a machine representation rather than to shrink the HTML.',\n checks: ['fact-coverage.context-cost'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'front-load-core-facts',\n title: 'Move the core facts to the front',\n effort: 'template',\n detail:\n 'A caller that reads the first few kilobytes should already have the facts. Everything after the front window costs a full read of the document.',\n checks: ['fact-position.first-core-fact-offset', 'fact-position.front-window'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'add-structured-data',\n title: 'Add JSON-LD for this page',\n effort: 'template',\n detail:\n 'Declare a schema.org type in a JSON-LD block. Choosing no type does not avoid the check: an unrecognised page is still scored against \"any recognised type present\".',\n checks: ['structured-data.present'],\n unlocks: (state) =>\n earnedOf(state, 'structured-data.present') === 0\n ? ['structured-data.required-properties', 'structured-data.text-agreement']\n : [],\n },\n {\n id: 'complete-required-properties',\n title: 'Complete the required properties for this page kind',\n effort: 'template',\n detail:\n 'The required-property table is published per page kind in the spec. It is not \"schema.org validity\" — schema.org defines no required properties — and it does not change without an ARS release.',\n checks: ['structured-data.required-properties'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'align-structured-data-with-text',\n title: 'Make the structured data agree with the page',\n effort: 'template',\n detail:\n 'The JSON-LD and the visible page reported different values for a core fact. Generate both from the same source so they cannot drift.',\n checks: ['structured-data.text-agreement'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'declare-canonical',\n title: 'Declare one canonical URL, in both representations',\n effort: 'config',\n detail:\n 'Add an absolute `<link rel=\"canonical\">` to the HTML and a `Link: <…>; rel=\"canonical\"` header to the machine representation, pointing at the same URL. A representation with no canonical cannot be attributed to a page.',\n checks: ['contract-discovery.canonical'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'add-cache-validators',\n title: 'Add cache headers an agent can act on',\n effort: 'config',\n detail:\n 'Send a Cache-Control a cache can use plus an ETag or Last-Modified. Repeat fetches are most of agent traffic, and a response with no validator has to be re-read in full every time.',\n checks: ['contract-discovery.cache-validators'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'publish-llms-txt',\n title: 'Publish /llms.txt',\n effort: 'config',\n detail:\n 'An H1 title, a short summary, and links to the pages that matter. It is worth 1 point of 100, deliberately: content negotiation is the mechanism that measurably improves retrieval, and we have observed no citation lift from llms.txt alone.',\n checks: ['contract-discovery.llms-txt'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'declare-sitemap',\n title: 'Declare a sitemap in robots.txt',\n effort: 'config',\n detail:\n 'Add a `Sitemap:` line. It is the one place an agent looks to find the rest of the site.',\n checks: ['contract-discovery.sitemap'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'declare-machine-endpoint',\n title: 'Declare a machine endpoint',\n effort: 'engineering',\n detail:\n 'A feed, an OpenAPI document, /.well-known/ucp — anything an agent can call — declared with a `Link` header or a `<link>`. ARS probes /robots.txt, /llms.txt and /.well-known/ucp and guesses at no other path.',\n checks: ['contract-discovery.machine-endpoint'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'state-quantities',\n title: 'State the numbers in text',\n effort: 'template',\n detail:\n 'Price, sizes, weights, hours, fees, lead times, dates — written out where an agent reads them, not left in an image or implied by a paragraph. An assistant builds a cited answer out of quantities it can lift; distinct ones count, so saying the same price three times is one number.',\n checks: ['evidence-density.quantities'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'label-facts',\n title: 'Label each fact with its term',\n effort: 'template',\n detail:\n 'A line that reads \"Returns: 60 days\" travels whole into an answer. The same fact inside a sentence has to be inferred, and an assistant that has to infer it usually leaves it out. Specification lists, definition lists and labelled bullets all count.',\n checks: ['evidence-density.definitions'],\n unlocks: NO_UNLOCKS,\n },\n {\n id: 'add-comparison-rows',\n title: 'Put the options side by side',\n effort: 'template',\n detail:\n 'Sizes, tiers, models, plans — one row each, in a table with at least two columns. One row states a fact; two or more let an assistant contrast them, which is the question people actually ask it.',\n checks: ['evidence-density.comparisons'],\n unlocks: NO_UNLOCKS,\n },\n]\n\n/** Effort order for the tie-break: the cheapest fix first. */\nconst EFFORT_ORDER: readonly ArsRecommendation['effort'][] = ['config', 'template', 'engineering']\n\nfunction earnedOf(state: CheckState, id: ArsCheckId): number {\n return state.get(id)?.earned ?? 0\n}\n\nfunction gapOf(state: CheckState, id: ArsCheckId): number {\n const check = state.get(id)\n return check === undefined ? 0 : Math.max(0, check.weight - check.earned)\n}\n\n/**\n * Ranked, deduplicated remedies for a scored result.\n *\n * Returns an empty array for a non-grade (`score: null`): an unscored or\n * opted-out target has no sub-scores, so there is nothing to recover and no\n * honest number to attach to advice.\n */\nexport function recommend(input: ArsRecommendationInput): ArsRecommendation[] {\n if (input.score === null) return []\n\n const state = new Map<ArsCheckId, ArsCheck>()\n const dimensionOf = new Map<ArsCheckId, ArsDimension>()\n for (const dimension of input.dimensions) {\n for (const check of dimension.checks) {\n state.set(check.id, check)\n dimensionOf.set(check.id, dimension)\n }\n }\n\n // Rank by RAW recovery — what the recommendation would be worth if it were the\n // only one — because the deduped value cannot be known until the order is\n // fixed. Ties: cheaper effort first, then declaration order for stability.\n //\n // A recommendation may only claim the checks it UNLOCKS if it also closes\n // something itself. Without that rule, a template whose own check is already\n // full could still claim a gated check's points and print advice that has\n // nothing to do with the gap it is being credited for.\n const ranked = TEMPLATES.map((template, index) => {\n const own = template.checks.reduce((sum, id) => sum + gapOf(state, id), 0)\n const unlocked = own > 0 ? template.unlocks(state) : []\n const ids = [...template.checks, ...unlocked]\n const raw = own + unlocked.reduce((sum, id) => sum + gapOf(state, id), 0)\n return { template, ids, raw, index }\n })\n .filter((entry) => entry.raw > 0)\n .sort((a, b) => {\n if (a.raw !== b.raw) return b.raw - a.raw\n const effort =\n EFFORT_ORDER.indexOf(a.template.effort) - EFFORT_ORDER.indexOf(b.template.effort)\n return effort !== 0 ? effort : a.index - b.index\n })\n\n const claimed = new Set<ArsCheckId>()\n /** Points already promised per dimension, so the total can never exceed its weight. */\n const spent = new Map<string, number>()\n const out: ArsRecommendation[] = []\n\n for (const entry of ranked) {\n let points = 0\n const closes: ArsCheckId[] = []\n const opens: ArsCheckId[] = []\n\n for (const id of entry.ids) {\n if (claimed.has(id)) continue\n const dimension = dimensionOf.get(id)\n if (dimension === undefined) continue\n const remaining = Math.max(\n 0,\n dimension.weight - dimension.earned - (spent.get(dimension.id) ?? 0),\n )\n const value = Math.min(gapOf(state, id), remaining)\n if (value <= 0) continue\n points += value\n spent.set(dimension.id, (spent.get(dimension.id) ?? 0) + value)\n claimed.add(id)\n if (entry.template.checks.includes(id)) closes.push(id)\n else opens.push(id)\n }\n\n if (points <= 0) continue\n out.push({\n id: entry.template.id,\n title: entry.template.title,\n pointsAvailable: points,\n effort: entry.template.effort,\n detail: entry.template.detail,\n checks: closes,\n unlocks: opens,\n })\n }\n\n return out\n}\n","/**\n * score.ts — the ARS 0.2 scoring engine. The whole pure half comes together here.\n *\n * THE CONTRACT. `score(evidence, ruleset)` is a pure function: same evidence,\n * same ruleset, same `ArsResult`, byte for byte, in any conformant\n * implementation in any language. No network, no clock, no randomness, no LLM.\n * The ESLint rule in `eslint.config.mjs` enforces the first three at build time;\n * the fourth has nowhere to hide, because there is no model call anywhere in this\n * package.\n *\n * INTEGER ARITHMETIC ONLY (§3.6). Every number below is produced by `idiv` /\n * `divRoundHalfUp`, never by `/` on values that do not divide, and never by\n * `Math.round`. Cross-language conformance is impossible with float rounding\n * drift, and publishing a standard whose scores differ in the third\n * implementation would be worse than publishing nothing. All inputs are\n * non-negative, so rounding is unambiguous half-up via\n * `(numerator + denominator / 2) / denominator`.\n *\n * FIXED WEIGHTS. 100 points for every page, whatever its kind. What varies by\n * page kind is the fact set and the byte reference (`./profiles`) — never a\n * weight. Redistribution would be a gaming vector: make the dimension you are bad\n * at inapplicable and everything else inflates.\n *\n * TWO GATES EXIST, AND THEY POINT THE SAFE WAY. D2.3 (`Vary: Accept`) and D2.4\n * (substance parity) are gated on D2.1 (a machine representation was served),\n * which is a MEASURED check gating others. That direction is fine and is what\n * makes the published ceiling provable: no content negotiation loses D2.1 (10) +\n * D2.3 (3) + D2.4 (3) → max 84 → capped at B. The forbidden direction — a\n * heuristic that can zero measured points — appears nowhere. In particular D2.4\n * and D5.3 are SCORED CHECKS, NOT GATES: a parity failure loses its own 3 points\n * and raises a `warn`, and leaves D2's other 17 measured points alone. That is\n * the whole reason \"measured 64 / heuristic 36\" is an honest split rather than a\n * presentational one.\n *\n * WHICH REPRESENTATION SCORES WHAT (the decision `./extract` states in its own\n * header, repeated here because it is the reason the golden pair means anything):\n * D3 (coverage) and D4 (position) score the AGENT representation, because ARS\n * measures what a caller actually receives. D1.3 (render independence) and D5\n * (structured data) score the representation that carries a document, because\n * those checks are about the HTML a caller that only reads HTML gets.\n *\n * MEASURED CHECKS NEVER AWARD POINTS FOR AN OBSERVATION WE DID NOT MAKE. When\n * the browser probe is missing, the sub-conditions that compare the two probes\n * (D1.1's \"no Accept-conditional redirect\", D6.1's \"self-consistent\") score 0 and\n * say so in their evidence. Awarding them by default would make a measured check\n * heuristic; deducting them silently would be unexplained. The evidence line is\n * the difference.\n *\n * WHAT LIVES IN THE RULESET AND WHAT LIVES HERE. `DEFAULT_RULESET.thresholds`\n * holds exactly the §3.6 numeric tables (density, context cost, offsets, front\n * window). The remaining checks are conjunctions of named conditions rather than\n * bands, and their point splits are `SUBPOINTS` below: published, frozen, and —\n * like the classification tables in `./classify` — NOT covered by `rulesetHash`,\n * because §3.9's `ArsRuleset` has no field for them. That gap is recorded in the\n * package README as a known limitation of 0.1 rather than papered over.\n */\n\nimport { classify, isRecognisedType, nodeForKind, pass1Signals } from './classify'\nimport type { ArsClassification } from './classify'\nimport {\n buildPolicyReport,\n buildRepresentation,\n extractFacts,\n hasPath,\n header,\n headerAll,\n mergeFacts,\n parseRobots,\n pathMatches,\n readPath,\n} from './extract'\nimport type {\n ArsRepresentation,\n ExtractedFact,\n JsonLdNode,\n MergedFact,\n RobotsFile,\n} from './extract'\nimport { attr, elementText } from './html'\nimport { profileFor } from './profiles'\nimport { recommend } from './recommend'\nimport { CHECK_META, DEFAULT_RULESET, DIMENSION_META } from './ruleset'\nimport type {\n ArsAudience,\n ArsBand,\n ArsBasis,\n ArsCheck,\n ArsCheckEvidence,\n ArsCheckId,\n ArsCostReport,\n ArsDimension,\n ArsDimensionId,\n ArsEvidence,\n ArsFactKind,\n ArsFactObservation,\n ArsFactProfile,\n ArsFlag,\n ArsFlagId,\n ArsGrade,\n ArsHttpCapture,\n ArsOutcome,\n ArsPolicyReport,\n ArsProbeRecord,\n ArsResult,\n ArsRuleset,\n ArsUnscoredReason,\n} from './types'\nimport { ARS_SPEC_VERSION } from './types'\n\n// ---------------------------------------------------------------------------\n// Integer arithmetic (§3.6)\n// ---------------------------------------------------------------------------\n\n/**\n * Exact integer division for non-negative safe integers. `%` is exact, the\n * subtraction is exact, and dividing by an exact multiple is exact, so this\n * never rounds — unlike `Math.floor(a / b)`, whose intermediate quotient is an\n * IEEE-754 double that can land on the wrong side of an integer boundary. A\n * scoring path that is \"almost always\" the same in two languages is not a\n * standard.\n */\nfunction idiv(numerator: number, denominator: number): number {\n if (denominator === 0) return 0\n return (numerator - (numerator % denominator)) / denominator\n}\n\n/** §3.6's half-up rounding, `(numerator + denominator / 2) / denominator`, in integers. */\nfunction divRoundHalfUp(numerator: number, denominator: number): number {\n if (denominator === 0) return 0\n return idiv(numerator + idiv(denominator, 2), denominator)\n}\n\n/**\n * AT-LEAST table lookup: flat `[threshold, value]` pairs in DESCENDING threshold\n * order; the first pair whose `threshold <= input` wins. No match scores 0, which\n * can only happen if a ruleset omits the table — a malformed ruleset must not\n * silently invent points.\n */\nfunction atLeast(pairs: readonly number[] | undefined, input: number): number {\n if (pairs === undefined) return 0\n for (let i = 0; i + 1 < pairs.length; i += 2) {\n const threshold = pairs[i]\n const value = pairs[i + 1]\n if (threshold === undefined || value === undefined) return 0\n if (input >= threshold) return value\n }\n return 0\n}\n\n/**\n * AT-MOST table lookup: flat `[threshold, value]` pairs in ASCENDING threshold\n * order; the first pair whose `input <= threshold` wins; no match scores 0.\n */\nfunction atMost(pairs: readonly number[] | undefined, input: number): number {\n if (pairs === undefined) return 0\n for (let i = 0; i + 1 < pairs.length; i += 2) {\n const threshold = pairs[i]\n const value = pairs[i + 1]\n if (threshold === undefined || value === undefined) return 0\n if (input <= threshold) return value\n }\n return 0\n}\n\n/** Recursively freezes a plain data structure. Used on `SUBPOINTS`. */\nfunction deepFreeze<T>(value: T): T {\n if (typeof value !== 'object' || value === null) return value\n for (const child of Object.values(value as Record<string, unknown>)) deepFreeze(child)\n return Object.freeze(value)\n}\n\n// ---------------------------------------------------------------------------\n// Sub-point splits\n// ---------------------------------------------------------------------------\n\n/**\n * The point split inside each check that scores a CONJUNCTION of named\n * conditions rather than a numeric band. §3.4 states the conditions (\"D1.1 2xx on\n * the agent path, ≤3 hops, no Accept-conditional redirect\"); this is how the\n * check's points are divided between them, and every split sums to the check's\n * weight in `DEFAULT_RULESET.weights`.\n *\n * Published here rather than in `DEFAULT_RULESET` because §3.9's `ArsRuleset` has\n * no field for them. The consequence is stated rather than hidden: these numbers\n * are NOT covered by `rulesetHash`, exactly like the classification tables in\n * `./classify`. Editing one moves conformance `expected.json` files and is\n * therefore a MINOR, and the corpus is what actually pins them.\n */\n/**\n * The per-check point splits.\n *\n * THESE MUST SUM TO `WEIGHTS`, and until ARS 0.2 nothing said so. The ruleset\n * carried the same numbers twice, here and in `WEIGHTS`, with fixture `052`\n * checking only that `DIMENSION_META` agreed with `WEIGHTS`. Rebalancing for\n * 0.2 changed `WEIGHTS` alone and every check kept emitting 0.1's points, so\n * the corpus re-scored with dimensions claiming 28 while their checks could\n * only pay 20. `subpointTotals()` below closes that, and `score.test.ts`\n * asserts the two tables agree check by check.\n */\nexport const SUBPOINTS = deepFreeze({\n /** D1.1, 11 = 5 + 3 + 3. */\n reachable: { status2xx: 5, withinRedirectLimit: 3, noAcceptConditionalRedirect: 3 },\n /** D1.2, 10 = 6 + 2 + 1 + 1. A disallowed assistant audience scores 0 for all four (§3.7). */\n robotsPolicy: { assistantAllowed: 6, parsesClean: 2, noOrphanRules: 1, sitemapDeclared: 1 },\n /**\n * D1.3, 7. AT-LEAST band over `100 × coreFactsInHtml / coreProfileSize`, plus\n * the `<noscript>` floor: a page whose facts are all client-rendered but which\n * ships a non-empty `<noscript>` has told a JS-less caller something, and §3.8\n * says that earns partial credit.\n */\n renderIndependence: {\n band: [100, 7, 75, 5, 50, 3, 25, 1] as readonly number[],\n noscriptFloor: 1,\n },\n /** D2.1, 9. All-or-nothing: a machine media type AND a body that is not HTML. */\n negotiatedResponse: { full: 9 },\n /** D2.2, 3. All-or-nothing. */\n declaredAlternates: { full: 3 },\n /** D2.3, 3. All-or-nothing, and 0 unless D2.1 > 0. */\n varyAccept: { full: 3 },\n /** D2.4, 3. All-or-nothing, and 0 unless D2.1 > 0 and a browser capture exists. */\n substanceParity: { full: 3 },\n /** D5.1, 2. Structured data present AND parsing; a partly-broken graph scores 1. */\n structuredDataPresent: { clean: 2, partial: 1 },\n /** D5.2, 3 = 1 (a recognised type) + 2 (required-property completeness, scaled). */\n requiredProperties: { recognisedType: 1, completeness: 2 },\n /** D5.3, 1. All-or-nothing. */\n textAgreement: { full: 1 },\n /** D6.1, 4 = 2 + 1 + 1. */\n canonical: { present: 2, absolute: 1, consistentAcrossProbes: 1 },\n /** D6.2, 2 = 1 + 1. */\n cacheValidators: { saneCacheControl: 1, validator: 1 },\n /**\n * D6.3, 1. `specShaped` — an H1 and at least one Markdown link — is the whole\n * point. `present` is 0 in 0.2: at two points 0.1 could pay one for the file\n * existing and one for it being usable, but at one point that split would make\n * \"exists\" and \"usable\" score identically, which is a distinction the standard\n * would then be printing a remedy for and paying nothing to fix.\n */\n llmsTxt: { present: 0, specShaped: 1 },\n /** D6.4, 1. All-or-nothing. */\n sitemap: { full: 1 },\n /** D6.5, 2. All-or-nothing over any ONE declared machine endpoint. */\n machineEndpoint: { full: 2 },\n})\n\n/**\n * The maximum each SUBPOINTS entry can pay, for the agreement assertion. A band\n * pays its highest value; `structuredDataPresent` and `llmsTxt` are graded, so\n * the best branch is the max, not the sum.\n */\nexport function subpointTotals(): Record<string, number> {\n const s = SUBPOINTS\n return {\n 'retrievability.reachable':\n s.reachable.status2xx + s.reachable.withinRedirectLimit + s.reachable.noAcceptConditionalRedirect,\n 'retrievability.robots-policy':\n s.robotsPolicy.assistantAllowed +\n s.robotsPolicy.parsesClean +\n s.robotsPolicy.noOrphanRules +\n s.robotsPolicy.sitemapDeclared,\n 'retrievability.render-independence': s.renderIndependence.band[1] ?? 0,\n 'machine-representation.negotiated-response': s.negotiatedResponse.full,\n 'machine-representation.declared-alternates': s.declaredAlternates.full,\n 'machine-representation.vary-accept': s.varyAccept.full,\n 'machine-representation.substance-parity': s.substanceParity.full,\n 'structured-data.present': s.structuredDataPresent.clean,\n 'structured-data.required-properties':\n s.requiredProperties.recognisedType + s.requiredProperties.completeness,\n 'structured-data.text-agreement': s.textAgreement.full,\n 'contract-discovery.canonical':\n s.canonical.present + s.canonical.absolute + s.canonical.consistentAcrossProbes,\n 'contract-discovery.cache-validators': s.cacheValidators.saneCacheControl + s.cacheValidators.validator,\n 'contract-discovery.llms-txt': s.llmsTxt.specShaped,\n 'contract-discovery.sitemap': s.sitemap.full,\n 'contract-discovery.machine-endpoint': s.machineEndpoint.full,\n }\n}\n\n// ---------------------------------------------------------------------------\n// SHA-256 and RFC 8785 canonical JSON\n// ---------------------------------------------------------------------------\n\n/**\n * WHY A HAND-ROLLED SHA-256 LIVES IN THE PURE HALF. `ArsResult` carries three\n * hashes and the determinism guarantee is stated in terms of them, so `score()`\n * has to compute two of them. `node:crypto` would make this package Node-only,\n * and `apps/rebilder-web` imports the root entry point; `crypto.subtle` is async\n * and `score()` is not. A dependency is out — the package's contract is zero\n * runtime dependencies, and a third-party hash version would be an unversioned\n * input to a hashed artifact, which is the same argument that made the tokenizer\n * hand-rolled. So: ~80 lines of FIPS 180-4, checked against the published test\n * vectors in `tests/score.test.ts`.\n */\nconst SHA256_K: readonly number[] = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]\n\nfunction rotr(value: number, bits: number): number {\n return ((value >>> bits) | (value << (32 - bits))) >>> 0\n}\n\n/** SHA-256 of a UTF-8 string, lowercase hex. FIPS 180-4. */\nexport function sha256Hex(message: string): string {\n const bytes = new TextEncoder().encode(message)\n const bitLength = bytes.length * 8\n // Padded length: message + 0x80 + zeros + 8 length bytes, to a 64-byte multiple.\n const padded = new Uint8Array((idiv(bytes.length + 9 + 63, 64) || 1) * 64)\n padded.set(bytes)\n padded[bytes.length] = 0x80\n // Length as a 64-bit big-endian bit count. Bodies are capped at 2 MiB, so the\n // high word is always zero; it is written anyway so the routine is correct for\n // any input a caller hands it.\n const view = new DataView(padded.buffer)\n view.setUint32(padded.length - 8, idiv(bitLength, 0x100000000), false)\n view.setUint32(padded.length - 4, bitLength >>> 0, false)\n\n const h = [\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n ]\n const w = new Uint32Array(64)\n\n for (let offset = 0; offset < padded.length; offset += 64) {\n for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4, false)\n for (let i = 16; i < 64; i++) {\n const a = w[i - 15] ?? 0\n const b = w[i - 2] ?? 0\n const s0 = (rotr(a, 7) ^ rotr(a, 18) ^ (a >>> 3)) >>> 0\n const s1 = (rotr(b, 17) ^ rotr(b, 19) ^ (b >>> 10)) >>> 0\n w[i] = ((w[i - 16] ?? 0) + s0 + (w[i - 7] ?? 0) + s1) >>> 0\n }\n\n let [a, b, c, d, e, f, g, hh] = h as [\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n ]\n for (let i = 0; i < 64; i++) {\n const s1 = (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) >>> 0\n const ch = ((e & f) ^ (~e & g)) >>> 0\n const temp1 = (hh + s1 + ch + (SHA256_K[i] ?? 0) + (w[i] ?? 0)) >>> 0\n const s0 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) >>> 0\n const maj = ((a & b) ^ (a & c) ^ (b & c)) >>> 0\n const temp2 = (s0 + maj) >>> 0\n hh = g\n g = f\n f = e\n e = (d + temp1) >>> 0\n d = c\n c = b\n b = a\n a = (temp1 + temp2) >>> 0\n }\n const next = [a, b, c, d, e, f, g, hh]\n for (let i = 0; i < 8; i++) h[i] = ((h[i] ?? 0) + (next[i] ?? 0)) >>> 0\n }\n\n let hex = ''\n for (const word of h) hex += word.toString(16).padStart(8, '0')\n return hex\n}\n\n/**\n * RFC 8785 (JCS) canonical JSON, over the value shapes ARS actually hashes:\n * objects, arrays, strings, booleans, null and JSON numbers.\n *\n * Two details make this RFC-conformant rather than merely deterministic:\n * object keys are sorted by UTF-16 code unit (JCS §3.2.3, which is what\n * JavaScript's default string comparison already does), and numbers are\n * serialised with `JSON.stringify`, whose output is the ECMAScript\n * `Number::toString` shortest round-trip form that JCS §3.2.2.3 mandates.\n * `undefined` and functions cannot appear in the data we hash and are dropped.\n */\nexport function canonicalJson(value: unknown): string {\n if (value === null) return 'null'\n if (typeof value === 'boolean') return value ? 'true' : 'false'\n if (typeof value === 'number') return Number.isFinite(value) ? JSON.stringify(value) : 'null'\n if (typeof value === 'string') return JSON.stringify(value)\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`\n if (typeof value === 'object') {\n const record = value as Record<string, unknown>\n const keys = Object.keys(record).filter((key) => record[key] !== undefined)\n keys.sort()\n return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(',')}}`\n }\n return 'null'\n}\n\n/** SHA-256 of the RFC 8785 canonical JSON of the frozen ruleset (§3.1). */\nexport function rulesetHash(ruleset: ArsRuleset): string {\n return sha256Hex(canonicalJson(ruleset))\n}\n\n/**\n * Headers excluded from `evidenceHash` (§3.3). Without this exclusion the hash\n * changes on every scan of every real site — `date` alone guarantees it — and the\n * replay story, which is the only reason the hash is published, dies.\n */\nconst VOLATILE_HEADERS: ReadonlySet<string> = new Set([\n 'date',\n 'age',\n 'set-cookie',\n 'x-request-id',\n 'cf-ray',\n 'report-to',\n])\n\nfunction stableHeaders(\n headers: Readonly<Record<string, readonly string[]>>,\n): Record<string, readonly string[]> {\n const out: Record<string, readonly string[]> = {}\n for (const [name, values] of Object.entries(headers)) {\n if (VOLATILE_HEADERS.has(name.toLowerCase())) continue\n out[name.toLowerCase()] = values\n }\n return out\n}\n\n/**\n * SHA-256 over the evidence bundle with the volatile fields removed: the header\n * denylist above, and `capturedAt`, which is wall-clock time and is never an\n * input to scoring. Bodies ARE hashed — `bodySha256` is already in the capture,\n * but hashing the body itself means a bundle whose body was edited without\n * updating its digest does not silently keep its identity.\n */\nexport function evidenceHash(evidence: ArsEvidence): string {\n const redactProbe = (probe: ArsProbeRecord | null): unknown => {\n if (probe === null) return null\n if (!probe.result.ok) return { requestHeaders: probe.requestHeaders, result: probe.result }\n const capture = probe.result.capture\n return {\n requestHeaders: probe.requestHeaders,\n result: {\n ok: true,\n capture: { ...capture, headers: stableHeaders(capture.headers) },\n },\n }\n }\n return sha256Hex(\n canonicalJson({\n evidenceVersion: evidence.evidenceVersion,\n target: evidence.target,\n vantage: evidence.vantage,\n probes: {\n agent: redactProbe(evidence.probes.agent),\n browser: redactProbe(evidence.probes.browser),\n parityConfirm: redactProbe(evidence.probes.parityConfirm),\n robotsTxt: redactProbe(evidence.probes.robotsTxt),\n llmsTxt: redactProbe(evidence.probes.llmsTxt),\n wellKnownUcp: redactProbe(evidence.probes.wellKnownUcp),\n },\n }),\n )\n}\n\n/**\n * `corpusHash` — SHA-256 over the FROZEN conformance corpus (§3.1). Computing it\n * requires reading the corpus directory, which the pure half cannot do, so it is\n * a constant regenerated at corpus freeze.\n *\n * ARS 0.2 ships as a DRAFT (§3.10, \"Calibration\") and its corpus is still open:\n * fixtures are landing. So the value below is deliberately NOT a corpus digest —\n * it is the SHA-256 of the ASCII string `ars-0.2-corpus-unfrozen`. Anyone who\n * recomputes the digest of the shipped corpus will find it does not match, which\n * is the correct signal: a score carrying this constant is a draft score. It is\n * computed rather than pasted so that no reader has to trust a magic literal.\n *\n * THE STRING CARRIES THE SPEC VERSION for the same reason `rulesetHash` exists:\n * 0.1 and 0.2 score the same page differently, so a 0.1 draft score and a 0.2\n * draft score must not be able to present identical identity triples.\n */\nexport const ARS_CORPUS_HASH = sha256Hex('ars-0.2-corpus-unfrozen')\n\n// ---------------------------------------------------------------------------\n// Header helpers\n// ---------------------------------------------------------------------------\n\n/** One entry of a `Link` header: the target IRI plus the parameters ARS reads. */\ninterface ParsedLink {\n readonly url: string\n readonly rel: readonly string[]\n readonly type: string | null\n}\n\n/**\n * Parses `Link` header values (RFC 8288) in the subset ARS scores: the target\n * IRI, `rel` as a token list, and `type`.\n *\n * Written as a scanner because the separator is a comma and target IRIs contain\n * commas — `<https://x/a,b>; rel=\"alternate\"` is one link, not two. Splitting on\n * `,` would silently drop half of the alternates a merchant declared and cost\n * them 4 points on D2.2.\n */\nexport function parseLinkHeaders(values: readonly string[]): ParsedLink[] {\n const out: ParsedLink[] = []\n for (const value of values) {\n for (const entry of splitLinkEntries(value)) {\n const open = entry.indexOf('<')\n const close = entry.indexOf('>', open + 1)\n if (open === -1 || close === -1) continue\n const url = entry.slice(open + 1, close).trim()\n if (url.length === 0) continue\n let rel: string[] = []\n let type: string | null = null\n for (const param of entry.slice(close + 1).split(';')) {\n const equals = param.indexOf('=')\n if (equals === -1) continue\n const name = param.slice(0, equals).trim().toLowerCase()\n const raw = param.slice(equals + 1).trim()\n const unquoted = raw.startsWith('\"') && raw.endsWith('\"') ? raw.slice(1, -1) : raw\n if (name === 'rel')\n rel = unquoted\n .toLowerCase()\n .split(/\\s+/)\n .filter((t) => t.length > 0)\n else if (name === 'type') type = unquoted.trim().toLowerCase()\n }\n out.push({ url, rel, type })\n }\n }\n return out\n}\n\n/** Splits on commas that are outside `<…>` and outside a quoted string. */\nfunction splitLinkEntries(value: string): string[] {\n const entries: string[] = []\n let depth = 0\n let quoted = false\n let start = 0\n for (let i = 0; i < value.length; i++) {\n const char = value.charAt(i)\n if (quoted) {\n if (char === '\"') quoted = false\n continue\n }\n if (char === '\"') quoted = true\n else if (char === '<') depth++\n else if (char === '>') depth = depth > 0 ? depth - 1 : 0\n else if (char === ',' && depth === 0) {\n entries.push(value.slice(start, i))\n start = i + 1\n }\n }\n entries.push(value.slice(start))\n return entries.map((entry) => entry.trim()).filter((entry) => entry.length > 0)\n}\n\n/** Comma/space-separated header token list, lowercased. */\nfunction headerTokens(value: string | null): string[] {\n if (value === null) return []\n return value\n .toLowerCase()\n .split(/[,\\s]+/)\n .map((token) => token.trim())\n .filter((token) => token.length > 0)\n}\n\n// ---------------------------------------------------------------------------\n// Scoring context\n// ---------------------------------------------------------------------------\n\n/** Everything the 22 checks read, computed exactly once. */\ninterface ScoreContext {\n readonly evidence: ArsEvidence\n readonly ruleset: ArsRuleset\n readonly agentCapture: ArsHttpCapture\n readonly browserCapture: ArsHttpCapture | null\n readonly agent: ArsRepresentation\n readonly browser: ArsRepresentation | null\n /** The representation that carries a tokenized document, if either does. */\n readonly structural: ArsRepresentation | null\n readonly classification: ArsClassification\n readonly profile: ArsFactProfile\n readonly facts: readonly MergedFact[]\n readonly agentFacts: readonly ExtractedFact[]\n readonly browserFacts: readonly ExtractedFact[]\n readonly structuralFacts: readonly ExtractedFact[]\n readonly policy: ArsPolicyReport\n readonly robots: RobotsFile | null\n readonly flags: ArsFlag[]\n}\n\ninterface CheckOutcome {\n readonly earned: number\n readonly evidence: ArsCheckEvidence[]\n readonly remedy?: string\n}\n\nconst YES = 'yes'\nconst NO = 'no'\nconst yesNo = (value: boolean): string => (value ? YES : NO)\n\nfunction measured(label: string, value: string): ArsCheckEvidence {\n return { label, value, basis: 'measured' }\n}\n\nfunction heuristic(label: string, value: string): ArsCheckEvidence {\n return { label, value, basis: 'heuristic' }\n}\n\n// ---------------------------------------------------------------------------\n// D1 — Retrievability\n// ---------------------------------------------------------------------------\n\nfunction checkReachable(context: ScoreContext): CheckOutcome {\n const { agentCapture, browserCapture, ruleset } = context\n const split = SUBPOINTS.reachable\n const status2xx = agentCapture.status >= 200 && agentCapture.status < 300\n const hops = agentCapture.redirects.length\n const withinLimit = hops <= ruleset.maxRedirects\n const sameFinalUrl = browserCapture !== null && browserCapture.finalUrl === agentCapture.finalUrl\n\n const earned =\n (status2xx ? split.status2xx : 0) +\n (withinLimit ? split.withinRedirectLimit : 0) +\n (sameFinalUrl ? split.noAcceptConditionalRedirect : 0)\n\n const evidence = [\n measured('HTTP status on the agent path', String(agentCapture.status)),\n measured('Redirect hops', `${hops} (limit ${ruleset.maxRedirects})`),\n measured(\n 'Both probes resolved to the same URL',\n browserCapture === null\n ? 'not comparable — no browser-control capture in this bundle'\n : yesNo(sameFinalUrl),\n ),\n ]\n return sameFinalUrl\n ? { earned, evidence }\n : {\n earned,\n evidence,\n remedy:\n 'Serve the same URL to both Accept headers. An Accept-conditional redirect sends the agent somewhere the browser never goes, and caches key on the URL.',\n }\n}\n\nfunction checkRobotsPolicy(context: ScoreContext): CheckOutcome {\n const { policy, robots } = context\n const split = SUBPOINTS.robotsPolicy\n const decision = policy.audiences.assistant\n const parsesClean = robots === null || robots.malformedLines === 0\n const noOrphanRules = robots === null || robots.orphanRules === 0\n\n const evidence = [\n measured('robots.txt', policy.robotsTxtStatus),\n measured(\n 'Assistant audience',\n decision.matchedGroup === null\n ? `${decision.decision} (no matching group)`\n : `${decision.decision} via User-agent: ${decision.matchedGroup}${\n decision.matchedRule === null ? '' : ` / ${decision.matchedRule}`\n }`,\n ),\n measured('Malformed lines', robots === null ? 'n/a' : String(robots.malformedLines)),\n measured(\n 'Rules before any User-agent line',\n robots === null ? 'n/a' : String(robots.orphanRules),\n ),\n measured('Sitemap: declared', yesNo(policy.sitemapDeclared)),\n measured(\n 'Training-crawler policy (never scored)',\n policy.trainingOptOut ? 'blocked — neutral, no effect on this score' : 'allowed',\n ),\n ]\n\n // §3.7: an accidental or ambiguous assistant disallow — a blanket group, a\n // malformed file — is SCORED, with D1.2 at zero and a `robots-contradiction`\n // warning. It is not an opt-out, because consent has to be specific.\n if (decision.decision === 'disallow') {\n context.flags.push({\n id: 'robots-contradiction',\n severity: 'warn',\n basis: 'measured',\n message:\n 'robots.txt disallows assistant crawlers through a group that does not name one, so it reads as a blanket rule rather than a deliberate choice. Assistant traffic is blocked as a side effect.',\n evidence: [evidence[1] ?? measured('Assistant audience', decision.decision)],\n })\n return {\n earned: 0,\n evidence,\n remedy:\n 'Name the assistant crawlers you mean to allow or block in their own robots.txt group. A blanket disallow blocks assistant fetches that users triggered on purpose.',\n }\n }\n\n const earned =\n split.assistantAllowed +\n (parsesClean ? split.parsesClean : 0) +\n (noOrphanRules ? split.noOrphanRules : 0) +\n (policy.sitemapDeclared ? split.sitemapDeclared : 0)\n\n return {\n earned,\n evidence,\n remedy: policy.sitemapDeclared\n ? undefined\n : 'Add a `Sitemap:` line to robots.txt. It is the one place an agent looks to find the rest of the site.',\n }\n}\n\nfunction checkRenderIndependence(context: ScoreContext): CheckOutcome {\n const { structural, structuralFacts, profile } = context\n const split = SUBPOINTS.renderIndependence\n const coreSize = profile.core.length\n\n if (structural === null || structural.doc === null) {\n return {\n earned: 0,\n evidence: [heuristic('HTML representation', 'none in this bundle — not evaluated')],\n }\n }\n\n const found = new Set<ArsFactKind>()\n for (const fact of structuralFacts) if (profile.core.includes(fact.kind)) found.add(fact.kind)\n const ratio = coreSize === 0 ? 0 : idiv(100 * found.size, coreSize)\n\n let noscriptText = ''\n for (const element of structural.doc.elements) {\n if (element.tag !== 'noscript') continue\n noscriptText = elementText(structural.doc, element.index).trim()\n if (noscriptText.length > 0) break\n }\n const hasNoscript = noscriptText.length > 0\n\n const banded = atLeast(split.band, ratio)\n const earned = Math.max(banded, hasNoscript ? split.noscriptFloor : 0)\n const full = atLeast(split.band, 100)\n\n if (ratio < 50) {\n context.flags.push({\n id: 'render-dependent',\n severity: 'info',\n basis: 'heuristic',\n message: `${found.size} of ${coreSize} core facts for this page kind were present in the HTML without running JavaScript. A caller that does not execute scripts sees the rest as missing.`,\n evidence: [heuristic('Core facts in the served HTML', `${found.size}/${coreSize}`)],\n })\n }\n\n return {\n earned,\n evidence: [\n heuristic('Core facts present without JavaScript', `${found.size}/${coreSize}`),\n heuristic('<noscript> fallback with content', yesNo(hasNoscript)),\n heuristic(\n 'Basis',\n 'inferred — ARS never executes JavaScript, so this measures the served HTML, not what a browser would render',\n ),\n ],\n remedy:\n earned === full\n ? undefined\n : 'Render the core facts for this page kind into the HTML the server sends. Agents do not run your JavaScript.',\n }\n}\n\n// ---------------------------------------------------------------------------\n// D2 — Machine representation\n// ---------------------------------------------------------------------------\n\n/** Media types that count as a machine representation for D2.1 (§3.4). */\nconst MACHINE_KINDS: ReadonlySet<ArsRepresentation['kind']> = new Set(['markdown', 'text', 'json'])\n\nfunction checkNegotiatedResponse(context: ScoreContext): CheckOutcome {\n const { agent } = context\n const typeIsMachine = MACHINE_KINDS.has(agent.kind)\n const bodyIsHtml = agent.looksLikeHtml\n const earned = typeIsMachine && !bodyIsHtml ? SUBPOINTS.negotiatedResponse.full : 0\n\n return {\n earned,\n evidence: [\n measured('Content-Type on the agent probe', agent.contentType ?? 'absent'),\n measured('Body is HTML', yesNo(bodyIsHtml)),\n measured(\n 'Request Accept header',\n context.evidence.probes.agent.requestHeaders['accept'] ??\n context.evidence.probes.agent.requestHeaders['Accept'] ??\n 'not recorded',\n ),\n ],\n remedy:\n earned > 0\n ? undefined\n : typeIsMachine\n ? 'The response declared a machine media type but the body is HTML. Send the representation the Content-Type promises.'\n : 'Return a machine representation — Markdown, plain text or JSON — when the request Accept header asks for one, with a matching Content-Type.',\n }\n}\n\nfunction checkDeclaredAlternates(context: ScoreContext): CheckOutcome {\n const { agentCapture, browserCapture, structural } = context\n const links = parseLinkHeaders([\n ...headerAll(agentCapture.headers, 'link'),\n ...(browserCapture === null ? [] : headerAll(browserCapture.headers, 'link')),\n ])\n // An alternate with no `type` is a language variant (`hreflang`), not a second\n // representation. Every international site declares those, and paying 4 points\n // for them would make the check meaningless.\n const headerAlternates = links.filter(\n (link) => link.rel.includes('alternate') && link.type !== null,\n )\n\n const documentAlternates: string[] = []\n if (structural !== null && structural.doc !== null) {\n for (const link of structural.doc.links) {\n if (!link.rel.includes('alternate')) continue\n if (link.type === null || link.href === null) continue\n documentAlternates.push(`${link.type} → ${link.href}`)\n }\n }\n\n const total = headerAlternates.length + documentAlternates.length\n return {\n earned: total > 0 ? SUBPOINTS.declaredAlternates.full : 0,\n evidence: [\n measured(\n 'Link: rel=\"alternate\" (typed)',\n headerAlternates.length === 0\n ? 'none'\n : headerAlternates.map((link) => `${link.type ?? '?'} → ${link.url}`).join(', '),\n ),\n measured(\n '<link rel=\"alternate\"> (typed)',\n documentAlternates.length === 0 ? 'none' : documentAlternates.join(', '),\n ),\n ],\n remedy:\n total > 0\n ? undefined\n : 'Declare the machine representation: `Link: <…>; rel=\"alternate\"; type=\"text/markdown\"` or a `<link rel=\"alternate\">` in the HTML. An endpoint an agent cannot find is an endpoint that does not exist.',\n }\n}\n\nfunction checkVaryAccept(context: ScoreContext, negotiated: number): CheckOutcome {\n const { agentCapture, browserCapture } = context\n const agentVary = headerTokens(header(agentCapture.headers, 'vary'))\n const browserVary =\n browserCapture === null ? [] : headerTokens(header(browserCapture.headers, 'vary'))\n const declared = agentVary.includes('accept') || browserVary.includes('accept')\n\n const evidence = [\n measured('Vary on the agent response', header(agentCapture.headers, 'vary') ?? 'absent'),\n measured(\n 'Vary on the browser response',\n browserCapture === null\n ? 'no browser capture'\n : (header(browserCapture.headers, 'vary') ?? 'absent'),\n ),\n ]\n\n // Gated on D2.1: `Vary: Accept` on a response that does not vary by Accept is\n // a claim about caching that is not true. Fixture 035 pins it.\n if (negotiated === 0) {\n return {\n earned: 0,\n evidence: [\n ...evidence,\n measured(\n 'Scored',\n 'no — this check is 0 unless a machine representation was served (D2.1)',\n ),\n ],\n }\n }\n\n if (!declared) {\n context.flags.push({\n id: 'vary-missing',\n severity: 'warn',\n basis: 'measured',\n message:\n 'The same URL returns different representations by Accept but does not send `Vary: Accept`. A shared cache can serve the Markdown to a browser, or the HTML to an agent.',\n evidence,\n })\n }\n\n return {\n earned: declared ? SUBPOINTS.varyAccept.full : 0,\n evidence,\n remedy: declared\n ? undefined\n : 'Send `Vary: Accept` on every response from a URL that negotiates on Accept.',\n }\n}\n\n/**\n * The kinds D2.4 compares. Explicitly four, and never description or free text\n * (§3.8): a prose difference between a Markdown summary and an HTML page is a\n * rendering difference, and calling it a substance divergence would be an\n * accusation we cannot support.\n */\nconst PARITY_KINDS: readonly ArsFactKind[] = ['price', 'currency', 'availability', 'title']\n\n/**\n * Two readings of one side's facts: the value it would PUBLISH for each kind\n * (the unqualified observation with the lowest byte offset, ties broken\n * lexicographically — the same choice `mergeFacts` makes for the published fact\n * set), and EVERY unqualified value it stated.\n *\n * Qualified values — ranges, \"from $9\" — never enter either map (§3.11).\n */\ninterface FactView {\n readonly representative: Map<ArsFactKind, string>\n readonly observed: Map<ArsFactKind, Set<string>>\n}\n\nfunction factView(facts: readonly ExtractedFact[]): FactView {\n const best = new Map<ArsFactKind, ExtractedFact>()\n const observed = new Map<ArsFactKind, Set<string>>()\n for (const fact of facts) {\n if (fact.qualified) continue\n const seen = observed.get(fact.kind)\n if (seen === undefined) observed.set(fact.kind, new Set([fact.normalized]))\n else seen.add(fact.normalized)\n\n const current = best.get(fact.kind)\n if (current === undefined) {\n best.set(fact.kind, fact)\n continue\n }\n if (fact.offset < current.offset) best.set(fact.kind, fact)\n else if (fact.offset === current.offset && fact.normalized < current.normalized)\n best.set(fact.kind, fact)\n }\n const representative = new Map<ArsFactKind, string>()\n for (const [kind, fact] of best) representative.set(kind, fact.normalized)\n return { representative, observed }\n}\n\n/**\n * The comparison rule for D2.4 and D5.3, and it is ASYMMETRIC on purpose:\n * **the value the left side would publish must appear somewhere among the values\n * the right side stated.**\n *\n * Both symmetric rules are wrong, and each is wrong in a way that matters:\n *\n * - Requiring the two REPRESENTATIVES to be equal produces false accusations on\n * ordinary pages. `tooling/fixtures/demo-pdp-before.html` names a backordered\n * variant above the line that says the product is in stock; its JSON-LD says\n * `InStock`, and both statements are true. Flagging that as a\n * structured-data divergence would be an accusation the evidence does not\n * support, and ARS reports observations rather than charges (§3.8).\n * - Accepting ANY shared value lets a real divergence hide behind an incidental\n * match: \"Free shipping over $50\" appears in both representations, so a page\n * whose headline price differs would still certify clean.\n *\n * The asymmetric rule catches the second and not the first, which is the\n * conservative direction: a missed divergence costs a merchant nothing, and a\n * false one is published on a scanner page next to their name.\n */\nfunction divergentKinds(\n left: FactView,\n right: FactView,\n kinds: readonly ArsFactKind[],\n): { compared: ArsFactKind[]; divergent: { kind: ArsFactKind; left: string; right: string }[] } {\n const compared: ArsFactKind[] = []\n const divergent: { kind: ArsFactKind; left: string; right: string }[] = []\n for (const kind of kinds) {\n const claim = left.representative.get(kind)\n const stated = right.observed.get(kind)\n if (claim === undefined || stated === undefined || stated.size === 0) continue\n compared.push(kind)\n if (!stated.has(claim)) {\n divergent.push({ kind, left: claim, right: [...stated].sort().join(' | ') })\n }\n }\n return { compared, divergent }\n}\n\nfunction checkSubstanceParity(context: ScoreContext, negotiated: number): CheckOutcome {\n const { agentFacts, browserFacts, browser, evidence: bundle } = context\n\n if (negotiated === 0 || browser === null) {\n return {\n earned: 0,\n evidence: [\n heuristic(\n 'Comparable',\n negotiated === 0\n ? 'no — there is one representation, so there is nothing to compare (this is the designed 84-point ceiling for a page with no content negotiation)'\n : 'no — no browser-control capture in this bundle',\n ),\n ],\n }\n }\n\n const agentValues = factView(agentFacts)\n const browserValues = factView(browserFacts)\n const { compared, divergent } = divergentKinds(agentValues, browserValues, PARITY_KINDS)\n\n const evidenceLines = [\n heuristic(\n 'Compared facts',\n compared.length === 0 ? 'none present in both representations' : compared.join(', '),\n ),\n heuristic(\n 'Values',\n divergent.length === 0\n ? 'agree'\n : divergent\n .map((entry) => `${entry.kind}: agent ${entry.left} / HTML ${entry.right}`)\n .join('; '),\n ),\n ]\n\n if (compared.length === 0) {\n return {\n earned: 0,\n evidence: [\n ...evidenceLines,\n heuristic(\n 'Scored',\n 'no — a comparison needs at least one comparable fact in both representations',\n ),\n ],\n remedy:\n 'State the same core facts in both representations. ARS could not compare them, so it could not award the parity points.',\n }\n }\n\n if (divergent.length === 0)\n return { earned: SUBPOINTS.substanceParity.full, evidence: evidenceLines }\n\n // §3.8: divergence must REPRODUCE on a third confirming probe taken ≥30s later\n // before the flag is set. Inventory and price genuinely change between two\n // sequential requests, and a one-shot difference is not evidence of anything.\n const confirm = bundle.probes.parityConfirm\n const confirmCapture = confirm !== null && confirm.result.ok ? confirm.result.capture : null\n const confirmRep = confirmCapture === null ? null : buildRepresentation(confirmCapture)\n if (confirmRep === null) {\n return {\n earned: 0,\n evidence: [\n ...evidenceLines,\n heuristic('Confirming probe', 'absent — divergence observed once and NOT flagged'),\n ],\n remedy:\n 'The two representations reported different values for a core fact. ARS did not flag it, because a single observation cannot distinguish a divergence from an inventory change.',\n }\n }\n\n const confirmFacts = extractFacts(confirmRep, {\n profile: context.profile,\n ruleset: context.ruleset,\n baseUrl: confirmRep.finalUrl,\n origin: bundle.target.origin,\n currencyHint: currencyHintOf(context.structural, context.agent),\n })\n const confirmValues = factView(confirmFacts)\n const reproduced = divergentKinds(\n confirmValues,\n browserValues,\n divergent.map((entry) => entry.kind),\n )\n\n if (reproduced.divergent.length === 0) {\n return {\n earned: SUBPOINTS.substanceParity.full,\n evidence: [\n ...evidenceLines,\n heuristic(\n 'Confirming probe',\n 'the difference did not reproduce — treated as a value that changed between requests',\n ),\n ],\n }\n }\n\n context.flags.push({\n id: 'substance-divergence',\n severity: 'warn',\n basis: 'heuristic',\n message: reproduced.divergent\n .map(\n (entry) =>\n `The agent representation reported ${entry.kind} ${entry.left}; the HTML representation reported ${entry.right} at capture time, on two captures taken apart.`,\n )\n .join(' '),\n evidence: evidenceLines,\n })\n\n return {\n earned: 0,\n evidence: [...evidenceLines, heuristic('Confirming probe', 'the difference reproduced')],\n remedy:\n 'Serve the same values in both representations. ARS reports what each one said; it does not assert which is correct.',\n }\n}\n\n// ---------------------------------------------------------------------------\n// D3 — Fact coverage\n// ---------------------------------------------------------------------------\n\ninterface CoverageMath {\n readonly coreFound: number\n readonly extendedFound: number\n readonly coveragePct: number\n readonly densityPct: number\n readonly factsPerKiB100: number\n}\n\n/** §3.6's fact weighting, verbatim, in quarter-units. */\nfunction coverageMath(context: ScoreContext): CoverageMath {\n const { facts, profile, ruleset, agent } = context\n const units = ruleset.thresholds['fact-coverage.fact-units'] ?? []\n const coreCorroboratedUnit = units[0] ?? 0\n const coreUnit = units[1] ?? 0\n const extendedCorroboratedUnit = units[2] ?? 0\n const extendedUnit = units[3] ?? 0\n const denominatorMultiplier =\n ruleset.thresholds['fact-coverage.core-denominator-multiplier']?.[0] ?? 0\n\n let coreUnits = 0\n let extendedUnits = 0\n let coreFound = 0\n let extendedFound = 0\n for (const fact of facts) {\n if (profile.core.includes(fact.kind)) {\n coreFound++\n coreUnits += fact.corroborated ? coreCorroboratedUnit : coreUnit\n } else if (profile.extended.includes(fact.kind)) {\n extendedFound++\n extendedUnits += fact.corroborated ? extendedCorroboratedUnit : extendedUnit\n }\n }\n\n const denominator = denominatorMultiplier * profile.core.length\n const coveragePct =\n denominator === 0\n ? 0\n : Math.min(100, divRoundHalfUp(100 * (coreUnits + extendedUnits), denominator))\n\n // The `max(1, bytes)` clamp is normative and replaces `max(1, bytes / 1024)`,\n // which let a 200-byte stub top the density band.\n const factsPerKiB100 = idiv(\n (coreFound * 100 + extendedFound * 25) * 1024,\n Math.max(1, agent.bytes),\n )\n const densityPct = atLeast(ruleset.thresholds['fact-coverage.density'], factsPerKiB100)\n\n return { coreFound, extendedFound, coveragePct, densityPct, factsPerKiB100 }\n}\n\nfunction checkCoreFacts(context: ScoreContext, math: CoverageMath): CheckOutcome {\n const weight = weightOf(context.ruleset, 'fact-coverage.core-facts')\n const earned = idiv(weight * math.coveragePct * math.densityPct + 5000, 10000)\n const missing = context.profile.core.filter(\n (kind) => !context.facts.some((fact) => fact.kind === kind),\n )\n\n return {\n earned,\n evidence: [\n heuristic(\n 'Core facts found',\n `${math.coreFound}/${context.profile.core.length}${missing.length === 0 ? '' : ` — missing ${missing.join(', ')}`}`,\n ),\n heuristic('Extended facts found', `${math.extendedFound}/${context.profile.extended.length}`),\n heuristic('Coverage', `${math.coveragePct}%`),\n heuristic(\n 'Density band',\n `${math.densityPct}% (${math.factsPerKiB100} hundredths of a fact per KiB)`,\n ),\n measured('Bytes the agent received', String(context.agent.bytes)),\n ],\n remedy:\n missing.length === 0\n ? undefined\n : `State ${missing.join(', ')} in the representation the agent receives. A fact only the HTML carries is a fact the caller never saw.`,\n }\n}\n\nfunction checkContextCost(context: ScoreContext): CheckOutcome {\n const table = context.ruleset.thresholds['fact-coverage.context-cost']\n const reference = context.profile.byteReference\n const ratio = reference === 0 ? 0 : idiv(100 * context.agent.bytes, reference)\n const earned = atMost(table, ratio)\n const full = atMost(table, 0)\n\n return {\n earned,\n evidence: [\n measured(\n 'Bytes the agent received',\n `${context.agent.bytes}${context.agent.truncated ? ' (truncated at the cap)' : ''}`,\n ),\n measured('Byte reference for this page kind', `${reference} (${context.profile.pageKind})`),\n measured('Ratio', `${ratio}% of the reference`),\n ],\n remedy:\n earned === full\n ? undefined\n : 'Serve a representation sized to the facts. The reference is what a page of this kind reasonably costs, not an absolute budget.',\n }\n}\n\n\n// ---------------------------------------------------------------------------\n// D7 — Evidence density\n// ---------------------------------------------------------------------------\n\n/**\n * WHY THIS DIMENSION EXISTS (ARS 0.2). The controlled work on what an assistant\n * actually lifts into an answer, rather than what it merely cites, finds the\n * effect concentrated in extractable evidence units: quantities, definitions\n * and comparisons carry large influence uplift, while conversational Q&A\n * phrasing carries none. D1-D6 grade whether an agent can REACH and PARSE a\n * page. Nothing before this graded whether, having parsed it, there was\n * anything quotable on it.\n *\n * ALL THREE ARE COUNTS OVER THE AGENT'S OWN COUNTED TEXT. No model, no\n * randomness, no clock. `quantities` and `comparisons` are `measured` because\n * they observe the artifact directly, a token shape and a markup structure;\n * `definitions` is `heuristic` because calling a `label: value` line a\n * definition is a judgement about intent, and the basis field says so.\n */\n\n/** Currency amount, percentage, number carrying a unit, or an ISO date. */\nconst QUANTITY = new RegExp(\n [\n String.raw`[$£€¥]\\s?\\d[\\d,]*(?:\\.\\d+)?`,\n String.raw`\\d[\\d,]*(?:\\.\\d+)?\\s?%`,\n String.raw`\\d[\\d,]*(?:\\.\\d+)?\\s?(?:kg|g|lb|lbs|oz|mm|cm|m|km|mi|in|ft|ml|l|kb|mb|gb|tb|hz|w|kw|v|°c|°f|hours?|hrs?|minutes?|mins?|seconds?|secs?|days?|weeks?|months?|years?)\\b`,\n String.raw`\\d{4}-\\d{2}-\\d{2}`,\n ].join('|'),\n 'giu',\n)\n\n/** `**Label:** value`, `- Label: value`, and `<dt>` rows once tokenized to text. */\nconst DEFINITION_LINE = /^\\s*(?:[-*+]\\s+)?(?:\\*\\*)?[A-Za-z][A-Za-z0-9 /&'()-]{1,40}(?:\\*\\*)?\\s*:\\s*\\S/\n\n/**\n * Block elements that hold ONE labelled fact when a page states them in markup\n * rather than in Markdown. Pinned, like every other table in this standard.\n *\n * WHY THIS SET EXISTS AT ALL. `countedText` joins every text node with a single\n * space and collapses whitespace runs, so an HTML document's counted text is one\n * line — deliberately, because a line model would need a display model and there\n * is no CSS resolution anywhere in this package. Splitting D7.2 on `\\n` would\n * therefore score EVERY HTML page at zero and pay only representations that\n * arrive already line-structured, which in practice means pages behind a\n * Markdown gateway. A check that only the editors' own product can satisfy is\n * exactly the self-serving design this standard must not contain, so D7.2\n * segments an HTML document structurally instead: each counted text node is\n * attributed to its nearest ancestor in this set, and each such element's own\n * text is one candidate line. Innermost wins by construction, so a `<p>` inside\n * an `<li>` is counted once and not twice.\n */\nconst LABELLED_BLOCK_TAGS = new Set(['li', 'dt', 'dd', 'p', 'td', 'th', 'div'])\n\nfunction checkQuantities(context: ScoreContext): CheckOutcome {\n const table = context.ruleset.thresholds['evidence-density.quantities']\n // DISTINCT, normalized on case and inner whitespace: a price stated in a\n // header, a buy box and a footer is one fact said three times, and paying\n // for the repetition would reward exactly the padding this score exists to\n // discourage.\n const seen = new Set<string>()\n for (const match of context.agent.text.matchAll(QUANTITY)) {\n seen.add(match[0].toLowerCase().replace(/\\s+/g, ''))\n }\n const count = seen.size\n const earned = atLeast(table, count)\n const full = atLeast(table, Number.MAX_SAFE_INTEGER)\n\n return {\n earned,\n evidence: [measured('Distinct quantities an answer could quote', `${count}`)],\n remedy:\n earned === full\n ? undefined\n : 'State the numbers a reader would ask for, in text: price, sizes, hours, fees, dates. A quantity an agent can lift is what a cited answer is built from.',\n }\n}\n\n/**\n * The candidate lines of a representation: one per labelled block element when\n * there is a document, and the text's own lines when there is not. Order is\n * document order in both cases, so two runs over one bundle agree.\n */\nfunction labelledSegments(context: ScoreContext): string[] {\n const doc = context.agent.doc\n if (doc === null) return context.agent.text.split('\\n')\n\n // One pass over counted text nodes, each attributed to its nearest ancestor\n // in LABELLED_BLOCK_TAGS. `Map` preserves insertion order, which is the order\n // the first text node of each element appeared.\n const byElement = new Map<number, string[]>()\n for (const node of doc.texts) {\n if (node.excludedBy !== null) continue\n if (node.text.trim().length === 0) continue\n let at = node.parent\n // Bounded by the tokenizer's own depth limit; a cycle cannot hang this.\n for (let hops = 0; at >= 0 && hops <= MAX_ANCESTOR_HOPS; hops += 1) {\n const element = doc.elements[at]\n if (element === undefined) break\n if (LABELLED_BLOCK_TAGS.has(element.tag)) {\n const parts = byElement.get(at)\n if (parts === undefined) byElement.set(at, [node.text])\n else parts.push(node.text)\n break\n }\n at = element.parent\n }\n }\n\n const segments: string[] = []\n for (const parts of byElement.values()) {\n segments.push(parts.join(' ').replace(/\\s+/g, ' ').trim())\n }\n return segments\n}\n\n/** Deep enough for any real document; the tokenizer caps nesting well below it. */\nconst MAX_ANCESTOR_HOPS = 256\n\nfunction checkDefinitions(context: ScoreContext): CheckOutcome {\n const table = context.ruleset.thresholds['evidence-density.definitions']\n let count = 0\n for (const line of labelledSegments(context)) {\n if (DEFINITION_LINE.test(line)) count += 1\n }\n const earned = atLeast(table, count)\n const full = atLeast(table, Number.MAX_SAFE_INTEGER)\n\n return {\n earned,\n evidence: [heuristic('Labelled term and value pairs', `${count}`)],\n remedy:\n earned === full\n ? undefined\n : 'Label your facts. A line that reads \"Returns: 60 days\" is liftable whole; the same fact inside a paragraph has to be inferred.',\n }\n}\n\n/**\n * Comparable ROWS, not tables. A table with one data row states a fact; two or\n * more let an assistant contrast options, which is the shape the absorption\n * work found doing the work. Counted from the tokenized document so it is a\n * structural observation, and from the markdown pipe form when there is no\n * document, so a markdown-only representation is not silently scored zero.\n */\nfunction checkComparisons(context: ScoreContext): CheckOutcome {\n const table = context.ruleset.thresholds['evidence-density.comparisons']\n let rows = 0\n\n const doc = context.agent.doc\n if (doc !== null) {\n // Cells per row, by walking children back to their parent `tr`. The\n // tokenizer records `parent` as an index into `elements`, so this is one\n // pass and no tree is built.\n const cellsByRow = new Map<number, number>()\n for (const element of doc.elements) {\n if (element.tag !== 'td' && element.tag !== 'th') continue\n const row = doc.elements[element.parent]\n if (row === undefined || row.tag !== 'tr') continue\n cellsByRow.set(element.parent, (cellsByRow.get(element.parent) ?? 0) + 1)\n }\n for (const cells of cellsByRow.values()) if (cells >= 2) rows += 1\n // A header row is not a comparison.\n rows = Math.max(0, rows - 1)\n } else {\n let pipeRows = 0\n for (const line of context.agent.text.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed.startsWith('|') || !trimmed.endsWith('|')) continue\n if (/^\\|[\\s:|-]+\\|$/.test(trimmed)) continue // the alignment rule\n if (trimmed.split('|').length - 2 >= 2) pipeRows += 1\n }\n rows = Math.max(0, pipeRows - 1)\n }\n\n const earned = atLeast(table, rows)\n const full = atLeast(table, Number.MAX_SAFE_INTEGER)\n\n return {\n earned,\n evidence: [measured('Comparable rows', `${rows}`)],\n remedy:\n earned === full\n ? undefined\n : 'Put options side by side in a table with a row each. An assistant comparing two things reaches for rows it can line up.',\n }\n}\n\n// ---------------------------------------------------------------------------\n// D4 — Fact position\n// ---------------------------------------------------------------------------\n\nfunction coreOffsets(context: ScoreContext): number[] {\n const offsets: number[] = []\n for (const fact of context.facts)\n if (context.profile.core.includes(fact.kind)) offsets.push(fact.offset)\n return offsets.sort((a, b) => a - b)\n}\n\nfunction checkFirstCoreFactOffset(context: ScoreContext, offsets: readonly number[]): CheckOutcome {\n const first = offsets[0]\n if (first === undefined) {\n return {\n earned: 0,\n evidence: [heuristic('First core fact', 'none found — nothing to position')],\n }\n }\n return {\n earned: atMost(context.ruleset.thresholds['fact-position.first-core-fact-offset'], first),\n evidence: [\n measured('Byte offset of the first core fact', String(first)),\n heuristic(\n 'Which fact',\n context.facts.find((fact) => fact.offset === first)?.kind ?? 'unknown',\n ),\n ],\n remedy:\n first <= 512\n ? undefined\n : 'Move the core facts to the top of the representation. A caller that stops reading early stops before them.',\n }\n}\n\nfunction checkFrontWindow(context: ScoreContext, offsets: readonly number[]): CheckOutcome {\n const windowRule = context.ruleset.thresholds['fact-position.front-window-size'] ?? []\n const floor = windowRule[0] ?? 0\n const divisor = windowRule[1] ?? 1\n const size = Math.max(floor, idiv(context.agent.bytes, divisor))\n\n if (offsets.length === 0) {\n return {\n earned: 0,\n evidence: [\n measured('Front window', `${size} bytes`),\n heuristic('Core facts inside it', 'none found — nothing to position'),\n ],\n }\n }\n\n const inside = offsets.filter((offset) => offset < size).length\n // The denominator is the core facts that are PRESENT, not the profile size:\n // absence is D3.1's job, and charging the same absence twice would make the\n // 100 points non-orthogonal. The evidence prints both numbers so a reader can\n // see which question was asked.\n const pct = idiv(100 * inside, offsets.length)\n\n return {\n earned: atLeast(context.ruleset.thresholds['fact-position.front-window'], pct),\n evidence: [\n measured('Front window', `${size} bytes (max(${floor}, bytes/${divisor}))`),\n heuristic('Core facts inside it', `${inside}/${offsets.length} found (${pct}%)`),\n heuristic('Core facts in this page kind', String(context.profile.core.length)),\n ],\n remedy:\n pct >= 90\n ? undefined\n : 'Front-load the core facts. Everything after the window costs the caller a full read.',\n }\n}\n\n// ---------------------------------------------------------------------------\n// D5 — Structured data\n// ---------------------------------------------------------------------------\n\nfunction checkStructuredDataPresent(context: ScoreContext): CheckOutcome {\n const { structural } = context\n const split = SUBPOINTS.structuredDataPresent\n if (structural === null) {\n return {\n earned: 0,\n evidence: [measured('HTML representation', 'none in this bundle — not evaluated')],\n }\n }\n\n const { blocks, parsed } = structural.jsonLd\n let microdata = 0\n let rdfa = 0\n if (structural.doc !== null) {\n for (const element of structural.doc.elements) {\n if (attr(element, 'itemtype') !== null) microdata++\n if (attr(element, 'typeof') !== null) rdfa++\n }\n }\n\n const jsonLdScore =\n blocks === 0 ? null : parsed === blocks ? split.clean : parsed > 0 ? split.partial : 0\n const otherScore = microdata > 0 || rdfa > 0 ? split.clean : null\n const earned = Math.max(jsonLdScore ?? 0, otherScore ?? 0)\n\n return {\n earned,\n evidence: [\n measured('JSON-LD blocks', `${parsed} of ${blocks} parsed`),\n measured('Microdata itemtype scopes', String(microdata)),\n measured('RDFa typeof scopes', String(rdfa)),\n ],\n remedy:\n earned === split.clean\n ? undefined\n : blocks > parsed\n ? 'One or more JSON-LD blocks did not parse. A block that does not parse is not structured data.'\n : 'Add JSON-LD for this page. It is the one machine representation every consumer already reads.',\n }\n}\n\n/**\n * The JSON-LD node D5.2 scores against: the node whose `@type` decided the page\n * kind, then any node with a recognised type. Scoring the first node in the\n * document would mark a page incomplete because its `BreadcrumbList` has no\n * `offers.price` (§ `nodeForKind` in ./classify).\n */\nfunction scoredNode(context: ScoreContext): JsonLdNode | null {\n const nodes = context.structural?.jsonLd.nodes ?? []\n const forKind = nodeForKind(nodes, context.profile.pageKind)\n if (forKind !== null) return forKind\n for (const node of nodes) if (node.types.some(isRecognisedType)) return node\n return null\n}\n\nfunction checkRequiredProperties(context: ScoreContext): CheckOutcome {\n const split = SUBPOINTS.requiredProperties\n const required = context.ruleset.requiredProperties[context.profile.pageKind] ?? []\n const node = scoredNode(context)\n\n if (node === null) {\n return {\n earned: 0,\n evidence: [\n measured('Recognised schema.org type', 'none'),\n measured('Required properties for this page kind', required.join(', ') || 'none'),\n measured(\n 'Scope',\n 'JSON-LD only in 0.1 — microdata satisfies D5.1 but is not walked for required properties',\n ),\n ],\n remedy:\n 'Declare a schema.org type in JSON-LD. Choosing no type does not avoid this check — an unrecognised page still scores against \"any recognised type present\".',\n }\n }\n\n const satisfied = required.filter((path) => hasPath(node, path))\n const missing = required.filter((path) => !hasPath(node, path))\n const completeness =\n required.length === 0\n ? split.completeness\n : divRoundHalfUp(split.completeness * satisfied.length, required.length)\n\n return {\n earned: split.recognisedType + completeness,\n evidence: [\n measured('Scored node @type', node.types.join(', ')),\n measured(\n 'Required properties',\n `${satisfied.length}/${required.length}${missing.length === 0 ? '' : ` — missing ${missing.join(', ')}`}`,\n ),\n measured('Table', `ruleset.requiredProperties.${context.profile.pageKind}`),\n ],\n remedy:\n missing.length === 0\n ? undefined\n : `Add ${missing.join(', ')} to the ${node.types[0] ?? 'top-level'} node.`,\n }\n}\n\nfunction checkTextAgreement(context: ScoreContext): CheckOutcome {\n const { structuralFacts } = context\n const fromJsonLd = factView(structuralFacts.filter((fact) => fact.source === 'json-ld'))\n const fromPage = factView(structuralFacts.filter((fact) => fact.source !== 'json-ld'))\n const { compared, divergent } = divergentKinds(fromJsonLd, fromPage, PARITY_KINDS)\n\n const evidenceLines = [\n heuristic(\n 'Compared facts',\n compared.length === 0\n ? 'none stated both in structured data and on the page'\n : compared.join(', '),\n ),\n heuristic(\n 'Values',\n divergent.length === 0\n ? 'agree'\n : divergent\n .map((entry) => `${entry.kind}: structured data ${entry.left} / page ${entry.right}`)\n .join('; '),\n ),\n ]\n\n if (compared.length === 0) {\n return {\n earned: 0,\n evidence: [...evidenceLines, heuristic('Scored', 'no — nothing was comparable')],\n remedy:\n 'State the core facts in both the structured data and the visible page, so the two can be checked against each other.',\n }\n }\n\n if (divergent.length > 0) {\n context.flags.push({\n id: 'structured-data-divergence',\n severity: 'warn',\n basis: 'heuristic',\n message: divergent\n .map(\n (entry) =>\n `The structured data reported ${entry.kind} ${entry.left}; the visible page reported ${entry.right}.`,\n )\n .join(' '),\n evidence: evidenceLines,\n })\n return {\n earned: 0,\n evidence: evidenceLines,\n remedy:\n 'Generate the structured data from the same source as the rendered page, so the two cannot drift.',\n }\n }\n\n return { earned: SUBPOINTS.textAgreement.full, evidence: evidenceLines }\n}\n\n// ---------------------------------------------------------------------------\n// D6 — Contract & discovery\n// ---------------------------------------------------------------------------\n\nfunction canonicalOf(\n capture: ArsHttpCapture | null,\n representation: ArsRepresentation | null,\n): string | null {\n if (capture !== null) {\n for (const link of parseLinkHeaders(headerAll(capture.headers, 'link'))) {\n if (link.rel.includes('canonical')) return link.url\n }\n }\n if (representation !== null && representation.doc !== null) {\n for (const link of representation.doc.links) {\n if (link.rel.includes('canonical') && link.href !== null) return link.href\n }\n }\n return null\n}\n\nfunction checkCanonical(context: ScoreContext): CheckOutcome {\n const split = SUBPOINTS.canonical\n const htmlCanonical =\n canonicalOf(context.browserCapture, context.browser) ??\n canonicalOf(context.agentCapture, context.agent)\n const agentCanonical = canonicalOf(context.agentCapture, context.agent)\n\n const present = htmlCanonical !== null\n const absolute = htmlCanonical !== null && /^https?:\\/\\//i.test(htmlCanonical)\n const consistent =\n htmlCanonical !== null && agentCanonical !== null && agentCanonical === htmlCanonical\n\n if (htmlCanonical !== null && agentCanonical !== null && agentCanonical !== htmlCanonical) {\n context.flags.push({\n id: 'canonical-mismatch',\n severity: 'warn',\n basis: 'measured',\n message: `The two representations of this URL declare different canonicals: ${agentCanonical} and ${htmlCanonical}.`,\n evidence: [\n measured('Agent probe canonical', agentCanonical),\n measured('HTML canonical', htmlCanonical),\n ],\n })\n }\n\n return {\n earned:\n (present ? split.present : 0) +\n (absolute ? split.absolute : 0) +\n (consistent ? split.consistentAcrossProbes : 0),\n evidence: [\n measured('Canonical (HTML)', htmlCanonical ?? 'absent'),\n measured('Canonical (agent representation)', agentCanonical ?? 'absent'),\n measured('Absolute', yesNo(absolute)),\n measured('Same across both probes', yesNo(consistent)),\n ],\n remedy: consistent\n ? undefined\n : agentCanonical === null\n ? 'Declare the canonical on the machine representation too — `Link: <https://…>; rel=\"canonical\"`. A representation with no canonical cannot be attributed to a page.'\n : 'Declare one canonical URL and use it in both representations.',\n }\n}\n\nfunction checkCacheValidators(context: ScoreContext): CheckOutcome {\n const split = SUBPOINTS.cacheValidators\n const cacheControl = header(context.agentCapture.headers, 'cache-control')\n const directives = headerTokens(cacheControl)\n const noStore = directives.includes('no-store')\n const maxAge = directives.some((token) => {\n const match = /^(?:max-age|s-maxage)=(\\d{1,10})$/.exec(token)\n return match !== null && Number(match[1]) > 0\n })\n const noCache = directives.includes('no-cache') || directives.includes('must-revalidate')\n const etag = header(context.agentCapture.headers, 'etag')\n const lastModified = header(context.agentCapture.headers, 'last-modified')\n const validator = etag !== null || lastModified !== null\n\n // \"Sane\" is: the response says how long it may be reused, or says to\n // revalidate — and revalidation only means anything with a validator.\n const sane = cacheControl !== null && !noStore && (maxAge || (noCache && validator))\n\n return {\n earned: (sane ? split.saneCacheControl : 0) + (validator ? split.validator : 0),\n evidence: [\n measured('Cache-Control', cacheControl ?? 'absent'),\n measured('ETag', etag ?? 'absent'),\n measured('Last-Modified', lastModified ?? 'absent'),\n ],\n remedy:\n sane && validator\n ? undefined\n : 'Send a `Cache-Control` a cache can act on, plus an `ETag` or `Last-Modified`. Repeat fetches are most of agent traffic.',\n }\n}\n\nfunction bodyOf(probe: ArsProbeRecord | null): string | null {\n if (probe === null || !probe.result.ok) return null\n const capture = probe.result.capture\n if (capture.status < 200 || capture.status >= 300) return null\n return typeof capture.body === 'string' ? capture.body : null\n}\n\nconst MARKDOWN_LINK = /\\[[^\\]\\n]{1,200}\\]\\(([^)\\s]{1,500})\\)/g\n\nfunction checkLlmsTxt(context: ScoreContext): CheckOutcome {\n const split = SUBPOINTS.llmsTxt\n const body = bodyOf(context.evidence.probes.llmsTxt)\n if (body === null || body.trim().length === 0) {\n return {\n earned: 0,\n evidence: [measured('/llms.txt', body === null ? 'absent or non-2xx' : 'empty')],\n remedy:\n 'Publish /llms.txt: an H1 title, a short summary, and links to the pages that matter. It is worth 1 point of 100, deliberately.',\n }\n }\n // The llms.txt convention: an H1 title, then Markdown links. Both halves are\n // checked because a file with a title and no links tells an agent nothing.\n const hasTitle = /^#\\s+\\S/m.test(body)\n MARKDOWN_LINK.lastIndex = 0\n const hasLinks = MARKDOWN_LINK.test(body)\n const specShaped = hasTitle && hasLinks\n\n return {\n earned: specShaped ? split.specShaped : split.present,\n evidence: [\n measured('/llms.txt', `${body.length} characters`),\n measured('H1 title', yesNo(hasTitle)),\n measured('Markdown links', yesNo(hasLinks)),\n ],\n remedy: specShaped ? undefined : 'Give /llms.txt an H1 title and at least one Markdown link.',\n }\n}\n\nfunction checkSitemap(context: ScoreContext): CheckOutcome {\n return {\n earned: context.policy.sitemapDeclared ? SUBPOINTS.sitemap.full : 0,\n evidence: [\n measured('Sitemap: in robots.txt', yesNo(context.policy.sitemapDeclared)),\n measured(\n 'Sitemaps declared',\n context.robots === null ? 'n/a' : context.robots.sitemaps.join(', ') || 'none',\n ),\n ],\n remedy: context.policy.sitemapDeclared ? undefined : 'Declare `Sitemap:` in robots.txt.',\n }\n}\n\n/**\n * Media types and URL shapes that count as a declared machine endpoint (§3.4\n * D6.5: UCP/ACP/MCP/OpenAPI/GraphQL/RSS/Atom/ICS/JSON feed).\n *\n * Credit comes from DECLARATION. ARS probes `/robots.txt`, `/llms.txt` and\n * `/.well-known/ucp` and nothing else — no guessing at `/sitemap.xml`, `/mcp` or\n * `/acp` — because an endpoint an agent cannot find is an endpoint that does not\n * exist. The three probed paths are the disclosed exception: they are published\n * conventions with published locations.\n */\nconst ENDPOINT_TYPES: readonly string[] = [\n 'application/rss+xml',\n 'application/atom+xml',\n 'application/feed+json',\n 'application/json',\n 'application/ld+json',\n 'application/vnd.api+json',\n 'application/schema+json',\n 'application/graphql',\n 'application/openapi+json',\n 'application/yaml',\n 'text/calendar',\n]\nconst ENDPOINT_RELS: readonly string[] = [\n 'service-desc',\n 'service-doc',\n 'api',\n 'describedby',\n 'ucp',\n 'mcp',\n]\nconst ENDPOINT_PATH_MARKERS: readonly string[] = [\n '/api',\n '/mcp',\n '/graphql',\n '/openapi',\n '/.well-known/',\n '.json',\n '.ics',\n '.rss',\n '.atom',\n]\n\nfunction checkMachineEndpoint(context: ScoreContext): CheckOutcome {\n const declarations: string[] = []\n\n const links = parseLinkHeaders([\n ...headerAll(context.agentCapture.headers, 'link'),\n ...(context.browserCapture === null ? [] : headerAll(context.browserCapture.headers, 'link')),\n ])\n for (const link of links) {\n if (link.rel.some((rel) => ENDPOINT_RELS.includes(rel)))\n declarations.push(`Link rel=${link.rel.join(' ')} → ${link.url}`)\n else if (link.type !== null && ENDPOINT_TYPES.includes(link.type))\n declarations.push(`Link type=${link.type} → ${link.url}`)\n }\n\n if (context.structural !== null && context.structural.doc !== null) {\n for (const link of context.structural.doc.links) {\n if (link.href === null) continue\n if (link.rel.some((rel) => ENDPOINT_RELS.includes(rel)))\n declarations.push(`<link rel=\"${link.rel.join(' ')}\"> → ${link.href}`)\n else if (link.type !== null && ENDPOINT_TYPES.includes(link.type))\n declarations.push(`<link type=\"${link.type}\"> → ${link.href}`)\n }\n }\n\n const llms = bodyOf(context.evidence.probes.llmsTxt)\n if (llms !== null) {\n MARKDOWN_LINK.lastIndex = 0\n let match: RegExpExecArray | null\n while ((match = MARKDOWN_LINK.exec(llms)) !== null) {\n const url = (match[1] ?? '').toLowerCase()\n if (ENDPOINT_PATH_MARKERS.some((marker) => url.includes(marker)))\n declarations.push(`llms.txt → ${match?.[1] ?? url}`)\n }\n }\n\n const ucp = bodyOf(context.evidence.probes.wellKnownUcp)\n if (ucp !== null && ucp.trim().length > 0) declarations.push('/.well-known/ucp')\n\n return {\n earned: declarations.length > 0 ? SUBPOINTS.machineEndpoint.full : 0,\n evidence: [\n measured(\n 'Declared machine endpoints',\n declarations.length === 0 ? 'none' : declarations.join('; '),\n ),\n measured('Probed paths', '/robots.txt, /llms.txt, /.well-known/ucp — ARS probes no others'),\n ],\n remedy:\n declarations.length > 0\n ? undefined\n : 'Declare one machine endpoint — a feed, an OpenAPI document, /.well-known/ucp — with a `Link` header or a `<link>`. ARS does not guess at paths.',\n }\n}\n\n// ---------------------------------------------------------------------------\n// Assembly\n// ---------------------------------------------------------------------------\n\nfunction weightOf(ruleset: ArsRuleset, id: ArsCheckId): number {\n return ruleset.weights[id] ?? 0\n}\n\nfunction buildCheck(ruleset: ArsRuleset, id: ArsCheckId, outcome: CheckOutcome): ArsCheck {\n const meta = CHECK_META[id]\n const weight = weightOf(ruleset, id)\n // Structural guarantee: `earned` is an integer in `[0, weight]`. Every branch\n // above already produces one; the clamp is what makes it impossible for a\n // future check to publish a number outside its own weight. Fixture 052 asserts\n // the property over the whole corpus.\n const earned = Math.max(0, Math.min(weight, outcome.earned))\n const check: ArsCheck = {\n id,\n label: meta.label,\n basis: meta.basis,\n weight,\n earned,\n evidence: outcome.evidence,\n }\n return outcome.remedy === undefined || earned === weight\n ? check\n : { ...check, remedy: outcome.remedy }\n}\n\n/**\n * Publication order. HAND-MAINTAINED AND THEREFORE DANGEROUS: a dimension\n * missing here is silently dropped from `dimensions`, and its checks' points\n * vanish from the total. ARS 0.2 shipped D7 without it for one commit and the\n * corpus re-scored against a maximum of 92. `score.test.ts` now asserts this\n * list covers `DIMENSION_META` exactly.\n */\nconst DIMENSION_ORDER: readonly ArsDimensionId[] = [\n 'retrievability',\n 'machine-representation',\n 'fact-coverage',\n 'fact-position',\n 'structured-data',\n 'contract-discovery',\n 'evidence-density',\n]\n\nfunction buildDimensions(checks: readonly ArsCheck[]): ArsDimension[] {\n return DIMENSION_ORDER.map((id) => {\n const own = checks.filter((check) => CHECK_META[check.id].dimension === id)\n return {\n id,\n label: DIMENSION_META[id].label,\n weight: DIMENSION_META[id].weight,\n earned: own.reduce((sum, check) => sum + check.earned, 0),\n basis: own.some((check) => check.basis === 'heuristic')\n ? ('heuristic' as ArsBasis)\n : ('measured' as ArsBasis),\n checks: own,\n }\n })\n}\n\n/** Pinned flag order, so two runs over the same evidence emit the same array. */\nconst FLAG_ORDER: readonly ArsFlagId[] = [\n 'substance-divergence',\n 'structured-data-divergence',\n 'robots-contradiction',\n 'paywalled',\n 'render-dependent',\n 'scanner-blocked',\n 'training-opt-out',\n 'assistant-opt-out',\n 'vary-missing',\n 'canonical-mismatch',\n 'body-truncated',\n 'vantage-variance',\n]\n\nfunction sortFlags(flags: readonly ArsFlag[]): ArsFlag[] {\n return [...flags].sort((a, b) => FLAG_ORDER.indexOf(a.id) - FLAG_ORDER.indexOf(b.id))\n}\n\n/** The band a score falls in. Bands headline; the integer is secondary (§3.6). */\nexport function bandFor(score: number, ruleset: ArsRuleset = DEFAULT_RULESET): ArsBand | null {\n for (const band of ruleset.bands) if (score >= band.min && score <= band.max) return band\n return null\n}\n\n// ---------------------------------------------------------------------------\n// Evidence plumbing\n// ---------------------------------------------------------------------------\n\nfunction captureOf(probe: ArsProbeRecord | null): ArsHttpCapture | null {\n return probe !== null && probe.result.ok ? probe.result.capture : null\n}\n\n/**\n * The currency the page prices in, read from structured data and Open Graph.\n * The SAME hint is used for both representations, deliberately: a hint is a\n * property of the page, and letting the two representations resolve `$` to\n * different currencies would manufacture a substance divergence out of nothing.\n */\nfunction currencyHintOf(\n structural: ArsRepresentation | null,\n agent: ArsRepresentation,\n): string | undefined {\n for (const representation of [structural, agent]) {\n if (representation === null) continue\n for (const node of representation.jsonLd.nodes) {\n for (const path of ['offers.priceCurrency', 'priceCurrency']) {\n const raw = readPath(node, path)\n if (raw !== null && /^[A-Za-z]{3}$/.test(raw.trim())) return raw.trim().toUpperCase()\n }\n }\n if (representation.doc === null) continue\n for (const meta of representation.doc.metas) {\n const key = meta.property ?? meta.name\n if (key !== 'og:price:currency' && key !== 'product:price:currency') continue\n const value = meta.content\n if (value !== null && /^[A-Za-z]{3}$/.test(value.trim())) return value.trim().toUpperCase()\n }\n }\n return undefined\n}\n\nfunction pathOf(url: string, fallback: string): string {\n try {\n return new URL(url).pathname\n } catch {\n return fallback\n }\n}\n\n/** robots.txt status and parse, from the probe record alone. */\nfunction readRobots(probe: ArsProbeRecord | null): {\n status: ArsPolicyReport['robotsTxtStatus']\n robots: RobotsFile | null\n} {\n if (probe === null) return { status: 'missing', robots: null }\n if (!probe.result.ok) return { status: 'error', robots: null }\n const capture = probe.result.capture\n if (capture.status >= 500) return { status: 'error', robots: null }\n if (capture.status >= 400) return { status: 'missing', robots: null }\n const body = typeof capture.body === 'string' ? capture.body : null\n if (body === null) return { status: 'missing', robots: null }\n const robots = parseRobots(body)\n const empty = robots.groups.length === 0 && robots.sitemaps.length === 0\n return { status: empty && robots.malformedLines > 0 ? 'unparseable' : 'ok', robots }\n}\n\n/** Declared paywalls only (§3.8). Undeclared soft paywalls need impersonation, which we refuse. */\nfunction detectPaywall(context: {\n structural: ArsRepresentation | null\n agentCapture: ArsHttpCapture\n}): string | null {\n if (context.agentCapture.status === 402) return 'HTTP 402'\n if (header(context.agentCapture.headers, 'www-authenticate') !== null) return 'WWW-Authenticate'\n for (const node of context.structural?.jsonLd.nodes ?? []) {\n const value = node.value['isAccessibleForFree']\n if (value === false || value === 'False' || value === 'false')\n return 'isAccessibleForFree: false'\n }\n return null\n}\n\n// ---------------------------------------------------------------------------\n// Non-grades\n// ---------------------------------------------------------------------------\n\n/**\n * The result shape for the three non-grades (§3.6). `score` is null and there is\n * no letter — an opt-out is a choice and an unscored target is a missing\n * observation, and neither is an F.\n *\n * The six dimensions are still present with their weights, because §3.9 says\n * `dimensions` always has 6 entries summing to 100, but every check reports\n * `earned: 0` with an evidence line naming the reason. A non-grade is a\n * statement that we did not score; publishing sub-scores next to it would be\n * scoring by another name.\n */\nfunction nonGrade(\n evidence: ArsEvidence,\n ruleset: ArsRuleset,\n outcome: ArsOutcome,\n reason: string,\n policy: ArsPolicyReport,\n flags: readonly ArsFlag[],\n): ArsResult {\n const agentCapture = captureOf(evidence.probes.agent)\n const browserCapture = captureOf(evidence.probes.browser)\n const checks = (Object.keys(CHECK_META) as ArsCheckId[]).map((id) =>\n buildCheck(ruleset, id, {\n earned: 0,\n evidence: [{ label: 'Not evaluated', value: reason, basis: CHECK_META[id].basis }],\n }),\n )\n const htmlBytes = browserCapture?.bytes ?? agentCapture?.bytes ?? 0\n const perToken = ruleset.thresholds['cost.approx-bytes-per-token']?.[0] ?? 4\n\n return {\n spec: 'ars',\n specVersion: ARS_SPEC_VERSION,\n rulesetHash: rulesetHash(ruleset),\n corpusHash: ARS_CORPUS_HASH,\n evidenceHash: evidenceHash(evidence),\n vantage: evidence.vantage,\n target: {\n url: evidence.target.url,\n finalUrl: agentCapture?.finalUrl ?? evidence.target.url,\n origin: evidence.target.origin,\n },\n outcome,\n score: null,\n grade: null,\n bandLabel: null,\n pageKind: 'unknown',\n pageKindBasis: 'heuristic',\n pageKindConfidence: 'low',\n factProfile: profileFor('unknown'),\n facts: [],\n dimensions: buildDimensions(checks),\n flags: sortFlags(flags),\n policy,\n cost: {\n htmlBytes,\n negotiatedBytes: null,\n approxHtmlTokens: idiv(htmlBytes, perToken),\n approxNegotiatedTokens: null,\n reductionRatio: null,\n firstCoreFactOffset: null,\n truncated: (agentCapture?.truncated ?? false) || (browserCapture?.truncated ?? false),\n },\n recommendations: [],\n measuredWeight: measuredWeightOf(ruleset),\n heuristicWeight: heuristicWeightOf(ruleset),\n }\n}\n\nfunction measuredWeightOf(ruleset: ArsRuleset): number {\n let total = 0\n for (const id of Object.keys(CHECK_META) as ArsCheckId[]) {\n if (CHECK_META[id].basis === 'measured') total += weightOf(ruleset, id)\n }\n return total\n}\n\nfunction heuristicWeightOf(ruleset: ArsRuleset): number {\n let total = 0\n for (const id of Object.keys(CHECK_META) as ArsCheckId[]) {\n if (CHECK_META[id].basis === 'heuristic') total += weightOf(ruleset, id)\n }\n return total\n}\n\n/** Probe error → the reason ARS publishes. `detail` carries the probe's own word for it. */\nfunction unscoredReasonFor(error: string): { reason: ArsUnscoredReason; detail?: string } {\n switch (error) {\n case 'challenge':\n return { reason: 'blocked-at-edge', detail: 'challenge' }\n case 'non-2xx':\n return { reason: 'non-2xx' }\n case 'too-many-redirects':\n return { reason: 'too-many-redirects' }\n case 'timeout':\n return { reason: 'unreachable', detail: 'timeout' }\n case 'blocked-redirect':\n return { reason: 'unreachable', detail: 'blocked-redirect' }\n case 'policy-rejected':\n return { reason: 'unreachable', detail: 'policy-rejected' }\n default:\n return { reason: 'unreachable' }\n }\n}\n\n// ---------------------------------------------------------------------------\n// score()\n// ---------------------------------------------------------------------------\n\n/**\n * The entire pure surface. No network. No clock. No randomness. No LLM.\n *\n * GATE ORDER, and why it is this order:\n * 1. `robots-disallow-scanner` — a statement about OUR conduct. If we were not\n * allowed to fetch, nothing else about the evidence should be reported.\n * Only `vantage: 'public'` is gated; an owner can consent for their own\n * origin (§3.7), and a merchant scanning their own store getting `unscored`\n * because they block unknown tokens is a product regression dressed as rigour.\n * 2. `robots-unavailable` — a persistent 5xx means we could not learn the policy.\n * 3. `opt-out` — the site's own decision, reported before any failure of ours,\n * because it is a choice and not a failure.\n * 4. Fetch failures, then a bundle with no body, then a truncated body.\n */\nexport function score(evidence: ArsEvidence, ruleset: ArsRuleset = DEFAULT_RULESET): ArsResult {\n const flags: ArsFlag[] = []\n const targetPath = pathOf(evidence.target.url, '/')\n const { status: robotsStatus, robots } = readRobots(evidence.probes.robotsTxt)\n const policy = buildPolicyReport(robots, robotsStatus, ruleset, targetPath)\n\n if (policy.trainingOptOut) {\n flags.push({\n id: 'training-opt-out',\n severity: 'info',\n basis: 'measured',\n message:\n 'This site blocks model-training crawlers while allowing assistant fetches. That is neutral in ARS: it never lowers the score.',\n evidence: [\n measured('Training audience', policy.audiences.training.matchedRule ?? 'disallowed'),\n measured('Effect on this score', 'none'),\n ],\n })\n }\n\n // 1 — we obey our own token, and say so.\n if (evidence.vantage === 'public' && robots !== null) {\n const scannerDecision = decideScannerToken(robots, targetPath)\n if (scannerDecision) {\n flags.push({\n id: 'scanner-blocked',\n severity: 'info',\n basis: 'measured',\n message:\n 'robots.txt disallows the rebilder-ars scanner. We obeyed it and did not score this page.',\n evidence: [measured('Matched rule', scannerDecision)],\n })\n return nonGrade(\n evidence,\n ruleset,\n { kind: 'unscored', reason: 'robots-disallow-scanner' },\n 'robots.txt disallows the rebilder-ars token',\n policy,\n flags,\n )\n }\n }\n\n // 2 — a policy we could not read is not a policy we may assume.\n if (robotsStatus === 'error') {\n return nonGrade(\n evidence,\n ruleset,\n { kind: 'unscored', reason: 'robots-unavailable' },\n 'robots.txt returned a persistent error',\n policy,\n flags,\n )\n }\n\n // 3 — a deliberate, well-formed opt-out. Not a failure, not ranked, no letter.\n if (policy.deliberateOptOut) {\n flags.push({\n id: 'assistant-opt-out',\n severity: 'info',\n basis: 'measured',\n message:\n 'This site names assistant crawlers in robots.txt and disallows them. ARS records the choice and does not grade the page.',\n evidence: [\n measured('Matched group', policy.audiences.assistant.matchedGroup ?? '(named group)'),\n measured('Matched rule', policy.audiences.assistant.matchedRule ?? 'Disallow'),\n ],\n })\n return nonGrade(\n evidence,\n ruleset,\n { kind: 'opt-out', audience: 'assistant' satisfies ArsAudience, wellFormed: true },\n 'the site opted out of assistant crawling',\n policy,\n flags,\n )\n }\n\n // 4 — fetch failures.\n const agentProbe = evidence.probes.agent\n if (!agentProbe.result.ok) {\n const { reason, detail } = unscoredReasonFor(agentProbe.result.error)\n if (reason === 'blocked-at-edge') {\n flags.push({\n id: 'scanner-blocked',\n severity: 'warn',\n basis: 'measured',\n message:\n 'The origin answered the agent probe with a challenge or a block. ARS reports the evidence and does not grade the page.',\n evidence: [measured('Probe error', agentProbe.result.error)],\n })\n }\n const outcome: ArsOutcome =\n detail === undefined ? { kind: 'unscored', reason } : { kind: 'unscored', reason, detail }\n return nonGrade(\n evidence,\n ruleset,\n outcome,\n `the agent probe failed: ${agentProbe.result.error}`,\n policy,\n flags,\n )\n }\n\n const agentCapture = agentProbe.result.capture\n if (agentCapture.status === 403 || agentCapture.status === 401 || agentCapture.status === 429) {\n flags.push({\n id: 'scanner-blocked',\n severity: 'warn',\n basis: 'measured',\n message: `The origin answered the agent probe with HTTP ${agentCapture.status}. ARS reports the evidence and does not grade the page.`,\n evidence: [measured('HTTP status', String(agentCapture.status))],\n })\n return nonGrade(\n evidence,\n ruleset,\n { kind: 'unscored', reason: 'blocked-at-edge', detail: `HTTP ${agentCapture.status}` },\n `the origin answered with HTTP ${agentCapture.status}`,\n policy,\n flags,\n )\n }\n if (agentCapture.status < 200 || agentCapture.status >= 300) {\n return nonGrade(\n evidence,\n ruleset,\n { kind: 'unscored', reason: 'non-2xx', detail: `HTTP ${agentCapture.status}` },\n `the origin answered with HTTP ${agentCapture.status}`,\n policy,\n flags,\n )\n }\n if (agentCapture.redirects.length > ruleset.maxRedirects) {\n return nonGrade(\n evidence,\n ruleset,\n {\n kind: 'unscored',\n reason: 'too-many-redirects',\n detail: `${agentCapture.redirects.length} hops`,\n },\n `the agent path took ${agentCapture.redirects.length} redirect hops`,\n policy,\n flags,\n )\n }\n\n const browserCapture = captureOf(evidence.probes.browser)\n if (agentCapture.truncated || (browserCapture?.truncated ?? false)) {\n flags.push({\n id: 'body-truncated',\n severity: 'warn',\n basis: 'measured',\n message: `A response exceeded the ${ruleset.maxBodyBytes}-byte body cap and was truncated. The fact set and the byte count would both be wrong, so the page is not scored.`,\n evidence: [\n measured('Body cap', `${ruleset.maxBodyBytes} bytes`),\n measured('Bytes read', `≥ ${agentCapture.bytes}`),\n ],\n })\n return nonGrade(\n evidence,\n ruleset,\n { kind: 'unscored', reason: 'truncated-evidence' },\n 'the response exceeded the body cap and was truncated',\n policy,\n flags,\n )\n }\n\n const agent = buildRepresentation(agentCapture)\n if (agent === null) {\n return nonGrade(\n evidence,\n ruleset,\n {\n kind: 'unscored',\n reason: 'evidence-incomplete',\n detail: 'the bundle carries no response body',\n },\n 'the evidence bundle carries hashes but no body, so it cannot be re-scored',\n policy,\n flags,\n )\n }\n const browser = browserCapture === null ? null : buildRepresentation(browserCapture)\n const structural =\n browser !== null && browser.doc !== null ? browser : agent.doc !== null ? agent : browser\n\n // ── classification (pass 1) ──────────────────────────────────────────────\n const classification = classify(pass1Signals(structural ?? agent, evidence.target.url))\n const profile = profileFor(classification.pageKind)\n\n // ── extraction (pass 2) ──────────────────────────────────────────────────\n const currencyHint = currencyHintOf(structural, agent)\n const extractContext = {\n profile,\n ruleset,\n baseUrl: agentCapture.finalUrl,\n origin: evidence.target.origin,\n currencyHint,\n }\n const agentFacts = extractFacts(agent, extractContext)\n const browserFacts =\n browser === null || browser === agent\n ? []\n : extractFacts(browser, { ...extractContext, baseUrl: browser.finalUrl })\n const structuralFacts =\n structural === agent ? agentFacts : structural === browser ? browserFacts : []\n const facts = mergeFacts(agentFacts, structuralFacts)\n\n const context: ScoreContext = {\n evidence,\n ruleset,\n agentCapture,\n browserCapture,\n agent,\n browser,\n structural,\n classification,\n profile,\n facts,\n agentFacts,\n browserFacts,\n structuralFacts,\n policy,\n robots,\n flags,\n }\n\n const paywall = detectPaywall(context)\n if (paywall !== null) {\n flags.push({\n id: 'paywalled',\n severity: 'info',\n basis: 'measured',\n message: `This page declares a paywall (${paywall}). ARS scores the portion it was served and does not attempt to reach the gated part.`,\n evidence: [measured('Paywall signal', paywall)],\n })\n }\n\n // ── the 22 checks ────────────────────────────────────────────────────────\n const math = coverageMath(context)\n const offsets = coreOffsets(context)\n const negotiated = checkNegotiatedResponse(context)\n\n const checks: ArsCheck[] = [\n buildCheck(ruleset, 'retrievability.reachable', checkReachable(context)),\n buildCheck(ruleset, 'retrievability.robots-policy', checkRobotsPolicy(context)),\n buildCheck(ruleset, 'retrievability.render-independence', checkRenderIndependence(context)),\n buildCheck(ruleset, 'machine-representation.negotiated-response', negotiated),\n buildCheck(\n ruleset,\n 'machine-representation.declared-alternates',\n checkDeclaredAlternates(context),\n ),\n buildCheck(\n ruleset,\n 'machine-representation.vary-accept',\n checkVaryAccept(context, negotiated.earned),\n ),\n buildCheck(\n ruleset,\n 'machine-representation.substance-parity',\n checkSubstanceParity(context, negotiated.earned),\n ),\n buildCheck(ruleset, 'fact-coverage.core-facts', checkCoreFacts(context, math)),\n buildCheck(ruleset, 'fact-coverage.context-cost', checkContextCost(context)),\n buildCheck(\n ruleset,\n 'fact-position.first-core-fact-offset',\n checkFirstCoreFactOffset(context, offsets),\n ),\n buildCheck(ruleset, 'fact-position.front-window', checkFrontWindow(context, offsets)),\n buildCheck(ruleset, 'structured-data.present', checkStructuredDataPresent(context)),\n buildCheck(ruleset, 'structured-data.required-properties', checkRequiredProperties(context)),\n buildCheck(ruleset, 'structured-data.text-agreement', checkTextAgreement(context)),\n buildCheck(ruleset, 'contract-discovery.canonical', checkCanonical(context)),\n buildCheck(ruleset, 'contract-discovery.cache-validators', checkCacheValidators(context)),\n buildCheck(ruleset, 'contract-discovery.llms-txt', checkLlmsTxt(context)),\n buildCheck(ruleset, 'contract-discovery.sitemap', checkSitemap(context)),\n buildCheck(ruleset, 'contract-discovery.machine-endpoint', checkMachineEndpoint(context)),\n buildCheck(ruleset, 'evidence-density.quantities', checkQuantities(context)),\n buildCheck(ruleset, 'evidence-density.definitions', checkDefinitions(context)),\n buildCheck(ruleset, 'evidence-density.comparisons', checkComparisons(context)),\n ]\n\n const dimensions = buildDimensions(checks)\n const total = dimensions.reduce((sum, dimension) => sum + dimension.earned, 0)\n const band = bandFor(total, ruleset)\n const grade: ArsGrade = band?.grade ?? 'F'\n\n const perToken = ruleset.thresholds['cost.approx-bytes-per-token']?.[0] ?? 4\n const htmlBytes = structural?.bytes ?? agent.bytes\n const negotiatedBytes = negotiated.earned > 0 ? agent.bytes : null\n const cost: ArsCostReport = {\n htmlBytes,\n negotiatedBytes,\n approxHtmlTokens: idiv(htmlBytes, perToken),\n approxNegotiatedTokens: negotiatedBytes === null ? null : idiv(negotiatedBytes, perToken),\n // Integer PERCENT of HTML bytes the machine representation eliminates:\n // 94 means \"94% fewer bytes\". §3.9 types this as a number and does not fix\n // its unit; a multiple (`4.2×`) would be a float, and this is the same\n // information with no rounding for two implementations to disagree about.\n reductionRatio:\n negotiatedBytes === null || htmlBytes === 0\n ? null\n : Math.max(0, 100 - idiv(100 * negotiatedBytes, htmlBytes)),\n firstCoreFactOffset: offsets[0] ?? null,\n truncated: agent.truncated || (browser?.truncated ?? false),\n }\n\n const published: ArsFactObservation[] = facts.map((fact) => ({\n kind: fact.kind,\n normalized: fact.normalized,\n source: fact.source,\n offset: fact.offset,\n corroborated: fact.corroborated,\n }))\n\n return {\n spec: 'ars',\n specVersion: ARS_SPEC_VERSION,\n rulesetHash: rulesetHash(ruleset),\n corpusHash: ARS_CORPUS_HASH,\n evidenceHash: evidenceHash(evidence),\n vantage: evidence.vantage,\n target: {\n url: evidence.target.url,\n finalUrl: agentCapture.finalUrl,\n origin: evidence.target.origin,\n },\n outcome: { kind: 'scored', grade, score: total },\n score: total,\n grade,\n bandLabel: band?.label ?? null,\n pageKind: classification.pageKind,\n pageKindBasis: 'heuristic',\n pageKindConfidence: classification.confidence,\n factProfile: profile,\n facts: published,\n dimensions,\n flags: sortFlags(flags),\n policy,\n cost,\n recommendations: recommend({ dimensions, score: total }),\n measuredWeight: measuredWeightOf(ruleset),\n heuristicWeight: heuristicWeightOf(ruleset),\n }\n}\n\n/**\n * The product token the probe sends (§3.3). This is the ONLY place in the scorer\n * where our own identity is an input to a decision, and the decision it drives is\n * to score nothing.\n */\nconst SCANNER_TOKEN = 'rebilder-ars'\n\n/**\n * Does robots.txt disallow the ARS scanner itself? Returns the matched rule when\n * it does, so the result can print the line rather than assert a verdict.\n *\n * Only a group that NAMES `rebilder-ars` counts. A blanket `User-agent: *`\n * disallow is not a decision about us: it is the accidental case (§3.7), which is\n * scored with `robots-contradiction`, not silently exempted. Rule selection is\n * RFC 9309 longest-match with ties to Allow, via `./extract`'s `pathMatches` —\n * the same matcher `decideRobots` uses, so the scanner gate and the audience\n * decision can never disagree about what a pattern means.\n */\nfunction decideScannerToken(robots: RobotsFile, path: string): string | null {\n for (const group of robots.groups) {\n if (!group.agents.some((agent) => agent === SCANNER_TOKEN)) continue\n let best: { field: 'allow' | 'disallow'; value: string } | null = null\n for (const value of group.allow) {\n if (!pathMatches(value, path)) continue\n if (best === null || value.length > best.value.length) best = { field: 'allow', value }\n }\n for (const value of group.disallow) {\n if (!pathMatches(value, path)) continue\n if (best === null || value.length > best.value.length) best = { field: 'disallow', value }\n }\n if (best !== null && best.field === 'disallow') {\n return `User-agent: ${SCANNER_TOKEN} / Disallow: ${best.value}`\n }\n }\n return null\n}\n","/**\n * The two request identities the standard is defined in terms of, in a leaf\n * module so a browser can import them without pulling in the Node probe.\n *\n * D2.4 IS THE REASON THESE ARE NORMATIVE. It compares what an origin serves an\n * agent against what it serves a browser, and the comparison is only meaningful\n * because the two requests differ in exactly one header. A probe that invents\n * its own `Accept` strings is measuring a different thing and reporting it under\n * the same name — which is worse than not measuring it, because the number still\n * looks like an ARS number.\n */\nexport const AGENT_ACCEPT = 'text/markdown;q=1.0, text/html;q=0.8, text/plain;q=0.5, */*;q=0.1'\nexport const BROWSER_ACCEPT = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'\nexport const ASSET_ACCEPT = 'text/plain,*/*;q=0.5'\n","/**\n * robots-policy.ts — the refusal token and the one function that decides\n * whether a site has refused us.\n *\n * WHY THIS IS ITS OWN MODULE RATHER THAN A PRIVATE FUNCTION IN `./probe`.\n *\n * There is now more than one probe. The Node probe fetches over the network; a\n * browser extension probes from inside a page the user is already looking at,\n * and cannot import `./probe` at all (that module carries a connection limiter\n * and DNS-level SSRF guards that have no meaning and no implementation in a\n * browser). Both must answer \"has this origin refused us?\" identically, because\n * a refusal honoured by one scanner and ignored by another is not a policy, it\n * is a coin flip — and the one being ignored is always the one a site operator\n * actually wrote down.\n *\n * So the decision lives here, at the bottom of the import graph, beside the\n * token it matches on. Pure, no clock, no network, safe under this package's\n * purity rule (`eslint.config.mjs`) and therefore usable from any runtime.\n */\nimport { parseRobots, pathMatches } from './extract'\n\n/**\n * The robots.txt token this scanner answers to. Matched case-insensitively.\n *\n * IT IS NOT VERSIONED, DELIBERATELY. A site that disallowed us under ARS 0.1 is\n * still refusing us under 0.2. Versioning the refusal token would let a spec\n * bump quietly re-open sites that already said no.\n */\nexport const ARS_ROBOTS_TOKEN = 'rebilder-ars'\n\n/**\n * Has this origin refused this path, by name? Returns the matching rule as a\n * human-readable string, or `null` when it has not.\n *\n * ONLY A GROUP THAT NAMES THE TOKEN COUNTS. A blanket `User-agent: *` disallow\n * is not a decision about us — it is the accidental case, which §3.7 scores with\n * a `robots-contradiction` flag rather than treating as consent or as refusal.\n * Reading a generic bot block as a refusal would also make the honest thing\n * (asking first) indistinguishable from the useless thing (refusing to look at\n * most of the web), and a scanner nobody can run is not a safer scanner.\n *\n * Rule selection uses `pathMatches`, the same matcher the scorer uses, so the\n * fetch gate and the published audience decision can never disagree about what\n * a pattern means. Longest match wins, `allow` beating `disallow` at equal\n * length by virtue of being tested first.\n */\nexport function robotsDisallowsScanner(robotsBody: string, path: string): string | null {\n const robots = parseRobots(robotsBody)\n for (const group of robots.groups) {\n if (!group.agents.some((agent) => agent.toLowerCase() === ARS_ROBOTS_TOKEN)) continue\n let best: { field: 'allow' | 'disallow'; value: string } | null = null\n for (const value of group.allow) {\n if (!pathMatches(value, path)) continue\n if (best === null || value.length > best.value.length) best = { field: 'allow', value }\n }\n for (const value of group.disallow) {\n if (!pathMatches(value, path)) continue\n if (best === null || value.length > best.value.length) best = { field: 'disallow', value }\n }\n if (best !== null && best.field === 'disallow') {\n return `User-agent: ${ARS_ROBOTS_TOKEN} / Disallow: ${best.value}`\n }\n }\n return null\n}\n"]}