GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / cosmic / tools/explore/verify

Vaccines (part 1)

A Python command-line tool in the verify folder of Cosmic that fetches build graph, metrics, board and games, using SHA-256.

700 lines of Python from cosmic, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1168 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Vaccines render · cosmic / tools/explore/verify/vaccines.py lines 1–700

Vaccines

A Python command-line tool in the verify folder of Cosmic that fetches build graph, metrics, board and games, using SHA-256.

rendercosmic / tools/explore/verify/vaccines.py · lines 1–700 of 1956 · Entry point · pattern handle_startendtag (shared by 2 files)

What it does
It fetches build graph, metrics, board and games. Defines 85 functions or classes, including now, overlay_digest_ok, sha256_file, _leaks, Summary. Uses libraries argparse, collections, colorsys, hashlib, html. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes; uses storage (browser storage, DuckDB or Parquet).
Inputs & outputs
In: JSON file build_graph.json; JSON file keys.json; JSON file .metrics.json; JSON file board.json; JSON file games.json; JSON file identity.json; JSON file cache.json; JSON file findings.json. Out: JSON file findings.json.
Downstream impact
Used directly by 2 files: Review (cosmic); Test Vaccines (cosmic).
What it achieves
It checks build graph (`check_build_graph`), checks board (`check_board`) and checks games (`check_games`). The independent verifier for Explore Code outputs, CVAA-style. It accepts `--minutes`, `--every` and `--report`.
Why it matters
Imported by Review. Checked by Test Vaccines.
Application
cosmic · tools/explore/verify · Python CLI
Uses
argparse, collections, colorsys, hashlib, html, html.parser, io, json
Used by
imported by Review (import), imported by Test Vaccines (import)
Produces
now, overlay_digest_ok, sha256_file, Summary, summarise, Output, vaccine, has_key, candidate_ok, v_first_law, v_religion, v_private
Defines here
now, overlay_digest_ok, sha256_file, _leaks, Summary, __init__, _skip, handle_starttag, handle_startendtag, handle_endtag, handle_data, _read, summarise, Output, __init__, p, by_ext, html_files, json_files, text, summary, summary_abs, json, kinds, site_base, fingerprint, vaccine, deco, has_key, candidate_ok
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/verify/vaccines.py:1-700 · blob 2e40e2a09c2fc5d90fdee1e73de884d95e6b3dea · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process, storage · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
r"""tools/explore/verify/vaccines.py - the independent verifier for Explore Code outputs, CVAA-style.

A vaccine is a named failure mode plus the executable check (its antibody) that makes an output
immune to it (after Ventusltd/cvaa). Each vaccine below carries the five CVAA sections in its
registry entry: Disease, Symptom, Antibody (the function), Dose (when it runs) and Provenance.
An antibody takes an Output and returns a list of finding strings; zero findings = immune.
The runner is fail-closed: an antibody that crashes is a finding, never a skip.

Vaccines (ids are stable; the report uses them):

  V1 first-law       every claim/card shows a key (repo@commit path:lines, blob SHA or file id);
                     anything inferred (duplicate, unreached, near-copy, dead code ...) says CANDIDATE/review
  V2 no-religion     no religious terms in generated text (quoted source code excluded); word list in
                     RELIGIOUS_WORDS or --words FILE (one word per line)
  V3 no-private      no token whose digest matches a non-public repository (Kuiper check_proof.leaks,
                     the guard that does not spell what it guards); HTML, text, JSON and Parquet strings
  V4 hosts           nothing is loaded from an external host except the allow-list
                     (cdn.jsdelivr.net for DuckDB search only); <a href> navigation is not a load
  V5 links           internal href/src targets exist and #anchors resolve to an id/name in the target
  V6 contracts       JSON matches its contract: GRAPH-CONTRACT.md (build_graph), chess/CONTRACT.md
                     (board, games: replayed with python-chess when available), lab overlay contract
                     (lab/common.py), lab metrics (overlay_sha256), visual graph; unknown schemas are
                     checked against any *CONTRACT*.md in the output or tools/explore that names them
  V7 determinism     rebuild twice -> identical bytes where promised (visualise.py; lab overlays by their
                     recorded sha256; chess board/players if present; the whole site with --rebuild-site,
                     identical after masking the wall-clock cut stamp, which build.py does not promise)
  V8 a11y-markup     <html lang>, non-empty <title>, alt on images, accessible names on controls and links
  V9 a11y-contrast   text/background colour pairs in CSS (files, <style>, style="") and the role palette
                     reach 4.5:1
  V11 clean-records  cleaning proposals/manifest (clean/CONTRACT.md): every record has a key and evidence, no record
                     proposes deleting source, categories are in the contract, nothing reachable is set aside
                     without a reason; the manifest partitions the graph
  V10 mobile         Playwright headless Chromium at 390x844 on a sample: no horizontal scroll, tap
                     targets >= 40px (controls and stand-alone links; links inside sentences exempt),
                     zero console errors, no request to a non-allow-listed host

Run:
    python vaccines.py run PATH [PATH ...] [--report R.md] [--rebuild-site SRC] [--no-mobile]
    python vaccines.py watch --minutes 90 --every 10      discover outputs, re-run, update the report
    python vaccines.py list                               print the registry (the five sections)

The verifier never edits what it checks, never publishes, never commits.
"""
import argparse
import collections
import colorsys  # noqa: F401  (kept for palette maths extensions)
import hashlib
import html
import html.parser
import io
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import threading
import time
import traceback
import urllib.parse
from datetime import datetime, timezone

