#!/usr/bin/env python3 """Validate every entry in entries/*.yaml. Usage: python3 scripts/validate.py [ENTRIES_DIR] Exits with status 1 and prints one line per problem when any entry is invalid. The site build runs this before it publishes anything, so a bad entry never reaches the website. Drafts are checked too, with looser rules for the fields that only matter once an entry is published (see VERIFIED_ONLY below). """ import datetime as dt import pathlib import re import sys import yaml TIERS = {"none", "easy", "mail", "no-opt-out", "unverified"} KINDS = {"deposit", "credit-card", "brokerage", "vehicle", "phone", "app", "other"} STATUSES = {"draft", "verified"} METHODS = {"mail", "email", "online", "phone"} DEADLINE_TYPES = {"received", "postmarked", "days-after-opening"} SOURCE_KINDS = {"web", "email"} UNVERIFIED_REASONS = {"blocked", "sign-in", "not-public", "unreadable", "unclear"} SLUG = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*$") SHA256 = re.compile(r"^[0-9a-f]{64}$") REQUIRED_KEYS = [ "id", "institution", "product", "kind", "status", "tier", "arbitration", "class_action_waiver", "quotes", "sources", "last_verified", ] def is_date(value): return isinstance(value, dt.date) and not isinstance(value, dt.datetime) def check_entry(path, entry): """Return a list of problems with one entry. An empty list means valid.""" problems = [] def bad(message): problems.append(f"{path.name}: {message}") if not isinstance(entry, dict): bad("the file must contain a YAML mapping") return problems for key in REQUIRED_KEYS: if key not in entry: bad(f"missing `{key}`") if problems: return problems if entry["id"] != path.stem: bad(f"`id` is {entry['id']!r} but the file is named {path.name}") if not SLUG.match(str(entry["id"])): bad("`id` must be lowercase words joined by hyphens") for key in ("institution", "product"): if not isinstance(entry[key], str) or not entry[key].strip(): bad(f"`{key}` must be non-empty text") if entry["kind"] not in KINDS: bad(f"`kind` must be one of {sorted(KINDS)}") if entry["status"] not in STATUSES: bad(f"`status` must be one of {sorted(STATUSES)}") if entry["tier"] not in TIERS: bad(f"`tier` must be one of {sorted(TIERS)}") if entry.get("summary") is not None and (not isinstance(entry["summary"], str) or len(entry["summary"]) > 70): bad("`summary` must be one short line of text (70 characters at most)") for key in ("arbitration", "class_action_waiver"): if entry[key] not in (True, False, None): bad(f"`{key}` must be true, false or null (unknown)") verified = entry["status"] == "verified" # Dates if not is_date(entry["last_verified"]): bad("`last_verified` must be a date like 2026-11-22") elif entry["last_verified"] > dt.date.today(): bad("`last_verified` is in the future") if entry.get("effective") is not None and not is_date(entry["effective"]): bad("`effective` must be a date or null") # The change log behind each company's feed, written by scripts/log_changes.py. changes = entry.get("changes") if changes is not None: if not isinstance(changes, list) or not changes: bad("`changes` must be a list of {date, summary}, newest first") else: dates = [] for i, change in enumerate(changes): if not isinstance(change, dict) or set(change) != {"date", "summary"}: bad(f"changes[{i}] must have exactly `date` and `summary`") continue if not is_date(change["date"]) or change["date"] > dt.date.today(): bad(f"changes[{i}].date must be a date, not in the future") else: dates.append(change["date"]) if not isinstance(change["summary"], str) or not 10 <= len(change["summary"]) <= 240: bad(f"changes[{i}].summary must be a sentence of 10 to 240 characters") if dates != sorted(dates, reverse=True): bad("`changes` must be newest first") # Sources source_ids = set() sources = entry["sources"] if not isinstance(sources, list) or not sources: bad("`sources` must list at least one source") sources = [] for i, source in enumerate(sources): where = f"sources[{i}]" if not isinstance(source, dict): bad(f"{where} must be a mapping") continue sid = source.get("id") if not sid or not SLUG.match(str(sid)): bad(f"{where} needs an `id` made of lowercase words joined by hyphens") elif sid in source_ids: bad(f"{where} repeats the id {sid!r}") else: source_ids.add(sid) if not source.get("title"): bad(f"{where} needs a `title`") if not is_date(source.get("retrieved")): bad(f"{where} `retrieved` must be a date") kind = source.get("kind", "web") if kind not in SOURCE_KINDS: bad(f"{where} `kind` must be one of {sorted(SOURCE_KINDS)}") elif kind == "email": # A notice the company emailed to customers. It has no public URL, so # the entry says who sent it and the page says it isn't published. if source.get("url"): bad(f"{where} is an email, so it has no `url`") if not source.get("from"): bad(f"{where} needs `from`: who sent the email") else: url = str(source.get("url", "")) if not url.startswith("https://"): bad(f"{where} `url` must start with https://") sha = source.get("sha256") if sha is not None and not SHA256.match(str(sha)): bad(f"{where} `sha256` must be 64 lowercase hex characters") archive = source.get("archive") if archive is not None and not str(archive).startswith("https://"): bad(f"{where} `archive` must start with https://") if source.get("via") is not None: if source["via"] != "archive": bad(f"{where} `via` can only be `archive`") elif not is_date(source.get("archived_on")) or not str(archive or "").startswith("https://web.archive.org/"): bad(f"{where} read from an archive needs `archived_on` and a Wayback `archive` link") if verified and entry.get("tier") != "unverified": # VERIFIED_ONLY; nothing was read to fingerprint if not sha: bad(f"{where} needs a `sha256` before the entry can be verified") # No `archive` link is allowed: the Wayback Machine sometimes can't save a # page. The page then says "Archived copy pending" until a later run adds one. # Quotes: every fact shown on the site points at a verbatim quote. quotes = entry["quotes"] if not isinstance(quotes, dict): bad("`quotes` must be a mapping of fact name to quote") quotes = {} for name, quote in quotes.items(): where = f"quotes.{name}" if not isinstance(quote, dict): bad(f"{where} must be a mapping with `text` and `source`") continue if not isinstance(quote.get("text"), str) or not quote["text"].strip(): bad(f"{where} needs the verbatim `text`") if quote.get("source") not in source_ids: bad(f"{where} `source` must be one of the source ids: {sorted(source_ids)}") # Optional: the specific products the terms appear in, each with its source. covers = entry.get("covers") if covers is not None: if not isinstance(covers, list) or not covers: bad("`covers` must be a list of products") covers = [] for i, item in enumerate(covers): if not isinstance(item, dict) or not item.get("name"): bad(f"covers[{i}] needs a `name`") elif item.get("source") not in source_ids: bad(f"covers[{i}] `source` must be one of the source ids") for name in entry.get("arbitration_mentions") or []: # Quotes that mention arbitration without being an agreement to arbitrate (only # for `none` entries); verify_sources.py removes exactly these before scanning. if entry["tier"] != "none": bad("`arbitration_mentions` is only for entries rated `none`") elif name not in quotes: bad(f"`arbitration_mentions` names quotes.{name}, which doesn't exist") elif "arbitrat" not in _quote(quotes, name): bad(f"quotes.{name} is listed in `arbitration_mentions` but doesn't mention arbitration") for name in entry.get("summary_cites") or []: if name not in quotes: bad(f"`summary_cites` names quotes.{name}, which doesn't exist") def needs_quote(name, reason): if name not in quotes: bad(f"needs a `quotes.{name}` entry because {reason}") tier = entry["tier"] opt_out = entry.get("opt_out") if tier == "unverified": if entry["arbitration"] is not None: bad("an `unverified` entry must have `arbitration: null`") if entry.get("unverified_reason") not in UNVERIFIED_REASONS: bad(f"an `unverified` entry needs `unverified_reason`, one of {sorted(UNVERIFIED_REASONS)}") elif "unverified_reason" in entry: bad("`unverified_reason` is only for entries rated `unverified`") else: needs_quote("arbitration", f"the tier is {tier!r}") if entry["class_action_waiver"] is True: needs_quote("class_action_waiver", "`class_action_waiver` is true") if entry.get("effective") is not None: needs_quote("effective", "`effective` is set") if "effective" in quotes and is_date(entry["effective"]): text = _quote(quotes, "effective") if not any(form in text for form in date_forms(entry["effective"])): bad(f"the effective date {entry['effective']} doesn't appear in quotes.effective") if tier == "none": if entry["arbitration"] is not False: bad("tier `none` requires `arbitration: false`") if tier in ("easy", "mail", "no-opt-out") and entry["arbitration"] is not True: bad(f"tier {tier!r} requires `arbitration: true`") if tier in ("none", "no-opt-out", "unverified") and opt_out: bad(f"tier {tier!r} must not have an `opt_out` section") if tier in ("easy", "mail"): if not isinstance(opt_out, dict): bad(f"tier {tier!r} needs an `opt_out` section") else: problems.extend(check_opt_out(path, tier, opt_out, quotes)) problems.extend(check_letter(path, opt_out, source_ids)) return problems def check_opt_out(path, tier, opt_out, quotes): problems = [] def bad(message): problems.append(f"{path.name}: {message}") method = opt_out.get("method") if method not in METHODS: bad(f"`opt_out.method` must be one of {sorted(METHODS)}") if tier == "mail" and method != "mail": bad("tier `mail` requires `opt_out.method: mail`") if tier == "easy" and method == "mail": bad("tier `easy` means no letter is needed; use tier `mail`") deadline_type = opt_out.get("deadline_type") if deadline_type not in DEADLINE_TYPES: bad(f"`opt_out.deadline_type` must be one of {sorted(DEADLINE_TYPES)}") elif deadline_type == "days-after-opening": if not isinstance(opt_out.get("window_days"), int) or opt_out["window_days"] <= 0: bad("`days-after-opening` needs a positive whole number in `opt_out.window_days`") if opt_out.get("deadline") is not None: bad("`days-after-opening` must have `opt_out.deadline: null`") starts = opt_out.get("window_starts") if starts is not None and (not isinstance(starts, str) or not starts.strip()): bad("`opt_out.window_starts` must be text, like `receiving the card`") else: if not is_date(opt_out.get("deadline")): bad(f"deadline type {deadline_type!r} needs a date in `opt_out.deadline`") # Optional: a window that applies when it ends later than the date, such as 30 days # from opening an account opened after the change takes effect. days = opt_out.get("window_days") if days is not None and (not isinstance(days, int) or days <= 0): bad("`opt_out.window_days` must be a positive whole number or null") starts = opt_out.get("window_starts") if days and (not isinstance(starts, str) or not starts.strip()): bad("a dated deadline with `window_days` needs `opt_out.window_starts`, like `opening the account`") if "deadline" not in quotes: bad("needs a `quotes.deadline` entry for the opt-out deadline") if "opt_out" not in quotes: bad("needs a `quotes.opt_out` entry saying how to reject") if not isinstance(opt_out.get("applies_to"), str) or not opt_out["applies_to"].strip(): bad("`opt_out.applies_to` must say which accounts a rejection covers") if method == "mail": address = opt_out.get("address") if not isinstance(address, str) or len(address.strip().splitlines()) < 2: bad("`opt_out.address` must be a mailing address of at least two lines") if "address" not in quotes: bad("needs a `quotes.address` entry for the mailing address") elif method == "email": email = opt_out.get("email") if not isinstance(email, str) or "@" not in email: bad("`opt_out.email` must be the address to send the rejection to") if "address" not in quotes: bad("needs a `quotes.address` entry showing the email address") elif method == "online": if not str(opt_out.get("url", "")).startswith("https://"): bad("`opt_out.url` must be the https:// address of the opt-out form") if "address" not in quotes: bad("needs a `quotes.address` entry showing where the form is") elif method == "phone": if not isinstance(opt_out.get("phone"), str) or not opt_out["phone"].strip(): bad("`opt_out.phone` must be the number to call") if "address" not in quotes: bad("needs a `quotes.address` entry showing the phone number") required = opt_out.get("required") if method == "mail" and (not isinstance(required, list) or not required): bad("`opt_out.required` must list what the letter has to include") if required and "required" not in quotes: bad("needs a `quotes.required` entry for what the letter must include") problems.extend(check_consistency(path, opt_out, quotes)) return problems # The letter tool (site) prints only what an entry's `opt_out.letter` says, so each # required item must be covered by a part of the letter. A gap here once meant printed # letters without a VIN or a company's form; these checks make that impossible. LETTER_FIELDS = {"name", "address", "phone", "email", "account", "account_name", "vin", "username", "agreement_date", "ssn"} LETTER_PARTS = {"statement", "title", "signature", "co_owners", "delivery", "envelope", "form"} LETTER_KEYS = {"form", "form_note", "title", "statement", "fields", "vin_optional", "signature", "co_owners", "covers"} def check_letter(path, opt_out, source_ids): problems = [] def bad(message): problems.append(f"{path.name}: {message}") if opt_out.get("method") != "mail": if "letter" in opt_out: bad("`opt_out.letter` is only for mail opt-outs") return problems letter = opt_out.get("letter") required = opt_out.get("required") or [] if not isinstance(letter, dict): bad("a mail opt-out needs `opt_out.letter`: which part of the letter covers each " "required item (`covers`), or `form` when the company's own form is required") return problems for key in set(letter) - LETTER_KEYS: bad(f"`opt_out.letter.{key}` isn't a known key; use {sorted(LETTER_KEYS)}") covers = letter.get("covers") if not isinstance(covers, list) or len(covers) != len(required): bad(f"`opt_out.letter.covers` needs one entry per required item ({len(required)}), in order") return problems fields = letter.get("fields") or [] if letter.get("form"): if letter["form"] not in source_ids: bad(f"`opt_out.letter.form` must be the id of the source with the form, not {letter['form']!r}") if any(c != "form" for c in covers) or fields or letter.get("statement"): bad("with `form`, no letter is made: every `covers` item is `form`, with no fields or statement") return problems if not isinstance(fields, list) or "name" not in fields: bad("`opt_out.letter.fields` must list the letter's fields, starting with `name`") for field in fields: if field not in LETTER_FIELDS: bad(f"unknown letter field {field!r}; use {sorted(LETTER_FIELDS)}") for item, cover in zip(required, covers): for part in str(cover).split("+"): if part in LETTER_FIELDS: if part not in fields: bad(f"{item!r} is covered by {part!r}, which isn't in `opt_out.letter.fields`") elif part not in LETTER_PARTS - {"form"}: bad(f"{item!r}: unknown cover {part!r}") elif part == "statement" and not letter.get("statement"): bad(f"{item!r} is covered by the statement, but `opt_out.letter.statement` is empty") elif part == "title" and not letter.get("title"): bad(f"{item!r} is covered by the title, but `opt_out.letter.title` is empty") elif part == "co_owners" and letter.get("co_owners") is not True: bad(f"{item!r} is covered by `co_owners`, which must then be true") return problems NUMBER_WORDS = {10: "ten", 14: "fourteen", 15: "fifteen", 20: "twenty", 21: "twenty-one", 30: "thirty", 45: "forty-five", 60: "sixty", 90: "ninety", 120: "one hundred twenty", 180: "one hundred eighty"} def _quote(quotes, name): quote = quotes.get(name) text = quote.get("text", "") if isinstance(quote, dict) else "" return re.sub(r"\s+", " ", text).strip().lower() def date_forms(day): """The ways a date is commonly written in agreements.""" return {f"{day:%B} {day.day}, {day.year}".lower(), f"{day:%b} {day.day}, {day.year}".lower(), f"{day.month}/{day.day}/{day.year}", f"{day:%m/%d/%Y}", day.isoformat()} def check_consistency(path, opt_out, quotes): """Every structured field must appear inside the quote it comes from, so a misread address, number or date can't pass just because the quote itself is genuine.""" problems = [] def bad(message): problems.append(f"{path.name}: {message}") where = _quote(quotes, "address") method = opt_out.get("method") if method == "mail" and isinstance(opt_out.get("address"), str): squashed = re.sub(r"[\s,.]+", " ", where) for line in opt_out["address"].strip().splitlines(): line_n = re.sub(r"[\s,.]+", " ", line.strip().lower()).strip() if line_n and line_n not in squashed: bad(f"address line {line.strip()!r} doesn't appear in quotes.address") if method == "email" and isinstance(opt_out.get("email"), str): if opt_out["email"].lower() not in where: bad(f"the email {opt_out['email']!r} doesn't appear in quotes.address") if method == "online" and isinstance(opt_out.get("url"), str): bare = re.sub(r"^https?://(www\.)?", "", opt_out["url"].lower()).rstrip("/") if bare not in where: bad(f"the form address {opt_out['url']!r} doesn't appear in quotes.address") if method == "phone" and isinstance(opt_out.get("phone"), str): number = re.sub(r"\D", "", opt_out["phone"])[-10:] if number not in re.sub(r"\D", "", where): bad(f"the phone number {opt_out['phone']!r} doesn't appear in quotes.address") deadline = " ".join(_quote(quotes, name) for name in quotes if name == "deadline" or name.startswith("deadline_")) if is_date(opt_out.get("deadline")): if not any(form in deadline for form in date_forms(opt_out["deadline"])): bad(f"the deadline {opt_out['deadline']} doesn't appear in quotes.deadline") days = opt_out.get("window_days") if isinstance(days, int): word = NUMBER_WORDS.get(days) # "prior to the 31st day" is a 30-day window, so the next day's ordinal counts too. nxt = days + 1 suffix = "th" if 10 <= nxt % 100 <= 20 else {1: "st", 2: "nd", 3: "rd"}.get(nxt % 10, "th") before_next_day = f"{nxt}{suffix} day" in deadline and ("prior to" in deadline or "before" in deadline) if not re.search(rf"\b{days}\b", deadline) and not (word and word in deadline) and not before_next_day: bad(f"the window of {days} days doesn't appear in quotes.deadline (or a deadline_* quote)") return problems def check_news(path): """news.yaml: a list of headlines, each linking straight to the publisher.""" problems = [] try: items = yaml.safe_load(path.read_text(encoding="utf-8")) or [] except yaml.YAMLError as error: return [f"{path.name}: not valid YAML: {error}"] if not isinstance(items, list): return [f"{path.name}: must be a list of headlines"] for i, item in enumerate(items): where = f"{path.name}[{i}]" if not isinstance(item, dict): problems.append(f"{where}: must be a mapping") continue for key in ("title", "outlet"): if not isinstance(item.get(key), str) or not item[key].strip(): problems.append(f"{where}: needs `{key}`") if not is_date(item.get("date")): problems.append(f"{where}: `date` must be a date like 2026-11-18") url = str(item.get("url", "")) if not url.startswith("https://"): problems.append(f"{where}: `url` must start with https://") elif "news.google.com" in url: problems.append(f"{where}: link to the publisher's page, not to Google News") return problems def main(argv): root = pathlib.Path(__file__).resolve().parent.parent entries_dir = pathlib.Path(argv[1]) if len(argv) > 1 else root / "entries" paths = sorted(entries_dir.glob("*.yaml")) if not paths: print(f"No entries found in {entries_dir}", file=sys.stderr) return 1 problems = [] news = entries_dir.parent / "news.yaml" if news.is_file(): problems.extend(check_news(news)) for path in paths: try: entry = yaml.safe_load(path.read_text(encoding="utf-8")) except yaml.YAMLError as error: problems.append(f"{path.name}: not valid YAML: {error}") continue problems.extend(check_entry(path, entry)) for problem in problems: print(problem, file=sys.stderr) if problems: print(f"{len(problems)} problem(s) in {len(paths)} entr{'y' if len(paths) == 1 else 'ies'}.", file=sys.stderr) return 1 print(f"OK: {len(paths)} entr{'y' if len(paths) == 1 else 'ies'}.") return 0 if __name__ == "__main__": sys.exit(main(sys.argv))