HERE = os.path.dirname(os.path.abspath(__file__))
EXPLORE = os.path.dirname(HERE)
KUIPER_TOOLS = os.environ.get('KUIPER_TOOLS', '/home/claude/kuiper2/tools')
PYLIB = os.environ.get('VACCINE_PYLIB', '/tmp/vk/8/pylib')  # optional python-chess
REPORT = '/tmp/vk/8/REPORT.md'
with open(os.path.abspath(__file__), 'rb') as _fh:
    CODE_VERSION = hashlib.sha256(_fh.read()).hexdigest()[:6]  # a changed antibody invalidates cached verdicts
STATE = '/tmp/vk/8/state'

TEXT_EXT = {'.html', '.htm', '.json', '.txt', '.md', '.xml', '.css', '.js', '.mjs', '.csv', '.tsv', '.svg'}
SKIP_DIRS = {'__pycache__', '.git', 'node_modules', 'shots', 'pylib', 'dl'}
CAP = 60  # findings listed per vaccine per output in the report (the count is always exact)

# ------------------------------------------------------------------ configuration
RELIGIOUS_WORDS = '''god gods goddess goddesses divine divinity holy sacred prayer prayers pray praying worship
scripture scriptures bible biblical quran koran torah talmud gospel gospels vedic vedas veda upanishad upanishads
bhagavad gita mahabharata ramayana purana puranas hindu hinduism christian christianity islam islamic muslim jewish
judaism buddhist buddhism sikh sikhism jesus christ allah buddha krishna shiva vishnu brahma karma dharma mantra
mantras sutra sutras temple temples church churches mosque mosques synagogue heaven heavenly hell soul souls
spiritual blessed blessing blessings miracle miracles prophet prophets angel angels deity deities sermon psalm
psalms pope priest priests monk monks salvation amen hallelujah guru chakra puja yajna rishi rishis brahmin
reincarnation nirvana enlightenment'''.split()

ALLOWED_HOSTS = {
    # host: predicate over the full URL; jsDelivr is allowed for the DuckDB search only.
    'cdn.jsdelivr.net': lambda url: 'duckdb' in url.lower(),
}
LOCAL_HOSTS = {'127.0.0.1', 'localhost', '::1', '0.0.0.0'}

KEY_RX = re.compile(r'[A-Za-z0-9_.-]+@[0-9a-f]{7,40}(?:[: ]+[^\s<>"]+)')       # repo@commit path or repo@commit:path
BLOB_RX = re.compile(r'\bblob[ :]+[0-9a-f]{40}\b|/blob/[0-9a-f]{7,40}/')
FILEID_RX = re.compile(r'\bfile(?: id)?[ #:]?\d+\b|\bfiles?\s*[:=]\s*\[?\d')
CANDIDATE_SIGNAL = re.compile(r'\b(duplicate of|duplicate_of|near[- ]copy|unreached|dead[ -]code|unused (?:file|code|module)|'
                              r'orphan(?:ed)? (?:file|code)|safe to (?:delete|remove)|can be (?:deleted|removed)|'
                              r'should be (?:deleted|removed)|set aside|redundant (?:file|copy|code))\b', re.I)
CANDIDATE_LABEL = re.compile(r'candidate|review', re.I)
NEGATION = re.compile(r'\b(never|not|no)\s+(a\s+)?(reason\s+to\s+)?(delet|remov)', re.I)


def now():
    return datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')


def overlay_digest_ok(path, recorded, o=None, vid='V6'):
    """True if the recorded overlay_sha256 matches the file bytes, or the lab's canonical digest
    (sha256 of json.dumps(obj, sort_keys=True, separators=(',', ':')), lab/common.py digest())."""
    if sha256_file(path) == recorded:
        return True
    try:
        obj = json.load(open(path, encoding='utf-8'))
    except Exception:
        return False
    canon = hashlib.sha256(json.dumps(obj, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
    if canon == recorded and o is not None:
        note = 'overlay_sha256 is the canonical-JSON digest (sorted keys), not the sha256 of the file bytes'
        if note not in o.notes[vid]:
            o.notes[vid].append(note)
    return canon == recorded


def sha256_file(p):
    h = hashlib.sha256()
    with open(p, 'rb') as fh:
        for b in iter(lambda: fh.read(1 << 20), b''):
            h.update(b)
    return h.hexdigest()


def _leaks():
    sys.path.insert(0, KUIPER_TOOLS)
    try:
        from check_proof import leaks  # noqa
        return leaks
    finally:
        sys.path.pop(0)


# ------------------------------------------------------------------ HTML summary (parsed once per file)
VOID = {'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr'}
RAW_SKIP = {'pre', 'code', 'script', 'style', 'textarea', 'svg'}
CARD_CLASSES = {'file', 'card', 'claim', 'piece', 'finding', 'candidate', 'kcard'}
CONTROL_TAGS = {'button', 'select', 'textarea', 'input'}


class Summary(html.parser.HTMLParser):
    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.lang = None
        self.title = None
        self._in_title = False
        self.ids = set()
        self.refs = []          # (tag, attr, value, rel, line)
        self.styles = []        # css text
        self.inline_styles = []  # (line, style)
        self.scripts = []       # executable inline script text
        self.importmaps = []
        self.ldjson = []
        self.text = []          # generated text pieces (outside RAW_SKIP)
        self.stack = []         # [tag, attrs, skip, card_index, name_parts]
        self.cards = []         # dict(label, line, text[], hrefs[])
        self.controls = []      # dict(tag, line, attrs, name_parts)
        self.label_for = set()
        self.imgs = []          # (line, attrs)
        self._script_type = None
        self._buf = None

    def _skip(self):
        return any(s[2] for s in self.stack)

    def handle_starttag(self, tag, attrs):
        a = {k: (v if v is not None else '') for k, v in attrs}
        line = self.getpos()[0]
        if tag == 'html' and self.lang is None:
            self.lang = a.get('lang', '')
        if tag == 'title' and not self._skip():
            self._in_title = True
            self.title = self.title or ''
        for k in ('id',):
            if a.get(k):
                self.ids.add(a[k])
        if tag == 'a' and a.get('name'):
            self.ids.add(a['name'])
        rel = a.get('rel', '').lower()
        for attr in ('href', 'src', 'data', 'action', 'poster'):
            if attr in a and a[attr] is not None:
                self.refs.append((tag, attr, a[attr].strip(), rel, line))
        if 'srcset' in a:
            for part in a['srcset'].split(','):
                u = part.strip().split(' ')[0]
                if u:
                    self.refs.append((tag, 'srcset', u, rel, line))
        if a.get('style'):
            self.inline_styles.append((line, a['style']))
        for k in ('title', 'alt', 'aria-label'):
            if a.get(k) and not self._skip():
                self.text.append(a[k])
        if tag == 'meta' and a.get('name', '').lower() in ('description', 'keywords') and a.get('content'):
            self.text.append(a['content'])
        if tag == 'label' and a.get('for'):
            self.label_for.add(a['for'])
        if tag == 'img':
            self.imgs.append((line, a))
        skip = tag in RAW_SKIP
        if tag == 'script':
            self._script_type = a.get('type', '').lower() if 'src' not in a else 'external'
            self._buf = []
        if tag == 'style':
            self._buf = []
        card = None
        classes = set(a.get('class', '').split())
        if (classes & CARD_CLASSES or 'data-key' in a or 'data-claim' in a or tag == 'article') and tag not in VOID:
            card = len(self.cards)
            ident = a.get('id') or (a.get('class', '').split() or [tag])[0]
            self.cards.append({'label': '%s#%s' % (tag, ident), 'line': line, 'text': [], 'hrefs': [],
                               'data': a.get('data-key', '') + ' ' + a.get('data-file', '')})
        name_parts = []
        role = a.get('role', '')
        is_control = tag in CONTROL_TAGS or role in ('button', 'link', 'checkbox', 'tab', 'switch', 'slider') or tag == 'a'
        if tag == 'input' and a.get('type', 'text').lower() == 'hidden':
            is_control = False
        if tag == 'a' and 'href' not in a and not role:
            is_control = False
        if is_control:
            ctl = {'tag': tag, 'line': line, 'attrs': a, 'name': name_parts,
                   'in_label': any(s[0] == 'label' for s in self.stack)}
            self.controls.append(ctl)
        for s in self.stack:
            if s[3] is not None and tag == 'a' and a.get('href'):
                self.cards[s[3]]['hrefs'].append(a['href'])
            if s[4] is not None and tag == 'img' and a.get('alt'):
                s[4].append(a['alt'])
        if tag in VOID:
            if tag == 'input' and is_control:
                pass
            return
        self.stack.append([tag, a, skip, card, name_parts if is_control else None])

    def handle_startendtag(self, tag, attrs):
        self.handle_starttag(tag, attrs)
        if tag not in VOID and self.stack and self.stack[-1][0] == tag:
            self.stack.pop()

    def handle_endtag(self, tag):
        if tag == 'title':
            self._in_title = False
        if tag == 'script' and self._buf is not None:
            t = ''.join(self._buf)
            st = self._script_type or ''
            if st == 'application/ld+json':
                self.ldjson.append(t)
            elif st == 'importmap':
                self.importmaps.append(t)
            elif st in ('', 'module', 'text/javascript', 'application/javascript'):
                self.scripts.append(t)
            self._buf = None
        if tag == 'style' and self._buf is not None:
            self.styles.append(''.join(self._buf))
            self._buf = None
        if tag in VOID:
            return
        for i in range(len(self.stack) - 1, -1, -1):
            if self.stack[i][0] == tag:
                del self.stack[i:]
                break

    def handle_data(self, data):
        if self._buf is not None:
            self._buf.append(data)
        if self._in_title:
            self.title += data
        skip = self._skip()
        if not skip:
            self.text.append(data)
        for s in self.stack:
            if s[3] is not None and not (s[2] or skip and s[0] != 'pre'):
                pass
        for s in self.stack:
            if s[3] is not None:
                if not skip:
                    self.cards[s[3]]['text'].append(data)
            if s[4] is not None:
                s[4].append(data)


def _read(path):
    with io.open(path, encoding='utf-8', errors='replace') as fh:
        return fh.read()


def summarise(path):
    s = Summary()
    try:
        s.feed(_read(path))
        s.close()
    except Exception as e:  # malformed HTML is a finding elsewhere; keep what was parsed
        s.parse_error = str(e)
    for c in s.cards:
        c['text'] = ' '.join(''.join(c['text']).split())
    s.text = ' '.join(' '.join(s.text).split())
    return s


# ------------------------------------------------------------------ the output under test
class Output:
    def __init__(self, root, name=None, rebuild_site=None, mobile=True, words=None):
        self.root = os.path.abspath(root)
        self.name = name or self.root
        self.rebuild_site = rebuild_site
        self.mobile_enabled = mobile
        self.words = words or RELIGIOUS_WORDS
        self.files = []
        if os.path.isfile(self.root):
            self.files = [os.path.basename(self.root)]
            self.base_dir = os.path.dirname(self.root)
        else:
            self.base_dir = self.root
            for dp, dns, fns in os.walk(self.root):
                dns[:] = sorted(d for d in dns if d not in SKIP_DIRS)
                for fn in sorted(fns):
                    self.files.append(os.path.relpath(os.path.join(dp, fn), self.root))
        self._sum = {}
        self._json = {}
        self.notes = collections.defaultdict(list)   # vaccine -> notes (not findings)
        self.status_override = {}                    # vaccine -> 'N/A' | 'INCONCLUSIVE'

    def p(self, rel):
        return os.path.join(self.base_dir, rel)

    def by_ext(self, *exts):
        return [f for f in self.files if os.path.splitext(f)[1].lower() in exts]

    @property
    def html_files(self):
        return self.by_ext('.html', '.htm')

    @property
    def json_files(self):
        return self.by_ext('.json')

    def text(self, rel):
        return _read(self.p(rel))

    def summary(self, rel):
        if rel not in self._sum:
            self._sum[rel] = summarise(self.p(rel))
        return self._sum[rel]

    def summary_abs(self, absp):
        rel = os.path.relpath(absp, self.base_dir)
        if rel in self._sum or (not rel.startswith('..') and os.path.exists(absp)):
            return self.summary(rel)
        key = '@' + absp
        if key not in self._sum:
            self._sum[key] = summarise(absp)
        return self._sum[key]

    def json(self, rel):
        if rel not in self._json:
            try:
                self._json[rel] = json.load(io.open(self.p(rel), encoding='utf-8'))
            except Exception as e:
                self._json[rel] = e
        return self._json[rel]

    def kinds(self):
        k = set()
        names = {os.path.basename(f) for f in self.files}
        if 'build_graph.json' in names:
            k.add('explore-site')
        if 'keys.json' in names and any(f.endswith('.metrics.json') for f in self.files):
            k.add('lab-overlays')
        if names & {'board.json', 'games.json'}:
            k.add('chess')
        if 'identity.json' in names:
            k.add('identity')
        if self.html_files:
            k.add('html')
        return k

    def site_base(self):
        for f in self.files:
            if os.path.basename(f) == 'build_graph.json':
                g = self.json(f)
                if isinstance(g, dict) and g.get('base'):
                    return g['base']
        return 'https://code.globalgrid2050.com/explore-code/'

    def fingerprint(self):
        h = hashlib.sha256()
        for f in self.files:
            try:
                st = os.stat(self.p(f))
                h.update(('%s %d %d\n' % (f, st.st_size, int(st.st_mtime))).encode())
            except OSError:
                pass
        return h.hexdigest()[:16]


# ------------------------------------------------------------------ registry
VACCINES = []


def vaccine(vid, name, disease, symptom, dose, provenance):
    def deco(fn):
        VACCINES.append({'id': vid, 'name': name, 'disease': disease, 'symptom': symptom, 'dose': dose,
                         'provenance': provenance, 'antibody': fn})
        return fn
    return deco


def has_key(text):
    return bool(KEY_RX.search(text) or BLOB_RX.search(text) or FILEID_RX.search(text))


def candidate_ok(text):
    """True unless the text names an inferred state without saying CANDIDATE/review (negations exempt)."""
    if not CANDIDATE_SIGNAL.search(text):
        return True
    if CANDIDATE_LABEL.search(text):
        return True
    t = NEGATION.sub('', text)
    return not CANDIDATE_SIGNAL.search(t)


# ---- V1
@vaccine('V1', 'first-law',
         'A claim is published without the key that lets anyone recompute it, or an inference is shown as a fact.',
         'A card or finding names a file with no repo@commit path:lines, blob or file id; a "duplicate" or '
         '"unreached" file is presented without CANDIDATE/review.',
         'every build',
         "Kuiper's first law (every claim carries its key); owner rule: candidates are reviewed, never deleted.")
def v_first_law(o):
    out = []
    checked = 0
    for rel in o.html_files:
        s = o.summary(rel)
        for c in s.cards:
            checked += 1
            txt = c['text'] + ' ' + c['data'] + ' ' + ' '.join(c['hrefs'])
            if not has_key(txt):
                out.append('%s:%d %s shows no key (repo@commit path:lines, blob or file id)' % (rel, c['line'], c['label']))
            if not candidate_ok(c['text']):
                m = CANDIDATE_SIGNAL.search(c['text'])
                out.append('%s:%d %s says "%s" without CANDIDATE/review' % (rel, c['line'], c['label'], m.group(0)))
    for rel in o.by_ext('.txt'):
        if not os.path.basename(rel).startswith('llms'):
            continue
        blocks = re.split(r'\n(?=### )', o.text(rel))
        for b in blocks[1:]:
            checked += 1
            if not re.search(r'github\.com/[^/\s]+/[^/\s]+/blob/[0-9a-f]{7,40}/\S+#L\d+', b) and not has_key(b):
                out.append('%s: block "%s" has no Source key' % (rel, b.split('\n', 1)[0][4:80]))
    for rel in o.json_files:
        d = o.json(rel)
        if not isinstance(d, dict):
            continue
        for fld in ('findings',):
            for i, f in enumerate(d.get(fld) or []):
                if not isinstance(f, str):
                    continue
                checked += 1
                if re.search(r'\bfiles? \d+', f) and not KEY_RX.search(f):
                    out.append('%s: findings[%d] names a file without repo@commit:path: %s' % (rel, i, f[:120]))
                if not candidate_ok(f):
                    out.append('%s: findings[%d] states an inference without CANDIDATE/review: %s' % (rel, i, f[:120]))
        if d.get('schema') == 'explore-lab-overlay-v1':
            checked += 1
            if d.get('state') not in ('measurement', 'CANDIDATE'):
                out.append('%s: state %r is neither "measurement" nor "CANDIDATE"' % (rel, d.get('state')))
            if not d.get('key'):
                out.append('%s: overlay has no "key" statement' % rel)
        if d.get('schema') == 'explore-chess-board-v1':
            for p in d.get('pieces') or []:
                checked += 1
                if not p.get('files') and not has_key(json.dumps(p)):
                    out.append('%s: piece %s carries no file ids or key' % (rel, p.get('id')))
        for rec_list in ('records', 'items', 'claims', 'cards'):
            for i, r in enumerate(d.get(rec_list) or []):
                if isinstance(r, dict):
                    checked += 1
                    blob = json.dumps(r)
                    if not (has_key(blob) or any(k in r for k in ('key', 'keys', 'blob', 'file', 'file_id', 'files', 'evidence'))):
                        out.append('%s: %s[%d] has no key/blob/file id' % (rel, rec_list, i))
                    if not candidate_ok(blob):
                        out.append('%s: %s[%d] states an inference without CANDIDATE/review' % (rel, rec_list, i))
    for rel in o.by_ext('.md'):
        for n, line in enumerate(o.text(rel).split('\n'), 1):
            if re.search(r'\bfile \d+\b', line):
                checked += 1
                if not KEY_RX.search(line):
                    out.append('%s:%d names "file N" without repo@commit:path' % (rel, n))
    if not checked:
        o.status_override['V1'] = 'N/A'
    o.notes['V1'].append('%d claims/cards/blocks checked' % checked)
    return out


# ---- V2
def _text_without_fences(t):
    return re.sub(r'```.*?```', ' ', t, flags=re.S)


GENERATED_JSON_KEYS = {'title', 'synopsis', 'achieves', 'why', 'context', 'label', 'note', 'strategy', 'meaning',
                       'hypothesis', 'algorithm', 'verdict', 'verdict_basis', 'description', 'summary', 'text', 'does',
                       'io', 'impact', 'name', 'headline', 'caption', 'plain', 'explanation', 'sentence', 'tagline'}


def _json_strings(x, out, key=None):
    if isinstance(x, dict):
        for k, v in x.items():
            _json_strings(v, out, k)
    elif isinstance(x, list):
        for v in x:
            _json_strings(v, out, key)
    elif isinstance(x, str) and key in GENERATED_JSON_KEYS:
        out.append(x)


@vaccine('V2', 'no-religion',
         'Generated prose borrows religious vocabulary, which the owner has ruled out of all generated text.',
         'A page, shard or JSON label written by a tool contains a word from the configured list.',
         'every build',
         'Owner instruction 2026-12-05 (Vikram): no religious terms in generated text. Quoted source code and '
         'repository-authored README text are not generated and are excluded.')
def v_religion(o):
    rx = re.compile(r'\b(%s)\b' % '|'.join(map(re.escape, sorted(set(o.words), key=len, reverse=True))), re.I)
    hits = collections.defaultdict(collections.Counter)  # term -> file -> n
    for rel in o.files:
        ext = os.path.splitext(rel)[1].lower()
        if ext in ('.html', '.htm'):
            s = o.summary(rel)
            t = ' '.join([s.title or '', s.text] + s.ldjson)
        elif ext in ('.txt', '.md'):
            t = _text_without_fences(o.text(rel))
            if os.path.basename(rel) == 'llms-full.txt' or re.match(r'llms-.*-\d\d\.txt$', os.path.basename(rel)):
                t = re.sub(r'(?m)^(?:    |\t).*$', ' ', t)
        elif ext == '.json':
            d = o.json(rel)
            if isinstance(d, Exception):
                continue
            parts = []
            _json_strings(d, parts)
            t = '\n'.join(parts)
        else:
            continue
        for m in rx.finditer(t):
            hits[m.group(1).lower()][rel] += 1
    out = []
    for term in sorted(hits, key=lambda k: -sum(hits[k].values())):
        files = hits[term]
        ex = ', '.join('%s (%d)' % (f, n) for f, n in files.most_common(6))
        out.append('"%s": %d occurrences in %d files, e.g. %s' % (term, sum(files.values()), len(files), ex))
    return out


# ---- V3
@vaccine('V3', 'no-private',
         'A non-public repository name is published.',
         'A token in any published text or Parquet string hashes to one of the Kuiper NOT_PUBLIC digests.',
         'every build',
         'Kuiper grid law L6 / ci_check K1; check_proof.leaks (names held as truncated SHA-256 digests, never spelled).')
def v_private(o):
    leaks = _leaks()
    out = []
    for rel in o.files:
        ext = os.path.splitext(rel)[1].lower()
        if ext in TEXT_EXT or ext in ('.py', '.yml', '.yaml'):
            n = leaks(o.text(rel))
            if n:
                out.append('%s: %d token(s) match a non-public digest (not spelled here)' % (rel, n))
        elif ext == '.parquet':
            try:
                import pyarrow.parquet as pq
                pf = pq.ParquetFile(o.p(rel))
                n = 0
                for rg in range(pf.num_row_groups):
                    t = pf.read_row_group(rg)
                    for col in t.columns:
                        if str(col.type) in ('string', 'large_string'):
                            n += leaks('\n'.join(x for x in col.to_pylist() if x))
                if n:
                    out.append('%s: %d token(s) in string columns match a non-public digest' % (rel, n))
            except ImportError:
                o.notes['V3'].append('%s: pyarrow missing, parquet not scanned' % rel)
    return out


# ---- V4
LOAD_CTX = re.compile(r'(fetch|import|Worker|importScripts|\.src\s*=|src\s*:|loadScript|XMLHttpRequest|\.open\(|'
                      r'WebSocket|EventSource|sendBeacon|@import|url\()\s*[\(\s\'"`]*$')
URL_LIT = re.compile(r'''["'`]((?:https?:)?//([A-Za-z0-9.-]+)(?::\d+)?[^"'`\s]*)''')
CSS_URL = re.compile(r'''(?:url\(\s*["']?|@import\s+["'])((?:https?:)?//([A-Za-z0-9.-]+)[^"')\s]*)''')
NON_LOAD_REL = {'canonical', 'alternate', 'next', 'prev', 'author', 'license', 'me', 'bookmark', 'help', 'search'}


def host_allowed(host, url):
    host = (host or '').lower()
    if host in LOCAL_HOSTS:
        return True
    pred = ALLOWED_HOSTS.get(host)
    return bool(pred and pred(url))


def external_loads(o, rel):
    """(line, kind, url, host) for every external load in an HTML/CSS/JS file."""
    found = []
    ext = os.path.splitext(rel)[1].lower()

    def js(text, kind):
        for m in URL_LIT.finditer(text):
            pre = text[max(0, m.start() - 48):m.start()]
            if LOAD_CTX.search(pre):
                found.append((text.count('\n', 0, m.start()) + 1, kind, m.group(1), m.group(2)))
        for m in re.finditer(r'''(?:import|from)\s*\(?\s*["'`]((?:https?:)?//([A-Za-z0-9.-]+)[^"'`]*)''', text):
            found.append((text.count('\n', 0, m.start()) + 1, kind + ' import', m.group(1), m.group(2)))

    def css(text, kind):
        for m in CSS_URL.finditer(text):
            found.append((text.count('\n', 0, m.start()) + 1, kind, m.group(1), m.group(2)))

    if ext in ('.html', '.htm'):
        s = o.summary(rel)
        for tag, attr, val, relv, line in s.refs:
            if tag == 'a' or tag == 'form' or (tag == 'link' and set(relv.split()) & NON_LOAD_REL and
                                               not set(relv.split()) & {'stylesheet', 'preload', 'modulepreload', 'icon', 'manifest', 'prefetch'}):
                continue
            u = urllib.parse.urlsplit(val)
            if u.scheme in ('http', 'https') or val.startswith('//'):
                found.append((line, '<%s %s>' % (tag, attr), val, u.hostname or ''))
        for t in s.scripts:
            js(t, 'inline script')
        for t in s.importmaps:
            for m in URL_LIT.finditer(t):
                found.append((0, 'importmap', m.group(1), m.group(2)))
        for t in s.styles:
            css(t, '<style>')
        for line, st in s.inline_styles:
            css(st, 'style=""')
    elif ext == '.css':
        css(o.text(rel), 'css')
    elif ext in ('.js', '.mjs'):
        js(o.text(rel), 'js')
    return found


@vaccine('V4', 'hosts',
         'A page silently depends on (and reports to) a third-party host.',
         'A script, stylesheet, image, frame, font, import or fetch points outside the site.',
         'every build',
         'Owner rule: self-contained pages; the one exception is jsDelivr serving DuckDB-WASM for search.')
def v_hosts(o):
    out = []
    agg = collections.defaultdict(list)
    for rel in o.by_ext('.html', '.htm', '.css', '.js', '.mjs'):
        for line, kind, url, host in external_loads(o, rel):
            if not host_allowed(host, url if not url.startswith('//') else 'https:' + url):
                agg[(host, kind)].append('%s:%d' % (rel, line))
    for (host, kind), where in sorted(agg.items(), key=lambda kv: -len(kv[1])):
        out.append('%s via %s: %d load(s), e.g. %s' % (host or '(no host)', kind, len(where), ', '.join(where[:5])))
    return out


# ---- V5
def _resolve_local(o, rel, val):
    """-> (absolute file path or None if not local, fragment)"""
    if not val or val.startswith(('mailto:', 'javascript:', 'data:', 'tel:', 'blob:', '{', '$')):
        return None, None
    base = o.site_base()
    if val.startswith(base):
        site_root = None
        for f in o.files:
            if os.path.basename(f) == 'build_graph.json':
                site_root = os.path.dirname(o.p(f))
        if site_root is None:
            return None, None
        u = urllib.parse.urlsplit(val[len(base):])
        target = os.path.join(site_root, urllib.parse.unquote(u.path))
    else:
        u = urllib.parse.urlsplit(val)
        if u.scheme or val.startswith('//'):
            return None, None
        if not u.path:
            target = o.p(rel)
        elif u.path.startswith('/'):
            return None, None  # root-absolute: depends on the host; not checkable offline
        else:
            target = os.path.normpath(os.path.join(os.path.dirname(o.p(rel)), urllib.parse.unquote(u.path)))
    if target.endswith(os.sep) or os.path.isdir(target):
        target = os.path.join(target, 'index.html')
    return target, urllib.parse.unquote(u.fragment) if u.fragment else None


@vaccine('V5', 'links',
         'A page links to something that is not there.',
         'An internal href/src names a missing file, or a #fragment names no id in its target.',
         'every build',