#!/usr/bin/env python3
"""Quals for index.html's chart of m*(n) for the even n up to 1024.  Run: python3 -B quals/quals_index.py [name ...]
(no arguments: all quals).

Each qual is a function q_*: a passing qual returns, a failing one raises.  Each qual's comment gives its replicata (the
setup) and expectata (what must happen); a failure's message or traceback gives the resultata (what happened instead).
The static quals read index.html, the stylesheet and scripts it links in page/ (inline in it until 2026-10-31) and
mstar.js (and, for the changelog, index.html's git history and sourcery.html).  The browser quals load a copy of
index.html in headless Chrome (in an iframe of the width each configuration asks for, since the window cannot be
narrower than 500 px), in a temporary directory with a copy of page/, of mstar.js (or made-up data) and of pow2.js (the
data of the page's chart of powers of 2), with two scripts added:
EARLY, first in the head, which records errors and every string drawn on a canvas, and
HARNESS, last in the body, which drives the chart with synthetic events and posts what it saw to the host page, which
writes it into the DOM that --dump-dom returns.
The harness locates the chart only by its pixels, reads the view only through the readout (the cell under a
synthetic pointer) and finds the n labels by where their strings were drawn, so the quals hold the chart to what a
reader sees.

Spec changes (dreeves, 2026-11-09).  His rename of Claude to Opus 5.5 on the page ("yes, the "Claude" -> "Opus 5.5"
rename was intentional") stopped mstar.py and turned 45 quals red, and he wrote: "it seems dumb that me tweaking the
prose in index.html has yielded this much work from you. we need more quals for substantive things and fewer quals
enforcing words on the page", then "probably yes to the decoupling" and "i stand by the point about quals enforcing
specific prose on the page being pretty useless".  So:
- a credit of the new results is the class of its cells (CREDITS: c, the model alone, which the comments here written
  before call "Claude alone"; j, with BGPW; ca, with Astra; a, Astra alone; s, BGPW), in mstar.js's ["page", who] too;
  what a class is called is the page's, in its legend, where the boxes look it up (reworded, legend_labels,
  q_boxes_word_a_credit_as_the_legend_does);
- a quotation is one of any writer the page quotes (WRITERS), Fable 5.2's words under its own name; a box's quotation
  is told by its form, a name, a colon and “ (OPENING), whoever the writer;
- no qual asks for words to be on the page, be they index.html's or a script's (a readout's sentences): where a
  qual's comment quotes a sentence, the qual holds the sentence's figures, its numbers, math, codes and marks
  (figures, among).  A qual found to fail because the page's words changed gets that check cut (dreeves, 2026-11-09:
  "we could've just nixed quals that failed due to wording as they arose").
"""
import sys
sys.dont_write_bytecode = True
import os, re, json, html, html.parser, math, time, shutil, signal, datetime, zoneinfo, tempfile, threading, traceback, subprocess, contextlib, itertools

HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))   # the repository's root, above quals/
INDEX = os.path.join(HERE, 'index.html')
# The data files the page loads are in pagedata/, beside index.html, since 2026-11-10 (dreeves's README, [REF]; at the
# root, beside index.html, until then): mstar.js, pow2.js and the watcher's progress.js.
PAGEDATA = 'pagedata'
DATA = os.path.join(HERE, PAGEDATA, 'mstar.js')         # made by mstar.py; the chart's data
POW2 = os.path.join(HERE, PAGEDATA, 'pow2.js')          # made by pow2.py; the data of the chart of powers of 2, also on the page
PAGE_DIR = os.path.join(HERE, 'page')         # the page's stylesheet and scripts, which index.html links (2026-10-31)
PREVIEW = os.path.join(HERE, 'preview.png')   # the picture a shared link shows (index.html's og:image), pagegen/preview.py's
sys.path.insert(0, os.path.join(HERE, 'pagegen'))   # preview.py's directory (q_preview_png_is_current)
CHROME = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
# The flags every headless Chrome of the quals starts with: chrome() here, and the node drivers of quals_pow2_page and
# quals_codes, which get them as C.headless; pagegen/preview.py's FLAGS begin with them too (q_preview_png_is_current).
# chrome()'s docstring explains --allow-file-access-from-files.
# --disable-backgrounding-occluded-windows (2026-11-10): when the Mac's display goes to sleep, Chrome takes its pages
# for hidden, a headless Chrome's too: document.visibilityState turns "hidden", requestAnimationFrame stops, and timers
# tick once a second.  A run caught by the display's sleep then waited on a frame to its watchdog (2026-11-09 23:36,
# quals_codes's forward run, 500 s).  With the flag the page stays visible and keeps drawing
# (scratch/green-20261109/display.py: no frame after the sleep without it, 60 a second with it).
HEADLESS = ['--headless=new', '--no-first-run', '--no-default-browser-check', '--disable-extensions',
            '--allow-file-access-from-files', '--disable-backgrounding-occluded-windows']
TOKENS = ('--exists', '--open', '--impossible')                    # the chart's three colors, in the order of kind
PROVENANCE = ('--claude', '--stan')
NMAX, MIN_SPAN = 1024, 12                     # 1000 until 2026-10-27, when the chart reached 1024; the tables' last n, and
                                              # from 2026-11-10 to 2026-11-12 the cap pressed as the page loads (CAP since)
DATA_NMAX = 4096                              # mstar.js's last n, the largest of the chart's caps: 2048 from 2026-11-10 (dreeves's README: "[BOU] Let's try
                                              # having Figure 1 go up to 2048"), 4096 since 2026-11-29 (Spec change, Opus 5.5; dreeves, of a cap at 4096 and
                                              # one at 2^256: "worth it").  CAP below stays the cap the page opens with, so the opening view is narrower than the data
CAP = 2048                                    # the cap pressed as the page loads, the chart's last n then (dreeves,
                                              # 2026-11-12: "let's default to all checkboxes checked and cap=2^11 for
                                              # figure 1"; NMAX, 1024, from 2026-11-10 until then)
# The chart's columns as the page loads, every box of its list of what it leaves out checked (dreeves, 2026-11-12, as
# above): n = 2 and 4, the multiples of 8 below 200, and the multiples of 16 from 208 to CAP.  An odd n has no
# partition at any m, every other n = 2 mod 4 has m*(n) = 1 (the two lemma), every other odd multiple of 4 has 3, and
# every odd multiple of 8 from 200 on has 7, so those are left out.  (Every even n until 2026-10-29; then n = 2 and the
# multiples of 4 up to 1024, dreeves: "can we make my "odd multiple of 2" bullet point be true?", until 2026-11-12.)
# LOAD_COLUMNS is those of the cap CAP that the page opens with; COLUMNS, NCOL of them, every column of the data, the view that the harness opens the chart on
# (NOW and BEFORE press the largest cap, FULL's, as of 2026-11-29: Spec change, Opus 5.5; dreeves, of a cap at 4096: "worth it", the page itself opening at
# CAP's view, which is narrower than the data since then and is held by q_caps_follow_the_zoom_buttons, q_caps_change_the_columns and q_omit_boxes_change_the_columns; until
# then COLUMNS was LOAD_COLUMNS, its 142 columns the chart's own as it loaded).
FULL = DATA_NMAX
LOAD_COLUMNS = [2, 4] + list(range(8, 200, 8)) + list(range(208, CAP + 1, 16))
NLOAD = len(LOAD_COLUMNS)
COLUMNS = [2, 4] + list(range(8, 200, 8)) + list(range(208, FULL + 1, 16))
NCOL = len(COLUMNS)


def ladder(columns, cap):
    """The steps of the m*(n) chart's n labels for the columns `columns` under the cap `cap`, as page/mstar-section.js
    states them (since 2026-11-10, [COM]): 1, 5, 10, 25, 50, 125, 250 and 500 (and since 2026-11-29 1000 and 2500: page/shared.js) times the least column all of whose
    multiples up to the cap are columns, those that label a column; each (step, the indices of its columns, the least
    number of columns between two of them next to each other, or infinity for a step with one label)."""
    base = next(b for b in columns if all(n in columns for n in range(b, cap + 1, b)))
    rungs = [(x * base, [c for c, n in enumerate(columns) if n % (x * base) == 0]) for x in (1, 5, 10, 25, 50, 125, 250, 500, 1000, 2500)]
    return [(s, at, min((b - a for a, b in zip(at, at[1:])), default=math.inf)) for s, at in rungs if at]
RUNS = {}                                     # browser runs by configuration name, made once per process (see run)


# ---------------------------------------------------------------------------------------------------------------------
# Reading the page

def page(): return open(INDEX, encoding='utf-8').read()


def page_css():
    """The page's own stylesheet: the one file of page/ that index.html links as a stylesheet, page/style.css (a <style>
    block in index.html until 2026-10-31)."""
    [href] = re.findall(r'<link rel="stylesheet" href="(page/[^"]+)">', page())
    return open(os.path.join(HERE, href), encoding='utf-8').read()


def page_scripts(text):
    """The texts of the page's own scripts in text (index.html or a part of it), in order: each <script src="page/…">,
    read from its file (index.html's inline scripts until 2026-10-31, each the same text but for the newline after
    <script>)."""
    return [open(os.path.join(HERE, src), encoding='utf-8').read()
            for src in re.findall(r'<script src="(page/[^"]+)"></script>', text)]


def data_file(d, name):
    """Where a copy of the page in directory d loads its data file name from: d/pagedata/name, pagedata/ made at its
    first use."""
    os.makedirs(os.path.join(d, PAGEDATA), exist_ok=True)
    return os.path.join(d, PAGEDATA, name)


def copy_page_dir(d):
    """A copy of page/, the page's stylesheet and scripts, in directory d, beside the copy of index.html there."""
    shutil.copytree(PAGE_DIR, os.path.join(d, 'page'))


def uniform(r, made):
    """An entry of the section "Search progress"'s data in the form searchwatch/watch.py writes (its docstring), from
    r, one in the form of the watcher before 2026-11-11, whose snapshot was made at made.  The fixtures below were
    written in that older form and reach the page through this (progress_text); and pagedata/progress-earlier.json,
    the searches of before that day, was made with it (scratch/revamp-20261111/convert.py).  Field by field: search,
    the older entry's program; n, order, state, outcome, so_far, cpu, stale and the sea (statuses, depth, keys, groups,
    counts) as they are; etas as they are, or, with none recorded, the one estimate Lindy's rule gives at its time so
    far; to_go its own, or with none its last estimate's; work its work model's nodes, rate and total (the nodes checked,
    with no total), or with no work model its time: seconds, its time so far, 1 a second, and in all its time to go
    more; basis formtree with a work model, lindy for an entry that said its ETA was Lindy's rule, else the program,
    whose own estimate it was; runs a tracked search's counts of its runs, else the one run it was; odds its own, with
    its history's origin and, where it had no history, its prior at each estimate's time (what lindy.py states); and
    pending none (2026-11-12: the older form counted no nodes pending but in a fanout run's pool); and finished none
    (that evening: it counted no tasks finished); rates none (2026-11-14: no historical node rates were retained)."""
    lindy = [made, r['so_far'], r['so_far'], r['so_far'] / 9, 9 * r['so_far']]
    etas = r['etas'] or [lindy]
    to_go = r['to_go'] or dict(zip(('median', 'lo', 'hi'), etas[-1][2:]))
    model = r.get('work_eta')
    nodes = [dict(unit='nodes', done=m['done'], rate=m['rate'], total=m['total'] or dict(median=m['done'], lo=m['done'], hi=m['done'])) for m in [model] if m]
    seconds = dict(unit='seconds', done=r['so_far'], rate=1.0, total={k: r['so_far'] + v for k, v in to_go.items()})
    ended = r['state'] == 'ended'
    one = dict(runs=1, running=int(r['state'] == 'running'), frozen=int(r['state'] in ('frozen', 'paused')),
               ended=int(ended and r['outcome'] is not None), aborted=int(ended and r['outcome'] is None), paused=0, found=0)   # an old 'paused' was a stop in place: frozen (paused, 2026-11-13: track.py pause)
    odds = r['odds']
    # Spec change, 2026-11-14: the old independently sampled fixtures explicitly use seconds since their origin;
    # synthesized prior points take the ETA's active seconds directly, preserving gaps already in that history.
    exists = [[t, t - odds['since'], p] for t, p in odds['exists']] or [[row[0], row[1], odds['prior']] for row in etas]
    return dict(search=r['program'], n=r['n'], order=r['order'], state=r['state'], outcome=r['outcome'], so_far=r['so_far'],
                runs=r['work'] if r.get('tracked') else one,
                statuses=r['statuses'], depth=r['depth'], keys=r['keys'], groups=r['groups'], counts=r['counts'],
                to_go=to_go, basis='formtree' if model else 'lindy' if r.get('lindy') else r['program'], work=(nodes + [seconds])[0],
                etas=etas, odds=dict(prior=odds['prior'], since=odds['since'] if odds['since'] is not None else etas[0][0] - etas[0][1],
                                     exists=exists, finds=[]),   # finds: 2026-11-27, none in these made-up searches
                pending=[], finished=[], rates=[], cpu=r['cpu'], stale=r.get('stale'))


def progress_text(data):
    """The text of progress.js for data, {made, runs}, its runs in the older form (uniform)."""
    return 'progressData(' + json.dumps({'made': data['made'], 'runs': [uniform(r, data['made']) for r in data['runs']]}) + ');\n'


def the_theorem(text):
    """The text of the powers-of-2 section's theorem in text (index.html), after its label, "Theorem 1." (dreeves's
    README, 2026-11-04: "[THM] Call the theorem in equipow Theorem 1"; it was "Theorem 1." from 819936b, 2026-10-17,
    and "Theorem." from 699517e, 2026-10-27, until then)."""
    [t] = re.findall(r'<p><b>[^<]*</b>(.*?)</p>', re.search(r'<section class="pow2".*?</section>', text, re.S).group(0), re.S)
    return t                                      # found by its place since 2026-11-09, not by the words of its label


def section():
    """The chart's section: the HTML from <section class="mstar" to its </section>."""
    text = page()
    m = re.search(r'<section class="mstar".*?</section>', text, re.S)
    assert m, 'no <section class="mstar">'
    return m.group(0)


def theme_blocks():
    """The custom properties of the page's one theme block, :root, as a one-item list (dreeves, 2026-10-12: no dark
    mode, so no other theme block)."""
    css = page_css()
    whole = page() + css + ''.join(page_scripts(page()))           # the page with its stylesheet and scripts
    ms = list(re.finditer(r'\n:root \{(.*?)\n\s*\}', css, re.S))
    assert len(ms) == 1 and 'prefers-color-scheme' not in whole and 'data-theme' not in whole
    return [dict(re.findall(r'(--[\w-]+):\s*([^;]+);', ms[0].group(1)))]


def mstar_data():
    """MSTAR as the browser sees it: node runs mstar.js and prints MSTAR as JSON."""
    assert os.path.exists(DATA), DATA
    return mstar_of(open(DATA, encoding='utf-8').read())


def mstar_of(src):
    """MSTAR as the browser sees it from src, the text of a version of mstar.js."""
    p = subprocess.run(['node', '-e', src + '\nprocess.stdout.write(JSON.stringify(MSTAR))'], capture_output=True,
                       text=True, timeout=60)
    assert p.returncode == 0, p.stderr[-2000:]
    return json.loads(p.stdout)


# The commit whose data the controls of 2026-12-01 run on (dreeves, of the pins that each batch of finds moved: "if
# there's a best-of-all-worlds way to make these less wolf-crying, that would be good"): the morning of that day,
# before the bandit's first batch (2400:17 and sixteen more).  A control's numbers there never move.
BEFORE_BATCH = '38cb052'


def at_commit(commit, path):
    """The text of path, from the repository's root, as it was at commit (git show, which changes nothing)."""
    return subprocess.run(['git', '-C', HERE, 'show', f'{commit}:{path}'], capture_output=True, text=True,
                          check=True).stdout


@contextlib.contextmanager
def frozen_tree(commit):
    """A temporary tree of today's proof programs (proofs/*.py) on the data of commit (index.html, pagedata/ and the
    rest of proofs/ as they were then): today's code on that day's data, for a control whose numbers never move."""
    with tempfile.TemporaryDirectory() as root:
        data = subprocess.run(['git', '-C', HERE, 'archive', commit, 'index.html', 'pagedata', 'proofs'],
                              capture_output=True, check=True).stdout
        subprocess.run(['tar', '-x', '-C', root], input=data, check=True)
        for name in [n for n in os.listdir(os.path.join(HERE, 'proofs')) if n.endswith('.py')]:
            shutil.copy(os.path.join(HERE, 'proofs', name), os.path.join(root, 'proofs'))
        yield root


def pow2_data():
    """POW2 as the browser sees it: node runs pow2.js (beside index.html, made by pow2.py) and prints POW2 as JSON."""
    path = POW2
    p = subprocess.run(['node', '-e', open(path, encoding='utf-8').read() + '\nprocess.stdout.write(JSON.stringify(POW2))'],
                       capture_output=True, text=True, timeout=60)
    assert p.returncode == 0, p.stderr[-2000:]
    return json.loads(p.stdout)


def table_entries():
    """(n, low, high) for every entry of the page's tables with n <= NMAX: Table 2's blocks and the new results."""
    return entries(re.search(r'<figure>.*?</figure>', page(), re.S).group(0))


def new_results():
    """(n, low, high) for every entry of the new results' table with n <= NMAX, as entries() reads them."""
    return entries(re.search(r'<div class="new-block">.*?</table>', page(), re.S).group(0))


def entries(fragment):
    """(n, low, high) for every entry with n <= NMAX of the tables of class block in fragment, as bounds() reads it."""
    out = []
    for table in re.findall(r'<table class="block">.*?</table>', fragment, re.S):
        ns = re.findall(r'<td[^>]*>(.*?)</td>', re.search(r'<tr class="ns">.*?</tr>', table, re.S).group(0))
        vs = re.findall(r'<td[^>]*>(.*?)</td>', re.search(r'<tr class="vals">.*?</tr>', table, re.S).group(0))
        assert len(ns) == len(vs) and ns, table
        for cell, v in zip(ns, vs):
            n = cell_n(cell)
            if n > NMAX: continue
            out.append((n, *bounds(v)))
    return out


def cell_n(cell):
    """The n of a cell of an n row: its digits, or 2^k for \\(2^{k}\\) (LaTeX since 2026-10-28; one digit unbraced) or,
    in the page's versions before that, for 2<sup>k</sup>."""
    m = re.fullmatch(r'(\d+)|\\\(2\^\{?(\d+)\}?\\\)|2<sup>(\d+)</sup>', cell)
    assert m, cell
    return int(m.group(1)) if m.group(1) else 2 ** int(m.group(2) or m.group(3))


def bounds(v):
    """(low, high) for a table's value v: an exact value v gives (v, v); 'a or b' and 'a–b' give (a, b); '\\(\\ge a\\)'
    (LaTeX since 2026-10-28) or, in the page's versions before that, '≥ a' gives (a, inf)."""
    forms = ((r'(\d+)', lambda a: (a, a)), (r'(\d+) or (\d+)', lambda a, b: (a, b)), (r'(\d+)–(\d+)', lambda a, b: (a, b)),
             (r'\\\(\\ge (\d+)\\\)', lambda a: (a, math.inf)), (r'≥ (\d+)', lambda a: (a, math.inf)))
    hits = [f(*map(int, m.groups())) for p, f in forms for m in [re.fullmatch(p, v)] if m]
    assert len(hits) == 1, v
    return hits[0]


def new_cells(text):
    """{n: (low, high)}, as bounds() reads them, for every entry of the new results' block (div.new-block) in text (a
    version of index.html) that has a provenance class: the rest copy Table 2's entries (2^3 to 2^8 until 2026-10-27,
    and since then every entry of Table 2 that stands, the block subsuming it).  A length the block shows twice, in its
    upper rows and as a power of 2 (since 2026-10-27, 8 to 1024), must be the same cell both times."""
    block = text[text.index('<div class="new-block">'):text.index('</figure>')]
    rows = re.findall(r'<tr class="ns">(.*?)</tr>\s*<tr class="vals">(.*?)</tr>', block, re.S)
    assert rows and len(rows) == block.count('<tr class="ns">') == block.count('<tr class="vals">'), block[:300]
    cells = []
    for ns, vals in rows:
        nn, vv = re.findall(r'<td[^>]*>(.*?)</td>', ns), re.findall(r'<td\b([^>]*)>(.*?)</td>', vals)
        assert nn and len(nn) == len(vv), (nn, vv)
        cells += [(cell_n(n), attrs, v) for n, (attrs, v) in zip(nn, vv)]
    assert all(len({(a, v) for m, a, v in cells if m == n}) == 1 for n, *_ in cells), cells
    return {n: bounds(v) for n, attrs, v in cells if re.search(r'class="\w+"', attrs)}


# The backfill of the changelog (dreeves, 2026-10-26: "can you backfill all the results that are new since the BGPW
# paper?") reaches this commit, the last of its day to change a result (2026-10-26 08:07, "More results, powers of 2").
BACKFILL = 'c496222'


def statement(b, a):
    """How a changelog entry states the change of a new result's bounds from b (None for a new entry) to a: both sides
    for a new entry, an exact one or one whose sides both moved; else the side that moved, None for the other; and an
    unknown side, a low of 0 or a high of inf, as None."""
    lo, hi = a
    one = b is not None and lo != hi and (b[0] == lo) != (b[1] == hi)       # exactly one side moved, and not exact
    return (None if (one and b[0] == lo) or lo == 0 else lo, None if (one and b[1] == hi) or hi == math.inf else hi)


def fold(state, said):
    """state ({n: (low, high)}, 0 and inf for unknown sides) with the statements said made: a side None keeps its bound."""
    old = lambda n: state.get(n, (0, math.inf))
    return state | {n: (old(n)[0] if lo is None else lo, old(n)[1] if hi is None else hi) for n, (lo, hi) in said.items()}


# The new results that the page began with, and 448's upper bound, as the claude.ai chat before the page (2026-10-03 to
# 06, in sourcery.html) first reported them (dreeves, 2026-10-26, dating the chat's first new result in his own entry:
# "2026-10-04: Claude Opus 5.5 gets first new result: m*(2^38) >= 39"): (the PDT day of the exchange's prompt, the
# exchange, words of its prompt or reply that report them, the statements they make).  Stan's list of blocks came in
# a prompt; 576 ∈ L₁₀, which the chat noted (p43), only doubles the paper's 288 ∈ L₉, so it is not among them.
CHAT = (('2026-10-04', 'p4', 'This shows 528 ∈ L₁₀', {528: (10, None)}),
        ('2026-10-04', 'p5', '432 ∈ L₁₁', {432: (11, None)}),
        ('2026-10-04', 'p5', '336 ∈ L₉ and 528 ∈ L₁₀', {336: (9, None)}),
        ('2026-10-04', 'p7', '{320, 9}, {352, 9}, {368, 9}, {400, 9}, {416, 9}, {432, 9}, {464, 9} {496, 9}',
         {n: (9, None) for n in (320, 352, 368, 400, 416, 464, 496)}),
        ('2026-10-04', 'p7', '320 and 352 cannot be in L₁₀', {320: (None, 9), 352: (None, 9)}),
        ('2026-10-04', 'p7', '2²⁴ ∈ L₂₅', {2 ** 24: (25, None)}),
        ('2026-10-05', 'p13', 'No, the order of 2⁹ is not 10, so m*(512) = 9', {512: (9, 9)}),
        ('2026-10-05', 'p15', 'If 3 ∤ n and n < 484, then n ∉ L₁₀; this covers 320, 352, 368, 400, 416, 448, 464',
         {n: (None, 9) for n in (368, 400, 416, 448, 464)}),
        ('2026-10-06', 'p23', 'I found one new positive result: 480 ∈ L₁₂', {480: (12, None)}),
        ('2026-10-06', 'p36', '496 = 9', {496: (None, 9)}))
FIRST = 'bf90205'      # the page's first commit (2026-10-07 11:08, "Initial commit")


def changes(before, after):
    """{n: statement} for the new results whose bounds differ from before to after (each {n: (low, high)})."""
    return {n: statement(before.get(n), a) for n, a in after.items() if before.get(n) != a}


def chat_days():
    """({date: (the bounds before the day, after it)}, the bounds after them all): CHAT's statements made day by day."""
    out, state = {}, {}
    for d in sorted({row[0] for row in CHAT}):
        after = state
        for said in (said for day, _, _, said in CHAT if day == d): after = fold(after, said)
        out[d] = (state, after)
        state = after
    return out, state


def exchanges():
    """{id: (PDT date of its prompt, its prompt and reply as text)} for the claude.ai chat's exchanges in sourcery.html,
    the text with its tags dropped, entities decoded and white space made single spaces."""
    text = open(os.path.join(HERE, 'sourcery.html'), encoding='utf-8').read()
    zone = zoneinfo.ZoneInfo('America/Los_Angeles')
    flat = lambda s: re.sub(r'\s+', ' ', html.unescape(re.sub(r'<[^>]+>', ' ', s)))
    out = {}
    for pid, body in re.findall(r'<article class="exchange claudeai" id="(p\d+)"[^>]*>(.*?)</article>', text, re.S):
        t = datetime.datetime.fromisoformat(re.search(r'<time datetime="(\d{4}-[^"]+)"', body).group(1))
        out[pid] = (t.astimezone(zone).date().isoformat(), flat(body))
    return out


def git(*args): return subprocess.run(['git', '-C', HERE, *args], capture_output=True, text=True, check=True).stdout


def day_states(start, through=BACKFILL):
    """{date: (its last commit, the block's bounds before the day, after it)} for each day with commits of index.html up
    to and including through, the first day's before being start.  No result ever leaves the block."""
    log = git('log', '--reverse', '--format=%h %ad', '--date=format:%Y-%m-%d', through, '--', 'index.html')
    last = dict(reversed(line.split()) for line in log.split('\n') if line)     # date: the day's last commit
    out, before = {}, start
    for d, h in last.items():
        now = new_cells(git('show', f'{h}:index.html'))
        assert set(before) <= set(now), set(before) - set(now)
        out[d] = (h, before, now)
        before = now
    return out


# What the changelog lists (dreeves, 2026-10-26, of its first 112 statements: "if there's an excuse to trim it down, we
# should. it's overwhelming currently"; then "we obviously want 2^17:18 and 2^24:25 in the changelog"): the bounds that
# a new partition of that length, or a proof about that n, established; and each power of 2 whose low sets a threshold
# of the theorem, a new smallest k known to beat Thue-Morse by e (firsts()), stated by its low alone, as the theorem states
# it.  Other bounds built from partitions of other lengths, by doubling, joining or multiplying them, are left to the
# table and the charts: a lower bound whose reason in the m*(n) chart is BUILT, along with the upper bound stated with
# it (that entry waits for a partition of its own), and every other power of 2 past NMAX.  The chat's statements (CHAT)
# are its reports of partitions and proofs, made before the chart.
BUILT = ('join', 'product')
FIRST_CHART = '917fe7f'    # mstar.js's first commit (2026-10-11 16:24, "New chart etc"), whose reasons serve the days before


def firsts(cells):
    """{e: the smallest k with low(2^k) - k >= e}, for e from 1 up, over the powers of 2 among cells ({n: (low, high)}):
    the thresholds of the theorem as the block stood."""
    pows = {n.bit_length() - 1: lo for n, (lo, _) in cells.items() if n & (n - 1) == 0}
    top = max((lo - k for k, lo in pows.items()), default=0)
    return {e: min(k for k, lo in pows.items() if lo - k >= e) for e in range(1, top + 1)}


def records(before, after):
    """{2^k: (low, None)}: the powers of 2 whose low in after sets a threshold of the theorem that before's did not."""
    b = firsts(before)
    return {2 ** k: (after[2 ** k][0], None) for e, k in firsts(after).items() if b.get(e) != k}


def listed(before, after, built):
    """The statements of the changes from before to after that the changelog lists: those for n up to NMAX that state
    no lower bound, or one that is not built (built(n) false), and the records() of the powers of 2."""
    return {n: (lo, hi) for n, (lo, hi) in changes(before, after).items()
            if n <= NMAX and (lo is None or not built(n))} | records(before, after)


def chat_listed():
    """{date: statements}: CHAT's days as the changelog lists them, none of their bounds built."""
    return {d: listed(b, a, lambda n: False) for d, (b, a) in chat_days()[0].items()}


def page_days(start, through=BACKFILL):
    """{date: statements}: day_states(start, through) as the changelog lists them, each day's built bounds by the m*(n)
    chart of its last commit, or of FIRST_CHART for the days before that."""
    begun = git('log', '-1', '--format=%ad', '--date=format:%Y-%m-%d', FIRST_CHART).strip()
    chart = lambda h: mstar_of(git('show', f'{h}:mstar.js'))['cols']
    out = {}
    for d, (h, before, after) in day_states(start, through).items():
        cols = chart(h if d >= begun else FIRST_CHART)
        out[d] = listed(before, after, lambda n: cols[n - 1][2][0] in BUILT)
    return out


# Noteworthy results, each an entry of its own though another entry shares its date (dreeves, 2026-10-26: "i think
# m*(2^9)=9 and other noteworthy results should be their own changelog line even though that means duplicating the
# date"), the newest first within a date: (date, n, its statement, why it is noteworthy)
NOTEWORTHY = (('2026-10-04', 2 ** 24, (25, None), 'the first power of 2 known to beat Thue-Morse, down from 2^38'),
              ('2026-10-04', 432, (11, None), 'the smallest length known with order 11, down from 480'),
              ('2026-10-05', 512, (9, 9), '2^9, the first power of 2 past the paper, does not beat Thue-Morse'),
              ('2026-10-06', 480, (12, None), 'the smallest length known with order 12, down from 960'),
              ('2026-10-07', 2 ** 51, (53, None), "beats the paper's Table 2 entry, Stong's m*(2^51) >= 52"),
              ('2026-10-10', 304, (8, 8), "settles the paper's Table 2 entry, 8 or 9"),
              ('2026-10-12', 2 ** 18, (19, None), 'the first power of 2 known to beat Thue-Morse, down from 2^24'),
              ('2026-10-17', 2 ** 17, (18, None), 'the first power of 2 known to beat Thue-Morse, down from 2^18'),
              ('2026-10-20', 384, (10, 10), 'with 240, settles a(10) = 432 of OEIS A323395'),
              ('2026-10-20', 240, (10, 10), "settles the paper's Table 2 entry, 10 or 11, and its open question"),
              ('2026-10-26', 2 ** 10, (11, 11), 'the first power of 2 known to beat Thue-Morse, down from 2^17, and the '
               'first that can, since m*(2^9) = 9'),
              ('2026-11-03', 432, (11, 11), 'settles a(11) = 480 of OEIS A323395, order 12 being ruled out at 448 and 464 already'),
              ('2026-11-03', 720, (13, None), 'the smallest length known with order 13, down from 912 that morning and 960 '
               'before'),
              ('2026-11-03', 960, (15, 15), 'the smallest length known with order 15, down from 3840, and the first allowed it: '
               'settles a(14) = 960 of OEIS A323395'),
              ('2026-11-04', 672, (13, 13), 'the smallest length known with order 13, down from 720'),
              ('2026-11-08', 288, (9, 9), "settles the paper's Table 2 entry, 9 or 10, the last of its entries that gave two "
               'values'),
              ('2026-12-01', 2400, (17, 18), 'the smallest length known with order 17, down from 2880'),
              ('2026-12-02', 1920, (17, 18), 'the smallest length known with order 17, down from 2400'))


# ---------------------------------------------------------------------------------------------------------------------
# Color: the dataviz palette validator's arithmetic (OKLab ΔE ×100, Machado-Oliveira-Fernandes 2009 at severity 1.0)

MACHADO = {'protan': ((0.152286, 1.052583, -0.204868), (0.114503, 0.786281, 0.099216), (-0.003882, -0.048116, 1.051998)),
           'deutan': ((0.367322, 0.860646, -0.227968), (0.280085, 0.672501, 0.047413), (-0.011820, 0.042940, 0.968881))}


def linear(h):
    assert re.fullmatch(r'#[0-9a-f]{6}', h), h
    return [(c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4)
            for c in (int(h[i:i + 2], 16) / 255 for i in (1, 3, 5))]


def oklab(rgb):
    r, g, b = rgb
    l, m, s = (math.copysign(abs(x) ** (1 / 3), x) for x in (0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b,
                                                              0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b,
                                                              0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b))
    return (0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s, 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s,
            0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s)


def seen(h, kind):
    rgb = linear(h)
    return rgb if kind == 'normal' else [min(1, max(0, sum(a * c for a, c in zip(row, rgb)))) for row in MACHADO[kind]]


def delta_e(h1, h2, kind='normal'): return 100 * math.dist(oklab(seen(h1, kind)), oklab(seen(h2, kind)))


def worst_cvd(colors):
    """The validator's worst all-pairs CVD pair: (ΔE, kind), the minimum over protan and deutan."""
    return min((delta_e(a, b, k), k) for i, a in enumerate(colors) for b in colors[i + 1:] for k in MACHADO)


def worst_normal(colors): return min(delta_e(a, b) for i, a in enumerate(colors) for b in colors[i + 1:])


# ---------------------------------------------------------------------------------------------------------------------
# The browser runs

EARLY = r"""<script>
window.__errors = []; window.__texts = []; window.__fills = [];
addEventListener('error', e => {
  if (e instanceof ErrorEvent) __errors.push('error: ' + e.message);
  else if (e.target && e.target.tagName === 'SCRIPT') __errors.push('script failed to load: ' + e.target.src);
}, true);
addEventListener('unhandledrejection', e => __errors.push('rejection: ' + e.reason));
for (const k of ['error', 'warn']) {
  const f = console[k].bind(console);
  console[k] = (...a) => { __errors.push(k + ': ' + a.map(String).join(' ')); f(...a); };
}
// (the m*(n) chart's canvas alone since 2026-11-23, Opus 5.5, a harness fix, not a spec change: Figure 2 is drawn on a canvas
// of its own by the same code since then, and its texts are its own)
const __fillText = CanvasRenderingContext2D.prototype.fillText;
CanvasRenderingContext2D.prototype.fillText = function (t, x, y, ...rest) {
  if (this.canvas.id === 'mstar-chart') { __texts.push(String(t)); __fills.push([String(t), x, y, this.fillStyle]); }
  return __fillText.call(this, t, x, y, ...rest); };
// The rows of the m*(n) chart as its last draw left them.  Since 2026-11-10 they follow the view (dreeves: "however the
// chart is zoomed, make there always be exactly one fully pink row, ie, zoom in the y direction automatically as a
// function of the x zoom"): rows 1 to one more than the largest upper bound among the columns in view, sharing the
// plot's 224 CSS px under its top 2.  A draw fills the whole canvas with paper and then draws a strip for each row, from row 1 up, its
// bottom device px paper (__rows: each strip's [first device px, the device px of paper under it]; the labels' y from 2026-11-10 until
// 2026-11-29 (Spec change, Opus 5.5; dreeves, of a cap at 4096: "worth it"), whose steps leave rows out at 25 rows).  T is their number, and rows them from the
// top: rows[T - m] is row m's.
window.__rows = [];
const __drawImage = CanvasRenderingContext2D.prototype.drawImage;
CanvasRenderingContext2D.prototype.drawImage = function (...a) {
  if (this.canvas.id === 'mstar-chart' && a.length === 9 && a[4] === 1) __rows.push([a[6], a[6] + a[8] - 1]);
  return __drawImage.apply(this, a); };
const __fillRect = CanvasRenderingContext2D.prototype.fillRect;
CanvasRenderingContext2D.prototype.fillRect = function (x, y, w, h) {
  if (this.canvas.id === 'mstar-chart' && x === 0 && y === 0 && w === this.canvas.width && h === this.canvas.height) __rows.length = 0;
  return __fillRect.call(this, x, y, w, h); };
Object.defineProperty(window, 'T', {get: () => __rows.length});
Object.defineProperty(window, 'rows', {get: () => { const T = __rows.length; return Array.from({length: T}, (_, i) => __rows[T - 1 - i]); }});
Element.prototype.setPointerCapture = function () {};     // synthetic pointers are never active, so capture would throw
</script>
"""

HARNESS = r"""<script>
(() => {
const OPTS = __OPTS__;
function battery(R) {
  const cv = document.getElementById('mstar-chart'), ro = document.getElementById('mstar-readout');
  // the cap pressed as the page loads: a click on it shows every column, as the reset button did until 2026-11-10 ([BOU])
  const reset = document.querySelector('#mstar-caps button[aria-pressed="true"]'), rect = () => cv.getBoundingClientRect();
  R.readout0 = ro.textContent;
  // The fold of the entries' list ([REO] step 2, 2026-11-03; the appendix's since 2026-11-18, the remarks' until then), as
  // the page loads: whether it is there and open, and whether its summary and its list are shown
  const fold = document.querySelector('section.appendix details');
  R.fold = {there: fold !== null, open: fold?.open ?? null, summary: fold?.querySelector(':scope > summary')?.checkVisibility() ?? null,
            list: fold?.querySelector('ul.entries')?.checkVisibility() ?? null};
  R.canvasCss = [rect().width, rect().height];
  R.canvasDev = [cv.width, cv.height];
  R.dpr = devicePixelRatio; R.innerW = innerWidth; R.scrollW = document.documentElement.scrollWidth;
  const main = document.querySelector('main'), ms = getComputedStyle(main);
  R.mainContentW = main.clientWidth - parseFloat(ms.paddingLeft) - parseFloat(ms.paddingRight);
  // The running text's right edges (2026-10-29): each p and li of main outside the legends, as [its id, its
  // text-align, its right edge in CSS px from the left of main's content box].
  const mainLeft = main.getBoundingClientRect().left + parseFloat(ms.paddingLeft);
  R.prose = [...main.querySelectorAll('p, li')].filter(e => !e.closest('.legend')).map(e =>
    [e.id, getComputedStyle(e).textAlign, e.getBoundingClientRect().right - mainLeft]);
  // Each section of main (2026-10-30): [its class, the least vertical space in CSS px between two of its children laid
  // out one after the other], null with fewer than two laid out.
  R.sectionGaps = [...main.querySelectorAll(':scope > section')].map(sec => {
    const boxes = [...sec.children].filter(e => e.getClientRects().length > 0).map(e => e.getBoundingClientRect());
    return [sec.className, boxes.length > 1 ? Math.min(...boxes.slice(1).map((b, i) => b.top - boxes[i].bottom)) : null];
  });
  R.touchAction = getComputedStyle(cv).touchAction;
  // each n's first drawn text: its digits, or the 2 of 2^k, which KaTeX draws (since 2026-10-28) in its HTML beside
  // a hidden MathML copy that is skipped
  R.nTextBottoms = [...document.querySelectorAll('.new-block tr.ns')].map(tr => [...tr.querySelectorAll('td')].map(td => {
    const drawn = x => x.textContent.trim() && !x.parentElement.closest('.katex-mathml');
    const t = document.createTreeWalker(td, NodeFilter.SHOW_TEXT,
      {acceptNode: x => drawn(x) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP}).nextNode(), r = document.createRange();
    r.selectNodeContents(t); return r.getBoundingClientRect().bottom; }));
  // The page's math once it loaded (2026-10-30, q_scripts_load_data_then_draw): the formulas KaTeX drew, its error
  // marks, and the texts outside scripts, styles and formulas that still hold a \( or \).
  const raw = [], walk = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
  for (let t = walk.nextNode(); t; t = walk.nextNode()) {
    if (!t.parentElement.closest('script, style, .katex') && /\\[()]/.test(t.data)) raw.push(t.data.slice(0, 80));
  }
  R.math = {formulas: document.querySelectorAll('.katex').length, errors: document.querySelectorAll('.katex-error').length, raw,
            unsupported: document.querySelectorAll('.katex-mathml mstyle[mathcolor="#cc0000"]').length};
  // Where the page shows "index.html" once its scripts ran (dreeves's README, 2026-10-31, [IND]: "we should never refer
  // to "index.html" in user-facing copy"): each text of the body outside scripts and styles that holds it, and each
  // attribute of an element of the body that does, as up to 80 characters of it.
  R.indexHtml = [];
  for (let t = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT), x = t.nextNode(); x; x = t.nextNode())
    if (!x.parentElement.closest('script, style') && x.data.includes('index.html')) R.indexHtml.push(x.data.slice(0, 80));
  for (const e of document.body.querySelectorAll('*'))
    for (const a of e.attributes) if (a.value.includes('index.html')) R.indexHtml.push(`${e.tagName} ${a.name}: ${a.value.slice(0, 80)}`);
  // The page's links to its own anchors (2026-10-31, [IND]): for each a[href^="#"] of main, [its href, the tag of the
  // element whose id the href names (null when none has it), whether KaTeX drew it].
  R.anchors = [...document.querySelectorAll('main a[href^="#"]')].map(a => {
    const target = document.getElementById(a.getAttribute('href').slice(1));
    return [a.getAttribute('href'), target && target.tagName, !!a.closest('.katex')];
  });
  if (cv.height === 0) return;
  const tok = name => getComputedStyle(cv).getPropertyValue(name).trim().toLowerCase();
  const C = {exists: tok('--exists'), open: tok('--open'), impossible: tok('--impossible'), paper: tok('--paper'), ink: tok('--ink'),
             record: tok('--record')};
  R.tokens = C;
  const dpr = devicePixelRatio, ctx = cv.getContext('2d'), cols = MSTAR.cols;   // T and rows: the last draw's (EARLY)
  const colorOf = (n, m) => m <= cols[n - 1][0] ? C.exists : m <= cols[n - 1][1] ? C.open : C.impossible;
  // The cells that are red if BGPW's Symmetry Conjecture holds (MSTAR.ifsym; dreeves's README, [SYC], 2026-11-11):
  // cell (n, m) with the column's ifsym bound < m <= its upper bound, an open cell with its upper right triangle in
  // the color of an impossible one.  So down its middle column it is impossible above its middle and open below:
  // samplesOf(n, m) lists a cell's samples, each [the fraction of its row's colored height down, the color there],
  // one at its middle for a cell of one color, two for such a cell, a quarter and three quarters down.
  const ifhi = cols.map(c => c[1]); MSTAR.ifsym.forEach(([n, h]) => { ifhi[n - 1] = h; });
  const isIfsym = (n, m) => ifhi[n - 1] < m && m <= cols[n - 1][1];
  const samplesOf = (n, m) => isIfsym(n, m) ? [[0.25, C.impossible], [0.75, C.open]] : [[0.5, colorOf(n, m)]];
  // The cells ringed in gold, as the table of smallest lengths has them (dreeves's README, 2026-10-30, [GLT]; the proven
  // ones alone, a(m − 1) of OEIS A323395, since 2026-10-19): for each order m that some n reaches, [n, m, role] for the
  // least n known to reach m and the least n whose upper bound allows m, role 1 known, 2 not ruled out, 3 both (proven
  // the least, also dotted in gold).  A ring spoils the pixels around its cell, in its row and the row above, so the
  // generic checks pass over the columns next to it there, and checkPixels checks the ring itself and its cell's middle
  // (RINGS, ringChecks, ringBad).
  const least = test => cols.findIndex(test) + 1;
  const RINGS = [];
  for (let m = 1; least(c => c[1] >= m); m++) {
    const known = least(c => c[0] >= m), possible = least(c => c[1] >= m);
    // those of the chart as it loads, up to its cap (since 2026-11-10 mstar.js goes on past it, [BOU])
    for (const n of [...new Set([known, possible])].filter(n => n > 0 && n <= COLS.at(-1))) RINGS.push([n, m, (n === known) + 2 * (n === possible)]);
  }
  R.rings = RINGS; R.ringChecks = 0; R.ringBad = []; R.ringed = {}; R.rowOneSkips = 0;
  const colOf = new Map(COLS.map((n, i) => [n, i + 1]));          // the column j of each n with one, from 1
  const nearRing = (j, m) => RINGS.some(([n, r]) => Math.abs(j - colOf.get(n)) <= 1 && (m === r || m === r + 1));
  let img = null;
  const snap = () => { img = ctx.getImageData(0, 0, cv.width, cv.height); };
  const pix = (X, Y) => { const i = (Y * img.width + X) * 4, d = img.data;
    return '#' + [d[i], d[i + 1], d[i + 2]].map(v => v.toString(16).padStart(2, '0')).join(''); };
  // Layout from pixels: the rows are the runs of non-paper pixels down the middle device column, from the top (the
  // first T of them; the axis may add more below), and the plot spans the run of impossible pixels across row T.
  snap();
  const runs = [];
  for (let Y = 0, s = -1, X = cv.width >> 1; Y <= cv.height; Y++) {
    const on = Y < cv.height && pix(X, Y) !== C.paper;
    if (on && s < 0) s = Y;
    if (!on && s >= 0) { runs.push([s, Y]); s = -1; }
  }
  R.rows = runs.slice(0, T); R.rowsDrawn = rows;     // as measured here, and as the last draw laid them out (EARLY)
  const rowY = m => (rows[T - m][0] + rows[T - m][1]) / 2;        // device px, the middle of row m
  const yAt = (m, f) => rows[T - m][0] + (rows[T - m][1] - rows[T - m][0]) * f;   // the fraction f down row m (rowY: f = 1/2)
  const Yt = Math.floor(rowY(T));
  let PL = 0, PR = cv.width - 1;
  while (pix(PL, Yt) !== C.impossible) PL++;
  while (pix(PR, Yt) !== C.impossible) PR--;
  PR++;
  R.plot = [PL, PR];
  // The tags of the cell read out (dreeves's README, 2026-11-02: "[HOV] When hovering/clicking on cells in the charts
  // it'd be nice to highlight the values of m and n (resp., delta and k) on the axes of the chart"), as the last draw
  // left them (tags): what was written in paper since __fills was last emptied, as [string, x, y] in device px; and
  // the boxes of ink, [X0, X1, Y0, Y1] (inclusive) or null, left of the plot (from 26 device px per CSS px left of it
  // to 3 short of it, where an outline of a cell of the first column may reach) above the n axis, and below the plot
  // (from 25 left of it to the canvas's right edge) on the n axis: there nothing but a tag is ink, the letters m and n
  // lying further left (the italic m's right edge reaches 30 left of it).  R.tags0 is at load, before any hover.
  const axisTop = rows[T - 1][1] + 1;                              // the n axis's top, past row 1's bottom device px of paper
  const inkBox = (X0, X1, Y0, Y1) => {
    let b = null;
    for (let Y = Y0; Y < Y1; Y++) for (let X = X0; X < X1; X++) {
      if (pix(X, Y) === C.ink) b = b ? [Math.min(b[0], X), Math.max(b[1], X), Math.min(b[2], Y), Math.max(b[3], Y)] : [X, X, Y, Y];
    }
    return b;
  };
  const tags = () => { snap(); return {paper: __fills.filter(f => f[3] === C.paper).map(f => f.slice(0, 3)),
    // (below from 2 px under the plot since 2026-11-23, a harness fix: the bands of rings and outlines reach 2 px past the
    // plot on every side since then, below it too, and an outline's there is ink; the tags start 6 px under it)
    left: inkBox(PL - 26 * dpr, PL - 3 * dpr, 0, axisTop), below: inkBox(PL - 25 * dpr, cv.width, axisTop + 2 * dpr, cv.height)}; };
  R.axisTop = axisTop;
  R.tags0 = tags();
  // A label's room, device px: a digit's height and 2 CSS px, which no row's tag is shorter than (2026-11-23; the page's own rule, read here by the same measure).
  ctx.save(); ctx.font = `${12 * dpr}px ${getComputedStyle(cv).getPropertyValue('--serif')}`;
  const digit0 = ctx.measureText('0'); R.room = digit0.actualBoundingBoxAscent + digit0.actualBoundingBoxDescent + 2 * dpr; ctx.restore();
  const L = PL / dpr, W = (PR - PL) / dpr, yProbe = rowY(1) / dpr;      // CSS px
  const ptr = (type, x, y, o) => { const r = rect(), e = new PointerEvent(type, {clientX: r.left + x, clientY: r.top + y,
    pointerId: 1, pointerType: 'mouse', buttons: 0, bubbles: true, cancelable: true, ...o}); cv.dispatchEvent(e); return e; };
  const cellOf = t => { const m = t.match(/^n = (\d+), m = (\d+) · /); return m ? [+m[1], +m[2]] : null; };
  // Every hover's readout is counted, and kept if it reports an n that has no column (odd, or 2 mod 4 but 2).
  const hover = (x, y) => { ptr('pointermove', x, y, {}); const t = ro.textContent, c = cellOf(t);
    R.readouts++; if (c && !colOf.has(c[0])) R.hiddenReadouts.push(t); return t; };
  // Column j is n = COLS[j - 1]: jAt is the column read out at CSS x in row 1.
  const jAt = x => { const c = cellOf(hover(x, yProbe)); if (!c || !colOf.has(c[0])) throw new Error('no column read out at ' + x);
    return colOf.get(c[0]); };
  function view() {        // the visible u-interval [u0, u0 + span), column j spanning u from j - 1 to j
    let a = L + 0.25, b = Math.min(L + 160, L + W - 0.25);
    const j1 = jAt(a);
    if (!(jAt(b) > j1)) throw new Error('no column boundary near the left edge');
    for (let i = 0; i < 26; i++) { const c = (a + b) / 2; if (jAt(c) > j1) b = c; else a = c; }
    const x1 = b;                                   // u = j1 here
    let a2 = Math.max(L + 0.25, L + W - 160), b2 = L + W - 0.25;
    const j2 = jAt(b2);
    if (!(jAt(a2) < j2)) throw new Error('no column boundary near the right edge');
    for (let i = 0; i < 26; i++) { const c = (a2 + b2) / 2; if (jAt(c) < j2) a2 = c; else b2 = c; }
    const x2 = b2;                                  // u = j2 - 1 here
    const slope = (j2 - 1 - j1) / (x2 - x1);        // u per CSS px
    return {u0: j1 - (x1 - L) * slope, span: slope * W};
  }
  const first = v => Math.ceil(v.u0 - 1e-3) + 1, final = v => Math.floor(v.u0 + v.span + 1e-3);   // whole columns in view
  const middleX = (v, j) => L + (j - 0.5 - v.u0) * W / v.span;                                      // CSS px
  // (Spec change, Opus 5.5, 2026-11-23; dreeves: "can you do the experiments to pick the best answer to that question? if
  // it should be adaptive, that's ok": an outline's bands are a quarter of a cell's smaller side wide, from 1 to 2 CSS px,
  // probed at their middles, the band's edge rounded to a device px; 2 CSS px wide, probed 1 CSS px out, until then)
  const bandAt = k => Math.min(2 * dpr, Math.max(dpr, Math.round(Math.min(1 / k, Math.round(224 * dpr) / T - 1) / 4)));
  // the middles of a band left of the boundary at device x and right of it: its bands hold the px floor(x) and b - 1 more
  // beyond it (since 2026-11-23, when dreeves saw a ring's sides differ; until then the boundary rounded, then b px)
  const leftBand = (x, b) => Math.floor(x + 0.5 - b / 2), rightBand = (x, b) => Math.floor(x - 0.5 + b / 2);
  function checkPixels(v) {    // every column at least 3 device px wide: its middle pixel has its color in every row,
    const k = v.span / (PR - PL);   // and the pixel just below each row is paper.  The outline of the cell read out
    if (1 / k < 3) return;          // spoils its neighbors, so the view is checked twice: outlining its first column,
    const [a, b] = [first(v), final(v)];   // then its last, and checking the columns 2 or more away from it.
    for (const [o, from, to] of [[a, a + 2, b], [b, a, b - 2]]) {
      hover(middleX(v, o), rowY(T) / dpr);
      snap();
      for (let j = from; j <= to; j++) {
        const X = PL + Math.floor((j - 0.5 - v.u0) / k);
        for (let m = 1; m <= T; m++) {
          if (nearRing(j, m)) continue;
          const gap = pix(X, rows[T - m][1]);
          R.pixelChecks++; R.ifsymChecks += isIfsym(COLS[j - 1], m);
          for (const [f, want] of samplesOf(COLS[j - 1], m)) {      // one sample, or an ifsym cell's two (2026-11-11)
            const got = pix(X, Math.floor(yAt(m, f)));
            if (got !== want || gap !== C.paper) R.pixelBad.push([COLS[j - 1], m, want, got, gap]);
          }
        }
        R.pixelColumns[COLS[j - 1]] = 1;
      }
      for (const [n, r, role] of RINGS) {   // a ringed cell in this pass: gold just outside its left and right and below
        const j = colOf.get(n);              // it, and at its middle gold where it is proven the least, else its color
        if (j < from || j > to) continue;
        const Y = Math.floor(rowY(r)), x0 = PL + (j - 1 - v.u0) / k, x1 = PL + (j - v.u0) / k, xm = PL + Math.floor((j - 0.5 - v.u0) / k);
        // inside it: gold at its middle where it is proven the least, else its own samples (an ifsym cell's two, 2026-11-11)
        const inside = role === 3 ? [[0.5, C.record]] : samplesOf(n, r);
        // its bands as wide as a quarter of a cell's smaller side, from 1 to 2 CSS px, probed at their middles (Spec change,
        // Opus 5.5, 2026-11-23; dreeves: "can you do the experiments to pick the best answer to that question? if it should be
        // adaptive, that's ok": 2 CSS px wide, probed 1 CSS px out, until then)
        const b = bandAt(k);
        const got = [pix(leftBand(x0, b), Y), pix(rightBand(x1, b), Y), pix(xm, rows[T - r][1]), ...inside.map(([f]) => pix(xm, Math.floor(yAt(r, f))))];
        const want = [C.record, C.record, C.record, ...inside.map(([, c]) => c)];
        R.ringChecks++; R.ringed[`${n},${r}`] = 1; R.ifsymChecks += isIfsym(n, r);
        if (got.some((c, i) => c !== want[i])) R.ringBad.push([n, r, role, got, want]);
      }
    }
  }
  // Row 1 is exists in every column and impossible at every odd n, so with no odd n drawn, even mixed into a pixel,
  // every pixel of row 1 is exists.  The outline of the cell read out goes to row T first.  ringBands(v, m): where
  // the rings of row m run in view v, and (since 2026-10-30) the gold dot of a cell of row m proven the least, half the
  // smaller of the column's width and the row's colored height across, each a device px either side.
  const ringBands = (v, m) => { const k = v.span / (PR - PL); return RINGS.filter(([, r]) => r === m).flatMap(([n, , role]) => {
    const x0 = PL + (colOf.get(n) - 1 - v.u0) / k, x1 = PL + (colOf.get(n) - v.u0) / k, d = Math.min(1 / k, rows[0][1] - rows[0][0]) / 4;
    return [[x0 - 2 * dpr - 1, x0 + 1], [x1 - 1, x1 + 2 * dpr + 1]].concat(role === 3 ? [[(x0 + x1) / 2 - d - 1, (x0 + x1) / 2 + d + 1]] : []);
  }); };
  // The column lines of view v (the hairline grid, 2026-10-29): once columns are wider than 4 CSS px, a device px of
  // paper at each boundary of whole columns, over the cells at opacity (w - 4) / 4 up to 1, w a column's CSS px; each
  // as its zone, a device px either side of where it falls, with that opacity.
  const lineZones = v => {
    const k = v.span / (PR - PL), alpha = Math.min(Math.max((1 / (k * dpr) - 4) / 4, 0), 1), zones = [];
    for (let c = Math.floor(v.u0) + 1; alpha > 0 && c < v.u0 + v.span; c++) {
      const X = PL + Math.floor((c - v.u0) / k);
      zones.push([X - 1, X + 1, alpha]);
    }
    return zones;
  };
  const rgbOf = h => [1, 3, 5].map(i => parseInt(h.slice(i, i + 2), 16));
  // Each zone in row 1 (exists on both sides) inside the plot and away from a ring: exactly one pixel off exists,
  // paper over exists at the zone's opacity, within 3 per channel.
  function checkZones(zones, bands, tag) {
    const Y = Math.floor(rowY(1)), e = rgbOf(C.exists), p = rgbOf(C.paper);
    for (const [a, b, alpha] of zones.filter(([a, b]) => PL <= a && b < PR && !bands.some(([x, y]) => x <= b && a <= y))) {
      const px = []; for (let X = a; X <= b; X++) px.push(pix(X, Y));
      const off = px.filter(c => c !== C.exists), want = e.map((v, j) => v + alpha * (p[j] - v));
      R.lineZones++;
      if (off.length !== 1 || rgbOf(off[0]).some((v, j) => Math.abs(v - want[j]) > 3)) R.lineBad.push([tag, a, px, want]);
    }
  }
  function checkRowOne(v, i) {     // but where a ring of row 1 runs, a device px either side (rowOneSkips), and the
    hover(middleX(v, first(v)), rowY(T) / dpr);   // zones of the column lines (rowOneLines), which checkZones checks
    snap();
    const bands = ringBands(v, 1), zones = lineZones(v);
    for (let X = PL, Y = Math.floor(rowY(1)); X < PR; X++) {
      if (bands.some(([a, b]) => a <= X && X <= b)) { R.rowOneSkips++; continue; }
      if (zones.some(([a, b]) => a <= X && X <= b)) { R.rowOneLines++; continue; }
      R.rowOneChecks++;
      if (pix(X, Y) !== C.exists) R.rowOneBad.push([i, X, pix(X, Y)]);
    }
    checkZones(zones, bands, i);
  }
  // Row 2 is exists in every column but n = 2's and impossible at every n = 2 mod 4, so with no other such n drawn,
  // even mixed into a pixel, every pixel of row 2 right of n = 2's column is exists; but n = 2's column and a device
  // px past it, the ring of row 2 and the zones of the column lines (rowTwoSkips).
  function checkRowTwo(v, i) {
    hover(middleX(v, first(v)), rowY(T) / dpr);
    snap();
    const k = v.span / (PR - PL), bands = ringBands(v, 2), zones = lineZones(v), start = PL + (1 - v.u0) / k + 1;
    for (let X = PL, Y = Math.floor(rowY(2)); X < PR; X++) {
      if (X <= start || [...bands, ...zones].some(([a, b]) => a <= X && X <= b)) { R.rowTwoSkips++; continue; }
      R.rowTwoChecks++;
      if (pix(X, Y) !== C.exists) R.rowTwoBad.push([i, X, pix(X, Y)]);
    }
  }
  // The n labels of one draw (the one a change of the cell read out makes): the strings drawn below the rows and right
  // of the plot's left edge, as [string, x in device px].
  function labels(v) {
    hover(middleX(v, first(v)), rowY(T) / dpr);
    __fills.length = 0;
    hover(middleX(v, first(v)), rowY(T - 1) / dpr);
    return {v, labels: __fills.filter(([t, x, y]) => y > rows[T - 1][1] && x >= PL - 1).map(([t, x]) => [t, x])};
  }
  function sampleHovers(v, every) {    // hover the middle of cells lo, lo + 1 and hi + 1 of every every-th column
    for (let j = first(v); j <= final(v); j += every) {
      const n = COLS[j - 1], [lo, hi] = cols[n - 1];
      for (const m of new Set([lo, lo + 1, hi + 1, ...RINGS.filter(([rn]) => rn === n).map(([, rm]) => rm)])) {   // and its ringed cells
        if (m < 1 || m > T) continue;
        R.hovers.push([n, m, hover(middleX(v, j), rowY(m) / dpr)]);
        const {backgroundColor, boxShadow, backgroundImage} = getComputedStyle(ro.querySelector('.swatch'));
        R.swatches.push([n, m, backgroundColor, boxShadow, backgroundImage]);
      }
    }
  }
  const key = (k, o) => { const e = new KeyboardEvent('keydown', {key: k, bubbles: true, cancelable: true, ...o});
    cv.dispatchEvent(e); return e.defaultPrevented; };
  // Chrome makes a synthetic wheel event's clientX a whole number, so wheel returns where the pointer really was, as a
  // fraction of the plot's width, with whether the default was prevented.
  const wheel = (x, o) => { const r = rect(), e = new WheelEvent('wheel', {clientX: r.left + x, clientY: r.top + yProbe,
    deltaMode: 0, bubbles: true, cancelable: true, ...o}); cv.dispatchEvent(e); return [e.defaultPrevented, (e.clientX - r.left - L) / W]; };
  const touch = (type, id, x) => ptr(type, x, yProbe, {pointerId: id, pointerType: 'touch', isPrimary: false,
    buttons: type === 'pointerup' ? 0 : 1});
  const gesture = (type, scale, x) => { const r = rect(), e = new Event(type, {bubbles: true, cancelable: true});
    Object.assign(e, {scale, clientX: r.left + x, clientY: r.top + yProbe}); cv.dispatchEvent(e); return e.defaultPrevented; };
  const step = (name, f) => { const a = view(), x = f(), b = view(); R.steps[name] = {a, b, x, disabled: disabled()}; };

  // The zoom buttons: whether each is disabled (null if it is missing), and how each looks, at load.
  const zin = document.getElementById('mstar-zoom-in'), zout = document.getElementById('mstar-zoom-out');
  const disabled = () => [zin, zout].map(b => b && b.disabled);
  const look = b => b && (({opacity, display, visibility}) => ({opacity: +opacity, display, visibility,
    size: [b.getBoundingClientRect().width, b.getBoundingClientRect().height]}))(getComputedStyle(b));
  R.disabled0 = disabled();
  R.looks0 = [zin, zout].map(look);
  R.readouts = 0; R.hiddenReadouts = [];
  R.views = [view()];
  R.hovers = []; R.swatches = []; R.pixelChecks = 0; R.pixelBad = []; R.pixelColumns = {}; R.steps = {}; R.rowOneChecks = 0; R.rowOneBad = [];
  R.ifsymChecks = 0;                                              // the checks above that fell on an ifsym cell
  R.rowOneLines = 0; R.lineZones = 0; R.lineBad = []; R.rowTwoChecks = 0; R.rowTwoSkips = 0; R.rowTwoBad = [];
  R.labelDraws = [labels(R.views[0])];
  checkRowOne(R.views[0], 0);
  checkRowTwo(R.views[0], 0);
  // A hover at the middle of every device px across row 1 of the full view: the n read out, left to right, each once.
  R.across = [];
  for (let X = PL; X < PR; X++) { const c = cellOf(hover((X + 0.5) / dpr, yProbe)); R.across.push(c && c[0]); }
  R.across = R.across.filter((n, i, a) => i === 0 || n !== a[i - 1]);
  sampleHovers(R.views[0], OPTS.hoverEvery);
  // Sweep: zoom in, go to the left end, and step right by 3/4 of a view at a time to the right end.
  cv.focus();
  for (let i = 0; i < 7; i++) key('+');
  for (let i = 0; i < 300; i++) key('ArrowLeft');
  for (let guard = 0; guard < 100; guard++) {
    const v = view();
    R.views.push(v);
    sampleHovers(v, OPTS.hoverEvery);
    checkPixels(v);
    checkRowOne(v, R.views.length - 1);
    checkRowTwo(v, R.views.length - 1);
    R.labelDraws.push(labels(v));
    if (v.u0 + v.span > NCOL - 1e-6) break;
    for (let i = 0; i < 6; i++) key('ArrowRight');
  }
  R.pixelColumns = Object.keys(R.pixelColumns).map(Number).sort((a, b) => a - b);
  // Zoomed in step by step until columns are wider than 4 CSS px (3 steps at 1280 px, about 6 px wide): the column
  // lines part drawn
  reset.click();
  let mid = view();
  for (let i = 0; i < 12 && (PR - PL) / mid.span / dpr <= 4; i++) { key('+'); mid = view(); }
  { const v = mid, zones = lineZones(v);
    R.midWidth = (PR - PL) / v.span / dpr; R.midZones = zones.length;
    hover(middleX(v, first(v)), rowY(T) / dpr); snap(); checkZones(zones, ringBands(v, 1), 'mid'); }
  // The cell read out is outlined in ink, just outside it.
  reset.click();
  for (let i = 0; i < 5; i++) key('+');
  {
    const v = view(), k = v.span / (PR - PL), j = Math.round(v.u0 + v.span / 2), n = COLS[j - 1], m = 2;
    R.outlineText = hover((PL + (j - 0.5 - v.u0) / k) / dpr, rowY(m) / dpr);
    snap();
    R.outline = {n, m, want: colorOf(n, m), ink: C.ink, middle: pix(PL + Math.floor((j - 0.5 - v.u0) / k), Math.floor(rowY(m))),
                 left: pix(leftBand(PL + (j - 1 - v.u0) / k, bandAt(k)), Math.floor(rowY(m))),
                 right: pix(rightBand(PL + (j - v.u0) / k, bandAt(k)), Math.floor(rowY(m)))};
  }
  // Interactions, each from a view zoomed in 3 steps about the middle unless said otherwise.
  const zoomed = () => { reset.click(); for (let i = 0; i < 3; i++) key('+'); };
  zoomed(); step('right', () => key('ArrowRight'));
  zoomed(); step('left', () => key('ArrowLeft'));
  zoomed(); step('plus', () => key('+'));
  zoomed(); step('equals', () => key('='));
  zoomed(); step('minus', () => key('-'));
  zoomed(); step('down', () => key('ArrowDown'));
  zoomed(); step('ctrlPlus', () => key('+', {ctrlKey: true}));
  zoomed(); step('metaRight', () => key('ArrowRight', {metaKey: true}));
  zoomed(); step('ctrlWheel', () => wheel(L + 0.3 * W, {deltaY: -100, ctrlKey: true}));
  zoomed(); step('metaWheel', () => wheel(L + 0.3 * W, {deltaY: 50, metaKey: true}));
  zoomed(); step('lineWheel', () => wheel(L + 0.3 * W, {deltaY: -3, deltaMode: 1, ctrlKey: true}));
  zoomed(); step('sideWheel', () => wheel(L + 0.3 * W, {deltaX: 60, deltaY: 5}));
  zoomed(); step('upWheel', () => wheel(L + 0.3 * W, {deltaY: 100, deltaX: 2}));
  zoomed(); step('drag', () => { ptr('pointerdown', L + 0.6 * W, yProbe, {buttons: 1});
    ptr('pointermove', L + 0.6 * W - 100, yProbe, {buttons: 1}); ptr('pointerup', L + 0.6 * W - 100, yProbe, {}); return 100; });
  zoomed(); step('pinch', () => { touch('pointerdown', 11, L + 0.4 * W); touch('pointerdown', 12, L + 0.6 * W);
    touch('pointermove', 11, L + 0.3 * W); touch('pointermove', 12, L + 0.7 * W);
    touch('pointerup', 11, L + 0.3 * W); touch('pointerup', 12, L + 0.7 * W); return [0.2 * W, 0.4 * W, 0.5 * W]; });
  zoomed(); step('swipe', () => { touch('pointerdown', 13, L + 0.5 * W); touch('pointermove', 13, L + 0.3 * W);
    touch('pointerup', 13, L + 0.3 * W); return 0.2 * W; });
  zoomed(); step('gesture', () => [gesture('gesturestart', 1, L + 0.25 * W), gesture('gesturechange', 2, L + 0.25 * W),
    gesture('gestureend', 2, L + 0.25 * W), 0.25 * W]);
  zoomed(); step('gestureWhileTouching', () => { touch('pointerdown', 21, L + 0.5 * W);
    const p = [gesture('gesturestart', 1, L + 0.25 * W), gesture('gesturechange', 2, L + 0.25 * W)];
    touch('pointerup', 21, L + 0.5 * W); return p; });
  zoomed(); step('reset', () => { key('ArrowRight'); key('+'); reset.click(); });
  zoomed(); step('zoomInFar', () => { for (let i = 0; i < 40; i++) key('+'); });
  R.labelDraws.push(labels(R.steps.zoomInFar.b));
  zoomed(); step('zoomOutFar', () => { for (let i = 0; i < 40; i++) key('-'); });
  zoomed(); step('panFar', () => { for (let i = 0; i < 300; i++) key('ArrowRight'); });
  zoomed(); step('wheelOutFar', () => wheel(L + 0.5 * W, {deltaY: 5000, ctrlKey: true})[0]);
  // A tap reads out the cell under it, and so does a mouse click.
  zoomed();
  {
    const v = view(), x = L + 0.37 * W, k = v.span / W;
    hover(L + 0.8 * W, rowY(5) / dpr);
    touch('pointerdown', 14, x); touch('pointerup', 14, x);
    R.tap = {want: [COLS[Math.floor(v.u0 + (x - L) * k)], 1], text: ro.textContent};
    ptr('pointerup', L + 0.2 * W, yProbe, {pointerId: 99});        // an up with no down: nothing happens
    R.tap.after = ro.textContent;
    const x2 = L + 0.63 * W;
    hover(L + 0.8 * W, rowY(5) / dpr);
    ptr('pointerdown', x2, yProbe, {buttons: 1}); ptr('pointerup', x2, yProbe, {});
    R.click = {want: [COLS[Math.floor(v.u0 + (x2 - L) * k)], 1], text: ro.textContent};
    R.clickPanel = panelReport();                                  // the panel the click opened ([REO], 2026-11-03)
  }
  // The zoom buttons: a click of each from a view zoomed in 3 steps; then, from the full view, clicks of + until it is
  // disabled and then of − until it is disabled, the view measured after each.
  try {
    zoomed(); step('zoomInButton', () => zin.click());
    zoomed(); step('zoomOutButton', () => zout.click());
    reset.click();
    R.clicks = [['start', view(), disabled()]];
    for (const [b, kind] of [[zin, 'in'], [zout, 'out']]) {
      for (let i = 0; i < 40 && !b.disabled; i++) { b.click(); R.clicks.push([kind, view(), disabled()]); }
    }
  } catch (e) { R.buttonsError = String(e && e.stack || e); }
  // The tags (q_axes_tag_the_cell_read_out), each from the draw of a hover, with the view and the readout then: in the
  // full view, its four corners (its first and last columns, in rows 1 and T) and a cell in the middle; in a view
  // zoomed in 7 steps and panned right ten eighths of it, the same at the plot's very ends, where its columns are cut
  // (the first's middle out of view, the last's in), then its first whole column in row 2; then (tagAway) that view
  // panned right by a whole view with the keys alone, from the draw of the last press.  (5 steps and an eighth until
  // 2026-11-12, when the chart came to open with 142 columns: that view's first column showed a hundredth of itself,
  // under a device px on a phone, and 3 steps and three eighths cut it at 0.74 and the last at 0.82; 7 steps and ten eighths
  // since 2026-11-29, with the 270 columns of the cap of 4096: 3 steps make 80 of them, whole at both ends, and these cut the first at 0.85 and the last at 0.65.)
  R.tagHovers = [];
  const tagHover = (v, x, m) => { __fills.length = 0; const text = hover(x, rowY(m) / dpr); R.tagHovers.push({v, text, rows, ...tags()}); };
  const tagCorners = v => [[L + 0.25, 1], [L + 0.25, T], [L + W - 0.25, T], [L + W - 0.25, 1], [L + W / 2, 3]]
    .forEach(([x, m]) => tagHover(v, x, m));
  reset.click();
  tagCorners(view());
  for (let i = 0; i < 7; i++) key('+');
  for (let i = 0; i < 10; i++) key('ArrowRight');
  {
    const v = view();
    tagCorners(v);
    tagHover(v, middleX(v, first(v)), 2);
    for (let i = 0; i < 7; i++) key('ArrowRight');
    __fills.length = 0;
    key('ArrowRight');
    const text = ro.textContent, t = tags();
    R.tagAway = {before: R.tagHovers.at(-1).text, text, rows, ...t, v: view()};
  }
  // (2026-11-19) The strips: in the full view, a hover on the cell in row 3 at the plot's middle, then straight down
  // onto the strip of the n labels, 10 CSS px below the plot's bottom (strips.column), then onto the strip of the m
  // labels at row 12, 10 CSS px left of the plot (strips.row): after each, the readout, the tags, and the pixels where
  // the outlines go: the cell's top edge, above it in its column, and its left edge, left of it in its row; its
  // column's left edge, left of it in rows 1 and T; and row 12's top edge, above it at the plot's middle and a quarter
  // of the way in.
  if (OPTS.strips) {                                               // (the real data's runs: made-up data has 8 rows)
    reset.click();
    const v = view(), x = L + W / 2, text = hover(x, rowY(3) / dpr), [n0] = cellOf(text), j = colOf.get(n0);
    const x0 = PL + (j - 1 - v.u0) * (PR - PL) / v.span, xm = PL + (j - 0.5 - v.u0) * (PR - PL) / v.span;
    const rings = () => { snap(); return {
      cell: [pix(Math.floor(xm), rows[T - 3][0] - dpr), pix(leftBand(x0, bandAt(v.span / (PR - PL))), Math.floor(rowY(3)))],   // (pix here takes whole px)
      column: [pix(leftBand(x0, bandAt(v.span / (PR - PL))), Math.floor(rowY(1))), pix(leftBand(x0, bandAt(v.span / (PR - PL))), Math.floor(rowY(T)))],
      // (a quarter and three quarters of the way across since 2026-11-23, a harness fix: at the plot's middle, until then,
      // column N, hovered there, has its outline, which since then is filled in whole device px and can reach the probe)
      row: [pix(Math.floor(PL + 3 * (PR - PL) / 4), rows[T - 12][0] - dpr), pix(Math.floor(PL + (PR - PL) / 4), rows[T - 12][0] - dpr)]}; };
    R.strips = {n: n0, cell: {text, ...rings()}};
    __fills.length = 0;
    R.strips.column = {text: hover(x, axisTop / dpr + 10), ...tags(), ...rings()};
    __fills.length = 0;
    R.strips.row = {text: hover(PL / dpr - 10, rowY(12) / dpr), ...tags(), ...rings()};
  }
}
// The panel of the m*(n) chart's columns ([REO], 2026-11-03), or of the chart of powers of 2's (id), as it stands:
// whether it is hidden, the page's fragment, whether its heading has the focus and which element has it, the kinds of
// its texts (data-why) in order, its generated text with each formula KaTeX drew written back as its TeX, \( ... \),
// its links' hrefs, KaTeX's error marks in it, and the page's width then.  Since [REO] step 2 (2026-11-03) a panel
// also shows the remarks' entry of its length, the li that holds its p.entry, moved in: the generated text and links
// leave out the entries it shows, and the report gives their p.entry ids (entries) and texts (entryText) apart, with
// the ids of the p.entry still in the remarks' list, in order (listed), the ids that two elements of the page share
// (dups), and the fold of the list (fold): whether it is there, open and shown.  Since 2026-11-04 ([CEL], [ROC]) also the
// box's kind (data-kind: the kind of the cell clicked, column or row), its parts as [kind, text, whether it is of
// Claude's English: data-claude] (parts), its copies of
// codes (copies: [data-join, data-order, role, digits]) and its constructions (constructions: [data-construction,
// role, TeX]).  Since 2026-11-18 (the appendix: "Appendix: Everything Known About Every Length"; dreeves: "i see that
// many of the boxes that pop up when you click a cell are missing witnesses. so make everything consistent and
// complete") a box's parts are its entry's facts, the li's own [data-why] children, then its body's (PARTS): the
// generated text keeps the facts and leaves out the rest of the entry, its heading and its notes by hand; the entries'
// list and fold are the appendix's.  Later that day (dreeves: "the whole point was to show just the information for the
// cell (unless you click the number for the whole column)") a cell's box hides its entry's facts (page/style.css), so
// that its parts, kinds (whys), text and links are those it shows (showing).
const HELD = 'li:has(> p.entry)';                                  // an entry, wherever it is
const PARTS = '[data-panel-entries] > li > [data-why], [data-panel-body] > [data-why]';   // a box's parts, in order, shown or not
const showing = e => getComputedStyle(e).display !== 'none';       // a part the box shows (a closed box's too)
function panelReport(id = 'mstar-panel') {
  const region = document.getElementById(id), c = region.cloneNode(true);
  const hid = [...region.querySelectorAll('[data-why]')].map(e => !showing(e));   // in document order, as the clone's
  c.querySelectorAll('.katex').forEach(k => k.replaceWith(`\\(${k.querySelector('annotation').textContent}\\)`));
  const held = [...c.querySelectorAll(HELD)], entryText = held.map(li => li.textContent.replace(/\s+/g, ' ').trim());
  // (by its first length since 2026-11-18, entry-N, when a box came to show a copy of the entry, with no id: its id until then)
  const entries = held.map(li => `entry-${li.querySelector('p.entry').dataset.lengths.split(' ')[0]}`);   // before the headings go
  [...c.querySelectorAll('[data-why]')].filter((_, i) => hid[i]).forEach(e => e.remove());
  held.forEach(li => [...li.children].filter(e => !e.hasAttribute('data-why')).forEach(e => e.remove()));
  c.querySelectorAll(PARTS).forEach(e => e.append(' '));         // parts are blocks: their texts apart, as on the page
  const ids = [...document.querySelectorAll('[id]')].map(e => e.id), fold = document.querySelector('section.appendix details');
  const parts = [...c.querySelectorAll(PARTS)];
  return {hidden: region.hidden, hash: location.hash, focus: document.activeElement === region.querySelector('h3'),
          active: document.activeElement.id, whys: [...region.querySelectorAll('[data-why]')].filter(showing).map(e => e.dataset.why),
          heading: c.querySelector('h3').textContent, text: c.textContent.replace(/\s+/g, ' ').trim(),
          links: [...c.querySelectorAll('a[href]')].map(a => a.getAttribute('href')),   // the clone's: no heading or note of an entry, no part hidden
          errors: region.querySelectorAll('.katex-error').length, scrollW: document.documentElement.scrollWidth,
          entries, entryText,
          listed: [...document.querySelectorAll('section.appendix ul.entries > li > p.entry')].map(p => p.id),
          dups: ids.filter((x, i) => ids.indexOf(x) !== i),
          fold: {there: fold !== null, open: fold?.open ?? null, shown: fold?.checkVisibility() ?? null},
          kind: region.dataset.kind ?? null,
          parts: parts.map(e => [e.dataset.why, e.textContent.replace(/\s+/g, ' ').trim(), e.hasAttribute('data-claude')]),
          codes: parts.flatMap(e => [...e.querySelectorAll('code')]).map(e => e.textContent.replace(/\s+/g, ' ').trim()),   // its code elements' texts (2026-11-16)
          copies: parts.flatMap(e => [...e.querySelectorAll('[data-join], code[data-code]')]).map(e => [e.dataset.join ?? e.dataset.code, e.dataset.order ?? e.dataset.code.split(':')[1], e.getAttribute('role'), e.textContent]),   // copies, and since 2026-11-18 examples' codes (data-code)
          constructions: parts.flatMap(e => [...e.querySelectorAll('[data-construction]')]).map(e => [e.dataset.construction, e.getAttribute('role'),
                                                                                                         e.textContent.trim()])};
}
// Every column's panel, opened by its fragment, nN, in turn (OPTS.panels; the run lifts Chrome's limit of 200 changes
// of a frame's address per 10 s, which these 514 changes pass in about 2 s), then the last one closed by its button
// (after); and the page loaded with a fragment, its panel open at load (OPTS.fragment): its report, then the report
// after Escape in its heading, and after the panel of n = 512 opened by its fragment and closed by its button.  Then
// ([REO] step 2, 2026-11-03) the entries' moves: 1024's panel again (again), a click on its code there (expanded: the
// code's aria-expanded and its box, in the panel or not, shown or not, its rows' k and marks), the powers-of-2 chart's
// panel of k = 10, n = 1024, whose entry is the same (crossed: both panels, and the box), its close button
// (crossClosed: both again), 512's panel and then 1024's while it is open (switched), and Escape (allClosed).
const hashed = h => new Promise(r => { addEventListener('hashchange', () => r(), {once: true}); location.hash = h; });
async function panels(R) {
  history.replaceState(null, '', location.pathname);
  R.innerW = innerWidth;
  R.panels = [];
  for (const n of COLS) { await hashed(`#n${n}`); R.panels.push({n, ...panelReport()}); }
  document.querySelector('#mstar-panel [data-panel-close]').click();
  R.after = panelReport();
}
async function fragment(R) {
  const region = document.getElementById('mstar-panel'), escape = () => new KeyboardEvent('keydown', {key: 'Escape', bubbles: true, cancelable: true});
  const key = escape();
  R.fragment = panelReport();
  region.querySelector('h3').dispatchEvent(key);
  R.escaped = {...panelReport(), prevented: key.defaultPrevented};
  await hashed('#n512');
  R.reopened = panelReport();
  region.querySelector('[data-panel-close]').click();
  R.closed = panelReport();
  await hashed('#n1024');
  R.again = panelReport();
  // (the panel's copy of the entry's code since 2026-11-18, data-code 1024:11, the code itself staying in the appendix;
  // until then the code, by its id, moved into the panel with its entry; connected: whether it is still in the page)
  const code = region.querySelector('code[data-code="1024:11"]');
  code.click();
  const box = () => document.getElementById(code.getAttribute('aria-controls'));
  const boxReport = () => ({expanded: code.getAttribute('aria-expanded'), connected: code.isConnected, inMstar: region.contains(box()),
    inPow2: document.getElementById('pow2-panel').contains(box()), inEntry: code.closest(HELD).contains(box()), shown: box()?.checkVisibility() ?? false,
    ks: [...box()?.querySelectorAll('[data-k]') ?? []].map(c => c.textContent), relations: [...box()?.querySelectorAll('[data-relation]') ?? []].map(c => c.textContent)});
  R.expanded = boxReport();
  await hashed('#k10');
  R.crossed = {mstar: panelReport(), pow2: panelReport('pow2-panel'), box: boxReport()};
  document.querySelector('#pow2-panel [data-panel-close]').click();
  R.crossClosed = {mstar: panelReport(), pow2: panelReport('pow2-panel'), box: boxReport()};
  await hashed('#n512');
  await hashed('#n1024');
  R.switched = panelReport();
  region.querySelector('h3').dispatchEvent(escape());
  R.allClosed = {mstar: panelReport(), pow2: panelReport('pow2-panel'), box: boxReport()};
}
// The boxes under the m*(n) chart (dreeves's README, 2026-11-03, [CEL] and [ROC]; since 2026-11-04, OPTS.boxes): in the
// chart's full view, located by its pixels as battery locates it, a click (pointerdown and pointerup) on each target of
// BOX_TARGETS in turn, [n, m] a cell, [n, null] the strip of the n labels under column n, [null, m] the strip of the m
// labels left of row m; then a hover on cell (4, 1), so that the outline of the cell read out leaves the target; then
// the box's report (boxReport): the panel's (panelReport), its kind (data-kind), its frame's color, its caret's middle
// and the middle there of the target's column (or of the m labels' strip), in CSS px from the viewport's left, its
// heading's swatch (classes, color, ring), its parts' kinds, the text of its parts of the kinds witness-* and proof-*
// (said, its math written back as TeX, Claude's quote with it where there is one), which of its parts are of Claude's
// English (claude: each part's data-claude),
// its copies of codes (data-join) and its constructions (data-construction), the searches' text, and the canvas's
// pixels where the target's outline goes, with the target's own color (its pixel at its middle, three quarters down its
// row, clear of the gold rings of the cells above and below and of its own gold dot).  Then (each with its report): the first
// target's box again, its code copy clicked (expanded: the box of the copy, its rows' k and marks); the box of cell
// (36, 2) and a click on its construction (derived: the derivation's rows and bound); the box of cell (528, 12) once
// its searches have loaded (searched); its close button (closed, with the pixels of its outline then); and the page's
// fragment set to #m16 and then #n1024m12 (hashed).
const BOX_TARGETS = [[1024, 8], [1024, 12], [528, 12], [480, 12], [480, 13], [480, 14], [672, 13], [240, 11], [1020, 4], [56, 6],
                     [36, 2], [80, 3], [16, 4], [1024, null], [null, 12], [null, 13], [null, 16]];   // [16, 4] since 2026-11-18
async function boxes(R) {
  const cv = document.getElementById('mstar-chart'), region = document.getElementById('mstar-panel');
  const tok = name => getComputedStyle(cv).getPropertyValue(name).trim().toLowerCase();
  const C = {exists: tok('--exists'), open: tok('--open'), impossible: tok('--impossible'), paper: tok('--paper'), ink: tok('--ink'),
             rule: tok('--rule')};
  R.tokens = C;
  const dpr = devicePixelRatio, ctx = cv.getContext('2d');           // T and rows: the last draw's (EARLY)
  let img = null;
  const snap = () => { img = ctx.getImageData(0, 0, cv.width, cv.height); };
  const pix = (X, Y) => { const i = (Math.floor(Y) * img.width + Math.floor(X)) * 4, d = img.data;
    return '#' + [d[i], d[i + 1], d[i + 2]].map(v => v.toString(16).padStart(2, '0')).join(''); };
  const hex = rgb => '#' + rgb.match(/\d+/g).slice(0, 3).map(v => (+v).toString(16).padStart(2, '0')).join('');
  snap();
  const runs = [];                                 // the rows: runs of pixels not paper down the middle device column
  for (let Y = 0, s = -1, X = cv.width >> 1; Y <= cv.height; Y++) {
    const on = Y < cv.height && pix(X, Y) !== C.paper;
    if (on && s < 0) s = Y;
    if (!on && s >= 0) { runs.push([s, Y]); s = -1; }
  }
  const measured = runs.slice(0, T), rowY = m => (rows[T - m][0] + rows[T - m][1]) / 2;   // device px
  if (JSON.stringify(measured) !== JSON.stringify(rows)) throw new Error('rows ' + JSON.stringify([measured, rows]));
  let PL = 0, PR = cv.width - 1;                   // the plot: the run of impossible pixels across row T
  while (pix(PL, rowY(T)) !== C.impossible) PL++;
  while (pix(PR, rowY(T)) !== C.impossible) PR--;
  PR++;
  const k = NCOL / (PR - PL), colOf = n => COLS.indexOf(n) + 1;     // columns per device px; column j from 1
  // (Spec change, Opus 5.5, 2026-11-23; dreeves: "can you do the experiments to pick the best answer to that question? if
  // it should be adaptive, that's ok": an outline's bands are a quarter of a cell's smaller side wide, from 1 to 2 CSS px,
  // probed at their middles, the band's edge rounded to a device px; 2 CSS px wide, probed 1 CSS px out, until then)
  const bandAt = k => Math.min(2 * dpr, Math.max(dpr, Math.round(Math.min(1 / k, Math.round(224 * dpr) / T - 1) / 4)));
  // the middles of a band left of the boundary at device x and right of it: its bands hold the px floor(x) and b - 1 more
  // beyond it (since 2026-11-23, when dreeves saw a ring's sides differ; until then the boundary rounded, then b px)
  const leftBand = (x, b) => Math.floor(x + 0.5 - b / 2), rightBand = (x, b) => Math.floor(x - 0.5 + b / 2);
  const x0 = j => PL + (j - 1) / k, x1 = j => PL + j / k;
  // where a target is, in device px of the canvas: a cell's middle; under column n, 10 CSS px below the plot; left of
  // row m, the middle of the strip left of the plot
  const placeOf = ([n, m]) => [n === null ? PL / 2 : (x0(colOf(n)) + x1(colOf(n))) / 2, m === null ? rows[T - 1][1] + 10 * dpr : rowY(m)];
  const ptr = (type, X, Y, o) => { const r = cv.getBoundingClientRect();
    cv.dispatchEvent(new PointerEvent(type, {clientX: r.left + X / dpr, clientY: r.top + Y / dpr, pointerId: 1, pointerType: 'mouse',
      buttons: 0, bubbles: true, cancelable: true, ...o})); };
  const click = t => { const [X, Y] = placeOf(t); ptr('pointerdown', X, Y, {buttons: 1}); ptr('pointerup', X, Y, {}); };
  const away = () => { const [X, Y] = placeOf([4, 1]); ptr('pointermove', X, Y, {}); };
  const tex = e => { const c = e.cloneNode(true);
    c.querySelectorAll('.katex').forEach(x => x.replaceWith(`\\(${x.querySelector('annotation').textContent}\\)`));
    return c.textContent.replace(/\s+/g, ' ').trim(); };
  // the pixels where target t's outline goes, just outside its cells: for a cell, left and right of it in its row;
  // for a column, left of it in rows 1 and T; for a row, above it at the plot's middle and a quarter of the way in
  const outlinePixels = ([n, m]) => { snap(); return n === null
    ? [pix((PL + PR) / 2, rows[T - m][0] - dpr), pix(PL + (PR - PL) / 4, rows[T - m][0] - dpr)]
    : m === null ? [pix(leftBand(x0(colOf(n)), bandAt(k)), rowY(1)), pix(leftBand(x0(colOf(n)), bandAt(k)), rowY(T))]
    : [pix(leftBand(x0(colOf(n)), bandAt(k)), rowY(m)), pix(rightBand(x1(colOf(n)), bandAt(k)), rowY(m))]; };
  const body = () => region.querySelector('[data-panel-body]');
  // A table's look (2026-11-18, when Table 5's row in a row's box came out unruled and stretched): how it collapses
  // its borders and sits in its grid, and its first th's and td's border, padding, alignment and weight
  const look = t => { const cell = c => { const z = getComputedStyle(c); return [z.borderTopWidth, z.borderTopStyle, z.borderTopColor, z.paddingTop, z.paddingLeft, z.textAlign, z.fontWeight]; };
    return [getComputedStyle(t).borderCollapse, getComputedStyle(t).justifySelf, cell(t.querySelector('th')), cell(t.querySelector('td'))]; };
  function boxReport(t) {
    const before = getComputedStyle(region, '::before'), b = region.getBoundingClientRect(), r = cv.getBoundingClientRect();
    const parts = [...region.querySelectorAll(PARTS)].filter(showing);   // its entry's facts, then its body's parts, as it shows them (2026-11-18)
    const sw = region.querySelector('h3 .swatch'), said = parts.filter(e => /^(witness|proof)/.test(e.dataset.why));
    snap();
    return {target: t, ...panelReport(), frame: hex(getComputedStyle(region).borderTopColor),
      caret: b.left + region.clientLeft + parseFloat(before.left) + parseFloat(before.borderLeftWidth),
      column: r.left + placeOf(t)[0] / dpr,
      own: t.includes(null) ? null : pix(placeOf(t)[0], rows[T - t[1]][0] + (rows[T - t[1]][1] - rows[T - t[1]][0]) * 3 / 4),   // clear of rings and dots
      swatch: sw && {cls: sw.className, color: hex(getComputedStyle(sw).backgroundColor), ring: getComputedStyle(sw).boxShadow},
      said: said.map(tex).join(' '),
      claude: parts.map(e => e.hasAttribute('data-claude')),
      copies: parts.flatMap(e => [...e.querySelectorAll('[data-join], code[data-code]')]).map(e => [e.dataset.join ?? e.dataset.code, e.dataset.order ?? e.dataset.code.split(':')[1], e.getAttribute('role'), e.textContent]),
      constructions: parts.flatMap(e => [...e.querySelectorAll('[data-construction]')]).map(e => [e.dataset.construction, e.getAttribute('role'), tex(e)]),
      searches: [...body().querySelectorAll('[data-why="searches"]')].map(e => e.innerText),
      tables: [...body().querySelectorAll('table')].map(table => [...table.rows].map(tr => [...tr.cells].map(tex))),
      looks: [...body().querySelectorAll('table')].map(look),       // its tables' looks (2026-11-18)
      cells: [...body().querySelectorAll('[data-why="row-cell"]')].map(p => [p.querySelector('.swatch').className,   // a row's cells (2026-11-18)
                                                                                [...p.querySelectorAll('a[href]')].at(-1).getAttribute('href')]),
      outline: outlinePixels(t)};
  }
  R.table3 = [...document.querySelector('section.smallest table').rows].map(tr => [...tr.cells].map(tex));
  R.table5 = [...document.getElementById('symmetry-table').closest('table').rows].map(tr => [...tr.cells].map(tex));   // (2026-11-18)
  R.table5proofs = [...document.getElementById('symmetry-table').closest('table').tBodies[0].rows].map(tr => tr.dataset.proof ?? null);
  R.looks = {smallest: look(document.querySelector('section.smallest table')), symmetry: look(document.getElementById('symmetry-table').closest('table'))};
  R.table4 = [...document.querySelector('[data-record-gaps]').querySelectorAll('thead tr, tbody tr')].map(tr => [...tr.cells].map(tex));
  // until the box's searches, if it has any, have loaded (at most 5 s)
  const loaded = async () => { for (let i = 0; i < 100 && [...body().querySelectorAll('[data-why="searches"] > div')].some(d => !d.childNodes.length); i++) await new Promise(r => setTimeout(r, 50)); };
  R.boxes = [];
  for (const t of BOX_TARGETS) {
    click(t);
    await loaded();
    away();
    R.boxes.push(boxReport(t));
  }
  // the first target's code copy, expanded (each of these two reports null where the box has no such button)
  click(BOX_TARGETS[0]);
  R.expanded = [...body().querySelectorAll('[data-join], code[data-code]')].slice(0, 1).map(copy => {   // or a code, 2026-11-18
    copy.click();
    const shown = document.getElementById(copy.getAttribute('aria-controls'));
    return {expanded: copy.getAttribute('aria-expanded'), inBox: region.contains(shown), shown: shown.checkVisibility(),
            ks: [...shown.querySelectorAll('[data-k]')].map(c => c.textContent),
            relations: [...shown.querySelectorAll('[data-relation]')].map(c => c.textContent)};
  })[0] ?? null;
  // a construction's derivation
  click([36, 2]);
  R.derived = [...body().querySelectorAll('[data-construction]')].slice(0, 1).map(built => {
    built.click();
    const steps = document.getElementById(built.getAttribute('aria-controls'));
    return {expanded: built.getAttribute('aria-expanded'), inBox: region.contains(steps), shown: steps.checkVisibility(),
            parts: [...steps.querySelectorAll('[data-part-order]')].map(x => [x.dataset.n, x.dataset.m]),   // (2026-11-18: its rows and bound until then)
            lines: [...steps.querySelectorAll(':scope > p')].map(x => x.textContent.replace(/\s+/g, ' ').trim()), claim: [steps.dataset.n, steps.dataset.m]};
  })[0] ?? null;
  // the searches of an open cell, once loaded
  click([528, 12]);
  await loaded();
  away();
  R.searched = boxReport([528, 12]);
  region.querySelector('[data-panel-close]').click();
  R.closed = {...panelReport(), outline: outlinePixels([528, 12])};
  // (2026-11-19) the mouse off the chart: the events a browser sends as it leaves the canvas, after a hover on (1024, 8),
  // and after a click on (528, 12), as on its way to the close button of the box that opened, which is then clicked;
  // the pixels where the cell's outline goes after each step (left)
  const leave = () => { const r = cv.getBoundingClientRect(), at = {clientX: r.left + r.width / 2, clientY: r.top - 12};
    ['pointerout', 'pointerleave'].forEach(type => cv.dispatchEvent(new PointerEvent(type, {...at, pointerId: 1, pointerType: 'mouse'})));
    ['mouseout', 'mouseleave'].forEach(type => cv.dispatchEvent(new MouseEvent(type, at))); };
  ptr('pointermove', ...placeOf([1024, 8]), {});
  R.left = {hovered: outlinePixels([1024, 8])};
  leave();
  R.left.left = outlinePixels([1024, 8]);
  click([528, 12]);
  await loaded();
  leave();
  R.left.open = outlinePixels([528, 12]);
  region.querySelector('[data-panel-close]').click();
  R.left.closed = outlinePixels([528, 12]);
  await hashed('#m16');
  R.hashed = [boxReport([null, 16])];
  await hashed('#n1024m12');
  R.hashed.push(boxReport([1024, 12]));
}
// The page loaded with a box's fragment (OPTS.boxFragment, 2026-11-04): its box as the page shows it then.
async function boxFragment(R) {
  R.atLoad = {...panelReport(), kind: document.getElementById('mstar-panel').dataset.kind};
}
// The appendix (2026-11-18; dreeves: "Appendix: Everything Known About Every Length"), as the page loads, before anything
// is clicked (OPTS.appendix): the classes of the sections right before and after it, whether its fold is open, its
// title, the entries left in the section "Where the new results come from" (remarks), and each entry of its list in
// order: the lengths its heading lists (data-lengths), its heading (its math as TeX), its facts, [data-why, data-n], and
// how many of its children are neither its heading, its mark nor a fact: notes, by hand
function appendixReport() {
  const s = document.querySelector('section.appendix');
  if (s === null) return null;
  const tex = e => { const c = e.cloneNode(true);
    c.querySelectorAll('.katex').forEach(x => x.replaceWith(`\\(${x.querySelector('annotation').textContent}\\)`));
    return c.textContent.replace(/\s+/g, ' ').trim(); };
  return {prev: s.previousElementSibling?.className ?? null, next: s.nextElementSibling?.className ?? null,
    open: s.querySelector('details').open, title: tex(s.querySelector('h2')),
    remarks: document.querySelectorAll('section.remarks p.entry').length,
    entries: [...s.querySelectorAll('ul.entries > li')].map(li => {
      const p = li.querySelector(':scope > p.entry');
      return {lengths: p?.dataset.lengths ?? null, heading: p && tex(p),
        facts: [...li.querySelectorAll(':scope > [data-why]')].map(e => [e.dataset.why, e.dataset.n ?? null]),
        notes: [...li.children].filter(e => e !== p && !e.hasAttribute('data-why') && !e.classList.contains('mk')).length};
    })};
}
// The appendix opened, then closed again (OPTS.appendix): KaTeX's drawing of its entries' math, which waits for the
// fold's first opening (page/math.js): the formulas drawn in its list before and after, and KaTeX's errors there
async function openAppendix() {
  const d = document.querySelector('section.appendix details'), list = d.querySelector('ul.entries');
  const before = list.querySelectorAll('.katex').length;
  d.open = true;
  await new Promise(r => d.addEventListener('toggle', r, {once: true}));
  const out = {before, after: list.querySelectorAll('.katex').length, errors: list.querySelectorAll('.katex-error').length};
  // (2026-11-18) the code of 12:3 in its entry, BGPW's Table 4 example, clicked: its digits and its partition's parts,
  // power sums' k and marks
  const twelve = list.querySelector('#entry-12').closest('li').querySelector('code[data-code="12:3"]');
  twelve.click();
  const shown = document.getElementById(twelve.getAttribute('aria-controls'));
  out.twelve = {digits: twelve.textContent, expanded: twelve.getAttribute('aria-expanded'), shown: shown.checkVisibility(),
    parts: [...shown.querySelectorAll('[data-part]')].map(e => e.textContent), ks: [...shown.querySelectorAll('[data-k]')].map(e => e.textContent),
    relations: [...shown.querySelectorAll('[data-relation]')].map(e => e.textContent),
    heights: [...shown.querySelectorAll('.partition-part')].map(e => [e.clientHeight, e.scrollHeight])};   // (2026-11-18)
  d.open = false;
  return out;
}
const R = {errors: window.__errors, opts: OPTS};
const go = async () => {
  try {
    if (OPTS.appendix) { R.appendix = appendixReport(); R.appendixOpened = R.appendix && await openAppendix(); }
    if (OPTS.fragment) await fragment(R);
    else if (OPTS.panels) await panels(R);
    else if (OPTS.boxes) await boxes(R);
    else if (OPTS.boxFragment) await boxFragment(R);
    else battery(R);
  } catch (e) { R.harnessError = String(e && e.stack || e); }
  R.texts = [...new Set(window.__texts)];
  parent.postMessage(JSON.stringify(R), '*');
};
const NCOL = __NCOL__, COLS = __COLUMNS__;                         // the columns' n as the page loads (COLUMNS)
addEventListener('load', () => document.fonts.ready.then(() => setTimeout(go, 50)));
})();
</script>
"""


# Headless Chrome's window is at least 500 px wide, so the page runs in an iframe as wide as the configuration asks;
# the harness posts its report to this host page, which writes it into its own DOM for --dump-dom.
HOST = """<!doctype html>
<html><head><meta charset="utf-8"></head><body style="margin: 0">
<iframe src="index.html" style="display: block; border: 0; width: __WIDTH__px; height: 1000px"></iframe>
<script>
addEventListener('message', e => {
  const pre = document.createElement('pre'); pre.id = 'harness-out'; pre.textContent = e.data; document.body.append(pre);
});
</script>
</body></html>
"""


IFSYM_FILE = 'proofs/symtree.py'              # the program that checks the symmetric-only proofs (mstar.SYMTREE), for made-up data


def real_past():
    """mstar.js's past, the sequences past the chart, as the page's data has it.  The made-up data takes it, as it takes
    the real nmax, for the real pow2.js beside it, whose joins use sequences past the chart since 2026-11-19 (Opus 5.5;
    page/pow2-section.js's LONG; q_sequences_past_the_chart_move_seven_firsts)."""
    s = open(DATA, encoding='utf-8').read()
    return json.loads(s[s.index('{'):s.rindex('}') + 1])['past']


def kinds_columns():
    """The in-chart rows of the made-up chart."""
    cols = []
    for n in range(1, DATA_NMAX + 1):
        two = (n & -n) - 1
        cols.append([0, 0, ['none'], ['odd']] if n % 2 else
                    [1, two, ['example', 'a made-up label'], ['two']] if two <= 7 else
                    [1, 7, ['example', 'a made-up label'], ['residue', 3]])
    for n, c in ((4, [2, 2, ['product', 2, 2], ['norm', 3]]), (8, [3, 3, ['table2'], ['table2']]),
                 (12, [2, 3, ['join', 4, 4, 4], ['two']]), (16, [4, 4, ['page', 's'], ['page', 'j']]),
                 (20, [3, 3, ['page', 'c'], ['two']]), (24, [4, 5, ['example', 'BGPW Table 5'], ['residue', 9]]),
                 (32, [5, 7, ['example', 'a made-up label'], ['norm', 5]]), (48, [6, 7, ['table2'], ['norm', 7]]),
                 (40, [1, 6, ['example', 'a made-up label'], ['prop44']])):   # prop44: since 2026-11-11 (40 = 2^3 · 5 < 2^7)
        cols[n - 1] = c
    return cols


def kinds_past(cols):
    """Transport the real past constructions to the orders of their made-up factors."""
    rows = real_past()
    orders = {n: c[0] for n, c in enumerate(cols, 1)}
    for row in rows:
        n, _, _, reason, _ = row
        if reason[0] in ('product', 'join'):
            combine = {'product': sum, 'join': min}[reason[0]]
            row[1] = combine(orders[k] for k in reason[1:])
        orders[n] = row[1]
    return rows


def kinds_data(violation=None):
    """Made-up data that follows the contract and uses every kind of reason: odd columns are ["none"] and ["odd"]; an even
    n has lo = 1 from an example and hi = 2^v - 1 ("two") if that is at most 7, else 7 by the residue condition mod 3;
    a few columns use the other kinds.  violation, if given, names the change in VIOLATIONS that breaks it."""
    cols = kinds_columns()
    # ifsym (2026-11-11, [SYC]): the columns 24 and 48 each have their top open cell red if the Symmetry Conjecture
    # holds: (24, 5), which is ringed (24 is the least n whose upper bound allows 5), and (48, 7), which is not
    # (Since 2026-11-18, when the chart's joins came to be of three parts and the page to require a join's or a
    # product's parts to have a sequence behind them, as mstar.py does: 12 is the join 4 + 4 + 4, not 4 + 8, and 32 an
    # example, not the product of 16, cited, and 2.)
    # codes (2026-11-18): one for each example, of its form: n/8 hex digits rounded up, the left half all +1, the padding
    # 0 (page/codes.js checks the form as the page loads, the power sums only at a click, which no run of this data makes)
    # (past: the real one since 2026-11-19, real_past(); [] until then.  Its rows' examples have codes of that form too,
    # since that day's rows, [n, lo, hi, loWhy, hiWhy], each of a column's form, whose examples examples lists: past's
    # loWhy is an example at each of its lengths)
    past = kinds_past(cols)
    data = {'nmax': DATA_NMAX, 'mtop': max(c[1] for c in cols) + 1, 'mtopAt': [DATA_NMAX + 2], 'past': past,
            'ifsym': [[24, 4, IFSYM_FILE], [48, 6, IFSYM_FILE]],
            'examples': [[n, f"{int('1' * (n // 2) + '0' * (-(n // 2) % 4), 2):0{-(-n // 8)}X}", 'https://oeis.org/A010060']
                         for n, c in [*enumerate(cols, 1), *((n, c) for n, *c in past)] if c[2][0] == 'example'],   # (codes, [n, code], until point 10 that night)
            'cols': cols}
    VIOLATIONS.get(violation, (lambda data: None,))[0](data)
    return 'const MSTAR = ' + json.dumps(data) + ';\n'


def column(n, entry):
    """A change to made-up data: column n becomes entry."""
    def change(data): data['cols'][n - 1] = entry
    return change


VIOLATIONS = {   # name: (a change that breaks the contract, what the page's error line must quote)
    'lo above hi': (column(100, [5, 3, ['example', 'a made-up label'], ['two']]),
                    "[100,[5,3,['example','a made-up label'],['two']]]"),
    'unknown kind': (column(100, [1, 3, ['guess'], ['two']]), "[100,[1,3,['guess'],['two']]]"),
    'arity': (column(100, [1, 3, ['join', 50], ['two']]), "[100,[1,3,['join',50],['two']]]"),
    # (the joins of three parts since 2026-11-18; of two until then, 40 + 50 and 50 + 50)
    'join lengths': (column(100, [1, 3, ['join', 40, 10, 40], ['two']]), "[100,[1,3,['join',40,10,40],['two']]]"),
    'join order': (column(100, [3, 3, ['join', 25, 50, 25], ['two']]), "[100,[3,3,['join',25,50,25],['two']]]"),
    # (2026-11-18) a join's part with no sequence behind it: 8, whose lower bound is cited (table2)
    'join part': (column(100, [1, 3, ['join', 8, 84, 8], ['two']]), "[100,[1,3,['join',8,84,8],['two']]]"),
    'product order': (column(100, [3, 3, ['product', 50, 2], ['two']]), "[100,[3,3,['product',50,2],['two']]]"),
    'two': (column(100, [1, 2, ['example', 'x'], ['two']]), "[100,[1,2,['example','x'],['two']]]"),
    'norm divisor': (column(100, [1, 3, ['example', 'x'], ['norm', 5]]), "[100,[1,3,['example','x'],['norm',5]]]"),
    'norm composite': (column(100, [1, 3, ['example', 'x'], ['norm', 9]]), "[100,[1,3,['example','x'],['norm',9]]]"),
    # (2026-11-11) BGPW's Proposition 4.4 at a length it does not reach: 136 = 2^3 · 17 is not below 2^7
    'prop44 n': (column(136, [1, 6, ['example', 'x'], ['prop44']]), "[136,[1,6,['example','x'],['prop44']]]"),
    'table2 n': (column(100, [1, 3, ['table2'], ['two']]), "[100,[1,3,['table2'],['two']]]"),
    'page who': (column(100, [1, 3, ['page', 'Stan'], ['two']]), "[100,[1,3,['page','Stan'],['two']]]"),
    'empty label': (column(100, [1, 3, ['example', ''], ['two']]), "[100,[1,3,['example',''],['two']]]"),
    'none at even n': (column(100, [0, 3, ['none'], ['two']]), "[100,[0,3,['none'],['two']]]"),
    'odd at even n': (column(100, [0, 0, ['none'], ['odd']]), "[100,[0,0,['none'],['odd']]]"),
    'example at odd n': (column(99, [0, 0, ['example', 'x'], ['odd']]), "[99,[0,0,['example','x'],['odd']]]"),
    'five entries': (column(100, [1, 3, ['example', 'x'], ['two'], 0]), "[100,[1,3,['example','x'],['two'],0]]"),
    'hi at mtop': (column(100, [1, 8, ['example', 'x'], ['residue', 3]]), "[100,[1,8,['example','x'],['residue',3]]]"),
    'mtop': (lambda data: data.update(mtop=9), '[9]'),
    'nmax': (lambda data: data.update(nmax=999), '[999,8]'),
    'mtopAt': (lambda data: data.update(mtopAt=[NMAX]), f'[[{NMAX}]]'),   # not past the chart (since 2026-11-03, [LIN])
    # since 2026-11-04 ([M17]) a list, one n per order from mtop on, which cannot fall: order m + 1 at n has order m there
    'mtopAt falls': (lambda data: data.update(mtopAt=[NMAX + 4, NMAX + 2]), f'[[{NMAX + 4},{NMAX + 2}]]'),
    # an example not past the chart (since 2026-11-04), after the real ones since 2026-11-19 (real_past; alone until then);
    # a row of a column's form since that day (Opus 5.5; dreeves: "yes, full anti-magic, add the new entries"), [n, m,
    # label] until then
    'past': (lambda data: data.update(past=data['past'] + [[NMAX, 3, 3, ['example', 'x'], ['residue', 3]]]),
             '[' + json.dumps(kinds_past(kinds_columns()) + [[NMAX, 3, 3, ['example', 'x'], ['residue', 3]]], separators=(',', ':')).replace('"', "'") + ']'),
    # ifsym (since 2026-11-11, [SYC]): the key missing; a bound not below the column's own (48: 6 to 7); one below its
    # lower bound; a file that is no program of proofs/; and the columns not rising
    'ifsym missing': (lambda data: data.pop('ifsym'), "['ifsym',null]"),
    'ifsym hi': (lambda data: data.update(ifsym=[[48, 7, IFSYM_FILE]]), f"['ifsym',[48,7,'{IFSYM_FILE}']]"),
    'ifsym lo': (lambda data: data.update(ifsym=[[48, 5, IFSYM_FILE]]), f"['ifsym',[48,5,'{IFSYM_FILE}']]"),
    'ifsym file': (lambda data: data.update(ifsym=[[48, 6, 'symtree.py']]), "['ifsym',[48,6,'symtree.py']]"),
    'ifsym order': (lambda data: data.update(ifsym=[[48, 6, IFSYM_FILE], [24, 4, IFSYM_FILE]]), f"['ifsym',[24,4,'{IFSYM_FILE}']]"),
}


# The state a configuration's page loads the m*(n) chart in (2026-11-12): (its cap, its columns, the edits to the page
# that make it).  NOW is the page as it is: every box of the chart's list checked and the cap 2048 pressed (dreeves:
# "let's default to all checkboxes checked and cap=2^11 for figure 1").  BEFORE is every page until then, the first two
# boxes checked, the state that made-up data and the boxes' targets were made for: kinds_data's odd multiples of 4 and
# of 8 have the orders that the bound 'two' allows, not the 3 and 7 that the third and fourth boxes state, so that the
# page refuses it as it loads under NOW; and the targets (36, 2) and (1020, 4) are cells of odd multiples of 4, which the
# third box leaves out.  (Its cap was 1024 until 2026-11-23, when caps became views of every column, Opus 5.5, a harness
# fix: a page that loads under a lower cap opens with that cap's view of columns up to 2048, which the harness's columns,
# the chart's, would not match; BEFORE's columns are so every n up to 2048 that its two boxes leave in.)
# (Spec change, Opus 5.5, 2026-11-29; dreeves, of a cap at 4096: "worth it": both open on every column of the data, the largest cap pressed by an edit to the copy of the
# page: the page itself opens at CAP, 2048, which shows less.  Until then the page's own opening view was every column, NOW's cap CAP and no edit.)
PRESS_FULL = ((f'data-cap="{CAP}" aria-pressed="true"', f'data-cap="{CAP}" aria-pressed="false"'),
              (f'data-cap="{FULL}" aria-pressed="false"', f'data-cap="{FULL}" aria-pressed="true"'))
NOW = (FULL, COLUMNS, PRESS_FULL)
BEFORE = (FULL, [2] + list(range(4, FULL + 1, 4)), (
    (' data-order="3" checked>', ' data-order="3">'), (' data-order="7" checked>', ' data-order="7">')) + PRESS_FULL)
# BOXED is BEFORE at the page's own cap, 2048: the boxes' runs click cells, and read the pixels at their middles, where cells are 1.4 CSS px wide, as they were until 2026-11-29; the
# 1,025 columns of the cap of 4096 are half that, under a device px or two on either window, and the band of a ring or an outline lies on the middle of the cells beside its own.
BOXED = (CAP, [2] + list(range(4, CAP + 1, 4)), BEFORE[2][:2])
CONFIGS = {   # name: (mstar.js, window width, device pixel ratio, theme, hover every this many columns, state)
    'light': ('real', 1280, 2, None, 1, NOW),
    'phone': ('real', 390, 3, None, 5, NOW),
    'kinds': ('kinds', 1280, 2, None, 1, BEFORE),
    'missing': (None, 1280, 2, None, 1, NOW),
    'fragment': ('real', 1280, 2, None, 1, NOW),
    'phone fragment': ('real', 390, 3, None, 5, NOW),
    'panels': ('real', 1280, 2, None, 1, NOW),
    'phone panels': ('real', 390, 3, None, 5, NOW),
    'kinds panels': ('kinds', 1280, 2, None, 1, BEFORE),
    'boxes': ('real', 1280, 2, None, 1, BOXED),
    'phone boxes': ('real', 390, 3, None, 5, BOXED),
    'box fragment': ('real', 1280, 2, None, 1, NOW),
} | {f'violates {v}': (v, 1280, 1, None, 1, BEFORE) for v in VIOLATIONS}


def state(name):
    """(The cap, the columns) of the m*(n) chart as the configuration name's page loads."""
    return CONFIGS[name][5][:2]


def edited(text, edits):
    """The page's text with each (old, new) of edits made, each old found exactly once."""
    for a, b in edits:
        assert text.count(a) == 1, a
        text = text.replace(a, b)
    return text
PANELS = ('panels', 'phone panels', 'kinds panels')   # the configurations that open every column's panel in turn ([REO], 2026-11-03)
FRAGMENTS = {'fragment': '#n1024', 'phone fragment': '#n1024'}   # the configurations that load the page with a fragment
# the configurations that click the boxes' targets (the harness's boxes) and that load the page with a cell's fragment,
# each beside a made-up progress.js, BOX_PROGRESS (2026-11-04, [CEL] and [ROC])
BOXES, BOX_LOADS = ('boxes', 'phone boxes'), {'box fragment': '#n1024m12'}
SOURCES = {'real': lambda: open(DATA, encoding='utf-8').read(), 'kinds': kinds_data} | {
    v: (lambda v=v: kinds_data(v)) for v in VIOLATIONS}           # mstar.js's text, by CONFIGS's first entry


def run(name):
    """The harness's report for one configuration, made on first use."""
    if name not in RUNS:
        data, width, dpr, theme, every, (_, cols, edits) = CONFIGS[name]
        d = tempfile.mkdtemp(prefix='index-quals-')
        text = edited(page(), edits)
        assert text.count('<head>\n') == 1 and text.count('</body>') == 1 and text.count('<html lang="en">') == 1
        opts = {'hoverEvery': every, 'panels': name in PANELS, 'fragment': name in FRAGMENTS, 'boxes': name in BOXES,
                'boxFragment': name in BOX_LOADS, 'appendix': name == 'light', 'strips': name in ('light', 'phone')}
        text = text.replace('<head>\n', '<head>\n' + EARLY).replace('</body>', HARNESS.replace(
            '__OPTS__', json.dumps(opts)).replace('__NCOL__', str(len(cols))).replace('__COLUMNS__', json.dumps(cols)) + '</body>')
        if theme: text = text.replace('<html lang="en">', f'<html lang="en" data-theme="{theme}">')
        open(os.path.join(d, 'index.html'), 'w', encoding='utf-8').write(text)
        copy_page_dir(d)
        if data is not None: open(data_file(d, 'mstar.js'), 'w', encoding='utf-8').write(SOURCES[data]())
        shutil.copy(POW2, data_file(d, 'pow2.js'))
        if name in BOXES or name in BOX_LOADS:
            open(data_file(d, 'progress.js'), 'w', encoding='utf-8').write(progress_text(BOX_PROGRESS))
        open(os.path.join(d, 'host.html'), 'w').write(HOST.replace('__WIDTH__', str(width)).replace(
            'src="index.html"', f'src="index.html{(FRAGMENTS | BOX_LOADS).get(name, "")}"'))
        dom = chrome(d, ['--disable-ipc-flooding-protection'] * (name in PANELS) + [f'--window-size={max(width, 500) + 40},1100', f'--force-device-scale-factor={dpr}',
                         '--virtual-time-budget=10000', '--dump-dom', 'file://' + os.path.join(d, 'host.html')])
        m = re.search(r'<pre id="harness-out">(.*?)</pre>', dom, re.S)
        assert m, (name, dom[-3000:])
        RUNS[name] = json.loads(html.unescape(m.group(1)))
        shutil.rmtree(d)
    return RUNS[name]


def chrome(d, args, stderr=subprocess.DEVNULL):
    """Headless Chrome with its own profile in directory d: the DOM it dumps.  This Chrome prints the dump and then
    does not exit, so the dump is read up to </html> and then Chrome's own process group is ended (end_group), all of
    it, before d may go (a watchdog sends it SIGTERM after 600 s, and the dump is then incomplete, which the caller's
    assert reports).  It lets file URLs read file URLs (--allow-file-access-from-files, since 2026-10-31, when the page's
    scripts left index.html for page/): plain file:// gives each file an origin of its own, so an uncaught error thrown
    in page/ reached the page's error listeners only as "Script error.", with no error object; over http(s), where the
    page is served, its files share its origin and the error comes through whole, as it does here with the flag."""
    p = subprocess.Popen([CHROME, *HEADLESS, f'--user-data-dir={d}/profile', *args],
                         stdout=subprocess.PIPE, stderr=stderr, text=True, start_new_session=True)
    stop = lambda: os.killpg(p.pid, signal.SIGTERM)
    watchdog = threading.Timer(600, stop)
    watchdog.start()
    out = []
    for line in p.stdout:
        out.append(line)
        if '</html>' in line: break
    watchdog.cancel()
    end_group(p)
    return ''.join(out)


def alive(pgid):
    """Whether any process of the process group pgid remains: EPERM says some do, though none may be signalled, as a
    zombie not yet reaped (macOS)."""
    try: os.killpg(pgid, 0)
    except ProcessLookupError: return False
    except PermissionError: pass
    return True


def gone(pgid, seconds):
    """Whether the process group pgid is gone, waiting up to seconds for it to be."""
    end = time.monotonic() + seconds
    while alive(pgid) and time.monotonic() < end: time.sleep(0.1)
    return not alive(pgid)


def end_group(p, term=10, kill=5):
    """End the process group that p leads, p started in a session of its own: SIGTERM to the whole group, whether or
    not p has exited, since Chrome's helpers can outlive its main process for a moment, writing into the profile the
    caller deletes next (2026-10-26: "Directory not empty", twice); p reaped; then wait until no process of the group
    remains, SIGKILL after term seconds, and fail loudly if any of it outlives that by kill seconds."""
    for sig, seconds in ((signal.SIGTERM, term), (signal.SIGKILL, kill)):
        with contextlib.suppress(ProcessLookupError, PermissionError): os.killpg(p.pid, sig)   # none left, or none signallable
        with contextlib.suppress(subprocess.TimeoutExpired): p.wait(timeout=seconds)
        if gone(p.pid, seconds): return
    raise AssertionError(f'process group {p.pid} outlived SIGKILL')


def console_lines():
    """The lines Chrome logs from the page's console when it loads index.html as is, with page/ and the real mstar.js
    beside it."""
    d = tempfile.mkdtemp(prefix='index-quals-')
    shutil.copy(INDEX, os.path.join(d, 'index.html'))
    copy_page_dir(d)
    shutil.copy(DATA, data_file(d, 'mstar.js'))
    shutil.copy(POW2, data_file(d, 'pow2.js'))
    with open(os.path.join(d, 'stderr.txt'), 'w') as f:
        chrome(d, ['--enable-logging=stderr', '--v=0', '--window-size=1280,1000', '--virtual-time-budget=10000',
                   '--dump-dom', 'file://' + os.path.join(d, 'index.html')], stderr=f)
    lines = [line for line in open(os.path.join(d, 'stderr.txt'), errors='replace') if ':CONSOLE' in line]
    shutil.rmtree(d)
    return lines


def valid_run(name):
    """A run on valid data: the harness finished and nothing recorded an error."""
    R = run(name)
    assert 'harnessError' not in R, R['harnessError']
    assert R['errors'] == [], R['errors']
    return R


def close(a, b, tol): return abs(a - b) <= tol


# The section "The smallest length known for each order" (Stan Wagon's suggestion, relayed 2026-10-17: "keep track of a
# table that shows the first n that gives 1,2,3,4,5,…,12"; dreeves: "yeah").  Orders 1 to 11 have their smallest
# lengths proven: OEIS A323395's a(0) to a(8), 240 as a(9), and (2026-10-20) 432 as a(10), after proof384.py; and order 12 too, since 2026-11-03: 480 as a(11), after the pin tree of 432:12.
SMALLEST_PROVEN = (2, 4, 8, 16, 32, 48, 96, 144, 192, 240, 432, 480)
# The cells (n, m) proven least in the m*(n) chart as it loads: (960, 15) since 2026-11-03; (1440, 16) since 2026-11-12,
# when the chart came to open up to 2048 (dreeves: "cap=2^11 for figure 1"), 1440 being past its cap before.
PROVEN_CELLS = [(n, m) for m, n in enumerate(SMALLEST_PROVEN, 1)] + [(960, 15), (1440, 16)]


def smallest_rows(data):
    """The rows the section's script makes from MSTAR's cols, computed here: for each order m from 1 while some n's upper
    bound allows m (least_columns), the texts of m, the least length known to reach m, a check mark if that is also the
    least n whose upper bound is at least m (else nothing), and that least n.  (dreeves, 2026-10-30: "why isn't 480:14
    highlighted in the chart?"; until then the rows stopped at the largest order known at some n.)  The least length
    known is best[m] = min(the least n whose lower bound is at least m, best[a] best[m - a] for 0 < a < m), a product
    f(x) g(x^n), n the length of f, having order at least the sum of theirs (dreeves's README, 2026-10-31, [MIN]; until
    then — where no n up to NMAX was known to reach m).  Then a row for each order past the chart, from mtop, the order
    no n up to NMAX allows, each not ruled out first at its n of mtopAt, the least n past NMAX that the chart's own
    tests leave open at that order (mstar.mtop_at), and reached first at its least product (dreeves's README,
    2026-11-03: "[LIN] Add one more line for m=16 to the "smallest length known for each order" table", then "yes, 1440
    instead of ">1024" if that's all we know so far"; and 2026-11-04: "[M17] Let's add m=17 to the "smallest length
    known" table"; until 2026-11-03 the rows stopped at the largest order allowed, and until 2026-11-04 at mtop).  An
    example past the chart (mstar.js's past, since 2026-11-04) reaches its order at its own length, as a known n does,
    and so its length goes into the products of later orders (2880 = 1440 · 2 at order 17)."""
    cols, top, at = data['cols'], data['mtop'], data['mtopAt']
    rows = [(m, possible) for m, _, possible in least_columns(cols)] + [(top + i, n) for i, n in enumerate(at)]
    assert [m for m, _ in rows] == list(range(1, len(rows) + 1)), rows
    known = {m: n for m, n, _ in least_columns(cols) if n is not None}
    for n, m, *_ in data['past']: known[m] = min(known.get(m, math.inf), n)   # (past's rows, [n, lo, ...], since 2026-11-19)
    best = {}
    for m, _ in rows: best[m] = min([known.get(m, math.inf)] + [best[a] * best[m - a] for a in range(1, m)])
    assert all(type(b) is int for b in best.values()), best
    # in the chart's order, the n not ruled out before the n known, the check mark last ([FLP], 2026-10-31)
    return [[str(m), str(possible), str(best[m]), '✓' if best[m] == possible else ''] for m, possible in rows]


def a323395_cells(cols):
    """The cells (n, m) the chart rings in gold and dots (dreeves, 2026-10-19), the proven ones of least_columns, whose
    least n known to reach m is also the least not ruled out: the terms a(m − 1) of OEIS A323395 that the data proves."""
    return [(known, m) for m, known, possible in least_columns(cols) if known == possible]


def smallest_rings(cols):
    """The cells the m*(n) chart rings in gold (dreeves's README, 2026-10-30, [GLT]), the chart's own least columns
    (least_columns), the table of smallest lengths' cells up to NMAX (its lengths from products beyond the chart, since
    2026-10-31, have no column): {(n, m): role} for the least n known of each order m and the least n not ruled out for
    it, one cell when they agree; role 1 known, 2 not ruled out, 3 both, proven the least (a323395_cells)."""
    out = {}
    for m, known, possible in least_columns(cols):
        for n in {known, possible} - {None}: out[(n, m)] = (n == known) + 2 * (n == possible)
    return out


def ring_note(m):
    """The readout's note on a ringed cell of order m (Claude's words, without the Claude: "…")."""
    return f'the least n of order {m}: a({m - 1}) of OEIS A323395'


# ---------------------------------------------------------------------------------------------------------------------
# Static quals

def q_384_proof_is_linked():
    # Replicata: the new-results table and remarks, plus the generated chart's smallest-length rows.
    # Expectata: 384's cell is of Astra's class (a); its remark (li#proof384) links the standalone checker proof384.py
    # and gives m* = 10; and order 11 is now proven to have smallest length 432.
    text = page()
    assert re.search(r'<td class="a"[^>]*>384</td>', text)
    remark = re.search(r'<li class="a" id="proof384">(.*?)</li>', text, re.S)
    assert remark, 'no remark for 384'
    assert 'href="proofs/proof384.py"' in remark.group(1) and '\\(m^* = 10\\)' in remark.group(1), remark.group(1)[:300]
    assert smallest_rows(mstar_data())[10] == ['11', '432', '432', '✓']


def q_section_follows_table2():
    # Replicata: index.html.
    # Expectata: the page's one <figure> (Table 2) is followed, with only blank lines and comments between, by
    # <section class="mstar" aria-labelledby="mstar-title"> (and that by <section class="pow2" until 2026-10-30, when
    # dreeves put the smallest lengths between).  In order, the
    # section holds: a paragraph introducing the chart (dreeves's, which replaced the h2 mstar-title by 2026-10-27,
    # and since 2026-10-29 follows his h2 of that id and leads his list of the n left out);
    # a legend whose swatches are exists, open and impossible, then (since
    # 2026-10-19) exists ringed in gold for a(m − 1) of OEIS A323395; the reset
    # button; the canvas mstar-chart (height 0 until drawn, focusable, an image with a label); and the readout
    # paragraph mstar-readout, polite live region.  (dreeves's copyedit dropped the caption paragraph.)
    text = page()
    assert text.count('<figure>') == 1 and text.count('</figure>') == 1
    after = text[text.index('</figure>') + len('</figure>'):]
    filler = r'(?:\s|<!--.*?-->)*'
    m = re.match(filler + r'<section class="mstar" aria-labelledby="mstar-title">.*?</section>', after, re.S)
    assert m, after[:400]
    # Since 2026-11-11 ([SYC]) the swatch ifsym follows open's: q_legend_has_an_item_for_every_kind_of_cell has the whole list.
    parts = [r'<p>', r'<ul class="legend">', r'<span class="swatch exists" aria-hidden="true">',
             r'<span class="swatch open" aria-hidden="true">', r'<span class="swatch ifsym" aria-hidden="true">',
             r'<span class="swatch impossible" aria-hidden="true">',
             r'<span class="swatch exists record" aria-hidden="true">',
             r'</ul>', r'<span class="caps" id="mstar-caps">',     # the reset button until 2026-11-10 ([BOU])
             r'<canvas id="mstar-chart" height="0" tabindex="0" role="img" aria-label=',
             r'<p id="mstar-readout" aria-live="polite">']
    assert re.search('.*?'.join(parts), section(), re.S), section()


def q_changelog_sits_under_the_authors_as_in_freshat():
    # Replicata: index.html's header.
    # Expectata (dreeves, 2026-10-26: "can you add a skeleton of a changelog at the top of the page, modeled after
    # doc.bmndr.co/freshat"): as FreshAt's changelog follows its byline, a <details class="changelog"> follows the
    # byline, the lede lines next after the title, whatever his words there (one or more since 2026-10-29, dreeves:
    # "yes to allowing 2 lines for the byline"), with only comments between,
    # and has no open attribute, so it starts closed; a summary, and the rest entries and one-line comments (TODO
    # comments for entries in Claude's words, and, since 2026-11-09, whatever comments dreeves keeps: he rewrote two
    # entries and dropped their comments' "TODO:", which the parser had required); each entry a <p> on its own line,
    # "YYYY-MM-DD: what changed" as in FreshAt, a real date, newest first.
    # Resultata before: no changelog.
    dates = [d for d, _ in changelog()]
    assert dates and all(datetime.date.fromisoformat(d).isoformat() == d for d in dates), dates
    assert dates == sorted(dates, reverse=True), dates


def changelog():
    """The changelog's entries, newest first, as (date, the rest after "date: "), the changelog asserted to be of the
    form q_changelog_sits_under_the_authors_as_in_freshat holds it to."""
    head = re.search(r'<header>\n(.*?)\n</header>', page(), re.S)
    assert head, 'no header'
    m = re.match(r'  <h1>[^\n]*</h1>\n(?:  <p class="lede">[^\n]*</p>\n)+(?:  <!--[^\n]*-->\n)*'
                 r'  <details class="changelog">\n    <summary>[^\n]*</summary>\n(.*?)\n  </details>\n',
                 head.group(1) + '\n', re.S)
    assert m, head.group(1)[:800]
    lines = [l.strip() for l in m.group(1).split('\n') if not re.fullmatch(r'\s*<!--.*-->', l)]
    entries = [re.fullmatch(r'<p>(\d{4}-\d{2}-\d{2}): (\S.*)</p>', l) for l in lines]
    assert entries and all(entries), lines
    return [e.groups() for e in entries]


# A statement of a new result's bounds in a changelog entry (dreeves, 2026-10-26: "yes please", to an entry with each
# update of the new results, and "can you backfill all the results that are new since the BGPW paper?"), in math, so
# without a Claude: "…": m*(n) = v, m*(n) ≥ a, m*(n) ≤ b or a ≤ m*(n) ≤ b, n's digits or 2^{k}, in LaTeX since 2026-10-28
STATEMENT = r'\\\((?:(\d+) \\le )?m\^\*\((\d+|2\^\{?\d+\}?)\) (=|\\ge|\\le) (\d+)\\\)'


def statements(rest):
    """{n: (low, high)} for an entry's rest: empty for an entry of his words; for one in math, its statements, joined by
    ', ' (nothing else), as statement() makes them: m*(n) = v (v, v), m*(n) ≥ a (a, None), m*(n) ≤ b (None, b) and
    a ≤ m*(n) ≤ b (a, b)."""
    # Spec change (2026-11-09): an entry that is not statements alone is one of his words, whatever math it holds, and
    # gives none (his "Claude Opus 5.5 gets first wholly new result: \\(m^*(2^{38}) \\ge 39\\)", in LaTeX since his
    # commit b5ce25c, had failed an assertion here that a statement stands only among statements; no qual reads his
    # words, 2026-11-07).
    found = re.findall(STATEMENT, rest) if re.fullmatch(f'{STATEMENT}(?:, {STATEMENT})*', rest) else []
    assert all(op == '\\le' for lo, _, op, _ in found if lo), rest
    out = {cell_n(n if n.isdigit() else f'\\({n}\\)'): (int(lo), int(v)) if lo else
           {'=': (int(v), int(v)), '\\ge': (int(v), None), '\\le': (None, int(v))}[op]
           for lo, n, op, v in found}
    assert len(out) == len(found), rest
    return out


def changelog_by_day():
    """{date: {n: (low, high)}}: the statements of all the changelog's entries of each day, no n twice in a day."""
    out = {}
    for d, rest in changelog():
        said = statements(rest)
        assert not set(said) & set(out.get(d, {})), (d, set(said) & set(out[d]))
        out[d] = out.get(d, {}) | said
    return out


def q_changelog_brings_every_new_result_up_to_date():
    # Replicata: the changelog's statements, day by day, oldest first, starting from no bounds (0 and inf); the block
    # (div.new-block); and the m*(n) chart's reasons for its bounds.
    # Expectata (dreeves, 2026-10-26: "yes please", to a changelog entry with each update of the new results; and, of
    # its first 112 statements, "if there's an excuse to trim it down, we should"): each statement tightens its n's
    # bounds, raising the low, lowering the high, or both, and is still true, the block's bounds for n lying within the
    # statements'; every n stated is in the block, or since 2026-11-11 a length of the chart past the block's, where the
    # chart's bounds lie within the statements'; and every entry of the block whose lower bound is a partition of its
    # own length (up to NMAX, not BUILT; past it, a power of 2 whose pow2.js loWhy is the join of one block of length
    # n, since 1024 got its example of order 11 on 2026-10-26) is up to date, its bounds exactly the statements', as
    # is every upper bound proved on the page (reason 'page') and the low of each power of 2 that sets a threshold of
    # the theorem (dreeves, 2026-10-26: "we obviously want 2^17:18 and 2^24:25 in the changelog").
    # Resultata before the trim: the 112 statements also brought every entry built from other partitions up to date.
    # Resultata after it, before the thresholds came back: no power of 2 past 512 had a statement.
    state = {}
    for d, said in sorted(changelog_by_day().items()):
        after = fold(state, said)
        moved = [(n, state.get(n, (0, math.inf)), after[n]) for n in said]
        assert all(a != b and b[0] <= a[0] <= a[1] <= b[1] for _, b, a in moved), (d, moved)
        state = after
    cells, cols, rows = new_cells(page()), mstar_data()['cols'], mstar_rows(mstar_data())
    # Since 2026-11-11 the changelog also states new bounds at lengths of the chart past the block's 1024 (the chart
    # reaches 2048 since 2026-11-10, and the first such bounds came that night: 1104 to 1776): those are held to the
    # chart's columns, as the block's are to the block.
    # Spec change (Opus 5.5, 2026-11-19; dreeves: "yes, full anti-magic, add the new entries"): and the lengths of past's
    # rows, past the chart, to their rows, as the columns' (mstar_rows); that day's statements at 2096 to 2992 among them.
    past = {n: tuple(rows[n][:2]) for n in state if n not in cells and n > NMAX and n in rows}
    assert set(state) <= set(cells) | set(past), set(state) - set(cells) - set(past)
    known = cells | past
    false = {n: (state[n], known[n]) for n in state if not state[n][0] <= known[n][0] <= known[n][1] <= state[n][1]}
    assert not false, false
    pows = pow2_data()['cols']
    own = ({n for n in cells if n <= NMAX and cols[n - 1][2][0] not in BUILT} |
           {n for n in cells if n > NMAX and pows[n.bit_length() - 2][2] == ['joins', [[[n, cells[n][0]]]]]})
    proved = {n for n in cells if n <= NMAX and cols[n - 1][3][0] == 'page'}
    # (Spec change, Opus 5.5, 2026-11-29; dreeves, who cut the changelog's lines for the 21 firsts past 2^128 that day, asked whether this should cover only the firsts up to 2^128,
    # the ones it covered before: "sure".  Every first of the theorem until then.)
    first = {2 ** k for k in firsts(cells).values() if k <= 128}
    stale = sorted({n for n in own if state.get(n) != cells[n]} |
                   {n for n in proved if state.get(n, (0, math.inf))[1] != cells[n][1]} |
                   {n for n in first if state.get(n, (0, math.inf))[0] != cells[n][0]})
    assert not stale, [(n, state.get(n), cells[n]) for n in stale]


def q_changelog_dates_the_page_s_first_results_by_the_chat():
    # Replicata: CHAT; the claude.ai chat's exchanges in sourcery.html; the changelog's statements of the days before
    # the page's first commit (FIRST); and that commit's new results.
    # Expectata (dreeves, 2026-10-26: "can you backfill all the results that are new since the BGPW paper?", having
    # dated the chat's first new result by the chat in his own entry): each row of CHAT has its words in its exchange,
    # whose prompt is of its day; the changelog's days before FIRST's state exactly CHAT's statements as the changelog
    # lists them (chat_listed()); and CHAT's statements leave each new result of FIRST at its bounds there.
    # Resultata before: the changelog had no statements.
    chat = exchanges()
    bad = [row[:3] for row in CHAT if row[1] not in chat or chat[row[1]][0] != row[0] or row[2] not in chat[row[1]][1]]
    assert not bad, bad
    begun = git('log', '-1', '--format=%ad', '--date=format:%Y-%m-%d', FIRST).strip()
    said, days, state = changelog_by_day(), chat_listed(), chat_days()[1]
    wrong = [(d, said.get(d, {}), days.get(d, {})) for d in sorted(set(said) | set(days))
             if d < begun and said.get(d, {}) != days.get(d, {})]
    assert not wrong, wrong
    cells = new_cells(git('show', f'{FIRST}:index.html'))
    assert {n: state.get(n) for n in cells} == cells, (state, cells)


def q_changelog_backfill_matches_the_page_s_history():
    # Replicata: the changelog's statements by day; and page_days(): for each day of index.html's commits through
    # BACKFILL, the new results whose bounds the day changed, the first day's from the bounds the chat had reported
    # (chat_days), as the changelog lists them (listed(), by that day's m*(n) chart).
    # Expectata (dreeves, 2026-10-26: "can you backfill all the results that are new since the BGPW paper?", and of
    # its first 112 statements, "if there's an excuse to trim it down, we should"): each day from the page's first to
    # the one before BACKFILL's states exactly its listed changes, as statement() makes them; BACKFILL's day states its
    # listed changes through BACKFILL, and may state later ones of that day.
    # Resultata before the trim: each day stated all its changes, those built from other partitions too.
    said, days = changelog_by_day(), page_days(chat_days()[1])
    first, last = min(days), max(days)
    wrong = [(d, said.get(d, {}), days.get(d, {})) for d in sorted(set(said) | set(days))
             if first <= d < last and said.get(d, {}) != days.get(d, {})]
    assert not wrong, wrong
    assert days[last].items() <= said.get(last, {}).items(), (days[last], said.get(last))


def q_changelog_gives_noteworthy_results_lines_of_their_own():
    # Replicata: the changelog's entries, and NOTEWORTHY.
    # Expectata (dreeves, 2026-10-26: "i think m*(2^9)=9 and other noteworthy results should be their own changelog
    # line even though that means duplicating the date"): each result of NOTEWORTHY is an entry of its date with no
    # other statement, and no other entry of that date states its n.
    # Resultata before: m*(2^9) = 9 was one statement of six in the entry of 2026-10-05.
    entries = [(d, statements(rest)) for d, rest in changelog()]
    bad = [row[:3] for row in NOTEWORTHY if (row[0], {row[1]: row[2]}) not in entries or
           sum(row[1] in said for d, said in entries if d == row[0]) != 1]
    assert not bad, bad


def q_changelog_keeps_powers_of_2_on_lines_of_their_own():
    # Replicata: the changelog's entries.
    # Expectata (dreeves, 2026-10-26: "how about also always separating the powers-of-2 results onto their own lines,
    # just for readability/organization reasons?"): no entry states both a power of 2 from 512 up (written 2^k, as in
    # the table's rows of powers of 2) and another n.
    # Resultata before: the entry of 2026-10-17 stated m*(800) = 11 and seven powers of 2.
    mixed = [(d, sorted(said)) for d, said in ((d, statements(rest)) for d, rest in changelog())
             if len({n >= 512 and n & (n - 1) == 0 for n in said}) > 1]
    assert not mixed, mixed


# The page in an iframe width px wide (Chrome's window is at least 500 px wide), with harness (a script, which may
# await sleep) run last in it, once the page has had half a second: what the harness posted to the host page, as JSON.
def framed(width, harness, mstar=None, edits=()):
    """What harness, a script run in the page width px wide, posts to its parent.  The page has its own data, or for
    the m*(n) chart the text mstar in place of mstar.js (made-up data, as kinds_data's), and the edits (old, new) made
    (as BEFORE's, since 2026-11-12)."""
    d = tempfile.mkdtemp(prefix='index-quals-')
    script = ('<script>\n(async () => {\n  const sleep = ms => new Promise(r => setTimeout(r, ms));\n  await sleep(500);\n'
              + harness + '\n})();\n</script>\n')
    text = edited(page(), edits)
    assert text.count('</body>') == 1
    open(os.path.join(d, 'index.html'), 'w', encoding='utf-8').write(text.replace('</body>', script + '</body>'))
    copy_page_dir(d)
    open(data_file(d, 'mstar.js'), 'w', encoding='utf-8').write(mstar or open(DATA, encoding='utf-8').read())
    shutil.copy(POW2, data_file(d, 'pow2.js'))
    open(os.path.join(d, 'host.html'), 'w').write(HOST.replace('__WIDTH__', str(width)))
    dom = chrome(d, [f'--window-size={max(width, 500) + 40},1100', '--virtual-time-budget=5000', '--dump-dom',
                     'file://' + os.path.join(d, 'host.html')])
    shutil.rmtree(d)
    m = re.search(r'<pre id="harness-out">(.*?)</pre>', dom, re.S)
    assert m, dom[-2000:]
    return json.loads(html.unescape(m.group(1)))


def q_changelog_starts_closed_and_fits_a_phone():
    # Replicata: index.html 390 px wide (a phone) and 1000 px, as loaded; then its changelog's summary clicked; then a
    # made-up entry too long for one line added to the changelog.
    # Expectata (dreeves, 2026-10-26, as for q_changelog_sits_under_the_authors_as_in_freshat): as loaded, the
    # changelog's summary shows and none of its entries; its cursor is a pointer, as on FreshAt's; clicked, it opens and
    # every entry shows, in the page's monospace font (--mono), as FreshAt's entries are in a <pre>; the long entry's
    # first line starts at the entry's left edge and each later line under the text after its date (the 13th
    # character, after "YYYY-MM-DD: "); and at each step the page is no wider than the window.
    # Resultata before: no changelog.
    for width in (390, 1000):
        got = framed(width, """
  const box = document.querySelector('header > details.changelog'), summary = box.querySelector('summary');
  const wider = () => document.documentElement.scrollWidth - innerWidth;
  const look = () => ({open: box.open, summary: summary.checkVisibility(), wider: wider(),
    entries: [...box.querySelectorAll('p')].map(p => p.checkVisibility())});
  const closed = look();
  summary.click();
  await sleep(50);
  const opened = look();
  const p = document.createElement('p');
  p.textContent = '2026-10-26: ' + 'made up '.repeat(40);
  box.append(p);
  await sleep(50);
  const text = p.firstChild, at = i => { const r = document.createRange(); r.setStart(text, i); r.setEnd(text, i + 1); return r.getBoundingClientRect().left; };
  const all = document.createRange(); all.selectNodeContents(p);
  const long = {left: p.getBoundingClientRect().left, date: at(12), wider: wider(),
    lines: [...all.getClientRects()].filter(r => r.width > 0).map(r => r.left)};
  parent.postMessage(JSON.stringify({closed, opened, long, font: getComputedStyle(p).fontFamily,
    mono: getComputedStyle(document.documentElement).getPropertyValue('--mono').trim(),
    cursor: getComputedStyle(summary).cursor}), '*');""")
        closed, opened, long = got['closed'], got['opened'], got['long']
        assert (closed['open'], closed['summary']) == (False, True) and closed['entries'] and not any(closed['entries']), (width, got)
        assert opened['open'] and opened['entries'] and all(opened['entries']), (width, got)
        assert got['cursor'] == 'pointer' and got['font'] == got['mono'], (width, got)
        assert len(long['lines']) > 1 and close(long['lines'][0], long['left'], 0.5), (width, long)
        assert all(close(x, long['date'], 0.5) for x in long['lines'][1:]), (width, long)
        assert max(closed['wider'], opened['wider'], long['wider']) <= 0, (width, got)


def q_chrome_s_whole_process_group_ends_before_its_folder_goes():
    # Replicata: two process groups in sessions of their own, as chrome() starts Chrome's: one whose leader exits at
    # once while a member lives on for a second, as Chrome's helpers outlive its main process for a moment; and one
    # whose members all ignore SIGTERM; each ended by end_group, the first with chrome()'s deadlines, the second with
    # short ones; and a group whose only member is its leader, exited but not yet reaped, a zombie.
    # Expectata: each of the first two still has a member once its leader is gone, the race itself; and end_group
    # returns only when no process of the group remains, the second only after its SIGTERM deadline, by SIGKILL.  The
    # zombie, which macOS lets no one signal (EPERM), counts as a member until reaped, and end_group ends it too.
    # Resultata before the zombie's case (2026-10-26, two suites at once): end_group's first version took EPERM, all
    # that remained of a Chrome being some such member, for an error, "Operation not permitted".
    # Resultata before (2026-10-26, quals_pow2_page, twice): "Directory not empty" from rmtree, the temporary folder
    # deleted once Chrome's main process had exited while a helper still wrote into its profile.
    lingers = subprocess.Popen(['sh', '-c', 'sleep 1 & exit 0'], start_new_session=True)
    lingers.wait(timeout=10)
    assert alive(lingers.pid), 'the member did not outlive its leader'
    end_group(lingers)
    assert not alive(lingers.pid)
    stubborn = subprocess.Popen(['sh', '-c', 'trap "" TERM; sleep 30 & wait'], start_new_session=True)
    time.sleep(0.2)
    t0 = time.monotonic()
    end_group(stubborn, term=0.5, kill=5)
    assert not alive(stubborn.pid) and time.monotonic() - t0 >= 0.5, time.monotonic() - t0
    zombie = subprocess.Popen(['sh', '-c', 'exit 0'], start_new_session=True)
    time.sleep(0.3)
    assert alive(zombie.pid), 'a zombie is no member'
    end_group(zombie)
    assert not alive(zombie.pid)


def q_every_headless_chrome_starts_with_the_same_flags():
    # Replicata: the files of quals/ (the suites and their node harnesses), read as text: each line that names Chrome's
    # flag for running headless; and HEADLESS, the flags that chrome() and the two drivers (quals_pow2_page's and
    # quals_codes's, as C.headless) start Chrome with.
    # Expectata: one line names that flag, HEADLESS's own in this file, so that no Chrome of the quals runs headless
    # without the rest of HEADLESS; and HEADLESS has --disable-backgrounding-occluded-windows.
    # Resultata before (2026-11-09 23:36, quals_codes's forward run): three places started Chrome, each with flags of
    # its own and none with that one.  The Mac's display went to sleep during the run.  Chrome then took the page for
    # hidden (document.visibilityState "hidden", no animation frame, timers once a second), and the driver waited on a
    # frame for 500 s, to its watchdog.  scratch/green-20261109/display.py counts the frames through a display's sleep:
    # none after it without the flag, 60 a second with it.
    flag = '--head' + 'less'                              # in two pieces, so that this line is no such line
    lines = [(f, i + 1) for f in sorted(os.listdir(os.path.join(HERE, 'quals'))) if f.endswith(('.py', '.cjs'))
             for i, line in enumerate(open(os.path.join(HERE, 'quals', f), encoding='utf-8')) if flag in line]
    assert [f for f, _ in lines] == ['quals_index.py'], lines
    assert flag + '=new' in HEADLESS and '--disable-backgrounding-occluded-windows' in HEADLESS, HEADLESS


def q_page_links_its_stylesheet_after_katex_s():
    # Replicata: index.html; and the page 1280 px wide (framed): every formula KaTeX drew, and the element holding it.
    # Expectata (dreeves's README, 2026-10-30: "[FAC] ... getting css and javascript out of index.html"): no <style>
    # block; the page's own stylesheet is a file, page/style.css, linked once, in the head, right after KaTeX's
    # stylesheet and before any script, where the style block stood, so that the page's rules still come after KaTeX's
    # in the cascade and win where both match at equal specificity: every formula's font size is that of the element
    # holding it (.katex at 1em), not KaTeX's 1.21em.
    # Resultata before: the page's CSS was a <style> block in that place.
    text = page()
    head = text[:text.index('</head>')]
    assert '<style' not in text and text.count('href="page/style.css"') == 1, 'a style block, or not one link'
    assert re.search(r'\n<link rel="stylesheet" href="https://cdn\.jsdelivr\.net/npm/katex@0\.16\.47/dist/katex\.min\.css" '
                     r'[^>\n]*>\n<link rel="stylesheet" href="page/style\.css">\n', head), head[-1500:]
    assert head.index('href="page/style.css"') < head.index('<script'), 'a script before the stylesheet'
    got = framed(1280, """
  parent.postMessage(JSON.stringify([...document.querySelectorAll('.katex')].map(k =>
    [getComputedStyle(k).fontSize, getComputedStyle(k.parentElement).fontSize])), '*');""")
    assert len(got) > 800 and all(a == b for a, b in got), (len(got), [s for s in got if s[0] != s[1]][:5])


def page_files():
    """The names of page/'s stylesheets and scripts, in order: the files there that index.html can link."""
    return sorted(n for n in os.listdir(PAGE_DIR) if n.endswith(('.css', '.js')))


def q_page_dir_holds_what_index_links():
    # Replicata: the files in page/, and the files of page/ that index.html links, as its stylesheet or as scripts.
    # Expectata (dreeves's README, 2026-10-30: "[FAC] ... getting css and javascript out of index.html"): page/ holds
    # exactly those files, hidden files aside (as Finder's .DS_Store, which git ignores), each linked once: none is
    # missing and none unused.
    # (2026-11-10, dreeves: "can you put READMEs in each directory": page/ holds its README.md too, so "exactly those
    # files" is now said of page/'s stylesheets and scripts (page_files), the kinds index.html links there: one that
    # the page does not load still fails, and so does a linked one that is missing.)
    # Resultata before: no page/; the page's CSS and scripts were inline.
    linked = [a or b for a, b in re.findall(r'<link rel="stylesheet" href="page/([^"]+)">|<script src="page/([^"]+)"></script>',
                                            page())]
    there = page_files()
    assert linked and len(linked) == len(set(linked)) and sorted(linked) == there, (linked, there)


def q_scripts_load_data_then_draw():
    # Replicata: index.html's script tags and the files of the page's own scripts (in page/ since 2026-10-31: inline
    # scripts before, each the same text); and the light run's look at the page's math once it loaded (R's math).
    # Expectata: in the head, three: page/math.js, which defines a function, and then KaTeX's two (since 2026-10-28;
    # dreeves: "could you convert all the math on the page to latex"), deferred, from jsDelivr at version 0.16.47, each
    # with its SHA-256 integrity, auto-render's onload only a call of that function, with no & in any script tag of the
    # head (dreeves's README, 2026-10-30: "[VSC] VS Code isn't happy about the "&amp;&amp;" in one of the jsdelivr
    # lines for KaTeX"); then exactly eight (seven until 2026-10-31), after </main> and before </body>: the script of
    # the pan and zoom both charts share (2026-10-30, q_both_charts_share_one_pan_and_zoom; six scripts before),
    # page/shared.js; a classic <script src="mstar.js"> (no type, async or defer, so it also loads from file://) and
    # then the m*(n) chart's, page/mstar-section.js; then the chart of powers of 2's, likewise (quals_pow2_page.py holds
    # those two); then the script of the table of smallest lengths, which reads MSTAR (2026-10-17),
    # page/smallest-section.js; then the script of the page's codes, which makes each code a button that shows its
    # partition (2026-10-31, dreeves's [REO] item 2; quals_codes.py), page/codes.js; then the script of the section
    # "Search progress", which loads progress.js itself (2026-10-17), page/progress-section.js.  Each of the page's own
    # scripts is a classic <script src> of its file in page/ (dreeves's README, [FAC]: "getting css and
    # javascript out of index.html"), so that each runs where it stands, in order, as when it was inline, and loads
    # from file://.  Once the page has loaded, its math is drawn: KaTeX drew formulas, none of them an error, and no text
    # outside scripts, styles and formulas still holds a \( or \).  (Until 2026-10-30 this pinned onload's code,
    # character for character, and said that it also wrapped each formula and the text glued to it in an nw span
    # (2026-10-29); that code has never glued anything, auto-render putting each formula alone in a span of its own, so
    # the gluing is not expected here: scratch/readme-20261030/NOTES.md.)
    text = page()
    head, body = text[:text.index('</head>')], text[text.index('</head>'):]
    katex = re.search(r'\n<script src="(page/math\.js)"></script>\n'
                      r'<script defer src="https://cdn\.jsdelivr\.net/npm/katex@0\.16\.47/dist/katex\.min\.js" '
                      r'integrity="sha256-[A-Za-z0-9+/]{43}=" crossorigin="anonymous"></script>\n'
                      r'<script defer src="https://cdn\.jsdelivr\.net/npm/katex@0\.16\.47/dist/contrib/auto-render\.min\.js" '
                      r'integrity="sha256-[A-Za-z0-9+/]{43}=" crossorigin="anonymous" onload="(\w+)\(\)"></script>\n', head, re.S)
    tags = re.findall(r'<script\b[^>]*>', head)
    # Spec change (Opus 5.5, 2026-11-12; dreeves: "is there something simpler we can do to make it fail louder? see
    # anti-postel in AGENTS.md"): four in the head, page/errors.js first of all the page's scripts, so that it hears
    # every other's errors and shows them (q_an_error_shows_at_the_top_of_the_window); then the three as before.
    assert katex and len(tags) == 4 and tags[0] == '<script src="page/errors.js">' and not any('&' in t for t in tags), tags
    [math_js] = page_scripts(katex[0])
    assert re.search(rf'^function {katex[2]}\(\) \{{$', math_js, re.M), math_js[:300]
    # Spec change (Opus 5.5, 2026-11-18): the appendix's script, page/appendix.js, between the table of smallest lengths'
    # and the codes', after both charts' scripts have given their facts and before page/codes.js makes buttons of the
    # codes and constructions it adds; its math is drawn when the appendix opens, which the light run's harness does
    # before it looks at the page's math (OPTS.appendix), so that the math looked at is the appendix's too.
    assert re.findall(r'<script\b[^>]*>', body) == [
        '<script src="page/shared.js">', '<script src="pagedata/mstar.js">', '<script src="page/mstar-section.js">',
        '<script src="pagedata/pow2.js">', '<script src="page/pow2-section.js">', '<script src="page/smallest-section.js">',
        '<script src="page/appendix.js">', '<script src="page/codes.js">', '<script src="page/progress-section.js">'], re.findall(r'<script\b[^>]*>', body)
    own = page_scripts(body)
    assert 'function panZoom(' in own[0] and '[data-smallest]' in own[3] and 'section.appendix' in own[4] \
        and 'template[data-partition]' in own[5] and 'progressData' in own[6], [js[:60] for js in own]
    assert text.index('</main>') < text.index('<script src="page/shared.js">', len(head)) < text.index('<script src="pagedata/mstar.js"></script>') < \
        text.index('</script>\n</body>')
    math = valid_run('light')['math']
    assert math['formulas'] > 800 and math['errors'] == 0 and math['raw'] == [], math


def q_chart_script_passes_node_check():
    # Replicata: the chart's script, the one that gets #mstar-chart (page/mstar-section.js since 2026-10-31, when this
    # qual was q_inline_script_passes_node_check; an inline script before, the page's first until 2026-10-30, when an
    # inline script for KaTeX came first in the head), saved as a .js file, through node --check.
    # Expectata: exit 0: it parses as a classic script.
    [js] = [s for s in page_scripts(page()) if "getElementById('mstar-chart')" in s]
    d = tempfile.mkdtemp(prefix='index-quals-')
    path = os.path.join(d, 'chart.js')
    open(path, 'w', encoding='utf-8').write(js)
    p = subprocess.run(['node', '--check', path], capture_output=True, text=True, timeout=60)
    shutil.rmtree(d)
    assert p.returncode == 0, p.stderr


def q_tokens_in_all_three_theme_blocks():
    # Replicata: the custom properties of index.html's three theme blocks.
    # Expectata: --exists, --open and --impossible are in it, as #rrggbb (one block since 2026-10-12: no dark mode).
    light, = theme_blocks()
    for t in TOKENS:
        assert t in light and re.fullmatch(r'#[0-9a-fA-F]{6}', light[t]), t


def q_palette_reads_for_color_blind_readers():
    # Replicata: the chart's three colors in each mode, with the validator's arithmetic, all pairs (any two touch).
    # Expectata: the worst pair in normal vision is at least the validator's floor 15.  (The colors are dreeves's to tweak
    # since 2026-10-12, so no comment states their numbers.  Until then it also held the color-blind pair to 8, exists
    # and impossible 0.25 apart in lightness, and each of the three 15 from each provenance hue, in a dark mode too.)
    light, = theme_blocks()
    assert worst_normal([light[t].lower() for t in TOKENS]) >= 15, [light[t] for t in TOKENS]


def q_chart_colors_stand_apart():
    # Replicata: the charts' colors and the table's provenance hues in each mode, and the page's CSS (dreeves,
    # 2026-10-12: the charts' gray and green too similar; their red too like the table's orange for Claude alone; "the
    # 'claude and BGPW' color could be a striping of the other two").
    # Expectata: the chart's colors are dreeves's to tweak (2026-10-12: "so i can tweak them myself"), so none is pinned
    # here; Claude and BGPW has no hue of its own (no --joint,
    # anywhere): its cells and legend key are stripes of --claude's and --stan's tints over a striped bar, and its glyph
    # is half in each hue.
    def lch(h):
        L, a, b = oklab(linear(h))
        return L, math.hypot(a, b), math.degrees(math.atan2(b, a)) % 360
    for mode, b in zip(('light',), theme_blocks()):
        assert '--joint' not in b, mode
    css = page_css()
    assert '--joint' not in css
    tints = ('repeating-linear-gradient(135deg, color-mix(in oklab, var(--claude) var(--tint), var(--paper)) 0 0.3rem, '
             'color-mix(in oklab, var(--stan) var(--tint), var(--paper)) 0.3rem 0.6rem)')
    bar = 'repeating-linear-gradient(90deg, var(--claude) 0 0.3rem, var(--stan) 0.3rem 0.6rem) bottom / 100% 3px no-repeat'
    half = 'linear-gradient(90deg, var(--claude) 50%, var(--stan) 50%)'
    assert f'td.j, .key.j {{ background: {tints}; }}' in css
    assert f'tr.vals td.j, .key.j {{ background: {bar}, {tints}; box-shadow: none; }}' in css
    assert (f'tr.ns td.j::before, .key.j > span, .remarks li.j .mk {{ background: {half}; -webkit-background-clip: text; '
            'background-clip: text; color: transparent; }') in css
    assert '<span class="key j" aria-hidden="true"><span>◆●</span></span>' in page()


def q_new_results_n_cells_line_up():
    # Replicata: index.html in the browser (light, desktop): in each n row of the new results' tables, the bottom of the
    # first line of each cell's n (its digits, or the 2 of 2^k).
    # Expectata (dreeves, 2026-10-12: "minor spacing issue (remember anti-magic)"): the nine rows' cells (six until
    # 2026-10-26, when the powers of 2 took a third row; seven until 2026-10-27, when the block took in Table 2 and
    # reached 1024 in six upper rows) line up within half a pixel, the uncolored copies of Table 2's entries among
    # them: every n cell of the new results takes the same room above its n, glyph or no glyph.
    rows = valid_run('light')['nTextBottoms']
    # (Spec change, Opus 5.5, 2026-11-19; q_sequences_past_the_chart_move_seven_firsts: ten rows since then, the powers of 2 in
    # four, the new firsts' cells having made three too wide for the column; nine until then.)
    # (Fable 5.2, 2026-11-21, with q_powers_of_2_on_the_page_follow_pow2_js: as many rows as the page's tables have, not the ten of that day; eleven since the powers of 2 took a fifth table.)
    assert len(rows) == ''.join(new_frames(page())).count('<tr class="ns">') and all(len(r) >= 5 for r in rows), rows
    assert all(max(r) - min(r) <= 0.5 for r in rows), rows


def q_new_results_fit_unscrolled_at_945_px():
    # Replicata: index.html with page/, mstar.js, pow2.js and progress.js beside it, in headless Chrome with a window
    # 945 px wide: the widths of the new results' seven tables and of their sideways-scrolling frame (.new-block .scroll).
    # Expectata (the CSS comment on the new results' side padding: "keeps it in one row, unscrolled, at 945 px"; since
    # 2026-10-25, when the powers of 2 reached 23, their two rows too, and since 2026-10-26, when they reached 35 and
    # took three rows, those three; since 2026-10-27, when the block took in Table 2 and reached 1024, its six upper
    # rows, and since later that day the block's two frames, one for them and one for the powers of 2): no table is
    # wider than its frame, so neither frame scrolls.
    d = tempfile.mkdtemp(prefix='index-quals-')
    try:
        for name in ('mstar.js', 'pow2.js', 'progress.js'): shutil.copy(os.path.join(HERE, PAGEDATA, name), data_file(d, name))
        copy_page_dir(d)
        script = ("<script>addEventListener('load', () => setTimeout(() => { const p = document.createElement('pre'); p.id = 'fit'; "
                  "p.textContent = JSON.stringify([...document.querySelectorAll('.new-block .scroll')].map(f => ({frame: f.clientWidth, "
                  "scroll: f.scrollWidth, tables: [...f.querySelectorAll('table.block')].map(t => t.getBoundingClientRect().width)}))); "
                  "document.body.append(p); }, 500));</script>\n")
        open(os.path.join(d, 'index.html'), 'w', encoding='utf-8').write(page().replace('</body>', script + '</body>'))
        dom = chrome(d, ['--window-size=945,1200', '--virtual-time-budget=4000', '--dump-dom', 'file://' + os.path.join(d, 'index.html')])
    finally:
        shutil.rmtree(d)
    m = re.search(r'<pre id="fit">(.*?)</pre>', dom)
    assert m, dom[-500:]
    R = json.loads(m.group(1))
    # (Spec change, Opus 5.5, 2026-11-19; q_sequences_past_the_chart_move_seven_firsts: the powers of 2 in four tables since
    # then; three until then.)
    # (Fable 5.2, 2026-11-21, with q_powers_of_2_on_the_page_follow_pow2_js: each frame's tables as the page has them, [6, 4] until then.)
    assert [len(f['tables']) for f in R] == [f.count('<table class="block">') for f in new_frames(page())], R
    assert all(f['scroll'] <= f['frame'] and max(f['tables']) <= f['frame'] for f in R), R


def new_frames(text):
    """The HTML inside each sideways-scrolling frame (div.scroll) of the new results' block in text, in page order:
    since 2026-10-27, one for the lengths other than powers of 2 and one for the powers of 2."""
    block = text[text.index('<div class="new-block">'):text.index('</figure>')]
    return re.findall(r'<div class="scroll">(.*?)</div>', block, re.S)


# The classes of the new results' cells, their credits, which the page's own legend words: the data and the scripts
# name a credit by its class alone (2026-11-09; dreeves, after his rename of Claude to Opus 5.5 on the page stopped
# mstar.py and turned 45 quals red: "it seems dumb that me tweaking the prose in index.html has yielded this much work
# from you", then "probably yes to the decoupling").
# cf since 2026-11-11 (dreeves, of the cells whose lower bounds Fable 5.2 raised that day and which still carried Opus 5.5's marks: "yes, please make the legend
# accurate"; q_opus_and_fable_is_a_category_of_its_own).
CREDITS = ('s', 'c', 'j', 'a', 'ca', 'cf')
TITLED = r"(<td(?: class=\"\w+\")? title=')([^']*)(')"                                              # a cell's title
LABELED = r'(<li><span class="key[^"]*" aria-hidden="true">(?:<span>)?[^<]*(?:</span>)?</span>)([^<]*)(</li>)'   # a legend label


def reworded(text):
    """index.html's text with the words of the new results' credits changed and nothing else: each title of a cell and
    each label of their legend, with every run of letters reversed (Opus 5.5 alone: supO 5.5 enola)."""
    turn = lambda x: x.group(1) + re.sub(r'[A-Za-z]+', lambda w: w.group(0)[::-1], x.group(2)) + x.group(3)
    text, cells = re.subn(TITLED, turn, text)
    text, labels = re.subn(LABELED, turn, text)
    assert cells > 100 and labels == len(CREDITS) + 1, (cells, labels)         # the legend's last label is the paper's
    return text


def legend_labels(text):
    """{class: label} for the new results' legend in text: each item whose key has a class of its own."""
    found = re.findall(r'<li><span class="key (\w+)" aria-hidden="true">(?:<span>)?[^<]*(?:</span>)?</span>([^<]*)</li>', text)
    assert sorted(k for k, _ in found) == sorted(CREDITS), found
    return dict(found)


def new_block_cells():
    """The new results' tables, frame by frame (new_frames), each table as a list of (n, its n cell as the page writes
    it, the n cell's attributes, the value cell's attributes, the value), in page order."""
    out = []
    for frame in new_frames(page()):
        out.append([])
        for t in re.findall(r'<table class="block">.*?</table>', frame, re.S):
            ns = re.findall(r'<td([^>]*)>(.*?)</td>', re.search(r'<tr class="ns">.*?</tr>', t, re.S).group(0))
            vs = re.findall(r'<td([^>]*)>(.*?)</td>', re.search(r'<tr class="vals">.*?</tr>', t, re.S).group(0))
            assert len(ns) == len(vs) and ns, t
            out[-1].append([(cell_n(c), c, a, va, v) for (a, c), (va, v) in zip(ns, vs)])
    return out


def q_new_results_subsume_table2():
    # Replicata: the new results' tables on index.html (each cell's n, attributes and value) and Table 2's entries.
    # Expectata (2026-10-27; dreeves: "how about making our color-coded table totally subsume the BGPW table? The
    # color-coding makes it nice and clear which cells are repeated from that table"; Stan Wagon, by dreeves: the
    # upper part "should include 256, 512, and 1024 for completeness", and "could the table and the chart go up to
    # 1024 as the natural stopping point, instead of 1000?"; dreeves, on the lengths: "multiples of 16 with
    # one-sentence explanation sounds good"; then "can we split the table into the non-powers-of-2 and the
    # powers-of-2 and move the note about multiples of 8 or 16 under the non-power-of-2 table?"): the block has two
    # frames, the first holding the upper rows, their n in digits, and the second the rows of powers of 2, written
    # 2^k, with k rising from 3; the upper rows' lengths are every multiple of 8 up to 304, as in Table 2,
    # then every multiple of 16 up to NMAX; every entry of Table 2 is in the block, as a cell without a provenance
    # class, titled "The published paper (2021)", with exactly Table 2's bounds, or as a classed cell whose bounds lie
    # within Table 2's (240, 304 and 2^51, each improved since); every unclassed cell is such a copy; and a length the
    # block shows twice, in the upper rows and as a power of 2 (8 to 1024), is the same cell both times.
    frames = new_block_cells()
    assert len(frames) == 2, [[[c for _, c, *_ in r] for r in f] for f in frames]
    upper, pows = frames
    rows = upper + pows
    assert all(re.fullmatch(r'\d+', c) for r in upper for _, c, *_ in r) and upper, [[c for _, c, *_ in r] for r in upper]
    assert all(re.fullmatch(r'\\\(2\^\{?\d+\}?\\\)', c) for r in pows for _, c, *_ in r) and pows, [[c for _, c, *_ in r] for r in pows]
    assert [n for r in upper for n, *_ in r] == list(range(8, 305, 8)) + list(range(320, NMAX + 1, 16))
    ks = [n.bit_length() - 1 for r in pows for n, *_ in r]
    assert ks[0] == 3 and ks == sorted(set(ks)), ks
    t2 = {}                                       # Table 2's entries, 2^51 among them
    for t in re.findall(r'<table class="block">.*?</table>', page()[:page().index('<div class="new-block">')], re.S):
        ns = re.findall(r'<td[^>]*>(.*?)</td>', re.search(r'<tr class="ns">.*?</tr>', t, re.S).group(0))
        vs = re.findall(r'<td[^>]*>(.*?)</td>', re.search(r'<tr class="vals">.*?</tr>', t, re.S).group(0))
        t2 |= {cell_n(c): bounds(v) for c, v in zip(ns, vs)}
    assert len(t2) == 39 and 2 ** 51 in t2, sorted(t2)
    cells = [cell for r in rows for cell in r]
    bare = lambda a: bool(re.fullmatch(r" title='[^']+'", a))   # a cell with no class, whatever its title says (2026-11-09)
    copies = {n: bounds(v) for n, c, a, va, v in cells if bare(a)}
    assert all(bare(a) and va == '' or re.fullmatch(r' class="(\w+)" title=\'[^\']+\'', a) and va == a.split(' title')[0]
               for n, c, a, va, v in cells), [cell for cell in cells if not bare(cell[2]) and not cell[3]]
    assert set(copies) <= set(t2) and all(copies[n] == t2[n] for n in copies), {n: (copies[n], t2.get(n)) for n in copies}
    classed = {n: bounds(v) for n, c, a, va, v in cells if not bare(a)}
    # Spec change (Claude, 2026-11-08): 288 among the classed cells, settled at 9 by the form-tree proof (quals_mstar's
    # q_288_is_settled_at_9); until then a copy of Table 2's 9 or 10.
    assert set(t2) <= set(copies) | set(classed) and set(t2) - set(copies) == {240, 288, 304, 2 ** 51}, set(t2) - set(copies)
    assert all(t2[n][0] <= classed[n][0] <= classed[n][1] <= t2[n][1] for n in (240, 288, 304, 2 ** 51)), classed
    twice = {n for n, *_ in cells if sum(m == n for m, *_ in cells) > 1}
    assert twice == {2 ** k for k in range(3, 11)}, sorted(twice)
    assert all(len({(a, va, v) for m, c, a, va, v in cells if m == n}) == 1 for n in twice), sorted(twice)


def q_new_results_say_which_lengths():
    # Replicata: the paragraph between the new results' two frames, right under the table of lengths other than
    # powers of 2 (the sentence dreeves asked for on 2026-10-27: "multiples of 16 with one-sentence explanation sounds
    # good", and where he put it: "move the note about multiples of 8 or 16 under the non-power-of-2 table"), its text
    # with tags dropped; the upper rows' lengths; mstar.js's columns.
    # Expectata: the paragraph names, as numbers, what the table and the chart give: 8 and 304, the step of the upper
    # rows up to their last length before the step doubles, 16, the step after, 7, which the two lemma (BGPW's
    # Theorem 4.1, linked) allows an odd multiple of 8 at most, and 200, the least n from which every odd multiple of
    # 8 up to NMAX has lo = hi = 7 in mstar.js (so that none of them, past 304, has anything to show); and it links
    # Theorem 4.1.
    # Spec change (2026-11-09; dreeves: "we need more quals for substantive things and fewer quals enforcing words on
    # the page"): the paragraph is his and is no longer read (until then it had to name 8, 304, 16, 7 and 200 and to
    # link Theorem 4.1); what it says is still held true of the table and the chart.
    lengths = [n for r in new_block_cells()[0] for n, *_ in r]
    steps = [b - a for a, b in zip(lengths, lengths[1:])]
    turn = lengths[steps.index(16)]
    assert set(steps) == {8, 16} and steps == sorted(steps), steps
    cols = mstar_data()['cols']
    sevens = [n for n in range(8, NMAX + 1, 16) if cols[n - 1][:2] != [7, 7]]
    least = max(sevens) + 16
    assert (turn, least, (8 & -8) - 1) == (304, 200, 7) and all(cols[n - 1][1] <= 7 for n in range(8, NMAX + 1, 16)), sevens


def q_remarks_name_the_chart_s_constructions():
    # Replicata: each remark sentence of the form Claude: “Order m from examples above, doubled (a = 2·b, ...) or joined
    # (a = b + c, ...); ...”, item by item, against mstar.js's loWhy at a (curly quotes since 2026-10-30, [CUR]).
    # Expectata: every item is the chart's own construction: a = 2·b is ["product", 2, b], a = b + c is ["join", b, c],
    # as their TODOs say ("how the m*(n) chart gets these").  (On 2026-10-12 the example at 560 made the chart's joins
    # 240 + 560, 336 + 560 and 432 + 560 win its ties at 800, 896 and 992, which a remark still called doublings.)
    # (2026-11-18, Opus 5.5: at least one such sentence, a check the qual lacked; since its sentences lost the writer
    # and the quotation mark that opened them, in the folds of model's text (2026-11-13), and came to write their
    # items in LaTeX, \(a = 2\cdot b\), it had found none, and so passed checking nothing.  Now each sentence with or
    # without its writer, its items in LaTeX, a join of any number of parts.)
    cols = mstar_data()['cols']
    sentences = re.findall(r'Order \d+ from examples above, (.*?); order', page())
    assert sentences, 'no remark sentence of that form'
    for s in sentences:
        for kind, body in re.findall(r'(doubled|joined) \((.*?\\\))\)', s):
            for a, b, c in re.findall(r'(\d+) = (?:2\\cdot (\d+)|(\d+(?: \+ \d+)+))', body):
                want = ['product', 2, int(b)] if kind == 'doubled' else ['join', *map(int, c.split(' + '))]
                assert (kind == 'doubled') == bool(b), (kind, a, b, c)
                assert cols[int(a) - 1][2] == want, (a, cols[int(a) - 1][2], want)


def q_2_18_shows_its_construction():
    # Replicata: the 2^18 remark on index.html, and certificate_2^18.wl beside it.
    # Expectata (dreeves, 2026-10-12: "for 2^18, index.html should show the proof, right? ... can we also get mathematica
    # code to generate the full list of 2^18/2 integers?"): the remark writes out the construction, (p320 # p560) ∨
    # (p48 # p432 # τ2), links the script; the script decodes the four blocks from hex
    # codes that are exactly codes on the page.  (Since 2026-10-31 each name links to its code, \href{#N:M}{...}, which
    # the comparison drops, unlink: q_codes_are_anchors_and_names_link_to_them.)
    li = re.search(r'<p class="entry">\\\(n = 2\^\{18\}\\\): .*?</li>', page(), re.S).group(0)
    assert '\\((p_{320} \\mathbin{\\#} p_{560}) \\vee (p_{48} \\mathbin{\\#} p_{432} \\mathbin{\\#} \\tau_2)\\)' in unlink(li), li
    assert 'certificate_2%5E18.wl"' in li, li
    wl = open(os.path.join(HERE, 'proofs', 'certificate_2^18.wl'), encoding='utf-8').read()   # proofs/: [FAC] 3a
    codes = re.findall(r'(p\d+) = fromHex\["([0-9A-F]+)", \d+\];', wl)
    assert [k for k, _ in codes] == ['p320', 'p560', 'p432', 'p48'], codes
    assert all(re.search(rf'<code id="\d+:\d+">{h}</code>', page()) for _, h in codes), codes


def q_2_17_shows_its_construction():
    # Replicata: the 2^17 remark on index.html, and certificate_2^17.wl beside it.
    # Expectata (as for 2^18, which dreeves asked for on 2026-10-12; 800's example of order 11, 2026-10-17, moved the
    # first power of 2 that beats Thue-Morse by 1 from 2^18 to 2^17): the remark writes out the construction,
    # (p112 # p800) v (p48 # p432 # tau_1), links the script; the script
    # decodes the four blocks from hex codes that are exactly codes on the page.  (Since 2026-10-31 each name links to
    # its code, \href{#N:M}{...}, which the comparison drops, unlink: q_codes_are_anchors_and_names_link_to_them.)
    li = re.search(r'<p class="entry">\\\(n = 2\^\{17\}\\\): .*?</li>', page(), re.S).group(0)
    assert '\\((p_{112} \\mathbin{\\#} p_{800}) \\vee (p_{48} \\mathbin{\\#} p_{432} \\mathbin{\\#} \\tau_1)\\)' in unlink(li), li
    assert 'certificate_2%5E17.wl"' in li, li
    wl = open(os.path.join(HERE, 'proofs', 'certificate_2^17.wl'), encoding='utf-8').read()   # proofs/: [FAC] 3a
    codes = re.findall(r'(p\d+) = fromHex\["([0-9A-F]+)", \d+\];', wl)
    assert [k for k, _ in codes] == ['p112', 'p800', 'p48', 'p432'], codes
    assert all(re.search(rf'<code id="\d+:\d+">{h}</code>', page()) for _, h in codes), codes


def q_chart_agrees_with_tables():
    # Replicata: mstar.js (the chart's data) and the entries of the page's tables with n up to NMAX.
    # Expectata: for each entry (n, low, high): the column's [lo, hi] lies inside [low, high], and an exact entry
    # (low = high) is lo = hi.  304's two entries (8 or 9 in Table 2, 8 since) both hold, and 240's (10 or 11 in
    # Table 2, 10 since 2026-10-20).
    cols = mstar_data()['cols']
    entries = table_entries()
    # Table 2's 38; since 2026-10-27 the new results' 83 upper cells (every multiple of 8 up to 304, then of 16 up to
    # 1024) and their powers of 2 up to 1024, 2^3 to 2^10
    assert len(entries) == 38 + 83 + 8, len(entries)
    for n, low, high in entries:
        lo, hi = cols[n - 1][:2]
        assert low <= lo <= hi <= high, (n, low, high, lo, hi)


def q_new_results_state_what_the_chart_proves():
    # Replicata: the new results' tables on index.html (every n, the powers of 2 included, with each cell's provenance
    # class, none for the copies of Table 2's entries) and the remarks' entries under "Where the new results come from"
    # (each entry's n's, its "m* = v", "≥ v", "∈ {a, b, ...}" or "∈ {a, …, b}", and its <li>'s class);
    # mstar.js's columns for n <= NMAX and pow2.js's for n = 2^k.
    # Expectata: every cell with a provenance class, and every remark, states exactly its chart's [lo, hi] at its n, so
    # no "≥" stands where a chart proves an upper bound (dreeves's report of 2026-10-11: 432's entry said ≥ 11 beside the
    # chart's 11–12; and 2^51's said ≥ 53 beside the powers-of-2 chart's 54–63 until 2026-10-12); the remarks are one
    # each for exactly the classed cells' n, and for uncolored ones they rederive (since 2026-10-27, 288's: "just
    # clarify that that one isn't technically new but is rederived here"); and each remark is marked like its cell,
    # its <li> of the cell's class, or of none.
    cols, pow2 = mstar_data()['cols'], pow2_data()['cols']
    def chart(n):
        k = n.bit_length() - 1
        assert n <= NMAX or n == 2 ** k <= 2 ** pow2_data()['kmax'], n
        return cols[n - 1][:2] if n <= NMAX else pow2[k - 1][:2]
    def n_of(cell):
        m = re.fullmatch(r'(\d+)|\\\(2\^\{?(\d+)\}?\\\)', cell)
        assert m, cell
        return int(m.group(1)) if m.group(1) else 2 ** int(m.group(2))
    forms = ((r'(\d+)', lambda a: (a, a)), (r'(\d+) or (\d+)', lambda a, b: (a, b)), (r'(\d+)–(\d+)', lambda a, b: (a, b)),
             (r'(?:\\\()?\\ge (\d+)(?:\\\))?', lambda a: (a, math.inf)), (r'= (\d+)', lambda a: (a, a)),
             (r'\\in \\\{(\d+)(?:, \d+)*, (\d+)\\\}', lambda a, b: (a, b)), (r'\\in \\\{(\d+), \\ldots, (\d+)\\\}', lambda a, b: (a, b)))
    def value(v):
        hits = [f(*map(int, m.groups())) for p, f in forms for m in [re.fullmatch(p, v)] if m]
        assert len(hits) == 1, v
        assert '\\ldots' in v or not v.startswith('\\in') or [int(t) for t in re.findall(r'\d+', v)] == list(range(hits[0][0], hits[0][1] + 1)), v
        return hits[0]
    table = []
    for t in re.findall(r'<table class="block">.*?</table>', ''.join(new_frames(page())), re.S):
        ns = re.findall(r'<td([^>]*)>(.*?)</td>', re.search(r'<tr class="ns">.*?</tr>', t, re.S).group(0))
        vs = re.findall(r'<td[^>]*>(.*?)</td>', re.search(r'<tr class="vals">.*?</tr>', t, re.S).group(0))
        assert len(ns) == len(vs) and ns, t
        table += [(n_of(n), *value(v), re.fullmatch(r'(?: class="(\w+)")? title=\'[^\']*\'', attr).group(1) or '')
                  for (attr, n), v in zip(ns, vs)]    # the cells without a provenance class copy Table 2's entries
    remarks = []
    entry = (r'<li(?: class="(\w+)")?(?: id="\w+")?>\s*<span class="mk" aria-hidden="true">[^<]*</span>\s*'
             r'<p class="entry">\\\(n = ([^:]*?)\\\): &nbsp;\\\(m\^\* (.*?)\\\)</p>')
    for cls, ns, v in re.findall(entry, page()):
        remarks += [(n_of(n if n.isdigit() else f'\\({n}\\)'), *value(v), cls) for n in ns.split(', ')]
    assert len(re.findall(entry, page())) == page().count('<p class="entry">'), 'an entry outside the form'
    # 512 and 1024 stand twice, in the upper rows and as powers of 2 (since 2026-10-27), as the same cell; each remark once
    cells = {n: c for n, lo, hi, c in table}
    assert len(remarks) == len({n for n, *_ in remarks}), remarks
    assert sorted(n for n, c in cells.items() if c) == sorted(n for n, lo, hi, c in remarks if c), (cells, remarks)
    assert all(cells[n] == c for n, lo, hi, c in remarks), [(n, c, cells.get(n)) for n, lo, hi, c in remarks]
    wrong = [(where, n, lo, hi, chart(n)) for where, got in (('table', [t for t in table if t[3]]), ('remark', remarks))
             for n, lo, hi, c in got if [lo, hi] != chart(n)]
    assert not wrong, wrong


def q_citations_match_the_page():
    # Replicata: mstar.js's reasons that cite the page: ["table2"] and ["page", who], as loWhy or hiWhy; and the new
    # results' cells, their provenance classes and titles.
    # Expectata: a ["table2"] column is one of Table 2's n; a ["page", who] column is one of the new results' n.  As
    # hiWhy, who is its cell's class (whose proof; the cell's title until 2026-11-09, when the credits became the
    # classes and the titles' words the page's alone).
    fig = re.search(r'<figure>.*?</figure>', page(), re.S).group(0)
    new = ''.join(new_frames(page()))
    value = lambda cell: int(cell) if cell.isdigit() else 2 ** int(re.fullmatch(r'\\\(2\^\{?(\d+)\}?\\\)', cell).group(1))
    titled = {value(n): (cls, who) for cls, who, n in
              re.findall(r"<td(?: class=\"(a|c|ca|cf|j|s)\")? title='([^']*)'>([^<]*)</td>", new)}
    classes = {n: cls for n, (cls, who) in titled.items() if cls}      # their classes; the rest, unclassed, copy Table 2's powers of 2
    # 240 (since 2026-10-20) and 288 (since 2026-11-08, the form-tree proof), the 44 multiples of 16 from 304 to 992 (512 written 2^9) and 32 larger powers of 2,
    # 2^17 to 2^72 (6 until 560 reached order 10 on 2026-10-12, 11 until 800 reached order 11 on 2026-10-17, 18
    # until 592, 608 and 656 reached order 10 and 848, 880, 896, 928, 944, 976 and 992 order 11 on 2026-10-25, 23
    # until 752 and 784 reached order 10 and 832 order 11 on 2026-10-26, 25 until 912 reached order 12 on 2026-10-28,
    # when 2^29 joined them, 26 until 768 reached order 12 that evening, when 2^39 joined them, 27 until 2026-11-03, when 2^28, 2^36 and 2^47 joined them, 30
    # until later that day, when 2^56 and 2^58 joined them); and since 1024 reached
    # order 11, later that
    # day, 2^10, 2^11 and 2^12; and since 2026-10-27, when the block reached 1024, 1008.  The unclassed cells, Table
    # 2's powers of 2 (2^3 to 2^8) until then, copy every entry of Table 2 that stands: up to 304 but 240, 288 and 304.
    # (1 + 44 + 33 + 1 until 2^56 and 2^58 joined them, later on 2026-11-03; 1 + 44 + 35 + 1 until 288 joined them,
    # on 2026-11-08.)  Spec change (Opus 5.5, 2026-11-19; q_sequences_past_the_chart_move_seven_firsts): 41 powers of 2 since
    # then, 2^22, 2^35, 2^42, 2^50, 2^55 and 2^63 the new firsts (35 until then).
    # (Fable 5.2, 2026-11-21, with q_powers_of_2_on_the_page_follow_pow2_js: the count of classed cells, 2 + 44 + 41 + 1 until then and changed at every new cell, is no longer asked.)
    assert sorted(n for n in titled if n not in classes) == [n for n in range(8, 305, 8) if n not in (240, 288, 304)], titled
    table2 = {n for n, *_ in table_entries()} - set(classes)
    assert len(table2) == 35, sorted(table2)          # 240, 288 and 304 are in both (36 until 288 joined them, 2026-11-08)
    cited = 0
    for n, (lo, hi, lw, hw) in enumerate(mstar_data()['cols'], 1):
        for w in (lw, hw):
            if w[0] == 'table2': assert n in table2 | {304}, (n, w); cited += 1
            if w[0] == 'page': assert n in classes, (n, w); cited += 1
        if hw[0] == 'page': assert classes[n] == hw[1], (n, hw, classes[n])
    assert cited, 'mstar.js cites neither table'


def q_claude_and_astra_is_a_category_like_claude_and_bgpw():
    # Replicata: the page's CSS, its legend, the new results' cells and the remarks' entries of 592, 608, 656, 752 and
    # 784.
    # Expectata (2026-10-25, the main session's ruling on dreeves's "a new 'Claude and Astra' category makes sense to
    # me"): as Claude and BGPW's (q_chart_colors_stand_apart), the class ca has no hue of its own: its cells and legend
    # key are stripes of --claude's and --astra's tints over a striped bar, and its glyph ◆✦ is half in each hue; the
    # legend has its key right after Astra's; the cells titled Claude and Astra are 592, 608,
    # 656 and 752, each of class ca with its value; and each of their remarks is an <li class="ca"> marked ◆✦.  (Since
    # 2026-10-26 also 784, credited for the reason 608 and 656 are, and 752 at 10, both by examples of order 10.)
    css = page_css()
    tints = ('repeating-linear-gradient(135deg, color-mix(in oklab, var(--claude) var(--tint), var(--paper)) 0 0.3rem, '
             'color-mix(in oklab, var(--astra) var(--tint), var(--paper)) 0.3rem 0.6rem)')
    bar = 'repeating-linear-gradient(90deg, var(--claude) 0 0.3rem, var(--astra) 0.3rem 0.6rem) bottom / 100% 3px no-repeat'
    half = 'linear-gradient(90deg, var(--claude) 50%, var(--astra) 50%)'
    assert 'td.ca { --glyph: "◆✦"; }' in css
    assert f'td.ca, .key.ca {{ background: {tints}; }}' in css
    assert f'tr.vals td.ca, .key.ca {{ background: {bar}, {tints}; box-shadow: none; }}' in css
    assert (f'tr.ns td.ca::before, .key.ca > span, .remarks li.ca .mk {{ background: {half}; -webkit-background-clip: text; '
            'background-clip: text; color: transparent; }') in css
    text = page()
    assert re.search(r'<li><span class="key a" aria-hidden="true">✦</span>[^\n]*</li>\n'
                     r'    <li><span class="key ca" aria-hidden="true"><span>◆✦</span></span>[^\n]*</li>\n', text)
    new = ''.join(new_frames(text))
    ca = []
    for t in re.findall(r'<table class="block">.*?</table>', new, re.S):
        ns = re.findall(r'<td([^>]*)>(.*?)</td>', re.search(r'<tr class="ns">.*?</tr>', t, re.S).group(0))
        vs = re.findall(r'<td([^>]*)>(.*?)</td>', re.search(r'<tr class="vals">.*?</tr>', t, re.S).group(0))
        assert len(ns) == len(vs), t
        for (a, n), (b, v) in zip(ns, vs):
            assert bool(re.fullmatch(r' class="ca" title=\'[^\']+\'', a)) == (b == ' class="ca"'), (n, a, b)   # the class, whatever its title's words (2026-11-09)
            if b == ' class="ca"': ca.append((n, v))
    # Spec change (Opus 5.5, 2026-11-19; q_sequences_past_the_chart_move_seven_firsts): the cells whose lows Astra's joins at 2^63 and 2^68 give, of the
    # sequences of order 13 past the chart, are of class ca too: 2^63, 2^65, 2^66, 2^67, 2^68, 2^71 and 2^72, each of their remarks an <li class="ca"> marked ◆✦
    # (592, 608, 656, 752 and 784 alone until then).
    # (Fable 5.2, 2026-11-21, with q_powers_of_2_on_the_page_follow_pow2_js: which cells are of the class, not what they read; until then each with its
    # value, 10 at the five lengths and 72–78, 74–81, 75–82, 76–83, 78–84, 81–88 and 82–89 at the powers of 2, which the first at 2^67 changed.)
    # (And later that day: the five lengths, then whichever powers of 2 carry the class, each one's entry of the class too; the powers 63, 65, 66, 67,
    # 68, 71 and 72 as a literal until then.)
    assert [n for n, v in ca][:5] == ['592', '608', '656', '752', '784'] and all(n.startswith('\\(2^') for n, v in ca[5:]), ca
    for n in [re.escape(n.removeprefix('\\(').removesuffix('\\)')) for n, v in ca]:
        li = re.search(r'<li class="(\w+)">\n      <span class="mk" aria-hidden="true">([^<]*)</span>\n      <p class="entry">\\\(n = '
                       + str(n) + r'\\\): ', text)
        assert li and li.groups() == ('ca', '◆✦'), (n, li and li.groups())


def q_opus_and_fable_is_a_category_of_its_own():
    # Replicata: the page's CSS, its legend, the new results' cells and the remarks' entries of 2^30, 2^33, 2^34, 2^51 and 2^52.
    # Expectata (dreeves, 2026-11-11, of the cells whose lower bounds Fable 5.2 raised that day and which still carried Opus 5.5's marks: "yes, please make the
    # legend accurate"): a class cf, as ca is one (q_claude_and_astra_is_a_category_like_claude_and_bgpw).  Both models being Claude, it has --claude's hue, as c
    # has, and a glyph of its own, ◆◇; the legend has its key right after c's (a comment line may stand between them), with a label, so that the charts'
    # credit('cf') has its words; the cells of class cf are 2^30, 2^33, 2^34, 2^51 and 2^52 (each lower bound from the joins at 2^30 and 2^51, which are Fable
    # 5.2's, each upper bound older), both rows of each; and each of their remarks is an <li class="cf"> marked ◆◇.
    # Resultata before: those cells were of class c, and 2^51's of class j, the classes of the legend lines for Opus 5.5 alone and for Opus 5.5 and BGPW.
    # Spec change (Opus 5.5, 2026-11-17): 480 is of class cf too, the other way around, its lower bound Opus 5.5's example and its upper bound 13 Fable 5.2's
    # run of a form-tree proof (searches/formtree/cells/480_14), its remark an <li class="cf"> marked ◆◇; of class c until then, at 12 to 14.
    css = page_css()
    assert 'td.cf { --hue: var(--claude); --glyph: "◆◇"; }' in css
    assert 'td.a, td.c, td.cf, td.j, td.s { background: color-mix(in oklab, var(--hue) var(--tint), var(--paper)); }' in css
    assert 'tr.vals td.a, tr.vals td.c, tr.vals td.cf, tr.vals td.j, tr.vals td.s { box-shadow: inset 0 -3px 0 var(--hue); }' in css
    assert '.key.cf { --hue: var(--claude); }' in css and '.remarks li.cf .mk { color: var(--claude); }' in css
    text = page()
    assert re.search(r'<li><span class="key c" aria-hidden="true">◆</span>[^\n]*</li>\n(?:    <!--[^\n]*-->\n)?'
                     r'    <li><span class="key cf" aria-hidden="true">◆◇</span>[^\n]*</li>\n', text)
    assert legend_labels(text)['cf'].strip()
    new = ''.join(new_frames(text))
    cf = []
    for t in re.findall(r'<table class="block">.*?</table>', new, re.S):
        ns = re.findall(r'<td([^>]*)>(.*?)</td>', re.search(r'<tr class="ns">.*?</tr>', t, re.S).group(0))
        vs = re.findall(r'<td([^>]*)>(.*?)</td>', re.search(r'<tr class="vals">.*?</tr>', t, re.S).group(0))
        assert len(ns) == len(vs), t
        for (a, n), (b, v) in zip(ns, vs):
            assert bool(re.fullmatch(r' class="cf" title=\'[^\']+\'', a)) == (b == ' class="cf"'), (n, a, b)
            if b == ' class="cf"': cf.append(n)
    # Spec change (Opus 5.5, 2026-11-19; q_sequences_past_the_chart_move_seven_firsts): the cells whose lows the joins past the chart give or raise, each a join
    # with a product of the sequences at 2528 or 2608, Fable 5.2's of 2026-11-11, are of class cf too: 2^22, 2^24, 2^27, 2^35, 2^36, 2^37, 2^38, 2^42, 2^43,
    # 2^46, 2^50, 2^55, 2^56 and 2^57 (2^24 of class j until then; (30, 33, 34, 51, 52) alone until then).
    # (Fable 5.2, 2026-11-21, with q_powers_of_2_on_the_page_follow_pow2_js: 480, then whichever powers of 2 carry the class, each one's entry of the class too; the powers 22 to 57 as a literal until then.)
    assert cf[0] == '480' and all(n.startswith('\\(2^') for n in cf[1:]), cf
    for name in [re.escape(n.removeprefix('\\(').removesuffix('\\)')) for n in cf]:
        li = re.search(r'<li class="(\w+)">\n      <span class="mk" aria-hidden="true">([^<]*)</span>\n      <p class="entry">\\\(n = %s\\\): ' % name, text)
        assert li and li.groups() == ('cf', '◆◇'), (name, li and li.groups())


def q_examples_of_2026_10_25_have_entries_and_codes():
    # Replicata: the remarks' entries of 592, 608, 656 (order 10) and 848, 880, 896, 928, 944, 976, 992 (order 11),
    # each code in them decoded by the paper's Table 5 convention (the left half of the signs, 1 = +1, then the rest by
    # (-1)^m symmetry), and mstar.js's columns.
    # Expectata: each n has an entry of its own, "m* = m", in 800's form: its one code block, p_n of order m, whose
    # signs have order exactly m (synthetic division here), symmetric for even m and antisymmetric for odd; and
    # mstar.js's column n is [m, m, ["example", "equipow p" + n], hiWhy].  (Its set SClaude[m][n], those signs' +1
    # positions, left the page on 2026-10-31: quals_codes.q_former_sets_are_halves_of_expansions keeps it.)
    text, cols = page(), mstar_data()['cols']
    def order(a):                                  # (x - 1) divides exactly order(a) times: synthetic division
        c, k = list(a), 0
        while not sum(c): c, k = [sum(c[:i + 1]) for i in range(len(c) - 1)], k + 1
        return k
    for n, m in [(592, 10), (608, 10), (656, 10)] + [(n, 11) for n in (848, 880, 896, 928, 944, 976, 992)]:
        li = re.search(r'<li class="\w+">\n      <span class="mk" aria-hidden="true">[^<]*</span>\n      <p class="entry">\\\(n = '
                       + str(n) + r'\\\): &nbsp;\\\(m\^\* = (\d+)\\\)</p>\n(.*?)\n    </li>', text, re.S)
        assert li and int(li.group(1)) == m, n
        lo, hi, lw, hw = cols[n - 1]
        assert [lo, hi, lw] == [m, m, ['example', f'equipow p{n}']], (n, cols[n - 1])
        codes = re.findall(r'<p class="code">\n        <span>\\\(p_\{(\d+)\}\\\) \\\(\(m = (\d+)\)\\\):</span>\n'
                           r'        <code id="\d+:\d+">([0-9A-F]+)</code>\n      </p>', li.group(2))
        assert len(codes) == 1 and codes[0][:2] == (str(n), str(m)), (n, codes)
        h = codes[0][2]
        left = [1 if b == '1' else -1 for b in bin(int(h, 16))[2:].zfill(4 * len(h))]
        a = left + [(-1) ** m * s for s in reversed(left)]
        assert len(a) == n and order(a) == m, (n, len(a), order(a))


def q_752_bound_cites_proof752():
    # Replicata: the remarks' entry of 752, mstar.js's column 752, and the repository's files.
    # Expectata (2026-10-25: proof752.py proves m*(752) <= 10, extending Astra's method for 384 with Claude's meet in
    # the middle): the entry links proof752.py at its GitHub address; mstar.js's column 752 has hi 10 and hiWhy
    # ["page", "Claude and Astra"]; and proof752.py is in the working directory.  Since 2026-10-26, when Claude's
    # search found an example of order 10 at 752, the entry is "m* = 10" and the column is [10, 10, ["example",
    # "equipow p752"], …].
    li = re.search(r'<p class="entry">\\\(n = 752\\\): &nbsp;\\\(m\^\* = 10\\\)</p>\n(.*?)\n    </li>',
                   page(), re.S)
    assert li, 'no entry for 752 alone'
    assert 'href="https://github.com/dreeves/equipow/blob/main/proofs/proof752.py"' in li.group(1), li.group(1)[:600]
    assert mstar_data()['cols'][752 - 1] == [10, 10, ['example', 'equipow p752'], ['page', 'ca']]
    assert os.path.isfile(os.path.join(HERE, 'proofs', 'proof752.py'))       # in proofs/ since [FAC] stage 3a


def q_288_bound_is_proved_here():
    # Replicata: index.html's figure of Table 2 and its remarks under "Where the new results come from", mstar.js's
    # column 288, and the repository's files.
    # Expectata (2026-10-25: proof288.py proves m*(288) <= 10, Table 2's upper value, so no cell changes; 2026-10-27,
    # dreeves, of the note under Table 2 that said so: "can you put that in the 'where the new results come from'
    # section instead and just clarify that that one isn't technically new but is rederived here?"): the figure no
    # longer mentions proof288.py; the remarks have an entry of 288 alone, "m* ∈ {9, 10}", right after 240's and right
    # before 304's, in an <li> without a class and with an empty marker, as 288's cell in the new results has no
    # provenance class (the paper's value), and it links proof288.py at its GitHub address; mstar.js's column 288
    # cites Table 2, [9, 10, …, ["table2"]]; and proof288.py is in the working directory.
    # Spec change (Claude, 2026-11-08: the form-tree proof settled m*(288) = 9, quals_mstar's q_288_is_settled_at_9):
    # the entry, still right after 240's and before 304's, is a new result, "m* = 9", in an <li> of class j with the
    # marker ◆●, as its cell is Claude's and BGPW's; it still links proof288.py, and links the form-tree proof too: its
    # Python checker proofs/formtree.py, its checker fkernel.cpp and its saved verdicts
    # searches/formtree/run288v_snapshot.tar.gz, each at its GitHub address and in the working directory, and the
    # search's directory searches/formtree; mstar.js's column 288 is [9, 9, ["product", 2, 144], ["page", "Claude and
    # BGPW"]].  Until then the entry read "m* ∈ {9, 10}" in an <li> without a class, and the column cited Table 2.
    text = page()
    fig = re.search(r'<figure>.*?</figure>', text, re.S).group(0)
    assert 'proof288' not in fig, fig[:600]
    li = re.search(r'<li class="j">\n      <span class="mk" aria-hidden="true">◆●</span>\n      <p class="entry">\\\(n = 288\\\): &nbsp;'
                   r'\\\(m\^\* = 9\\\)</p>\n(.*?)\n    </li>', text, re.S)
    files = ('proofs/proof288.py', 'proofs/formtree.py', 'proofs/fkernel.cpp', 'searches/formtree/run288v_snapshot.tar.gz')
    assert li and all(f'href="https://github.com/dreeves/equipow/blob/main/{f}"' in li.group(1) for f in files) \
        and 'href="https://github.com/dreeves/equipow/tree/main/searches/formtree"' in li.group(1), li and li.group(1)
    listed = re.findall(r'<p class="entry">\\\(n = (.*?)\\\): ', text)
    assert listed[listed.index('288') - 1:listed.index('288') + 2] == ['240', '288', '304'], listed
    col = mstar_data()['cols'][288 - 1]
    assert col == [9, 9, ['product', 2, 144], ['page', 'j']], col
    assert all(os.path.isfile(os.path.join(HERE, *f.split('/'))) for f in files), files


def q_examples_of_2026_10_26_have_entries_and_codes():
    # Replicata: the remarks' entries of 752 and 784 (order 10) and 832 (order 11), each code in them decoded by the
    # paper's Table 5 convention (the left half of the signs, 1 = +1, then the rest by (-1)^m symmetry), the order of
    # the remarks' entries, and mstar.js's columns.
    # Expectata (2026-10-26, the second recording pass): each n has an entry of its own, "m* = m", in the form of the
    # first pass's (q_examples_of_2026_10_25_have_entries_and_codes): its one code block, p_n of order m, whose signs
    # have order exactly m (synthetic division here), symmetric for even m and antisymmetric for odd; mstar.js's column
    # n is [m, m, ["example", "equipow p" + n], hiWhy]; no entry lists n with another n; and the entries run in order
    # of n among the examples': 656's, 752's, 784's, 800's, 832's, 848's.  (Its set SClaude[m][n] left the page on
    # 2026-10-31: quals_codes.q_former_sets_are_halves_of_expansions keeps it.)
    text, cols = page(), mstar_data()['cols']
    def order(a):                                  # (x - 1) divides exactly order(a) times: synthetic division
        c, k = list(a), 0
        while not sum(c): c, k = [sum(c[:i + 1]) for i in range(len(c) - 1)], k + 1
        return k
    for n, m in ((752, 10), (784, 10), (832, 11)):
        li = re.search(r'<li class="\w+">\n      <span class="mk" aria-hidden="true">[^<]*</span>\n      <p class="entry">\\\(n = '
                       + str(n) + r'\\\): &nbsp;\\\(m\^\* = (\d+)\\\)</p>\n(.*?)\n    </li>', text, re.S)
        assert li and int(li.group(1)) == m, n
        lo, hi, lw, hw = cols[n - 1]
        assert [lo, hi, lw] == [m, m, ['example', f'equipow p{n}']], (n, cols[n - 1])
        codes = re.findall(r'<p class="code">\n        <span>\\\(p_\{(\d+)\}\\\) \\\(\(m = (\d+)\)\\\):</span>\n'
                           r'        <code id="\d+:\d+">([0-9A-F]+)</code>\n      </p>', li.group(2))
        assert len(codes) == 1 and codes[0][:2] == (str(n), str(m)), (n, codes)
        h = codes[0][2]
        left = [1 if b == '1' else -1 for b in bin(int(h, 16))[2:].zfill(4 * len(h))]
        a = left + [(-1) ** m * s for s in reversed(left)]
        assert len(a) == n and order(a) == m, (n, len(a), order(a))
    listed = [ns.split(', ') for ns in re.findall(r'<p class="entry">\\\(n = (.*?)\\\): ', text)]
    assert [ns for ns in listed if {'752', '784', '832'} & set(ns)] == [['752'], ['784'], ['832']], listed
    run = [ns[0] for ns in listed if ns[0] in ('656', '752', '784', '800', '832', '848')]
    assert run == ['656', '752', '784', '800', '832', '848'], run


def q_example_at_1024_has_its_entry_code_and_cell():
    # Replicata: the remarks' entry of 1024, its code decoded by the paper's Table 5 convention (the left half of the
    # signs, 1 = +1, then the rest by (-1)^m symmetry), the new results' cells of the powers of 2, and pow2.js's column
    # 2^10.
    # Expectata (2026-10-26: Claude's lattice search found an example of order 11 at 1024; with m*(2^9) = 9 it makes 2^10
    # the first power of 2 to beat Thue-Morse, and the norm bound for 3 caps it at 11): an entry of its own, "m* = 11",
    # an <li class="c"> marked ◆, in the form of the examples' entries (q_examples_of_2026_10_26_have_entries_and_codes),
    # right after 992's, the last of the examples' until 1008's came between them (2026-10-27 night,
    # q_examples_at_720_and_1008_have_their_entries_and_codes); its one code block, p1024 of order 11, whose signs have order
    # exactly 11 (synthetic division here) and are antisymmetric (its set SClaude[11][1024], their +1 positions, left
    # the page on 2026-10-31); the cell 2^10, of class c titled Claude alone, value 11, right after 2^9's; and
    # pow2.js's column 2^10 is [11, 11, ["joins", [[[1024, 11]]]], ["mstar", ["norm", 3]]]: since 2026-10-27, when the
    # m*(n) chart reached 1024, its hi is that chart's column 1024 (before, ["norm", 3] by pow2.py's own norm bound,
    # the same one).
    text = page()
    li = re.search(r'<li class="c">\n      <span class="mk" aria-hidden="true">◆</span>\n      <p class="entry">\\\(n = '
                   r'1024\\\): &nbsp;\\\(m\^\* = 11\\\)</p>\n(.*?)\n    </li>', text, re.S)
    assert li, 'no entry of 1024 alone'
    codes = re.findall(r'<p class="code">\n        <span>\\\(p_\{(\d+)\}\\\) \\\(\(m = (\d+)\)\\\):</span>\n'
                       r'        <code id="\d+:\d+">([0-9A-F]+)</code>\n      </p>', li.group(1))
    assert len(codes) == 1 and codes[0][:2] == ('1024', '11'), codes
    h = codes[0][2]
    left = [1 if b == '1' else -1 for b in bin(int(h, 16))[2:].zfill(4 * len(h))]
    a, k = left + [-s for s in reversed(left)], 0
    c = a
    while not sum(c): c, k = list(itertools.accumulate(c[:-1])), k + 1
    assert len(a) == 1024 and k == 11 and all(a[1023 - i] == -a[i] for i in range(1024)), (len(a), k)
    listed = [ns.split(', ') for ns in re.findall(r'<p class="entry">\\\(n = (.*?)\\\): ', text)]
    assert listed[listed.index(['992']) + 1:listed.index(['992']) + 3] == [['1008'], ['1024']], listed
    row = re.search(r'<td title=\'[^\']*\'>\\\(2\^3\\\)</td>.*?</tr>\s*<tr class="vals">.*?</tr>',
                    text, re.S).group(0)
    ns = re.findall(r'<td([^>]*)>\\\(2\^\{?(\d+)\}?\\\)</td>', row)
    vals = re.findall(r'<td([^>]*)>([^<]*)</td>', row.split('<tr class="vals">')[1])
    i = [k for _, k in ns].index('10')
    assert ns[i - 1][1] == '9' and re.fullmatch(r' class="c" title=\'[^\']+\'', ns[i][0]) and vals[i] == (' class="c"', '11'), (ns, vals)
    # (2026-11-16; dreeves: "ok, go ahead with breaking ties in favor of the mod-3 argument": the m*(n) chart's reason
    # at 1024 is the residue condition mod 3, which comes before the norm bound since that day and gives the same 11;
    # ["mstar", ["norm", 3]] until then)
    assert pow2_data()['cols'][9] == [11, 11, ['joins', [[[1024, 11]]]], ['mstar', ['residue', 3]]], pow2_data()['cols'][9]


def q_symmetric_example_at_528():
    # Replicata: the remarks' entry of 528 and its code blocks, each decoded by the paper's Table 5 convention (the left
    # half of the signs, 1 = +1, then the rest by (-1)^m symmetry), and synthetic division by x - 1.
    # Expectata (2026-10-27, dreeves: "sure", to putting a symmetric 528 example on the page; four were found that day
    # by a lattice search, scratch/sym528): the entry keeps the join's code p192 and adds p528 (m = 10), which decodes
    # to a symmetric sequence of length 528, exact order 10, +1 at 0; since 2026-10-31 a third code follows them, p528
    # (m = 11) (q_example_at_528_has_its_entry_and_code).  (Its set SClaudeSym[10][528], beside the join's
    # SClaude[10][528], left the page on 2026-10-31: quals_codes.q_former_sets_are_halves_of_expansions keeps both.)
    li = re.search(r'<p class="entry">\\\(n = 528\\\): .*?</li>', page(), re.S)
    assert li, 'no entry of 528'
    codes = re.findall(r'\\\(p_\{(\d+)\}\\\) \\\(\(m = (\d+)\)\\\):</span>\n\s*<code id="\d+:\d+">([0-9A-F]+)</code>',
                       li.group(0))
    assert [c[:2] for c in codes] == [('192', '9'), ('528', '10'), ('528', '11')], codes
    h = codes[1][2]
    left = [1 if b == '1' else -1 for b in bin(int(h, 16))[2:].zfill(4 * len(h))]
    a, k = left + left[::-1], 0
    c = a
    while not sum(c): c, k = list(itertools.accumulate(c[:-1])), k + 1
    assert len(a) == 528 and k == 10 and a == a[::-1] and a[0] == 1, (len(a), k)


def q_1024_doubled_settles_2_11_and_2_12():
    # Replicata: the new results' cells of the powers of 2, the remarks' entries of 2^11 and 2^12, the changelog's
    # statements of 2026-10-26, and pow2.js's columns 2^11 and 2^12.
    # Expectata (2026-10-26: the example of order 11 at 1024 times τ1 and τ2 has orders 12 and 13, which the residue
    # condition mod 3 allows and no more): pow2.js's columns are [12, 12, ["joins", [[[1024, 11], [2, 1]]]],
    # ["residue", [3]]] and [13, 13, ["joins", [[[1024, 11], [4, 2]]]], ["residue", [3]]]; the cells 2^11 and 2^12, of
    # class c titled Claude alone, values 12 and 13, right after 2^10's; each has an entry of its own, "m* = 12" and
    # "m* = 13", right before 2^17's (its wording unpinned since 2026-10-30); and the
    # changelog states m*(2^11) = 12 and m*(2^12) = 13 on 2026-10-26, together on a line of their own.
    # Since 2026-11-10 the m*(n) chart's data reach 2048 ([BOU]), so 2^11 is one of its columns and pow2.js takes its
    # upper bound from there, the same bound by the same residue condition: ["mstar", ["residue", 3]].
    cols, text = pow2_data()['cols'], page()
    assert cols[10] == [12, 12, ['joins', [[[1024, 11], [2, 1]]]], ['mstar', ['residue', 3]]], cols[10]
    # (Spec change, Opus 5.5, 2026-11-29; dreeves, of a cap at 4096: "worth it": the m*(n) chart's data reach 4096, so 2^12 is one of its columns too, and pow2.js takes its
    # upper bound from there, the same bound by the same condition: ["mstar", ["residue", 3]]; ["residue", [3]] until then.)
    assert cols[11] == [13, 13, ['joins', [[[1024, 11], [4, 2]]]], ['mstar', ['residue', 3]]], cols[11]
    row = re.search(r'<td title=\'[^\']*\'>\\\(2\^3\\\)</td>.*?</tr>\s*<tr class="vals">.*?</tr>',
                    text, re.S).group(0)
    ns = re.findall(r'<td([^>]*)>\\\(2\^\{?(\d+)\}?\\\)</td>', row)
    vals = re.findall(r'<td([^>]*)>([^<]*)</td>', row.split('<tr class="vals">')[1])
    i = [k for _, k in ns].index('10')
    # (Fable 5.2, 2026-11-21, with q_powers_of_2_on_the_page_follow_pow2_js: the three side by side; until then also 2^17 right after them, which 2^13's cell now is.)
    assert [k for _, k in ns[i:i + 3]] == ['10', '11', '12'], ns
    assert all(re.fullmatch(r' class="c" title=\'[^\']+\'', a) for a, _ in ns[i + 1:i + 3]), ns
    assert vals[i + 1:i + 3] == [(' class="c"', '12'), (' class="c"', '13')], vals
    listed = re.findall(r'<p class="entry">\\\(n = (.*?)\\\): ', text)
    j = listed.index('2^{11}')
    assert listed[j:j + 2] == ['2^{11}', '2^{12}'], listed
    for k, m in ((11, 12), (12, 13)):
        li = re.search(r'<li class="c">\n      <span class="mk" aria-hidden="true">◆</span>\n      <p class="entry">\\\(n = '
                       rf'2\^\{{{k}\}}\\\): &nbsp;\\\(m\^\* = {m}\\\)</p>\n(.*?)\n    </li>', text, re.S)
        assert li, k
    entries = [(d, statements(rest)) for d, rest in changelog()]
    assert ('2026-10-26', {2 ** 11: (12, 12), 2 ** 12: (13, 13)}) in entries, entries[:4]


def q_example_at_816_has_its_entry_and_code():
    # Replicata: the remarks' entries of 720 and 816, 816's code decoded by the paper's Table 5 convention (the left
    # half of the signs, 1 = +1, then the rest by (-1)^m symmetry), the new results' cells, and mstar.js's columns 720
    # and 816.
    # Expectata (2026-10-26: Claude's lattice search found an antisymmetric example of order 11 at 816, which the
    # norm bound for the residue sums mod 5 leaves at 11 to 14; 2026-10-28: w12.py found a symmetric example of order
    # 12 there, which replaced it and its code; 2026-11-03: a pin tree rules order 13 out): 816 has an entry of its own, "m* = 12" ("m* ∈ {12, 13, 14}" until 2026-11-03), an
    # <li class="c"> marked ◆, right after 800's and before 832's (its wording unpinned since 2026-10-30); its
    # one code block, p816 of order 12, whose signs have order exactly 12 (synthetic division here) and are
    # symmetric (its set SClaude[12][816] left the page on 2026-10-31); 720's entry alone
    # (it shared one with 816 before; its own example since 2026-10-27,
    # q_examples_at_720_and_1008_have_their_entries_and_codes); the cell 816 of value 12 (12–14 until 2026-11-03); and mstar.js's
    # column 816 is [12, 12, ["example", "equipow p816"], ["page", "Claude alone"]] ([12, 14, ["example", "equipow p816"], ["norm", 5]] until 2026-11-03).
    text = page()
    li = re.search(r'<li class="c">\n      <span class="mk" aria-hidden="true">◆</span>\n      <p class="entry">\\\(n = '
                   r'816\\\): &nbsp;\\\(m\^\* = 12\\\)</p>\n(.*?)\n    </li>', text, re.S)
    assert li, 'no entry of 816 alone'
    codes = re.findall(r'<p class="code">\n        <span>\\\(p_\{(\d+)\}\\\) \\\(\(m = (\d+)\)\\\):</span>\n'
                       r'        <code id="\d+:\d+">([0-9A-F]+)</code>\n      </p>', li.group(1))
    assert len(codes) == 1 and codes[0][:2] == ('816', '12'), codes
    h = codes[0][2]
    left = [1 if b == '1' else -1 for b in bin(int(h, 16))[2:].zfill(4 * len(h))]
    a, k = left + list(reversed(left)), 0
    c = a
    while not sum(c): c, k = list(itertools.accumulate(c[:-1])), k + 1
    assert len(a) == 816 and k == 12 and all(a[815 - i] == a[i] for i in range(816)), (len(a), k)
    listed = [ns.split(', ') for ns in re.findall(r'<p class="entry">\\\(n = (.*?)\\\): ', text)]
    i = listed.index(['816'])
    assert listed[i - 1:i + 2] == [['800'], ['816'], ['832']] and ['720'] in listed, listed
    assert new_cells(text)[816] == (12, 12), new_cells(text)[816]
    assert mstar_data()['cols'][816 - 1] == [12, 12, ['example', 'equipow p816'], ['page', 'c']], mstar_data()['cols'][816 - 1]


def q_examples_at_720_and_1008_have_their_entries_and_codes():
    # Replicata: the remarks' entries of 720 and 1008, their codes decoded by the paper's Table 5 convention (the left
    # half of the signs, 1 = +1, then the rest by (-1)^m symmetry), the new results' cells, and mstar.js's columns 720
    # and 1008.
    # Expectata (2026-10-27: Claude's lattice search, w11.py at 720 and at 1008, found antisymmetric examples of order
    # 11 there; 2026-10-28: w12.py found a symmetric example of order 12 at 1008, which replaced its order-11 example
    # and code, and that evening Astra's faster w12 found one at 720, which did the same): each has an entry of its
    # own, an <li class="c"> marked ◆ among the examples in order of n, 720's "m* ∈ {13, 14}" ("m* ∈ {12, 13, 14}" until 2026-11-03) between 688's (656's
    # until 2026-11-01, when 672's and then 688's example entries came between them) and 752's, and 1008's "m* = 13" ("m* ∈ {12, 13}" until 2026-11-03) between 992's and 1024's (its wording unpinned since 2026-10-30); each a code block of its
    # order m (11 at 720, 12 at 1008), whose signs have order exactly m (synthetic division here) and are
    # antisymmetric at 720 and symmetric at 1008 (their sets SClaude[m][n] left the page on 2026-10-31), each followed by that of order 13
    # (since 2026-11-03: q_results_of_2026_11_03_have_entries_and_codes at 1008, and at 720 q_example_at_720_has_its_code_of_order_13,
    # the beam campaign's; 720's was its only one until then); no other
    # entry names 720 or 1008 (their joins' entries are gone); the cells 13–14 and 13 (12–14 and 12–13 until 2026-11-03);
    # and mstar.js's columns [13, 14, ["example", "equipow p720"], ["residue", 16]] and [13, 13, ["example",
    # "equipow p1008"], ["residue", 5]].
    # (Spec change, Opus 5.5, 2026-11-18: the entries are in the appendix, one length each, in order, since the entry of
    # 640, 704 and 736 was split; so 720's entry comes between 704's and 736's.)
    text = page()
    listed = [ns.split(', ') for ns in re.findall(r'<p class="entry">\\\(n = (.*?)\\\): ', text)]
    for n, m, values, before, after, cell, more in ((720, 12, '\\\\in \\\\\\{13, 14\\\\\\}', '704', '736', (13, 14), ('13',)),
                                                    (1008, 12, '= 13', '992', '1024', (13, 13), ('13',))):
        li = re.search(r'<li class="c">\n      <span class="mk" aria-hidden="true">◆</span>\n      <p class="entry">\\\(n = '
                       rf'{n}\\\): &nbsp;\\\(m\^\* {values}\\\)</p>\n(.*?)\n    </li>', text, re.S)
        assert li, f'no entry of {n} alone'
        codes = re.findall(r'<p class="code">\n        <span>\\\(p_\{(\d+)\}\\\) \\\(\(m = (\d+)\)\\\):</span>\n'
                           r'        <code id="\d+:\d+">([0-9A-F]+)</code>\n      </p>', li.group(1))
        assert [c[:2] for c in codes] == [(str(n), o) for o in (str(m),) + more], codes
        h = codes[0][2]
        left = [1 if b == '1' else -1 for b in bin(int(h, 16))[2:].zfill(4 * len(h))]
        a, k = left + [(-1) ** m * s for s in reversed(left)], 0
        c = a
        while not sum(c): c, k = list(itertools.accumulate(c[:-1])), k + 1
        assert len(a) == n and k == m and all(a[n - 1 - i] == (-1) ** m * a[i] for i in range(n)), (n, len(a), k)
        i = listed.index([str(n)])
        assert listed[i - 1:i + 2] == [[before], [str(n)], [after]], listed[i - 1:i + 2]
        assert sum(str(n) in ns for ns in listed) == 1, (n, [ns for ns in listed if str(n) in ns])
        assert new_cells(text)[n] == cell, new_cells(text)[n]
    cols = mstar_data()['cols']
    assert cols[720 - 1] == [13, 14, ['example', 'equipow p720'], ['residue', 16]], cols[720 - 1]
    assert cols[1008 - 1] == [13, 13, ['example', 'equipow p1008'], ['residue', 5]], cols[1008 - 1]


def q_example_at_912_has_its_entry_and_code():
    # Replicata: the remarks' entries naming 912, its code decoded by the paper's Table 5 convention (the left half of
    # the signs, 1 = +1, then the rest by (-1)^m symmetry), the new results' cell, and mstar.js's column 912.
    # Expectata (2026-10-28: Claude's lattice search w12.py found a symmetric example of order 12 at 912): an entry of
    # its own, an <li class="c"> marked ◆, "m* = 13" ("m* ∈ {12, 13}" until 2026-11-03), between 896's and 928's (its wording unpinned since 2026-10-30); a code block, p912 of order 12, whose signs have order exactly 12 (synthetic
    # division here) and are symmetric (its set SClaude[12][912] left the page on 2026-10-31), followed since 2026-11-03 by that of order 13
    # (q_results_of_2026_11_03_have_entries_and_codes); the built entry of
    # 672 and 768 no longer names 912; the cell 13 (12–13 until 2026-11-03); mstar.js's column [13, 13, ["example", "equipow p912"],
    # ["residue", 5]].
    text = page()
    li = re.search(r'<li class="c">\n      <span class="mk" aria-hidden="true">◆</span>\n      <p class="entry">\\\(n = '
                   r'912\\\): &nbsp;\\\(m\^\* = 13\\\)</p>\n(.*?)\n    </li>', text, re.S)
    assert li, 'no entry of 912 alone'
    codes = re.findall(r'<p class="code">\n        <span>\\\(p_\{(\d+)\}\\\) \\\(\(m = (\d+)\)\\\):</span>\n'
                       r'        <code id="\d+:\d+">([0-9A-F]+)</code>\n      </p>', li.group(1))
    assert [c[:2] for c in codes] == [('912', '12'), ('912', '13')], codes
    h = codes[0][2]
    left = [1 if b == '1' else -1 for b in bin(int(h, 16))[2:].zfill(4 * len(h))]
    a, k = left + list(reversed(left)), 0
    c = a
    while not sum(c): c, k = list(itertools.accumulate(c[:-1])), k + 1
    assert len(a) == 912 and k == 12 and all(a[911 - i] == a[i] for i in range(912)), (len(a), k)
    listed = [ns.split(', ') for ns in re.findall(r'<p class="entry">\\\(n = (.*?)\\\): ', text)]
    i = listed.index(['912'])
    assert listed[i - 1:i + 2] == [['896'], ['912'], ['928']], listed[i - 1:i + 2]
    assert sum('912' in ns for ns in listed) == 1 and ['672'] in listed, [ns for ns in listed if '672' in ns]   # 672 and 768 until 768's example
    assert new_cells(text)[912] == (13, 13), new_cells(text)[912]
    assert mstar_data()['cols'][912 - 1] == [13, 13, ['example', 'equipow p912'], ['residue', 5]], mstar_data()['cols'][912 - 1]


def q_example_at_768_has_its_entry_and_code():
    # Replicata: the remarks' entries naming 768, its code decoded by the paper's Table 5 convention (the left half of
    # the signs, 1 = +1, then the rest by (-1)^m symmetry), the new results' cell, and mstar.js's column 768.
    # Expectata (2026-10-28 evening: Claude's lattice search w12.py found symmetric examples of order 12 at 768): an
    # entry of its own, an <li class="c"> marked ◆, "m* ∈ {12, 13}", between 752's and 784's (its wording unpinned since 2026-10-30); its one code block, p768 of order 12, whose signs have order exactly 12 (synthetic
    # division here) and are symmetric (its set SClaude[12][768] left the page on 2026-10-31); the built entry it
    # shared with 672 now names 672 alone; the cell 12–13; mstar.js's column [12, 13, ["example", "equipow p768"],
    # ["residue", 5]].
    text = page()
    li = re.search(r'<li class="c">\n      <span class="mk" aria-hidden="true">◆</span>\n      <p class="entry">\\\(n = '
                   r'768\\\): &nbsp;\\\(m\^\* = 13\\\)</p>\n(.*?)\n    </li>', text, re.S)   # "m* ∈ {12, 13}" until 2026-11-03
    assert li, 'no entry of 768 alone'
    codes = re.findall(r'<p class="code">\n        <span>\\\(p_\{(\d+)\}\\\) \\\(\(m = (\d+)\)\\\):</span>\n'
                       r'        <code id="\d+:\d+">([0-9A-F]+)</code>\n      </p>', li.group(1))
    # Since 2026-11-03 the entry also has the beam campaign's code of order 13 after it (q_example_at_768_has_its_code_of_order_13).
    assert [c[:2] for c in codes] == [('768', '12'), ('768', '13')], codes
    h = codes[0][2]
    left = [1 if b == '1' else -1 for b in bin(int(h, 16))[2:].zfill(4 * len(h))]
    a, k = left + list(reversed(left)), 0
    c = a
    while not sum(c): c, k = list(itertools.accumulate(c[:-1])), k + 1
    assert len(a) == 768 and k == 12 and all(a[767 - i] == a[i] for i in range(768)), (len(a), k)
    listed = [ns.split(', ') for ns in re.findall(r'<p class="entry">\\\(n = (.*?)\\\): ', text)]
    i = listed.index(['768'])
    assert listed[i - 1:i + 2] == [['752'], ['768'], ['784']], listed[i - 1:i + 2]
    assert sum('768' in ns for ns in listed) == 1 and ['672'] in listed, [ns for ns in listed if '672' in ns or '768' in ns]
    assert new_cells(text)[768] == (13, 13), new_cells(text)[768]                                   # 12–13 until 2026-11-03
    assert mstar_data()['cols'][768 - 1] == [13, 13, ['example', 'equipow p768'], ['residue', 5]], mstar_data()['cols'][768 - 1]


def q_examples_at_576_and_624_have_their_entries_and_codes():
    # Replicata: the remarks' entries naming 576 and 624, their codes decoded by the paper's Table 5 convention (the left
    # half of the signs, 1 = +1, then the rest by (-1)^m symmetry), the new results' cells, the changelog's statements
    # of 2026-10-31, and mstar.js's columns.
    # Expectata (2026-10-31: Claude's lattice search scratch/w11-624-576/w11.py found antisymmetric examples of order
    # 11 at 576 and 624): each n has an entry of its own, an <li class="c"> marked ◆, "m* = 12" ("m* ∈ {11, 12}" until 2026-11-03), among the
    # examples in order of n (576 between 560 and 592, 624 between 608 and 656; its wording unpinned); a code block, p_n of order 11, whose
    # signs have order exactly 11 (synthetic division here) and are antisymmetric (its set SClaude[11][n] left the page
    # on 2026-10-31), followed since 2026-11-03 by that of order 12 (q_results_of_2026_11_03_have_entries_and_codes); no other entry names n (its old entry is gone); the cell 12 (11–12 until 2026-11-03); the changelog states
    # 11 ≤ m*(n) ≤ 12 on 2026-10-31; and mstar.js's column [12, 12, ["example", "equipow p<n>"], ["residue", M]], M the
    # modulus of n's residue condition at order 13.
    # Resultata before: 576 was 10 to 12, its lo the join 240 + 336, 624 was 10 to 12, its lo the join 240 + 384; no example of order 11 at 576 and 624.
    text = page()
    listed = [ns.split(', ') for ns in re.findall(r'<p class="entry">\\\(n = (.*?)\\\): ', text)]
    said = changelog_by_day().get('2026-10-31', {})
    # (Spec change, Opus 5.5, 2026-11-18: the entries are in the appendix, one length each, in order, so 624's is followed
    # by 640's, which until then shared an entry with 704 and 736 after 1024's, and no longer by 656's.)
    for n, before, after, M in ((576, 560, 592, 5), (624, 608, 640, 25)):
        li = re.search(r'<li class="c">\n      <span class="mk" aria-hidden="true">◆</span>\n      <p class="entry">\\\(n = '
                       + str(n) + r'\\\): &nbsp;\\\(m\^\* = 12\\\)</p>\n(.*?)\n    </li>', text, re.S)
        assert li, f'no entry of {n} alone'
        codes = re.findall(r'<p class="code">\n        <span>\\\(p_\{(\d+)\}\\\) \\\(\(m = (\d+)\)\\\):</span>\n'
                           r'        <code id="\d+:\d+">([0-9A-F]+)</code>\n      </p>', li.group(1))
        assert [c[:2] for c in codes] == [(str(n), '11'), (str(n), '12')], codes
        h = codes[0][2]
        left = [1 if b == '1' else -1 for b in bin(int(h, 16))[2:].zfill(4 * len(h))]
        a, k = left + [-s for s in reversed(left)], 0
        c = a
        while not sum(c): c, k = list(itertools.accumulate(c[:-1])), k + 1
        assert len(a) == n and k == 11 and all(a[n - 1 - i] == -a[i] for i in range(n)), (n, len(a), k)
        i = listed.index([str(n)])
        assert listed[i - 1:i + 2] == [[str(before)], [str(n)], [str(after)]], listed[i - 1:i + 2]
        assert sum(str(n) in ns for ns in listed) == 1, (n, [ns for ns in listed if str(n) in ns])
        assert new_cells(text)[n] == (12, 12), new_cells(text)[n]
        assert said.get(n) == (11, 12), (n, said.get(n))
        assert mstar_data()['cols'][n - 1] == [12, 12, ['example', f'equipow p{n}'], ['residue', M]], mstar_data()['cols'][n - 1]


def q_example_at_528_has_its_entry_and_code():
    # Replicata: the remarks' entry of 528, its code blocks decoded by the paper's Table 5 convention (the left half
    # of the signs, 1 = +1, then the rest by (-1)^m symmetry), the new results' cell of 528, the changelog's statements
    # of 2026-10-31, and mstar.js's column.
    # Expectata (2026-10-31: Claude's lattice search scratch/w11-624-576/w11.py found antisymmetric examples of order
    # 11 at 528): the entry, an <li class="c"> marked ◆ (Claude alone: both bounds are Claude's now), says
    # "m* ∈ {11, 12}"; its last code is p528 (m = 11), whose signs have order exactly 11 (synthetic division here),
    # are antisymmetric and have +1 at 0 (its set SClaude[11][528], the page's last, left the page later that day);
    # no other entry names 528; the cell is 11–12; the changelog states m*(528) ≥ 11 on 2026-10-31 (only its low
    # moved: 2026-10-04 said ≥ 10 and 2026-10-11 ≤ 12); and mstar.js's column is [11, 12, ["example",
    # "equipow p528"], ["residue", 5]].
    # Resultata before: 528 was 10 to 12, Claude and BGPW, with no example of order 11.
    text = page()
    li = re.search(r'<li class="c">\n      <span class="mk" aria-hidden="true">◆</span>\n      <p class="entry">\\\(n = 528'
                   r'\\\): &nbsp;\\\(m\^\* \\in \\\{11, 12\\\}\\\)</p>\n(.*?)\n    </li>', text, re.S)
    assert li, 'no entry of 528 alone, class c, m* in {11, 12}'
    codes = re.findall(r'\\\(p_\{(\d+)\}\\\) \\\(\(m = (\d+)\)\\\):</span>\n\s*<code id="\d+:\d+">([0-9A-F]+)</code>', li.group(1))
    assert codes and codes[-1][:2] == ('528', '11'), codes
    h = codes[-1][2]
    left = [1 if b == '1' else -1 for b in bin(int(h, 16))[2:].zfill(4 * len(h))]
    a, k = left + [-s for s in reversed(left)], 0
    c = a
    while not sum(c): c, k = list(itertools.accumulate(c[:-1])), k + 1
    assert len(a) == 528 and k == 11 and all(a[527 - i] == -a[i] for i in range(528)) and a[0] == 1, (len(a), k)
    listed = [ns.split(', ') for ns in re.findall(r'<p class="entry">\\\(n = (.*?)\\\): ', text)]
    assert sum('528' in ns for ns in listed) == 1, [ns for ns in listed if '528' in ns]
    assert new_cells(text)[528] == (11, 12), new_cells(text)[528]
    assert changelog_by_day().get('2026-10-31', {}).get(528) == (11, None), changelog_by_day().get('2026-10-31')
    assert mstar_data()['cols'][527] == [11, 12, ['example', 'equipow p528'], ['residue', 5]], mstar_data()['cols'][527]


def q_example_at_672_has_its_entry_and_code():
    # Replicata: the remarks' entry naming 672, its code decoded by the paper's Table 5 convention, the new results'
    # cell of 672, the changelog's statements of 2026-11-01, and mstar.js's column.
    # Expectata (2026-11-01: Claude's lattice search scratch/w11-624-576/w12/w12.py found a symmetric example of order
    # 12 at 672): 672 has an entry of its own, an <li class="c"> marked ◆, "m* ∈ {12, 13}", between 656's and 688's
    # (720's until 688's example entry came between them, also on 2026-11-01);
    # its one code, p672 (m = 12), has signs of order exactly 12 (synthetic division here), symmetric, +1 at 0;
    # its code is <code id="672:12"> (the page's sets left it on 2026-10-31); no other entry names 672; the cell is
    # 12–13; the changelog states 12 ≤ m*(672) ≤ 13 on 2026-11-01; mstar.js's column is [12, 13, ["example",
    # "equipow p672"], ["residue", 5]].
    # Resultata before: 672 was 11 to 13 (built: 2 * 336), with no example of order 12.
    # Since 2026-11-04 m* = 13, the cell 13 and the column [13, 13, ...]: q_example_at_672_has_its_code_of_order_13.  Its code of order 12 stays.
    text = page()
    li = re.search(r'<li class="c">\n      <span class="mk" aria-hidden="true">◆</span>\n      <p class="entry">\\\(n = 672'
                   r'\\\): &nbsp;\\\(m\^\* = 13\\\)</p>\n(.*?)\n    </li>', text, re.S)
    assert li, 'no entry of 672 alone, m* = 13'
    codes = re.findall(r'\\\(p_\{(\d+)\}\\\) \\\(\(m = (\d+)\)\\\):</span>\n\s*<code id="672:12">([0-9A-F]+)</code>', li.group(1))
    assert len(codes) == 1 and codes[0][:2] == ('672', '12'), codes
    h = codes[0][2]
    left = [1 if b == '1' else -1 for b in bin(int(h, 16))[2:].zfill(4 * len(h))]
    a, k = left + left[::-1], 0
    c = a
    while not sum(c): c, k = list(itertools.accumulate(c[:-1])), k + 1
    assert len(a) == 672 and k == 12 and a == a[::-1] and a[0] == 1, (len(a), k)
    listed = [ns.split(', ') for ns in re.findall(r'<p class="entry">\\\(n = (.*?)\\\): ', text)]
    i = listed.index(['672'])
    assert listed[i - 1:i + 2] == [['656'], ['672'], ['688']], listed[i - 1:i + 2]
    assert sum('672' in ns for ns in listed) == 1, [ns for ns in listed if '672' in ns]
    assert new_cells(text)[672] == (13, 13), new_cells(text)[672]
    assert changelog_by_day().get('2026-11-01', {}).get(672) == (12, 13), changelog_by_day().get('2026-11-01')
    assert mstar_data()['cols'][671] == [13, 13, ['example', 'equipow p672'], ['residue', 5]], mstar_data()['cols'][671]


def q_example_at_688_has_its_entry_and_code():
    # Replicata: the remarks' entries naming 688 and 544, 688's code decoded by the paper's Table 5 convention, the new
    # results' cells of 688 and 544, the changelog's statements of 2026-11-01, and mstar.js's column.
    # Expectata (2026-11-01: Claude's lattice search scratch/w11-624-576/w10s/w10s.py found a symmetric example of order
    # 10 at 688): 688 has an entry of its own, an <li class="c"> marked ◆, "m* = 10", between 672's and 720's; its one
    # code, p688 (m = 10), has signs of order exactly 10 (synthetic division here), symmetric, +1 at 0; its code is
    # <code id="688:10">; the entry it shared with 544 names 544 alone; no other entry names 688; the cells are 10 and,
    # at 544, 9–10; the changelog states m*(688) = 10 on 2026-11-01; mstar.js's column is [10, 10, ["example",
    # "equipow p688"], ["residue", 3]].
    # Resultata before: 688 was 9 to 10 (built: the join 192 + 496), in one entry with 544.
    text = page()
    li = re.search(r'<li class="c">\n      <span class="mk" aria-hidden="true">◆</span>\n      <p class="entry">\\\(n = 688'
                   r'\\\): &nbsp;\\\(m\^\* = 10\\\)</p>\n(.*?)\n    </li>', text, re.S)
    assert li, 'no entry of 688 alone, m* = 10'
    codes = re.findall(r'\\\(p_\{(\d+)\}\\\) \\\(\(m = (\d+)\)\\\):</span>\n\s*<code id="688:10">([0-9A-F]+)</code>', li.group(1))
    assert len(codes) == 1 and codes[0][:2] == ('688', '10'), codes
    h = codes[0][2]
    left = [1 if b == '1' else -1 for b in bin(int(h, 16))[2:].zfill(4 * len(h))]
    a, k = left + left[::-1], 0
    c = a
    while not sum(c): c, k = list(itertools.accumulate(c[:-1])), k + 1
    assert len(a) == 688 and k == 10 and a == a[::-1] and a[0] == 1, (len(a), k)
    listed = [ns.split(', ') for ns in re.findall(r'<p class="entry">\\\(n = (.*?)\\\): ', text)]
    i = listed.index(['688'])
    # (Spec change, Opus 5.5, 2026-11-18: the entries are in the appendix, one length each, in order, since the entry of
    # 640, 704 and 736 was split; so 688's entry comes before 704's, not 720's.)
    assert listed[i - 1:i + 2] == [['672'], ['688'], ['704']], listed[i - 1:i + 2]
    assert sum('688' in ns for ns in listed) == 1, [ns for ns in listed if '688' in ns]
    assert ['544'] in listed, [ns for ns in listed if '544' in ns]
    assert (new_cells(text)[688], new_cells(text)[544]) == ((10, 10), (10, 10)), (new_cells(text)[688], new_cells(text)[544])   # 544 9 to 10 until 2026-11-03
    assert changelog_by_day().get('2026-11-01', {}).get(688) == (10, 10), changelog_by_day().get('2026-11-01')
    assert mstar_data()['cols'][687] == [10, 10, ['example', 'equipow p688'], ['residue', 3]], mstar_data()['cols'][687]


def q_results_of_2026_11_03_have_entries_and_codes():
    # Replicata: the remarks' entries of 2026-11-03's examples, their codes decoded by the paper's Table 5 convention, the new results' cells, the changelog's
    # statements of that day, and mstar.js's columns.
    # Expectata: each n has one entry, an <li class="c"> marked ◆, "m* = M", among the examples in order of n; one code p_n (m = M), <code id="n:M">, has signs of
    # order exactly M (synthetic division here), (-1)^M-symmetric, +1 at 0; no other entry names n; the cell is M; the changelog states m*(n) = M on 2026-11-03.
    # And 960's entry says that it settles a(14) = 960 of A323395: no length below 960 allows order 15 (hi < 15 in mstar.js).  The codes of order M - 1 at 576, 624, 912 and
    # 1008 stay, before the new ones, as 528 keeps its code of order 10 (q_former_sets_are_halves_of_expansions: dreeves, "being careful not to lose anything").
    # Resultata before: 544's and 960's entries gave only joins or doubling, and 576's, 624's, 912's and 1008's codes had order one less.
    text = page()
    listed = [ns.split(', ') for ns in re.findall(r'<p class="entry">\\\(n = (.*?)\\\): ', text)]
    # (Spec change, Opus 5.5, 2026-11-18: the entries are in the appendix, one length each, in order, so 624's is followed
    # by 640's, which until then shared an entry with 704 and 736 after 1024's, and no longer by 656's.)
    for n, M, before, after in ((544, 10, '528', '560'), (576, 12, '560', '592'), (624, 12, '608', '640'), (912, 13, '896', '928'),
                                (960, 15, '944', '976'), (1008, 13, '992', '1024')):
        li = re.search(r'<li class="c">\n      <span class="mk" aria-hidden="true">◆</span>\n      <p class="entry">\\\(n = %d\\\): &nbsp;\\\(m\^\* = %d\\\)</p>\n(.*?)\n    </li>' % (n, M), text, re.S)
        assert li, f'no entry of {n} alone, m* = {M}'
        codes = re.findall(r'\\\(p_\{(\d+)\}\\\) \\\(\(m = (\d+)\)\\\):</span>\n\s*<code id="%d:%d">([0-9A-F]+)</code>' % (n, M), li.group(1))
        assert len(codes) == 1 and codes[0][:2] == (str(n), str(M)), codes
        h = codes[0][2]
        left = [1 if b == '1' else -1 for b in bin(int(h, 16))[2:].zfill(4 * len(h))]
        a = left + [(-1) ** M * t for t in reversed(left)]
        k, c = 0, a
        while not sum(c): c, k = list(itertools.accumulate(c[:-1])), k + 1
        assert len(a) == n and k == M and a[0] == 1, (n, len(a), k)
        i = listed.index([str(n)])
        assert listed[i - 1:i + 2] == [[before], [str(n)], [after]], listed[i - 1:i + 2]
        assert sum(str(n) in ns for ns in listed) == 1, [ns for ns in listed if str(n) in ns]
        assert new_cells(text)[n] == (M, M), new_cells(text)[n]
        assert changelog_by_day().get('2026-11-03', {}).get(n) == (M, M), changelog_by_day().get('2026-11-03')
        assert mstar_data()['cols'][n - 1][:3] == [M, M, ['example', f'equipow p{n}']], mstar_data()['cols'][n - 1]
    cols = mstar_data()['cols']
    assert next(n for n, c in enumerate(cols, 1) if c[1] >= 15) == 960 and cols[959][0] == 15
    li = re.search(r'<p class="entry">\\\(n = 960\\\): .*?</li>', text, re.S).group(0)
    assert 'a(14) = 960' in li and 'A323395' in li, li


def first_entry(cols, text, k, lo, hi):
    """Asserts of a first 2^k (for q_powers_of_2_on_the_page_follow_pow2_js since 2026-11-21; for the quals of each day's firsts until
    then): pow2.js's [lo, hi] at 2^k, its column before at lo - 2, its cell, and its entry writing out
    its join, as pow2.js has it (each product's blocks in order, a run of one length as a power, tau_j as 2 or 2^j), with
    its products' orders, the least of them lo."""
    assert cols[k - 1][:2] == [lo, hi] and cols[k - 2][0] == lo - 2, cols[k - 2:k]
    assert new_cells(text)[2 ** k] == (lo, hi), new_cells(text).get(2 ** k)
    li = re.search(r'<p class="entry">\\\(n = 2\^\{%d\}\\\): .*?</li>' % k, text, re.S).group(0)
    products = cols[k - 1][2][1]
    def factors(p):
        runs = [(n, len(list(g))) for n, g in itertools.groupby(n for n, m in p)]
        power = {2 ** m: m for n, m in p if n == 2 ** m}
        # (Spec change, Opus 5.5, 2026-11-29: an exponent of two digits is braced, as TeX needs: until the firsts past 2^128 none had one.)
        tex = lambda n, c: f'{n}^{{{c}}}' if c > 9 else f'{n}^{c}'
        return '\\cdot '.join(('2' if power[n] == 1 else tex(2, power[n])) if n in power else f'{n}' if c == 1 else tex(n, c) for n, c in runs)
    assert f'\\(2^{{{k}}} = ' + ' + '.join(factors(p) for p in products) + '\\)' in li, li
    orders = [sum(m for n, m in p) for p in products]
    said = re.sub(r'<!--.*?-->|<[^>]+>', ' ', li, flags=re.S)                # the entry's text: "of orders 33, 31 and 31."
    assert min(orders) == lo and among(f'of orders {", ".join(map(str, orders[:-1]))} and {orders[-1]}.', said), (orders, li)


def names_base(text, k, base, t, order):
    """Asserts that 2^k's entry names the 2^base entry, each product times tau_t, and order."""
    li = re.search(r'<p class="entry">\\\(n = 2\^\{%d\}\\\): .*?</li>' % k, text, re.S).group(0)
    assert f'\\(2^{{{base}}}\\)' in li and f'\\tau_{t}\\)' in li and re.search(rf'(?<![\d.]){order}(?![\d.])', li), li


# Cut on 2026-11-21 (Fable 5.2, at dreeves's word, quoted in q_powers_of_2_on_the_page_follow_pow2_js below): seven quals that pinned the powers-of-2 firsts as
# they stood on the day each was written, and had been cut back and re-pinned at every first that moved since: q_912_moves_excess_3_to_2_29 and
# q_768_moves_excess_5_to_2_39 (2026-10-28), q_firsts_of_2026_11_03, q_firsts_move_to_2_56_and_2_58, q_first_for_excess_4_moves_to_2_30 and
# q_first_for_excess_7_moves_to_2_51 (2026-11-11), and q_sequences_past_the_chart_move_seven_firsts (2026-11-19).  What they asked of the page (each first's
# entry and join, the lifted entries, the cells, the theorem's statements and the list of firsts) q_powers_of_2_on_the_page_follow_pow2_js asks of whatever
# pow2.js holds; what they pinned of pow2.js itself (which power is first for which excess, by which join) quals_pow2 holds to the sequences
# (q_each_first_is_the_least, q_every_lo_recomputes, q_new_lower_bounds); the codes past the chart they decoded quals_symmetry decodes
# (q_symmetry_codes_have_their_orders_and_symmetries); and the changelog's statements of those days are in q_changelog_keeps_the_firsts_of_their_days.  Other
# quals' comments still name them as the dates of their own spec changes.


def pow2_firsts(cols):
    """{e: K}: for e = 1, 2, ..., the least k at which pow2.js's lo - k reaches e (the first power of 2 known to beat
    Thue-Morse by e), and first_of(k), the largest of them up to k."""
    excess = [c[0] - k for k, c in enumerate(cols, 1)]
    assert excess == sorted(excess), excess                    # a join at 2^k, each product times tau_1, is one at 2^(k + 1)
    firsts = {e: next(k for k, x in enumerate(excess, 1) if x >= e) for e in range(1, max(excess) + 1)}
    return firsts, lambda k: max(K for K in firsts.values() if K <= k)


def pow2_page_follows(cols, text):
    """Asserts that the page's powers of 2 are what cols (pow2.js's columns) give: q_powers_of_2_on_the_page_follow_pow2_js."""
    firsts, first_of = pow2_firsts(cols)
    def lifted(ps, t):
        """Each product of ps times tau_t: its tau_j, if it has one, becomes tau_(j + t)."""
        return [[b for b in p if b[0] != 2 ** b[1]] + [[2 ** j, j] for j in [t + sum(m for n, m in p if n == 2 ** m)] if j] for p in ps]
    # Spec change (Opus 5.5, 2026-11-23; dreeves: "it never made sense to hard-code 72"): each column from the first first on is the lift of its first's
    # join, or (past the lifts, as from 2^74 once the chart reaches 2^128) the product of two lower columns' joins, all their pairwise products, at the
    # sum of their bounds; until then the lift alone.  (times: pow2.py's product of two products, the tau factors merged.)
    join = lambda c, a: [[[2 ** a, a]]] if c[2][0] == 'thue-morse' else c[2][1]
    times = lambda p, q: sorted([b for b in p + q if b[0] != 2 ** b[1]], key=lambda b: -b[0]) + [[2 ** t, t] for t in [sum(m for n, m in p + q if n == 2 ** m)] if t]
    for k in range(min(firsts.values()), len(cols) + 1):
        K0 = first_of(k)
        products = sorted(map(sorted, cols[k - 1][2][1]))
        assert cols[k - 1][2] == ['joins', lifted(cols[K0 - 1][2][1], k - K0)] or any(
            cols[a - 1][0] + cols[k - a - 1][0] == cols[k - 1][0] and products == sorted(sorted(times(p, q)) for p in join(cols[a - 1], a) for q in join(cols[k - a - 1], k - a))
            for a in range(1, k // 2 + 1)), (k, K0, cols[k - 1][2])
    entries = pow2_entries(text)
    assert {K for K in firsts.values() if K >= ENTRIES_FROM} <= set(entries), (firsts, entries)
    for k in entries:
        lo, hi = cols[k - 1][:2]
        if k in firsts.values(): first_entry(cols, text, k, lo, hi)          # its join written out, with its products' orders
        else: names_base(text, k, first_of(k), k - first_of(k), lo)          # names its first's entry, times tau_(k - first), and its order
    for n, cell in new_cells(text).items():                                  # every cell of a power of 2
        k = n.bit_length() - 1
        assert n != 2 ** k or cell == tuple(cols[k - 1][:2]), (k, cell, cols[k - 1][:2])
    said = [(int(k), rel, int(v)) for k, rel, v in re.findall(r'\(2\^\{?(\d+)\}?\) (=|\\ge) (\d+)', the_theorem(text))]
    assert said and len({k for k, _, _ in said}) == len(said), said
    for k, rel, v in said:                                                   # each statement of the theorem: true, and a bound only at a first
        assert (cols[k - 1][:2] == [v, v]) if rel == '=' else (cols[k - 1][0] == v and firsts.get(v - k) == k), (k, rel, v, cols[k - 1][:2])
    assert set(firsts.values()) <= {k for k, _, _ in said}, (firsts, said)   # and every first is stated
    assert re.search(r'(?<![\d.])' + ', '.join(str(firsts[e]) for e in sorted(firsts)) + r'(?![\d,])', text), firsts      # the list under it, whole


ENTRIES_FROM = 21      # the entries of the powers of 2 past 2^20 follow the scheme; 2^20's and those below it (2^11, 2^12, 2^17, 2^18) are older and freer


def pow2_entries(text):
    """The k of the remarks' entries of 2^k that follow the scheme, rising."""
    return sorted(k for k in map(int, re.findall(r'<p class="entry">\\\(n = 2\^\{(\d+)\}\\\)', text)) if k >= ENTRIES_FROM)


def figures_reach(text):
    """{figure: (the last number of its section's heading, the last number of its canvas's accessible description)}, figure mstar or pow2, as the page's text has them."""
    last = lambda t: int(re.findall(r'\d+', t)[-1])
    out = {}
    for name in ('mstar', 'pow2'):
        [title] = re.findall(rf'<h2 id="{name}-title">(.*?)</h2>', text, re.S)
        [label] = re.findall(rf'<canvas id="{name}-chart"[^>]* aria-label=\'([^\']*)\'', text)
        out[name] = (last(title), last(label))
    return out


def q_figures_state_how_far_they_reach():
    # 2026-11-29 (Opus 5.5; Astra's review of that night: the accessible description of Figure 2 still ended at 128 when its data had come to reach 256).
    # Replicata: the headings of the two figures' sections and the accessible descriptions of their canvases; mstar.js's nmax and pow2.js's kmax.
    # Expectata: the last number of each heading and of each description is the last column of the figure's data: 4096 and 256 that day.  Control: the page before that
    # review's fix, whose Figure 2 description ended at 128, fails.
    # Resultata before: the heading of Figure 2 said 256 and its description, the one thing a reader of a screen reader gets of it, 128.
    reach = {'mstar': (mstar_data()['nmax'],) * 2, 'pow2': (pow2_data()['kmax'],) * 2}
    assert figures_reach(page()) == reach, (figures_reach(page()), reach)
    stale = page().replace('for k from 1 to 256;', 'for k from 1 to 128;')
    assert stale != page() and figures_reach(stale) != reach


def q_exponents_of_two_digits_are_braced():
    # 2026-11-29 (Opus 5.5; a TeX slip of that day's new entries of the powers of 2: "7360^10", which sets as 7360 to the first, then a 0).
    # Replicata: the page's math, its comments left out: every \\( ... \\) and \\[ ... \\].
    # Expectata: none has an exponent or subscript of two or more digits with no braces, as "7360^10" or "x_12", which KaTeX sets as the first digit alone.  Controls: two
    # made-up formulas, the one with a bare two-digit exponent refused, the one with braces not.
    # Resultata before: 17 of the entries of 2^135 to 2^254 had such exponents, and no qual saw them.
    bare = lambda f: re.findall(r'[0-9A-Za-z})]\^[0-9]{2,}|_[0-9]{2,}', f)
    found = [(f[:60], bare(f)) for f in re.findall(r'\\\((.*?)\\\)|\\\[(.*?)\\\]', re.sub(r'<!--.*?-->', '', page(), flags=re.S), re.S) for f in f if bare(f)]
    assert not found, found[:5]
    assert bare('7360^10 + 1') and bare('x_12') and not bare('7360^{10} + x_{12} + 2^9')


def q_powers_of_2_on_the_page_follow_pow2_js():
    # 2026-11-21 (Fable 5.2; dreeves, 2026-11-20, of quals that had to be changed for a page improvement: "i wish we could be more thoughtful about adding more
    # quals that might catch real regressions and fewer that merely wolf-cry when make improvements to the page", then "let's not cut things preemptively. when
    # they cry wolf, let's remember this conversation"; and that night, when two moved firsts had needed about 15 pinned numbers changed, of replacing those
    # pins by one qual that holds every entry, cell and theorem number to the generated data: "that's fine, i think, if it's as much of a no-brainer question as
    # it sounds like").
    # Replicata: pow2.js's columns; the remarks' entries of the powers of 2 past 2^20; the new results' cells of the powers of 2; the theorem's statement and
    # the list of firsts under it.
    # Expectata: with the firsts read off pow2.js (for e = 1, 2, ..., the least k at which lo - k reaches e): every column from the first first on is the lift
    # of its first's join, each product times tau_(k - first); each first past 2^20 has an entry that writes its join out as pow2.js has it, with its products'
    # orders, the least of them lo, the column before it at lo - 2 (first_entry); every other entry past 2^20 names its first's entry, tau_(k - first) and its
    # order (names_base); every cell of a power of 2 reads pow2.js's lo and hi; each statement of the theorem is true of pow2.js, a bound only at a first, and
    # every first is stated; and the list under it is the firsts.  Controls, made from the data as it is: a wrong number in the list, in the theorem's bound,
    # a bound at a power that is no first, a wrong join in a first's entry, a wrong tau in a lifted entry, a wrong cell, or a first one later in the data,
    # and it fails.  (On 2026-11-21 it passed on the page of that night and on the page before it with its data, and failed on either page with the other's.)
    # Resultata before: seven quals pinned those numbers as the firsts stood on the day of each (the note below), so every moved first turned them red until
    # their numbers were changed by hand; no qual held an entry, a cell or the theorem to the data.
    cols, text = pow2_data()['cols'], page()
    pow2_page_follows(cols, text)
    # Controls, each from the data as it is: one wrong number on the page, or in the data, and it fails.
    firsts, first_of = pow2_firsts(cols)
    K = max(firsts.values()); lo, hi = cols[K - 1][:2]
    def fails(cols, text):
        try: pow2_page_follows(cols, text)
        except AssertionError: return True
        return False
    def swap(old, new, t=None):
        t = text if t is None else t
        assert t.count(old) == 1, (old, t.count(old))
        return t.replace(old, new)
    listed = ', '.join(str(firsts[e]) for e in sorted(firsts))
    assert fails(cols, swap(listed + '.', listed[:-len(str(K))] + str(K + 1) + '.'))                                   # the list's last first
    theorem = the_theorem(text)
    assert fails(cols, swap(theorem, swap(f'(2^{{{K}}}) \\ge {lo}\\)', f'(2^{{{K}}}) \\ge {lo + 1}\\)', theorem)))            # the theorem's bound at it
    assert fails(cols, swap(theorem, swap(f'(2^{{{K}}}) \\ge {lo}\\)', f'(2^{{{K + 1}}}) \\ge {lo + 1}\\)', theorem)))        # a bound at a power that is no first
    assert fails(cols, swap(f'\\(2^{{{K}}} = ', f'\\(2^{{{K}}} = 2\\cdot '))                                           # the first's entry: its join
    k = max(k for k in pow2_entries(text) if k not in firsts.values()); t = k - first_of(k)
    li = re.search(r'<p class="entry">\\\(n = 2\^\{%d\}\\\): .*?</li>' % k, text, re.S).group(0)
    assert fails(cols, swap(li, swap(f'\\tau_{t}\\)', f'\\tau_{t + 1}\\)', li)))                                       # a lifted entry: its tau
    wrong = json.loads(json.dumps(cols)); wrong[k - 1][1] += 1
    assert fails(wrong, text)                                                                                         # a cell: its high end
    wrong = json.loads(json.dumps(cols)); wrong[K - 1][0] -= 1
    assert fails(wrong, text)                                                                                         # the data: a first one later


def q_changelog_keeps_the_firsts_of_their_days():
    # 2026-11-21 (Fable 5.2): the changelog's statements that the quals cut above held, in one place.
    # Replicata: the changelog's statements by day.
    # Expectata: on 2026-11-11, m*(2^30) >= 34 and m*(2^51) >= 58; on 2026-11-19, the bounds at 2^22, 2^35, 2^42, 2^50, 2^55, 2^63 and 2^68; on 2026-11-21,
    # m*(2^34) >= 39 and m*(2^67) >= 77, and m*(2480) = m*(2512) = 13.  A past day's line does not change when a later result moves a first.
    # Resultata before: the same assertions, in the quals of those days' firsts.
    said = changelog_by_day()
    for day, bounds in (('2026-11-11', {2 ** 30: (34, None), 2 ** 51: (58, None)}),
                        ('2026-11-19', {2 ** 22: (25, None), 2 ** 35: (40, None), 2 ** 42: (48, None), 2 ** 50: (57, None), 2 ** 55: (63, None),
                                        2 ** 63: (72, None), 2 ** 68: (78, None)}),
                        ('2026-11-21', {2 ** 34: (39, None), 2 ** 67: (77, None), 2480: (13, 13), 2512: (13, 13)})):
        assert {n: said.get(day, {}).get(n) for n in bounds} == bounds, (day, said.get(day))


def q_changelog_records_the_december_first_improvements_in_figure_2():
    # Compare the catalogue on either side of the December 1 batch, within the plotted range.
    # Both earlier firsts belong in that day's changelog. Only excess 15 was recorded.
    def firsts(commit):
        lines = at_commit(commit, 'pagedata/pow2-firsts.txt').splitlines()[1:]
        return dict(tuple(map(int, line.split())) for line in lines)
    before, after = firsts(BEFORE_BATCH), firsts('50c7b65')
    day = changelog_by_day()['2026-12-01']
    for excess, k in after.items():
        if k <= 256 and k < before[excess]:
            assert day.get(2**k) == (k + excess, None), (excess, k, day.get(2**k))


def q_example_at_720_has_its_code_of_order_13():
    # Replicata: the remarks' entry naming 720, its codes decoded by the paper's Table 5 convention (the left half of the signs, 1 = +1, then the
    # rest by (-1)^m symmetry), the new results' cell of 720, the changelog's statements of 2026-11-03, and mstar.js's column.
    # Expectata (2026-11-03: the beam campaign's lattice search, scratch/beam-campaign-20261103/, found an antisymmetric example of order 13 at 720):
    # 720's entry, an <li class="c"> marked ◆, its statement of m* \(m^* \in \{13, 14\}\), between 688's and 752's; its codes p720 (m = 12) and
    # p720 (m = 13), in that order, the second <code id="720:13">, its signs of order exactly 13 (synthetic division here), antisymmetric, +1 at
    # 0; no other entry names 720; the cell 13 to 14; the changelog's statement of 720 on 2026-11-03 is (13, None) (quals_index's statement()); mstar.js's column
    # [13, 14, ["example", "equipow p720"], ['residue', 16]].
    # Resultata before: 720 was 12 to 14, with one code, of order 12.
    text = page()
    entry = '<p class="entry">\\(n = 720\\): &nbsp;\\(m^* \\in \\{13, 14\\}\\)</p>'
    li = re.search(r'<li class="c">\n      <span class="mk" aria-hidden="true">◆</span>\n      ' + re.escape(entry) + r'\n(.*?)\n    </li>', text, re.S)
    assert li, 'no entry of 720 alone with its new statement'
    codes = re.findall(r'\\\(p_\{(\d+)\}\\\) \\\(\(m = (\d+)\)\\\):</span>\n\s*<code id="(\d+:\d+)">([0-9A-F]+)</code>', li.group(1))
    assert [c[:3] for c in codes] == [('720', '12', '720:12'), ('720', '13', '720:13')], codes
    h = codes[1][3]
    left = [1 if b == '1' else -1 for b in bin(int(h, 16))[2:].zfill(4 * len(h))]
    a = left + [-t for t in reversed(left)]
    k, c = 0, a
    while not sum(c): c, k = list(itertools.accumulate(c[:-1])), k + 1
    assert len(a) == 720 and k == 13 and a[0] == 1 and all(a[720 - 1 - i] == -a[i] for i in range(720)), (len(a), k)
    listed = [ns.split(', ') for ns in re.findall(r'<p class="entry">\\\(n = (.*?)\\\): ', text)]
    i = listed.index(['720'])
    # (Spec change, Opus 5.5, 2026-11-18: the entries are in the appendix, one length each, in order, since the entry of
    # 640, 704 and 736 was split; so 720's entry comes between 704's and 736's.)
    assert listed[i - 1:i + 2] == [['704'], ['720'], ['736']], listed[i - 1:i + 2]
    assert sum('720' in ns for ns in listed) == 1, [ns for ns in listed if '720' in ns]
    assert new_cells(text)[720] == (13, 14), new_cells(text)[720]
    assert changelog_by_day().get('2026-11-03', {}).get(720) == (13, None), changelog_by_day().get('2026-11-03')
    assert mstar_data()['cols'][720 - 1] == [13, 14, ['example', 'equipow p720'], ['residue', 16]], mstar_data()['cols'][720 - 1]


def q_pin_trees_are_on_the_page():
    # Replicata: the remarks' entries of 432 and 816, the new results' cells, the changelog's statements of 2026-11-03, the section of the pin trees, the OEIS note on A323395, the table of smallest lengths, and mstar.js.
    # Expectata (the user, 2026-11-03: "let's add them to the github, including an explanation of how the new stuff works"): 432's entry says m* = 11 and 816's m* = 12, each with its code still there and a Claude paragraph linking its proof file; the cells read 11 and 12;
    # the changelog states m*(432) = 11 and m*(816) = 12 on that day; a section explains the method (a <section class="pintree"> with its h2 and a Claude block quote), states each proof's certificates, and links both checkers, both proofs and searches/pintree;
    # A323395's note says this page proves a(11) = 480; the table's row for order 12 is 480, 480, proven.
    # Resultata before: 432 was 11 to 12 and 816 was 12 to 14; A323395's note said a(11) is 432 or 480.
    text = page()
    GH = 'https://github.com/dreeves/equipow/blob/main/'
    for n, M, proof in ((432, 11, 'pintree_432_12.json.gz'), (816, 12, 'pintree_816_13.json.gz')):
        li = re.search(r'<li class="c">\n      <span class="mk" aria-hidden="true">◆</span>\n      <p class="entry">\\\(n = %d\\\): &nbsp;\\\(m\^\* = %d\\\)</p>\n(.*?)\n    </li>' % (n, M), text, re.S)
        assert li, f'no entry of {n} alone, m* = {M}'
        assert f'<code id="{n}:{M}">' in li.group(1), n
        assert f'{GH}proofs/{proof}' in li.group(1), li.group(1)[:400]
        assert new_cells(text)[n] == (M, M), new_cells(text)[n]
        assert changelog_by_day().get('2026-11-03', {}).get(n) == (M, M), changelog_by_day().get('2026-11-03')
    sec = re.search(r'<section class="pintree" aria-labelledby="pintree-title">(.*?)</section>', text, re.S)
    assert sec, 'no section of the pin trees'
    body = sec.group(1)
    assert '<blockquote class="claude">' in body and '<h2 id="pintree-title">' in body, body[:300]
    for link in ('proofs/pintree.py', 'proofs/pintree_second.py', 'proofs/pintree_432_12.json.gz', 'proofs/pintree_816_13.json.gz'): assert f'{GH}{link}' in body, link
    assert 'https://github.com/dreeves/equipow/tree/main/searches/pintree' in body
    assert '3,119' in body and '187,269' in body, body[:300]
    oeis = re.search(r'<section class="oeis" aria-labelledby="oeis-title">.*?</section>', text, re.S).group(0)
    note = dict(zip(OEIS, re.findall(r'<li>(.*?)</li>', re.search(r'<ul>(.*?)</ul>', oeis, re.S).group(1), re.S)))['A323395']
    assert 'a(11) = 480' in note and 'is 432 or 480' not in note, note
    assert smallest_table()[11] == ['12', '480', '480', '✓'], smallest_table()[11]


def formtree_checker():
    """proofs/formtree.py, the form trees' Python checker, as a module (it loads proofs/pintree.py itself)."""
    import importlib.util
    spec = importlib.util.spec_from_file_location('formtree', os.path.join(HERE, 'proofs', 'formtree.py'))
    module = importlib.util.module_from_spec(spec); spec.loader.exec_module(module)
    return module


def bound_steps(ft, path):
    """A form-tree stream's bound steps, in order, as proofs/formtree.py's checker (ft) reads them: (the form's modulus,
    its grid's step, the grid's offset, the lower bound and the upper bound that the step's two certificates prove,
    the grid's values within them).  The checker then takes each line itself, so a stream it refuses stops this."""
    out, task = [], None
    for parts in (line.split() for line in ft.open_text(path)):
        kind, numbers = parts[0], [int(x) for x in parts[1:]]
        if kind == 'T':
            task = ft.Task(ft.Cell(numbers[0], numbers[1]))
            continue
        if kind == 'E':
            assert task.done, 'a task of the stream did not close'
            continue
        if kind == 'B':
            i, sym = numbers[0], numbers[1]
            U = ft.Certificate(numbers, 3, task.cell.m); D = ft.Certificate(numbers, U.end, task.cell.m)
            M, w, st, c0 = task.forms[i]
            hi, lo = task.bound(U, M, w, 1), -task.bound(D, M, w, -1)
            first, count = ft.grid_count(max(lo, 0) if sym else lo, hi, c0, st)
            out.append((M, st, c0 % st, lo, hi, [first + st * j for j in range(count)]))
        task.feed(kind, numbers)
    return out


def q_form_trees_have_their_exposition():
    # Replicata: the page's section on form-tree proofs, without its comment; the paths and ids its links name; the
    # finished proof at 288 for order 10 (its top, searches/formtree/top_288_10.json.gz, and its tasks' verdicts, in
    # run288v_snapshot.tar.gz, assembled by proofs/formtree.py; the run's counts, run288v_progress.json); the
    # manifests of the single cells' proofs (searches/formtree/cells/*/manifest.json); and the bound steps of
    # searches/formtree/fixtures/small.txt, a small real stream, as proofs/formtree.py's checker reads them.
    # Expectata (dreeves's README, [FTP], 2026-11-10: "add exposition, attributed to Claude, that defines and describes
    # form-tree proofs"): the page has a <section class="formtree" aria-labelledby="formtree-title"> with a block quote
    # and an <h2 id="formtree-title">.  What it says holds on the data, whatever its words: every link in it into the
    # repository names a file (blob) or a folder (tree) that is there, and every link into the page an id that is
    # there (a link elsewhere is not read: until 2026-11-10 it was refused, a ban on something done on purpose);
    # every number in it with a thousands separator is one of the proofs' counts (the assembled proof at 288: tasks,
    # nodes, splits, the splits' children, pins without a split, certificates, and the tasks the Python checker read
    # too, their nodes in all and the most in one of them; a single cell's tasks, nodes or certificates); and each
    # <li data-step="k"> holds the numbers of the
    # stream's k-th bound step: the form's modulus, its grid's step and (when not 0) offset, its two bounds and the
    # values left.  No sentence, number or item has to be there.
    # Resultata before: the page cited form-tree proofs (the changelog, the entries of 288 and 752, the Symmetry
    # section) and said nowhere what one is.
    import glob, io, tarfile
    text = page()
    sec = re.search(r'<section class="formtree" aria-labelledby="formtree-title">(.*?)</section>', text, re.S)
    assert sec, 'no section of the form trees'
    assert '<blockquote class="claude">' in sec.group(1) and '<h2 id="formtree-title">' in sec.group(1), sec.group(1)[:300]
    said = re.sub(r'<!--.*?-->', '', sec.group(1), flags=re.S)
    hrefs = re.findall(r'href="([^"]*)"', said)
    assert all(f'id="{h[1:]}"' in text for h in hrefs if h.startswith('#')), hrefs
    repo = [m for m in (re.fullmatch(r'https://github\.com/dreeves/equipow/(blob|tree)/main/([^#?]+)', h) for h in hrefs) if m]
    there = {'blob': os.path.isfile, 'tree': os.path.isdir}
    assert all(there[r.group(1)](os.path.join(HERE, *r.group(2).split('/'))) for r in repo), hrefs
    ft = formtree_checker()
    FT = os.path.join(HERE, 'searches', 'formtree')
    n, m, starts, stats = ft.check_top(os.path.join(FT, 'top_288_10.json.gz'))
    with tarfile.open(os.path.join(FT, 'run288v_snapshot.tar.gz'), 'r:gz') as t:
        member = t.getmember('verdicts.jsonl')
        assert member.size < 200e6, member.size                 # 46 MB as saved: nothing larger is read into memory
        verdicts = [json.loads(line) for line in io.TextIOWrapper(t.extractfile(member), encoding='ascii') if line.strip()]
    total = ft.assemble([s['name'] for s in starts], verdicts)
    progress = json.load(open(os.path.join(FT, 'run288v_progress.json')))
    read_twice = sum(v['py'] is True for v in verdicts)
    assert (n, m, total['tasks'], total['nodes'], total['certs'], read_twice) == \
        (288, 10, progress['tasks_done'], progress['nodes'], progress['certificates'], progress['python_sampled']), (total, progress)
    cells = [json.load(open(f)) for f in sorted(glob.glob(os.path.join(FT, 'cells', '*', 'manifest.json')))]
    assert cells, 'no single cell has a manifest'
    counts = {total[k] for k in ('tasks', 'nodes', 'splits', 'fixes', 'certs')} | {total['nodes'] - total['tasks'], read_twice}
    counts |= {sum(v['nodes'] for v in verdicts if v['py'] is True), max(v['nodes'] for v in verdicts if v['py'] is True)}
    counts |= {c[k] for c in cells for k in ('tasks', 'nodes', 'certificates')}
    plain = re.sub(r'<[^>]*>', ' ', said)
    big = [int(s.replace(',', '')) for s in re.findall(r'(?<![\d,.])\d{1,3}(?:,\d{3})+(?![\d,])', plain)]
    assert all(b in counts for b in big), ([b for b in big if b not in counts], sorted(counts))
    steps = bound_steps(ft, os.path.join(FT, 'fixtures', 'small.txt'))
    for k, li in re.findall(r'<li data-step="(\d+)">(.*?)</li>', said, re.S):
        M, st, c0, lo, hi, values = steps[int(k) - 1]
        numbers = {int(x) for x in re.findall(r'-?\d+', re.sub(r'<[^>]*>', ' ', li).replace('−', '-'))}
        need = {M, st, lo, hi, *values} | ({c0} if c0 else set())
        assert need <= numbers, (k, sorted(need - numbers), li)


def q_form_tree_sizes_at_480_link_the_run_and_the_remaining_case():
    # Replicata: read the form-tree overview against the manifest for the unrestricted run.
    # Expectata: it reports the size of that proof and links both the checking record
    # and the remaining open order. Resultata before: order 14 appeared as an estimate.
    overview = blank_comments(page()).split('id="formtree-title"', 1)[1].split('</section>', 1)[0]
    path = 'searches/formtree/cells/480_14/manifest.json'
    with open(os.path.join(HERE, path)) as stream:
        run = json.load(stream)
    assert 0 < run['python_checked'] < run['tasks'] and run['open'] == run['refused'] == 0
    assert f'href="{REPO}{path}"' in overview and 'href="#root480"' in overview
    figures = {int(s.replace(',', '')) for s in re.findall(r'\b\d[\d,]*\b', re.sub(r'<[^>]*>', ' ', overview))}
    assert {run['tasks'], run['nodes']} <= figures, (run['tasks'], run['nodes'])


def q_form_trees_section_is_styled_as_the_pin_trees_is():
    # Replicata: page/style.css without its comments: each rule's list of selectors.
    # Expectata: the form trees' section, a block quote like the pin trees' right above it, is laid out as that one is
    # (the text's measure, the quote's rule and the space between its parts, its lists, its attribution's color): in
    # every list of selectors that names .pintree, each selector with .pintree stands with .formtree in its place too.
    # (A rule for the form trees' section alone is made on purpose and is not read; until 2026-11-10 it was refused.)
    # Resultata before: no rule named .formtree, so the section's text ended 40 px past the measure
    # (q_prose_has_one_measure: 776 px for 736) and its quote had neither rule nor spacing.
    style = re.sub(r'/\*.*?\*/', '', page_css(), flags=re.S)
    lists = [[s.strip() for s in selectors.split(',')] for selectors in re.findall(r'([^{}]+)\{[^{}]*\}', style)]
    pin = [(s, l) for l in lists for s in l if '.pintree' in s]
    assert pin and all(s.replace('.pintree', '.formtree') in l for s, l in pin), [s for s, l in pin if s.replace('.pintree', '.formtree') not in l]


def q_example_at_768_has_its_code_of_order_13():
    # Replicata: the remarks' entry naming 768, its codes decoded by the paper's Table 5 convention (the left half of the signs, 1 = +1, then the
    # rest by (-1)^m symmetry), the new results' cell of 768, the changelog's statements of 2026-11-03, and mstar.js's column.
    # Expectata (2026-11-03: the beam campaign's lattice search, scratch/beam-campaign-20261103/, found an antisymmetric example of order 13 at 768):
    # 768's entry, an <li class="c"> marked ◆, its statement of m* \(m^* = 13\), between 752's and 784's; its codes p768 (m = 12) and
    # p768 (m = 13), in that order, the second <code id="768:13">, its signs of order exactly 13 (synthetic division here), antisymmetric, +1 at
    # 0; no other entry names 768; the cell 13 to 13; the changelog's statement of 768 on 2026-11-03 is (13, 13) (quals_index's statement()); mstar.js's column
    # [13, 13, ["example", "equipow p768"], ['residue', 5]].
    # Resultata before: 768 was 12 to 13, with one code, of order 12.
    text = page()
    entry = '<p class="entry">\\(n = 768\\): &nbsp;\\(m^* = 13\\)</p>'
    li = re.search(r'<li class="c">\n      <span class="mk" aria-hidden="true">◆</span>\n      ' + re.escape(entry) + r'\n(.*?)\n    </li>', text, re.S)
    assert li, 'no entry of 768 alone with its new statement'
    codes = re.findall(r'\\\(p_\{(\d+)\}\\\) \\\(\(m = (\d+)\)\\\):</span>\n\s*<code id="(\d+:\d+)">([0-9A-F]+)</code>', li.group(1))
    assert [c[:3] for c in codes] == [('768', '12', '768:12'), ('768', '13', '768:13')], codes
    h = codes[1][3]
    left = [1 if b == '1' else -1 for b in bin(int(h, 16))[2:].zfill(4 * len(h))]
    a = left + [-t for t in reversed(left)]
    k, c = 0, a
    while not sum(c): c, k = list(itertools.accumulate(c[:-1])), k + 1
    assert len(a) == 768 and k == 13 and a[0] == 1 and all(a[768 - 1 - i] == -a[i] for i in range(768)), (len(a), k)
    listed = [ns.split(', ') for ns in re.findall(r'<p class="entry">\\\(n = (.*?)\\\): ', text)]
    i = listed.index(['768'])
    assert listed[i - 1:i + 2] == [['752'], ['768'], ['784']], listed[i - 1:i + 2]
    assert sum('768' in ns for ns in listed) == 1, [ns for ns in listed if '768' in ns]
    assert new_cells(text)[768] == (13, 13), new_cells(text)[768]
    assert changelog_by_day().get('2026-11-03', {}).get(768) == (13, 13), changelog_by_day().get('2026-11-03')
    assert mstar_data()['cols'][768 - 1] == [13, 13, ['example', 'equipow p768'], ['residue', 5]], mstar_data()['cols'][768 - 1]


def q_example_at_672_has_its_code_of_order_13():
    # Replicata: the remarks' entry naming 672, its codes decoded by the paper's Table 5 convention (the left half of the signs, 1 = +1, then the
    # rest by (-1)^m symmetry), the new results' cell of 672, the changelog's statements of 2026-11-04, the table of smallest lengths, and mstar.js's column.
    # Expectata (2026-11-04: the tilted search, searches/tilted/, found an antisymmetric example of order 13 at 672):
    # 672's entry, an <li class="c"> marked ◆, its statement of m* \\(m^* = 13\\), between 656's and 688's; its codes p672 (m = 12) and
    # p672 (m = 13), in that order, the second <code id="672:13">, its signs of order exactly 13 (synthetic division here), antisymmetric, +1 at
    # 0; no other entry names 672; the cell 13 to 13; the changelog's statement of 672 on 2026-11-04 is (13, 13) (quals_index's statement()), on a line of its own
    # (NOTEWORTHY: the smallest length known with order 13); order 13's row reads 480, 672, unproven; mstar.js's column [13, 13, ["example", "equipow p672"], ['residue', 5]].
    # Resultata before: 672 was 12 to 13, with one code, of order 12, and order 13's least known length was 720.
    text = page()
    entry = '<p class="entry">\\(n = 672\\): &nbsp;\\(m^* = 13\\)</p>'
    li = re.search(r'<li class="c">\n      <span class="mk" aria-hidden="true">◆</span>\n      ' + re.escape(entry) + r'\n(.*?)\n    </li>', text, re.S)
    assert li, 'no entry of 672 alone with its new statement'
    codes = re.findall(r'\\\(p_\{(\d+)\}\\\) \\\(\(m = (\d+)\)\\\):</span>\n\s*<code id="(\d+:\d+)">([0-9A-F]+)</code>', li.group(1))
    assert [c[:3] for c in codes] == [('672', '12', '672:12'), ('672', '13', '672:13')], codes
    h = codes[1][3]
    assert h == '94E71B4AB0A5E5785A33AC2F58C2778C2D699A17D467584AD5B4297A4EB48D2BCAD2B3C5255AE612A567', h
    left = [1 if b == '1' else -1 for b in bin(int(h, 16))[2:].zfill(4 * len(h))]
    a = left + [-t for t in reversed(left)]
    k, c = 0, a
    while not sum(c): c, k = list(itertools.accumulate(c[:-1])), k + 1
    assert len(a) == 672 and k == 13 and a[0] == 1 and all(a[672 - 1 - i] == -a[i] for i in range(672)), (len(a), k)
    listed = [ns.split(', ') for ns in re.findall(r'<p class="entry">\\\(n = (.*?)\\\): ', text)]
    i = listed.index(['672'])
    assert listed[i - 1:i + 2] == [['656'], ['672'], ['688']], listed[i - 1:i + 2]
    assert sum('672' in ns for ns in listed) == 1, [ns for ns in listed if '672' in ns]
    assert new_cells(text)[672] == (13, 13), new_cells(text)[672]
    assert changelog_by_day().get('2026-11-04', {}).get(672) == (13, 13), changelog_by_day().get('2026-11-04')
    assert smallest_table()[12] == ['13', '480', '672', ''], smallest_table()[12]
    assert mstar_data()['cols'][672 - 1] == [13, 13, ['example', 'equipow p672'], ['residue', 5]], mstar_data()['cols'][672 - 1]


def q_example_at_1440_settles_a_15():
    # Replicata: the section of the table of smallest lengths, its code decoded by the paper's Table 5 convention, the table as the page draws it, the
    # changelog's entries, the OEIS section's note on A323395, and mstar.js.
    # Expectata (2026-11-04: the tilted search, searches/tilted/, found a symmetric example of order 16 at 1440): the section holds one code, <code id="1440:16">, its signs of
    # order exactly 16 (synthetic division here), symmetric, +1 at 0, and says m* is 16 or 17; 1440 has no remark, Table 1 having no cell for it
    # (q_new_results_state_what_the_chart_proves); order 16's row of the table reads 1440, 1440, proven, since mstar.js's mtopAt is 1440; the changelog has an entry of 2026-11-04
    # stating a(15) = 1440 (no m*(1440) statement, for the same reason: q_changelog_brings_every_new_result_up_to_date); and the OEIS note on A323395 states a(15) = 1440.
    # Resultata before: order 16's row read 1440, 1920, not proven, and no example of order 16 was known below 1920.
    text = page()
    section = re.search(r'<section class="smallest".*?</section>', text, re.S).group(0)
    codes = re.findall(r'\\\(p_\{(\d+)\}\\\) \\\(\(m = (\d+)\)\\\):</span>\n\s*<code id="(\d+:\d+)">([0-9A-F]+)</code>', section)
    # 2026-12-02 (Opus 5.5): the section holds 1440:16 among its codes (until then as its one code; p_1920, the smallest
    # length known with order 17, is a code block of the section since that day).
    assert ('1440', '16', '1440:16') in [c[:3] for c in codes], codes
    h = next(c[3] for c in codes if c[2] == '1440:16')
    assert h == '9E21C6F54B340E3CAF46C59F362A518761CD3896A8DAB346DC58D731D72B46AC9A3630DAA94E91D235364CD316F68A7B8AF8E336A449B12CD9E0D6D51AA55C49AC65CCCB90F2D5EA2A166DB9936D0369D05CF5A95CA006EF87B2', h
    left = [1 if b == '1' else -1 for b in bin(int(h, 16))[2:].zfill(4 * len(h))]
    a = left + left[::-1]
    k, c = 0, a
    while not sum(c): c, k = list(itertools.accumulate(c[:-1])), k + 1
    assert len(a) == 1440 and k == 16 and a[0] == 1 and a == a[::-1], (len(a), k)
    assert '\\(m^*(1440) \\in \\{16, 17\\}\\)' in section, 'the bounds at 1440'
    listed = [ns.split(', ') for ns in re.findall(r'<p class="entry">\\\(n = (.*?)\\\): ', text)]
    assert not any('1440' in ns for ns in listed) and 1440 not in new_cells(text), listed
    assert smallest_table()[15] == ['16', '1440', '1440', '✓'], smallest_table()[15]
    # Since 2026-11-10 mstar.js reaches 2048 ([BOU]) and 1440 is one of its columns, the example its lower bound, and
    # no column before it allows order 16 (until then: mtopAt's first n was 1440, and past held the example).
    cols = mstar_data()['cols']
    assert cols[1439][:3] == [16, 17, ['example', 'equipow p1440']] and max(c[1] for c in cols[:1439]) == 15, cols[1439]
    # Since 2026-11-11 past is not empty: the Symmetry section has symmetric sequences of order 12 at 2096, 2128 and
    # 2192, longer than the chart (quals_mstar's q_past_lists_the_example_of_order_16_at_1440 holds the list).  What
    # this qual needs of past is that none of them reaches order 16, so that 1440 stays the least length known there.
    # 2026-11-30: the four new centers reach 17, 18 and 19 beyond the chart.
    # Retain the check for every other past row and verify the proof of least
    # length using all rows, including those new witnesses and the 1440 column.
    rows = mstar_rows(mstar_data())
    higher = {n: m for n, m, *_ in mstar_data()['past'] if m >= 16}
    with open(os.path.join(HERE, 'proofs', 'symcenters.json'), encoding='utf-8') as src:
        centers = json.load(src)
    from runpy import run_path
    witness = run_path(os.path.join(HERE, 'proofs', 'cubicedge.py'))['higher_witness']
    cubic = {19712: 16, 19744: 16, 39424: 17}
    for n, m in cubic.items():
        w = witness(n)
        assert len(w) == n and set(w) == {-1, 1}
        moments = [sum(s*math.comb(i,j) for i,s in enumerate(w)) for j in range(m+1)]
        assert moments[:m] == [0]*m and moments[m] != 0, n
    assert higher == {int(n): c['order'] for n, c in centers.items()} | cubic, higher
    assert min(n for n, c in rows.items() if c[0] >= 16) == min(n for n, c in rows.items() if c[1] >= 16) == 1440
    assert any(d == '2026-11-04' and '\\(a(15) = 1440\\)' in rest for d, rest in changelog()), changelog()[:3]
    # Spec change (2026-11-07; dreeves, of quals that failed on his rewrite of the OEIS notes: "if i wrote something, that
    # shouldn't make a qual fail, right?"): this qual no longer asks the OEIS note on A323395 to state a(15) = 1440.


OEIS = ('A323395', 'A306248', 'A323610', 'A323629', 'A323614')                # the OEIS section's entries on this problem
RELATED = ('A382832', 'A382833', 'A362039', 'A010060', 'A106400', 'A001969', 'A000069', 'A140047')   # and related ones


def q_oeis_section_links_the_family():
    # Replicata: index.html: the section after the table of smallest lengths.
    # Expectata (dreeves, 2026-10-28: "can you make a section that links to all the relevant OEIS entries and notes any
    # discrepancies?"): a <section class="oeis" aria-labelledby="oeis-title"> with its h2 oeis-title (its place, a
    # TODO comment, a block quote by Claude and its attribution "— Claude" were pinned too until 2026-10-30, when
    # dreeves's edits took them out), with two lists: one item per entry on this problem (OEIS:
    # A323395, A306248, A323610, A323629, A323614), then one per related entry (RELATED: A382832, A382833, A362039,
    # A010060, A106400, A001969, A000069, A140047), each in that order and each linking https://oeis.org/ and its
    # number, once, and no other entry.
    sec = re.search(r'<section class="oeis" aria-labelledby="oeis-title">.*?</section>', page(), re.S)
    assert sec, 'no section "oeis"'
    body = sec.group(0)
    assert '<h2 id="oeis-title">' in body, body[:400]
    lists = [re.findall(r'<li>(.*?)</li>', ul, re.S) for ul in re.findall(r'<ul>(.*?)</ul>', body, re.S)]
    links = [[re.findall(r'href="https://oeis\.org/(A\d{6})"', li) for li in items] for items in lists]
    assert links == [[[a] for a in OEIS], [[a] for a in RELATED]], links


def q_oeis_notes_hold_on_the_chart():
    # Replicata: the OEIS section's first list, and mstar.js (its columns, past examples, mtop and mtopAt).
    # Expectata: what Claude's words in the notes (each note's text after "Claude:") say of the chart holds there; nothing
    # has to be said, and dreeves's words are not read at all.  Every \(a(k) = N\) and
    # \(a(k) \le N\): a(k), OEIS's least n that is k-powerful, is the least n of order k + 1, so for = the least n known
    # to reach k + 1 (a column's lo, or a past example) is N and so is the least not ruled out (a column's hi, or past
    # the chart mtopAt), and for \le the least known is at most N.  "through \(n = N\)": m*(2n) settled for every
    # n <= N.  "\(m^*(M)\) is open": lo < hi at M.  "description through 1024" in a note on L_m: the chart's L_m through
    # 1024 is the comment's description (A323610: 48 and the multiples of 8 from 64; A323614: 144 and the multiples of
    # 16 from 192; A323629: 96, 112, ..., 176 and the multiples of 8 from 192).
    # Spec change (2026-11-07; dreeves, of three quals that failed on his rewrite of these notes: "if i wrote something,
    # that shouldn't make a qual fail, right?", and "quals like that never made any dang sense"): before, this qual asked
    # each note to state particular numbers (A323395's:
    # 432, 448, 464, 480, 672, 864, 960, 1440), so his rewrite, which states only a(11) = 480, failed it; and
    # q_oeis_errors_say_how_to_fix_them, which asked A323629's note to mark its error ("Error:", with both generating
    # functions) and A323395's to state a(12) <= 864, a(13) <= 960 and a(12) <= 672, is gone: his notes now say that OEIS
    # fixed both entries.
    # Resultata before: red on his notes for the A323395 numbers (and the errors qual on the missing "Error:").
    text = page()
    body = re.search(r'<section class="oeis" aria-labelledby="oeis-title">.*?</section>', text, re.S).group(0)
    notes = dict(zip(OEIS, re.findall(r'<li>(.*?)</li>', re.search(r'<ul>(.*?)</ul>', body, re.S).group(1), re.S)))
    data = mstar_data()
    cols = data['cols']
    lo, hi = (lambda n: cols[n - 1][0]), (lambda n: cols[n - 1][1])
    known = lambda m: min([n for n in range(2, NMAX + 1, 2) if lo(n) >= m] + [n for n, o, *_ in data['past'] if o >= m])   # (past's rows, [n, lo, ...], since 2026-11-19)
    allowed = lambda m: next((n for n in range(2, NMAX + 1, 2) if hi(n) >= m), None) or data['mtopAt'][m - data['mtop']]
    said = ' '.join(note.split('Claude:', 1)[1] for note in notes.values() if 'Claude:' in note)   # Claude's words alone
    for k, rel, N in re.findall(r'\\\(a\((\d+)\) (=|\\le) (\d+)\\\)', said):
        k, N = int(k), int(N)
        assert known(k + 1) == allowed(k + 1) == N if rel == '=' else known(k + 1) <= N, (k, rel, N, known(k + 1), allowed(k + 1))
    for N in map(int, re.findall(r'through \\\(n = (\d+)\\\)', said)):
        assert all(lo(2 * n) == hi(2 * n) for n in range(1, N + 1)), N
    for M in map(int, re.findall(r'\\\(m\^\*\((\d+)\)\\\) is open', said)):
        assert lo(M) < hi(M), M
    rules = {'A323610': (6, lambda n: n == 48 or (n % 8 == 0 and n >= 64)),
             'A323629': (7, lambda n: n in (96, 112, 128, 144, 160, 176) or (n % 8 == 0 and n >= 192)),
             'A323614': (8, lambda n: n == 144 or (n % 16 == 0 and n >= 192))}
    for a, (m, rule) in rules.items():
        assert 'description through 1024' not in notes[a].split('Claude:', 1)[-1] or (NMAX == 1024 and all(
            (lo(n) >= m) == rule(n) and (hi(n) >= m) == rule(n) for n in range(2, NMAX + 1, 2))), a


# ---------------------------------------------------------------------------------------------------------------------
# Browser quals

# A writer's name, a colon and then a quotation mark: a quotation of its words.  Opus 5.5 and Fable 5.2 since
# 2026-11-09 (the rename in this file's header); Claude until then, and still where the page says so.
# 2026-12-03: dreeves's “Astra adds” introduces a quotation in an existing paragraph.
# 2026-12-05: Gemini Neon added to the page's attributed AI writers (extends enforcement, weakens nothing).
WRITERS = r'(?:Opus 5\.5|Fable 5\.2|Claude|Astra(?: adds)?|Gemini Neon)'
QUOTED = WRITERS + r': ["“”]'
# A plain word: a token of letters alone, with hyphens, dashes or apostrophes inside and punctuation around, that has
# two letters or more together: what the page's prose is made of.  No qual asks for one to be on the page (dreeves,
# 2026-11-09: "i stand by the point about quals enforcing specific prose on the page being pretty useless").
# figures(text) is a text without them: its numbers, times, math, codes and marks, in order, one space between.  A qual
# that used to ask for a sentence of the page asks for its figures, with the sentence left in the qual to read.
PLAIN = re.compile(r'''[("“‘'\[]*[A-Za-z]+(?:[-–—'’][A-Za-z]+)*[)"”’'\].,;:!?…]*''')


def figures(text):
    return ' '.join(t for t in text.split() if not (PLAIN.fullmatch(t) and re.search('[A-Za-z]{2}', t)))


def among(said, text):
    """Whether said's figures stand among text's, in a row: from the start of one of text's figures to the end of one,
    or to the marks that close it (a colon, a quotation mark)."""
    assert figures(said), said
    return re.search(r'(?<!\S)' + re.escape(figures(said)) + r'(?!\S*[A-Za-z0-9])', figures(text)) is not None


# How a quotation opens: a writer's name (at most 40 characters, with no colon and no quotation mark), a colon and “.
# A box's is page/shared.js's.  Which name it is is not a qual's business: every qual that named Claude turned red
# when the page's writer became Opus 5.5 (2026-11-09).
OPENING = r'[^:“”"]{1,40}: “'
# A part's bound as the boxes' text writes it, \(m^*(N) \ge V\) or \le, and its colon (2026-11-18, dreeves's point 10:
# every part starts with its bound, and a quotation opens after it, at the part's words)
BOUND = r'\\\(m\^\*\([^)]*\) \\(?:ge|le) \d+\\\): '


def unquoted(part):
    """A box's part without its quotation's marks: the opening (OPENING) after its bound (BOUND; at its start until
    2026-11-18) and the ” at its end."""
    return re.sub('^(' + BOUND + ')' + OPENING + '|”$', r'\1', part)


def q_figures_are_a_text_without_its_words():
    # Replicata: figures and among, by which a qual holds a sentence of the page without its words, on fixed texts: a
    # line of the progress section, a box of the m*(n) chart, an entry's sentence, a tracked search's counts.
    # Expectata (dreeves, 2026-11-09: "we need more quals for substantive things and fewer quals enforcing words on the
    # page"): a text's figures are its tokens that are not plain words, in order (numbers, times, math, codes, marks,
    # single letters); they are the same for a text and for it with other words in the words' places; said's figures
    # stand among text's when they stand there in a row and whole: a number changed, a number cut short or another
    # order does not pass, a mark closing the last figure (a colon, a quotation mark) does; and a said of words alone
    # is refused.
    N = '\u202f'
    line = f'2h{N}0m{N}0s + 1–3{N}h to go = 3–5{N}h (Fri 7pm – 9pm)'
    assert figures(line) == '2h 0m 0s + 1–3 h = 3–5 h 7pm – 9pm)', figures(line)
    box = ('Opus 5.5: “\\(m^*(1024) \\le 11\\): norm bound, \\(p = 3 \\nmid n\\): for \\(s_r\\) = 342, 341, 341 and '
           '\\(\\sum s_r^2 =\\) 349,526; at \\(m = 12\\)”')
    assert figures(f'2h{N}0m{N}0s + 1–3{N}h left = 3–5{N}h (Friday 7pm – 9pm)') == figures(line)
    assert figures('2 runs: 1 running, 0 frozen, 1 ended, 0 aborted; 0 found; running.') == '2 1 0 1 0 0' == figures('2 sessions: 1 live, 0 held, 1 over, 0 killed; 0 hits; live.')
    assert among('\\(p = 3 \\nmid n\\)', box) and among('= 342, 341, 341 and \\(\\sum s_r^2 =\\) 349,526;', box) and among('\\(m = 12\\)', box)
    assert not among('= 342, 341, 34 and', box) and not among('= 342, 342, 341 and', box) and not among('341, 342', box)
    assert among('of orders 33, 31 and 31.', 'a join of orders 33, 31 and 31. More')
    assert not among('of orders 33, 31 and 31.', 'a join of orders 33, 32 and 31. More')
    refused = False
    try:
        among('words alone', box)
    except AssertionError:
        refused = True
    assert refused, 'among took a said of words alone'


def visible_text():
    """index.html's text a reader sees, with every comment, script, style and tag (attribute values with it) blanked out
    character for character, so positions are the file's."""
    text = page()
    for pat in (r'<!--.*?-->', r'<script\b[^>]*>.*?</script>', r'<style>.*?</style>', r'<[^>]*>'):
        text = re.sub(pat, lambda m: re.sub(r'[^\n]', '\0', m.group(0)), text, flags=re.S)
    return text


def q_quotes_of_claude_and_astra_are_curly():
    # Replicata: index.html's text a reader sees (visible_text), its tags' attribute values and its scripts (in page/
    # since 2026-10-31, inline before); and the light run's readouts of the m*(n) chart's cells ringed in gold.
    # Expectata (dreeves's README, 2026-10-30: "[CUR] Curly quotes for quoting Claude and Astra"): each quotation of
    # Claude's or Astra's words (QUOTED) opens with “ and closes with ”, the next quotation mark after it, in the text
    # and in an attribute value (as the zoom buttons' titles); no Claude: or Astra: in a script is followed by a straight
    # ", the scripts' strings that write such quotations into the page (the m*(n) readout's note on a ringed cell, the
    # record-gaps table's error line, the labels of a paired study's dots) among them; and a ringed cell's readout
    # quotes Claude with “ and ”.  HTML comments keep straight quotes.
    # Resultata before: 55 quotations in the text, 2 in titles and 3 in scripts, all with straight quotes.
    text = visible_text()
    html = re.sub(r'(<(script|style)\b[^>]*>).*?(</\2>)', r'\1\3', re.sub(r'<!--.*?-->', '', page(), flags=re.S), flags=re.S)
    tags = [v for t in re.findall(r'<[a-zA-Z][^>]*>', html) for v in re.findall(r"""=(?:'([^']*)'|"([^"]*)")""", t)
            for v in v if v]
    quotes = [(s, m) for s in [text] + tags for m in re.finditer(QUOTED, s)]
    assert quotes, 'no quotation of Claude or Astra'
    bad = [s[m.start():m.end() + 60].replace('\0', '') for s, m in quotes
           if m.group(0)[-1] != '“' or (re.compile(r'["“”]').search(s, m.end()) or [''])[0] != '”']
    assert bad == [], (len(bad), bad[:5])
    scripts = page_scripts(page())
    assert not any(re.search(WRITERS + ': "', js) for js in scripts), [re.findall('.{30}' + WRITERS + ': ".{30}', js) for js in scripts]
    R = valid_run('light')
    rings = set(a323395_cells(mstar_data()['cols']))
    notes = [t for n, m, t in R['hovers'] if (n, m) in rings]
    # A note may or may not quote Claude (dreeves's 6220ea2, 2026-10-30, dropped Claude: “…” from the m*(n) chart's
    # ring notes); one that does uses “ and ”.
    assert notes and all(not re.search(WRITERS + ': "', t) and t.count('“') == t.count('”') for t in notes), notes[:3]


# The page's codes as anchors, and no "index.html" for its readers (dreeves's README, 2026-10-31: "[IND] Find a better
# way to refer to things like "index.html p320" -- we should never refer to "index.html" in user-facing copy. How about
# just drop the "index.html" and make the "p320" or whatever be a hyperlink / anchor link? If that doesn't work for
# hovertext, we could just say "equipow p320" instead of "index.html p320".")

# The names in the page's math of sequences whose codes the page does not show, so that a name there has no code to link
# to: BGPW's example of order 10 at 240 (the published paper's Table 5), a factor of 2^20's construction.  Since
# 2026-10-31 each is a part of a construction (data-construction), whose derivation cites mstar.js's source of it.
OFF_PAGE = ('p_{240}',)


def blank_comments(text):
    """text with each HTML comment blanked out character for character, so that positions are text's."""
    return re.sub(r'<!--.*?-->', lambda m: re.sub(r'[^\n]', ' ', m.group(0)), text, flags=re.S)


def unlink(text):
    """text with each link of a name to its code, \\href{#N:M}{name} (2026-10-31, [IND]), written as the name alone."""
    return re.sub(r'\\href\{#\d+:\d+\}\{([pq]_\{\d+\})\}', r'\1', text)


def page_codes(text):
    """[(start, end, n, m, attributes, hex)] for each code of the code blocks (<p class="code">) of text, a version of
    index.html with its comments blanked: its block's span in text; its order m, the (m = M) of its block's labels in
    order, one for each code and each join of codes (<span data-join="IDS" data-order="M">, since 2026-10-31) of the
    block; its length n, by the paper's Table 5 convention (the hex digits give the left half of the signs, the rest
    follows by (-1)^m symmetry); and its <code> tag's attributes."""
    out = []
    for b in re.finditer(r'<p class="code">(.*?)</p>', text, re.S):
        ms = [int(x) for x in re.findall(r'\\\(\(m = (\d+)\)\\\)', b.group(1))]
        tags = re.findall(r'<code([^>]*)>([0-9A-F]+)</code>|<span data-join="[^"]*" data-order="\d+">', b.group(1))
        assert len(ms) == len(tags) == b.group(1).count('<code') + b.group(1).count(' data-join=') >= 1, b.group(1)
        out += [(b.start(), b.end(), 8 * len(h), m, attrs, h) for m, (attrs, h) in zip(ms, tags) if h]
    return out


def q_codes_are_anchors_and_names_link_to_them():
    # Replicata: index.html outside its comments: the codes of its code blocks (page_codes) and the names p_{N} and
    # q_{N} in its math; and the light run's links to anchors of the page (R's anchors) and its math.
    # Expectata ([IND]: "make the "p320" or whatever be a hyperlink / anchor link"): each code is <code id="N:M">, N its
    # length and M its order, the ids distinct; a name in a code's own block with that code's length is the code's own
    # name (p_{448} in its label, p_{192} in its and in the join beside it); a name inside a join of codes (<span
    # data-join="IDS">, since 2026-10-31: a button, which holds no link) stands for the code that IDS lists at its
    # place, and is that code's own name; a name p_{N} inside a construction (<span data-construction="N:M">, since
    # 2026-10-31: a button too, whose derivation's rows link to the codes instead, which quals_derivations'
    # q_leaves_resolve checks) stands for the best known sequence of length N, the code N:L with L mstar.js's lower
    # bound at N, and is that code's own name, or else it is one of OFF_PAGE, which no code carries, each of which is
    # such a part; every other name is \href{#N:M}{name}, a link to the one code whose own names include it; every
    # \href of the page is such a link; and in the light run each is an <a> that KaTeX drew, to the <code> of its id,
    # and KaTeX drew no command in its error color (an \href it does not trust, it draws as its name in red).
    # Resultata before: no code had an id, and no name was a link.  Then (2026-10-31, the constructions made buttons,
    # their names no longer links) this qual, which knew no constructions, found 9 names unlinked besides OFF_PAGE's.
    text = blank_comments(page())
    codes = page_codes(text)
    ids = [f'{n}:{m}' for _, _, n, m, _, _ in codes]
    assert [a for *_, a, _ in codes] == [f' id="{i}"' for i in ids] and len(set(ids)) == len(ids), \
        [(i, a) for i, (*_, a, _) in zip(ids, codes) if a != f' id="{i}"'][:5]
    names = [(f.start(1) + x.start(), x.group(0), int(x.group(1)))         # (position, name, N)
             for f in re.finditer(r'\\\((.*?)\\\)', text, re.S) for x in re.finditer(r'\b[pq]_\{(\d+)\}', f.group(1))]
    own = lambda i, n: [f'{c[2]}:{c[3]}' for c in codes if c[0] <= i < c[1] and c[2] == n]
    owners = {}                                                             # name: the ids of the codes it is an own name of
    for i, name, n in names:
        for c in own(i, n): owners.setdefault(name, set()).add(c)
    links = {x.start(2): (x.group(1), x.group(2)) for x in re.finditer(r'\\href\{#([^}]*)\}\{([pq]_\{\d+\})\}', text)}
    parts = {}                                                              # a name inside a join: the id it stands for
    for x in re.finditer(r'<span data-join="([^"]*)" data-order="\d+">(.*?)</span>', text, re.S):
        inside = [i for i, name, n in names if x.start(2) <= i < x.end(2)]
        assert len(inside) == len(x.group(1).split(' ')), (inside, x.group(1))
        parts.update(zip(inside, x.group(1).split(' ')))
    assert [(name, parts[i]) for i, name, n in names if i in parts and owners.get(name) != {parts[i]}] == [], parts
    cols = mstar_data()['cols']
    built = {}                                                              # a name inside a construction: the id it stands for
    for x in re.finditer(r'<span data-construction="[^"]*">(.*?)</span>', text, re.S):
        built.update((i, f'{n}:{cols[n - 1][0]}') for i, name, n in names if x.start(1) <= i < x.end(1) and not own(i, n))
    assert [(name, built[i]) for i, name, n in names if i in built and owners.get(name, set()) != {built[i]}
            and not (name in OFF_PAGE and name not in owners)] == [], built
    assert sorted({name for i, name, n in names if i in built and name in OFF_PAGE}) == sorted(OFF_PAGE), built
    others = [(i, name) for i, name, n in names if not own(i, n) and i not in parts and i not in built]
    assert text.count('\\href') == len(links) == sum(i in links for i, _ in others), (text.count('\\href'), len(links))
    unlinked = sorted({name for i, name in others if i not in links})
    assert unlinked == [] and not owners.keys() & set(OFF_PAGE), unlinked
    bad = [(name, links[i]) for i, name in others if i in links and (links[i][1] != name or owners.get(name) != {links[i][0]})]
    assert bad == [], bad
    R = valid_run('light')
    # Spec change (2026-11-07; dreeves, asked whether a code may also be linked by an ordinary HTML link, as the
    # Asymptotics section's "1440:16" was, or only by its name in math: "consistency is good?"): every link to a code
    # is still its name, \href{#N:M}{p_{N}}, drawn by KaTeX; a link to another element of the page, as Astra's to the
    # complete proof of 384, may be an ordinary link, but must name an element that is there.  Before, every link to
    # an anchor of the page had to be such a name.
    assert all(target for _, target, _ in R['anchors']), R['anchors']
    assert sorted(a for a in R['anchors'] if a[1] == 'CODE') == sorted([f'#{t}', 'CODE', True] for t, _ in links.values()), \
        (R['anchors'][:5], len(links))
    assert R['math']['unsupported'] == 0, R['math']


def q_readers_never_see_index_html():
    # Replicata: index.html outside its comments; page/'s stylesheet and scripts outside their comments (/* ... */, and in
    # a script a // at a line's start or after a space, to the line's end); mstar.js's and pow2.js's data as node sees
    # it (their reasons, not their first lines' comments); and the light run: the page's text and attribute values once
    # its scripts ran (R's indexHtml) and the readouts of its hovers.
    # Expectata ([IND]: "we should never refer to "index.html" in user-facing copy ... If that doesn't work for
    # hovertext, we could just say "equipow p320" instead of "index.html p320""): none of them holds "index.html"; and
    # the readout of a cell that an example of the page settles names it as equipow and its name: 320's, "(equipow
    # p320)", and 352's, "(equipow BGPW 352)".
    # Resultata before: 34 of mstar.js's example labels ("index.html p320", "index.html BGPW 352", ...), and so the
    # light run's readouts of their columns.
    assert 'index.html' not in blank_comments(page())
    for name in page_files():          # the stylesheet and the scripts, as the replicata says: not page/'s README.md (2026-11-10)
        src = re.sub(r'/\*.*?\*/', '', open(os.path.join(PAGE_DIR, name), encoding='utf-8').read(), flags=re.S)
        code = re.sub(r'(^|(?<=\s))//[^\n]*', '', src, flags=re.M) if name.endswith('.js') else src
        assert 'index.html' not in code, (name, re.findall(r'.{0,40}index\.html.{0,20}', code)[:3])
    for data in (mstar_data(), pow2_data()):
        text = json.dumps(data, ensure_ascii=False)
        assert 'index.html' not in text, re.findall(r'.{30}index\.html.{20}', text)[:5]
    R = valid_run('light')
    assert R['indexHtml'] == [], R['indexHtml'][:5]
    shown = [t for n, m, t in R['hovers'] if 'index.html' in t]
    assert shown == [], (len(shown), shown[:3])
    for n, label in ((320, 'equipow p320'), (352, 'equipow BGPW 352')):
        assert any(f'({label})' in t for k, m, t in R['hovers'] if k == n), [t for k, m, t in R['hovers'] if k == n]


def q_page_loads_clean():
    # Replicata: index.html with the real mstar.js in headless Chrome, 1280 px wide at 2 device px per CSS px; and the
    # page loaded as is (nothing added), with Chrome logging its console to stderr.
    # Expectata: no errors, console errors or warnings; the canvas is drawn (nonzero height, as wide as main's content);
    # the chart opens showing all NCOL = 142 columns, COLUMNS, up to 2048 (since 2026-11-12; 257 before, n = 2 and the
    # multiples of 4 up to 1024).  The plain
    # load logs nothing at all to the console.
    assert console_lines() == [], console_lines()
    R = valid_run('light')
    assert R['canvasDev'][1] > 0 and close(R['canvasCss'][0], R['mainContentW'], 1), R
    v = R['views'][0]
    assert close(v['u0'], 0, 0.01) and close(v['span'], NCOL, 0.05), v


def q_sections_space_their_parts():
    # Replicata: the light run: each section of main, and the space between each two of its children laid out one after
    # the other (the least per section).
    # Expectata (dreeves, 2026-10-30: "what's up with the spacing here?", of the smallest lengths' heading, paragraph and
    # table, flush once his edit took them out of the block quote whose grid had spaced them): at least 12 px, as every
    # section with two or more parts has, in each of the page's 8 sections (9 until the section of sets left the page
    # on 2026-10-31).
    # Resultata before: 0 px in the sections smallest, oeis and lattice.
    R = valid_run('light')
    tight = [(c, g) for c, g in R['sectionGaps'] if g is not None and g < 12]
    assert len(R['sectionGaps']) >= 8 and not tight, (tight, R['sectionGaps'])


def q_prose_has_one_measure():
    # Replicata: the light run (1280 px wide, main's content box 960 px): every p and li of main outside the legends.
    # Expectata (dreeves, 2026-10-29, of the paragraph above the m*(n) chart, which ran the column's full width, and the
    # powers-of-2 chart's caption, 46rem: "the right margin seems to be inconsistent here"): the running text has one
    # measure, the 46rem of the text sections, so each justified p or li ends 736 px from the left of main's content
    # box (within 0.5 px), while tables and charts may span the column.  The charts' readouts are their charts': as
    # wide as the column, and ragged (text-align start), as their text changes under the pointer.
    # Resultata before: justified text ended 672 px (the header's 42rem), 736 and 960 px from it.
    R = valid_run('light')
    assert close(R['mainContentW'], 960, 0.5), R['mainContentW']
    ends = sorted({round(right, 1) for _, align, right in R['prose'] if align == 'justify'})
    assert len(ends) == 1 and close(ends[0], 736, 0.5), ends
    readouts = {i: (align, round(right, 1)) for i, align, right in R['prose'] if i in ('mstar-readout', 'pow2-readout')}
    assert readouts == {'mstar-readout': ('start', 960.0), 'pow2-readout': ('start', 960.0)}, readouts


def q_drawn_cells_match_data():
    # Replicata: the light and phone runs: the full view, and a sweep of the NCOL columns, COLUMNS (142 of them, n = 2,
    # 4, 8, 16, …, 2048, since 2026-11-12; 257, n = 2, 4, 8, 12, …, 1024, before), zoomed in, so every column is at
    # least 3 device px wide.
    # Expectata: every column is checked, in every row of its view (since 2026-11-10 the rows follow the view, at
    # dreeves's word: rows 1 to one more than the largest upper bound among the view's columns, so each column is
    # checked from row 1 to the row above its upper bound at least; the full view has the rows it had, one more than
    # the largest upper bound up to its cap, laid out as the harness measures them): its middle pixel has its color from mstar.js (exists up
    # to lo, open up to hi, impossible above) as the page's tokens give it, and the pixel below each row is paper.  In
    # the full view and every view of the sweep, every pixel of row 1 is exists, from the plot's left edge to its
    # right: no odd column (impossible in every row, since lo = hi = 0) is drawn, not even mixed into a pixel; but for
    # the ring of a cell of row 1 (q_chart_rings_the_smallest_lengths_in_gold), and since 2026-10-30 the gold dot of a
    # cell of row 1 proven the least, passed over a device px either side (rowOneSkips), the cells next to a ring in its
    # row and the row above, which that qual checks instead, and the column lines of the zoomed views (rowOneLines),
    # which q_mstar_grid_lines_come_with_zoom checks.
    data = mstar_data()
    assert all(data['cols'][n - 1][0] >= 1 for n in COLUMNS), 'some column has no exists cell in row 1'
    for name in ('light', 'phone'):
        R = valid_run(name)
        assert R['pixelBad'] == [], (name, R['pixelBad'][:10])
        assert R['pixelColumns'] == COLUMNS, (name, sorted(set(COLUMNS) ^ set(R['pixelColumns']))[:20])
        assert R['pixelChecks'] >= sum(data['cols'][n - 1][1] + 1 for n in COLUMNS), (name, R['pixelChecks'])
        assert len(R['rows']) == max(data['cols'][n - 1][1] for n in COLUMNS) + 1 and R['rows'] == R['rowsDrawn'], (name, R['rows'], R['rowsDrawn'])
        assert R['rowOneBad'] == [], (name, len(R['rowOneBad']), R['rowOneBad'][:10])
        assert R['rowOneChecks'] + R['rowOneSkips'] + R['rowOneLines'] == len(R['views']) * (R['plot'][1] - R['plot'][0]), (name, R['rowOneChecks'])
        assert R['rowOneSkips'] <= len(R['views']) * (4 * R['dpr'] + 6), (name, R['rowOneSkips'])


def q_aria_labelledby_names_an_element():
    # Replicata: index.html: each aria-labelledby attribute and each id.
    # Expectata: each id an aria-labelledby names is an element's, so a screen reader announces each section by its
    # heading.
    # Resultata before (2026-10-29): the m*(n) chart's section named mstar-title, which no element had had since
    # dreeves's paragraph replaced its h2 on 2026-10-27; his new h2 had the id pow-title.
    text = page()
    ids = set(re.findall(r'\bid="([^"]+)"', text))
    names = [i for n in re.findall(r'\baria-labelledby="([^"]+)"', text) for i in n.split()]
    assert names and [i for i in names if i not in ids] == [], [i for i in names if i not in ids]


def q_no_block_opens_inside_a_paragraph():
    # Replicata: index.html, its tags in order (html.parser), with the <p> elements open at each.
    # Expectata (dreeves, 2026-10-29: "what's up with the spacing of my <ul> list there?", a list written inside a <p>):
    # no block element (p, ul, ol, li outside a list, table, div, blockquote, figure, section, details, pre, h1-h6)
    # starts while a <p> is open.  An HTML parser closes the <p> there instead, and its </p> then makes an empty
    # paragraph, which the section's grid spaces like any other.
    # Resultata before: the list of exceptions above the m*(n) chart started inside its paragraph, after a <br>.
    BLOCK = {'p', 'ul', 'ol', 'table', 'div', 'blockquote', 'figure', 'section', 'details', 'pre',
             'h1', 'h2', 'h3', 'h4', 'h5', 'h6'}
    class Paragraphs(html.parser.HTMLParser):
        def __init__(self):
            super().__init__(convert_charrefs=True)
            self.open, self.bad = 0, []
        def handle_starttag(self, tag, attrs):
            if tag in BLOCK and self.open: self.bad.append((self.getpos(), tag))
            self.open += tag == 'p'
        def handle_endtag(self, tag):
            self.open -= tag == 'p' and self.open > 0
    parser = Paragraphs()
    parser.feed(page())
    assert parser.bad == [], parser.bad


def q_mstar_leaves_out_odd_multiples_of_2():
    # Replicata: mstar.js; the light and phone runs: row 2 of the full view and of every view of the sweep.
    # Expectata (dreeves, 2026-10-29: "can we make my "odd multiple of 2" bullet point be true?", of his "Odd multiples
    # of 2 except 2 itself are left out; for all n=4k+2 for some k ≥ 0, m*(4k+2) = 1"): every n = 2 mod 4 has lo = hi =
    # 1 in mstar.js and every multiple of 4 lo >= 2; the chart's columns as the page loads are COLUMNS, NCOL = 142 of
    # them (n = 2 and the multiples of 4 up to 1024, 257, until 2026-11-12, when dreeves asked for every box checked and
    # the cap 2^11 as the page loads; q_page_loads_clean measures the full view's); and row 2, impossible at every n = 2 mod 4, is exists in every pixel
    # right of n = 2's column, so no other n = 2 mod 4 is drawn, not even mixed into a pixel: but for a device px past
    # n = 2's column, the ring of row 2 and its gold dot (since 2026-10-30: (4, 2) is proven the least) and the zones of
    # the column lines (rowTwoSkips), at most a fifth of the pixels.
    cols = mstar_data()['cols']
    assert all(cols[n - 1][:2] == [1, 1] for n in range(2, FULL + 1, 4)) and all(cols[n - 1][0] >= 2 for n in COLUMNS[1:])
    assert COLUMNS[:4] == LOAD_COLUMNS[:4] == [2, 4, 8, 16] and NLOAD == 142
    for name in ('light', 'phone'):
        R = valid_run(name)
        assert R['rowTwoBad'] == [], (name, len(R['rowTwoBad']), R['rowTwoBad'][:10])
        total = len(R['views']) * (R['plot'][1] - R['plot'][0])
        assert R['rowTwoChecks'] + R['rowTwoSkips'] == total and R['rowTwoSkips'] <= total / 5, (name, R['rowTwoSkips'], total)


def omit_boxes():
    """The boxes of the page's list of what the m*(n) chart leaves out ([COM]), in page order, each (factor, start,
    order, checked): a checked box leaves out the odd multiples of its factor from its start on, each of which has
    m*(n) = its order."""
    listed = re.findall(r'<ul [^>]*id="mstar-omit"[^>]*>(.*?)</ul>', blank_comments(page()), re.S)
    assert len(listed) == 1, len(listed)
    boxes = [(int(f), int(a), int(o), c == ' checked') for f, a, o, c in re.findall(
        r'<input type="checkbox" data-factor="(\d+)" data-from="(\d+)" data-order="(\d+)"( checked)?>', listed[0])]
    assert boxes and len(boxes) == listed[0].count('<input'), listed[0]
    return boxes


def q_omit_boxes_state_what_the_data_holds():
    # Replicata (dreeves's README, [COM], 2026-11-10: "Be more principled about what to omit from Figure 1. Idea:
    # checkboxes for what's omitted, in terms of the biggest power of two factor"): the boxes of the page's list of
    # what the m*(n) chart leaves out, each with its factor, the n its class starts from and the order it states; and
    # mstar.js.
    # Expectata: every n up to CAP that a box would leave out, the odd multiples of its factor from its start on, has
    # lo = hi = the order the box states, and each box has such n; and the n that the boxes checked as the page loads
    # do not leave out are COLUMNS, the columns that the other quals of this chart measure (since 2026-11-12, when
    # dreeves asked for every box checked and the cap 2^11 as the page loads, up to CAP, 2048; up to NMAX, 1024, with
    # the first two boxes checked, before).
    # Resultata before: no box; the chart left out the odd n and the odd multiples of 2 but 2, whatever the reader wanted.
    boxes, cols = omit_boxes(), mstar_data()['cols']
    left_out = lambda n, box: n >= box[1] and n % (2 * box[0]) == box[0]
    for box in boxes:
        ns = [n for n in range(1, FULL + 1) if left_out(n, box)]
        assert ns and all(cols[n - 1][:2] == [box[2], box[2]] for n in ns), (box, [n for n in ns if cols[n - 1][:2] != [box[2], box[2]]][:5])
    shown = [n for n in range(1, FULL + 1) if not any(b[3] and left_out(n, b) for b in boxes)]
    assert shown == COLUMNS, (len(shown), shown[:6])


def caps():
    """The caps of the m*(n) chart ([BOU], 2026-11-10): its buttons in page order, each (cap, k of its label 2^k,
    pressed as the page loads).  A click on one makes its cap the chart's last column."""
    listed = re.findall(r'<span class="caps" id="mstar-caps">(.*?)</span>', blank_comments(section()), re.S)
    assert len(listed) == 1, len(listed)
    found = re.findall(r'<button type="button" data-cap="(\d+)" aria-pressed="(true|false)">\\\(2\^\{?(\d+)\}?\\\)</button>', listed[0])
    assert found and len(found) == listed[0].count('<button'), listed[0]
    return [(int(c), int(k), p == 'true') for c, p, k in found]


def q_caps_follow_the_zoom_buttons():
    # Replicata: the chart's section, and mstar.js.
    # Expectata (dreeves's README, [BOU], 2026-11-10: "Let's try having Figure 1 go up to 2048. Actually, let's try
    # this: replace the reset-zoom button with "cap:" and then buttons for 2^6, 2^7, 2^8, 2^9, 2^10, 2^11"): right
    # after the zoom-in button, with only blank space and comments between, the caps: six buttons, their caps 64, 128,
    # ..., 2048, each labelled the power of 2 that its cap is; one of them pressed as the page loads, CAP's, 2048's
    # since 2026-11-12 (dreeves: "let's default to all checkboxes checked and cap=2^11 for figure 1"; 1024's before,
    # so that the chart opened as it was); the largest cap is mstar.js's nmax; and the section has no reset button.
    # Resultata before: a reset button, ↺, and a chart that ended at 1024.
    s = section()
    zin = re.search(r'<button type="button" id="mstar-zoom-in"[^>]*>[^<]*</button>', s)
    group = re.search(r'<span class="caps" id="mstar-caps">', s)
    assert zin and group and re.fullmatch(r'(?:\s|<!--.*?-->)*', s[zin.end():group.start()], re.S), s[zin.end():zin.end() + 300]
    # (Spec change, Opus 5.5, 2026-11-29; dreeves, of a cap at 4096: "worth it": seven buttons, to 4096, where the data ends; six, to 2048, until then.)
    assert [c for c, _, _ in caps()] == [2 ** k for k in range(6, 13)] and all(c == 2 ** k for c, k, _ in caps()), caps()
    assert [c for c, _, on in caps() if on] == [CAP], caps()
    assert max(c for c, _, _ in caps()) == mstar_data()['nmax'] == len(mstar_data()['cols']), mstar_data()['nmax']
    assert 'mstar-reset' not in page()


# The boxes to click, 15 times, for every state of the four boxes once, from any state.
GRAY = [2, 3, 2, 1, 2, 3, 2, 0, 2, 3, 2, 1, 2, 3, 2]


def columns_follow_the_controls(width, order):
    """What the m*(n) chart shows, the page width px wide, as its controls are clicked: each cap of order in turn, and
    under each the boxes one at a time through all 16 of their states (GRAY), the cap clicked again after each (a box's
    change shows every column since 2026-11-23, when caps became views), and back to the state as loaded.  In each
    state (states): hovers in row 1 at the middle of 30 columns' places (the first three, the last three and 24 spread
    evenly), were the columns those the cap pressed shows (expected), side by side over the whole plot
    (bad: the probes that read out another n); the caps pressed; the zoom buttons; the chart's height; and the n
    labels of one draw.  Then, with none checked: a hover and a click on the column of n = 7, and a click on the first
    box of the list, which has the focus (odd, opened, closed, focus); a click on the column of n = 8 and one on the
    cap pressed (capClosed, capFocus); a click on + and one on the cap pressed (zoomed, reset); and the boxes back to
    the state as loaded (the last of states)."""
    got = framed(width, """
  const errors = []; addEventListener('error', e => errors.push(String(e.message)));
  Element.prototype.setPointerCapture = function () {};     // synthetic pointers are never active, so capture would throw
  const cv = document.getElementById('mstar-chart'), ro = document.getElementById('mstar-readout');
  const panel = document.getElementById('mstar-panel'), boxes = [...document.querySelectorAll('#mstar-omit input')];
  const caps = [...document.querySelectorAll('#mstar-caps button')];
  const out = document.getElementById('mstar-zoom-out'), zin = document.getElementById('mstar-zoom-in');
  const LEFT = 44, RIGHT = 16, TOP = 2, PLOT = 224, y1 = TOP + PLOT - 3;        // y1: in row 1, the plot's lowest
  const fills = [], fillText = CanvasRenderingContext2D.prototype.fillText;
  CanvasRenderingContext2D.prototype.fillText = function (t, x, y, ...rest) { fills.push([String(t), x, y, this.textAlign]); return fillText.call(this, t, x, y, ...rest); };
  const pressed = () => caps.filter(b => b.getAttribute('aria-pressed') === 'true');
  // the columns the cap pressed shows: those up to it of the n no checked box leaves out, or the first 12 where those
  // are fewer (since 2026-11-23, when caps became views of every column; until then the n up to it, the chart's columns)
  const expected = () => { const all = Array.from({length: MSTAR.nmax}, (_, i) => i + 1).filter(n =>
    !boxes.some(b => b.checked && n >= +b.dataset.from && n % (2 * b.dataset.factor) === +b.dataset.factor));
    return all.slice(0, Math.max(all.filter(n => n <= +pressed()[0].dataset.cap).length, 12)); };
  const ptr = (type, x, y) => { const r = cv.getBoundingClientRect(); cv.dispatchEvent(new PointerEvent(type,
    {clientX: r.left + x, clientY: r.top + y, pointerId: 1, pointerType: 'mouse', buttons: 0, bubbles: true, cancelable: true})); };
  const nAt = x => { ptr('pointermove', x, y1); const m = ro.textContent.match(/^n = (\\d+), m = (\\d+)/); return m ? +m[1] : null; };
  const place = (E, c) => LEFT + (c + 0.5) * (cv.getBoundingClientRect().width - LEFT - RIGHT) / E.length;
  // the top row of the view, which is the rows: read out at the plot's top, since rows that are short are labeled by steps (2026-11-29)
  const topAt = x => { ptr('pointermove', x, TOP + 1); const m = ro.textContent.match(/m = (\\d+)/); return m ? +m[1] : null; };
  function look() {
    const E = expected(), dpr = devicePixelRatio, base = (TOP + PLOT) * dpr;
    const probes = [...new Set([0, 1, 2, E.length - 3, E.length - 2, E.length - 1,
      ...Array.from({length: 24}, (_, i) => Math.floor((i + 0.5) * E.length / 24))])];
    const bad = probes.map(c => [c, E[c], nAt(place(E, c))]).filter(([, want, got]) => want !== got);
    fills.length = 0;
    nAt(place(E, 0));                                         // a change of the cell read out draws the chart again
    const labels = fills.filter(([t, x, y]) => /^\\d+$/.test(t) && Math.abs(y - (base + 7 * dpr)) < 1).map(([t, x]) => [+t, x / dpr]);
    R.states.push({caps: pressed().map(b => +b.dataset.cap), checked: boxes.map(b => b.checked), ncol: E.length, bad,
      rows: fills.filter(([t, , , align]) => align === 'right').map(([t]) => +t), top: topAt(place(E, 0)),
      out: out.disabled, zin: zin.disabled, height: cv.getBoundingClientRect().height, labels, strangers: labels.filter(([n]) => !E.includes(n))});
  }
  const set = want => boxes.forEach((b, i) => { if (b.checked !== want[i]) b.click(); });
  const start = boxes.map(b => b.checked), R = {states: []};
  for (const c of ORDER) {
    const cap = caps.find(b => +b.dataset.cap === c);
    cap.click();
    look();
    for (const b of GRAY) { boxes[b].click(); cap.click(); look(); }   // (a box shows every column: its cap again, since caps are views)
    set(start);
  }
  set([false, false, false, false]);
  const E = expected(), at = n => place(E, E.indexOf(n));
  R.odd = nAt(at(7));
  ptr('pointerdown', at(7), y1); ptr('pointerup', at(7), y1);
  await sleep(100);
  R.opened = !panel.hidden;
  boxes[0].focus(); boxes[0].click();
  R.closed = panel.hidden; R.focus = document.activeElement === boxes[0];
  boxes[0].click();
  ptr('pointerdown', at(8), y1); ptr('pointerup', at(8), y1);
  await sleep(100);
  R.capOpened = !panel.hidden;
  pressed()[0].focus(); pressed()[0].click();
  R.capClosed = panel.hidden; R.capFocus = document.activeElement === pressed()[0];
  const cap = pressed()[0];                                  // the cap of these columns, clicked again once zoomed in
  zin.click();
  R.zoomed = !out.disabled; R.zoomedCaps = pressed().length;
  cap.click();
  R.reset = out.disabled; R.resetCaps = pressed().map(b => +b.dataset.cap);
  set(start); look();
  // The views: 8 clicks on +, then 40 presses of ArrowLeft and 80 of ArrowRight, an eighth of the view each: in each,
  // the n read out just inside the plot's two edges, and the rows that the draw labelled.
  const W = cv.getBoundingClientRect().width - LEFT - RIGHT;
  const seen = () => { const ends = [nAt(LEFT + 0.01), nAt(LEFT + W - 0.01)]; fills.length = 0; nAt(LEFT + W / 2);
    R.views.push({ends, rows: fills.filter(([t, , , align]) => align === 'right').map(([t]) => +t), top: topAt(LEFT + W / 2)}); };
  R.views = [];
  for (let i = 0; i < 8; i++) { zin.click(); seen(); }
  for (const [key, times] of [['ArrowLeft', 40], ['ArrowRight', 80]]) for (let i = 0; i < times; i++) {
    cv.dispatchEvent(new KeyboardEvent('keydown', {key, bubbles: true, cancelable: true})); seen(); }
  R.errors = errors;
  parent.postMessage(JSON.stringify(R), '*');""".replace('ORDER', json.dumps(order)).replace('GRAY', json.dumps(GRAY)))
    assert got['errors'] == [], (width, got['errors'][:3])
    return got


def labels_step(labels, top):
    """Are labels the multiples of their first, 1 or 5 or 10 ..., up to top (the rows from 1 to top, every labels[0]th labeled), the last label at
    most a step below the top?"""
    return labels[:1] != [0] and labels == list(range(labels[0], top + 1, labels[0])) and top - labels[-1] < labels[0] and labels[0] in (1, 5, 10, 25, 50)


def columns_as_stated(got, width, order, least):
    """columns_follow_the_controls's states, as they must be: 17 per cap of order, all 16 states of the boxes under
    it; in each, one cap pressed, the chart showing the n up to that cap that no checked box leaves out, or the first 12
    of them where those are fewer (every probe reads out the n expected there, − is disabled at the largest cap alone, and
    + exactly when those columns are at most the 12 of the closest view); its rows 1 to one more than the largest upper
    bound among its columns; its n labels the multiples of one step, all of them up to its last column, each a column, at
    least `least` of them, each two at least 48 CSS px apart; and the chart as tall in every state.  (Spec change, Opus 5.5, 2026-11-23; dreeves: "could we kill more if-statements if the zoom-out button always worked unless you're already seeing the full x-range?", then "whatever has the least if-statements / is otherwise most anti-magic":
    until then a cap was the chart's last column, so that − was disabled under every cap and the view never more than
    the n up to it.)"""
    boxes, states, cols = omit_boxes(), got['states'], mstar_data()['cols']
    start = [b[3] for b in boxes]
    assert len(boxes) == 4 and len(states) == 16 * len(order) + 1 and states[-1]['checked'] == start, (len(states), states[-1]['checked'])
    for i, cap in enumerate(order):
        under = states[16 * i:16 * i + 16]
        assert all(s['caps'] == [cap] for s in under) and under[0]['checked'] == start, (width, cap, [s['caps'] for s in under])
        assert len({tuple(s['checked']) for s in under}) == 16, (width, cap)
    for s in states:
        [cap] = s['caps']
        every = [n for n in range(1, DATA_NMAX + 1) if not any(c and n >= b[1] and n % (2 * b[0]) == b[0] for b, c in zip(boxes, s['checked']))]
        want = every[:max(len([n for n in every if n <= cap]), MIN_SPAN)]
        # (Spec change, Opus 5.5, 2026-11-29; dreeves, of a cap at 4096: "worth it": the chart opens at a cap below the data's end, so − is disabled where
        # the view is every column the boxes leave in (as "until you're already seeing the full x-range" has it), not at the largest cap of those clicked:
        # the same thing at the cap that is the data's last column.)
        assert s['ncol'] == len(want) and s['bad'] == [] and s['out'] == (len(want) == len(every)) and s['zin'] == (len(want) <= MIN_SPAN), (
            width, cap, s['checked'], s['ncol'], len(want), s['bad'][:5], s['out'], s['zin'])
        # (Spec change, Opus 5.5, 2026-11-29; dreeves, of a cap at 4096: "worth it": the rows are read off the top of the plot, since the labels step
        # where rows are short, every fifth at 25 rows; the labels are then all the multiples of their step up to the top row.)
        assert s['top'] == max(cols[n - 1][1] for n in want) + 1 and labels_step(s['rows'], s['top']), (width, cap, s['checked'], s['top'], s['rows'])
        ns, xs = [n for n, _ in s['labels']], [x for _, x in s['labels']]
        assert len(ns) >= least and ns == list(range(ns[0], want[-1] + 1, ns[0])), (width, cap, s['checked'], ns)
        assert s['strangers'] == [] and all(b - a >= 48 for a, b in zip(xs, xs[1:])), (width, cap, s['checked'], s['labels'])
    assert len({s['height'] for s in states}) == 1, sorted({s['height'] for s in states})
    return {(s['caps'][0], tuple(s['checked'])): s['ncol'] for s in states}


def q_omit_boxes_change_the_columns():
    # Replicata: the page 1280 px wide, and again 390 px wide, a phone's width; a click on the cap pressed as it loads,
    # CAP's (2048's since 2026-11-12, 1024's before); the boxes of its list clicked one at a time through all 16 of their
    # states, from the state as loaded, then to none checked, then back to the state as loaded (columns_follow_the_controls).
    # Expectata: in each state the chart shows all its columns, exactly those n (every probe reads out the n expected
    # there, and − is disabled); its n labels are the multiples of one step, all of them up to the cap, each a column, at
    # least three of them (two at 390 px), each two at least 48 CSS px apart; the odd column reads out n = 7 and the
    # click opens its box; the click on a box of the list closes that box and leaves the focus on the checkbox; and no
    # script error anywhere.
    # Resultata before: no boxes.  Then (2026-11-10, found by clicking through the 16 states at eight widths), with the
    # label steps 1 to 125 times the spacing of the last two columns: at 390 px the six states with the first box
    # unchecked stopped the chart with "Error drawing the chart: Error: [298,1024]", since no step left 48 px between
    # its labels; and where few multiples of a step were columns the labels were few: at 1280 px, 400 and 800 alone
    # with only the first box unchecked, or only the second.
    for width, least in ((1280, 3), (390, 2)):
        got = columns_follow_the_controls(width, [CAP])
        ncol = columns_as_stated(got, width, [CAP], least)
        assert ncol[CAP, tuple(b[3] for b in omit_boxes())] == NLOAD and ncol[CAP, (False,) * 4] == CAP, ncol
        assert got['odd'] == 7 and got['opened'] and got['closed'] and got['focus'], (got['odd'], got['opened'], got['closed'], got['focus'])


def q_rows_follow_the_view():
    # Replicata: the page 1280 px wide, as it loads but for a click on the cap pressed; then 8 clicks on +, 40 presses
    # of ArrowLeft and 80 of ArrowRight on the chart, an eighth of the view each (columns_follow_the_controls's
    # views): after each, the n read out just inside the plot's left and right edges, and the rows that the draw
    # labelled.
    # Expectata (dreeves, 2026-11-10: "however the chart is zoomed, make there always be exactly one fully pink row, ie,
    # zoom in the y direction automatically as a function of the x zoom"): in every view the rows are 1 to one more
    # than the largest upper bound among the columns from the one n to the other, so that the top row is impossible
    # in each of them and the row under it is not; the 128 views have five or more different numbers of rows; and the
    # chart is as tall in all of them (columns_as_stated, of the states).
    # Resultata before: 16 rows in every view (19 with mstar.js to 2048), most of them impossible in every column of
    # a view of small n.
    got, cols = columns_follow_the_controls(1280, [CAP]), mstar_data()['cols']
    ALL = [2, 4] + list(range(8, 200, 8)) + list(range(208, DATA_NMAX + 1, 16))          # every column that the boxes as loaded leave in, to the data's end
    assert len(got['views']) == 128, len(got['views'])
    for v in got['views']:
        a, b = v['ends']
        # (Spec change, Opus 5.5, 2026-11-29; dreeves, of a cap at 4096: "worth it": the views reach past CAP, so the columns are all of the data's that the
        # boxes leave in, the first box's and the others' as loaded, not CAP's COLUMNS.)
        assert v['top'] == max(cols[n - 1][1] for n in ALL if a <= n <= b) + 1 and labels_step(v['rows'], v['top']), v
    assert len({v['top'] for v in got['views']}) >= 5, sorted({v['top'] for v in got['views']})


def q_caps_change_the_columns():
    # Replicata: the page 1280 px wide, and again 390 px wide; a click on each cap in turn, 64, 128, 256, 512, 1024 and
    # then 2048, the one pressed as the page loads (since 2026-11-12; 2048 and then 1024 before); under each, the boxes
    # through all 16 of their states; then, with
    # none checked, a click on the column of n = 8 and one on the cap pressed, which has the focus; a click on + and
    # one more on that cap (columns_follow_the_controls).
    # Expectata (dreeves's README, [BOU], 2026-11-10: "replace the reset-zoom button with "cap:" and then buttons"): a
    # click on a cap presses it alone and makes it the chart's last column: in each state the chart shows all its
    # columns, exactly the n up to the cap that no checked box leaves out, with − disabled, and + too where they are
    # at most 12; its n labels are the multiples of one step, all of them up to the cap, each a column, each two at
    # least 48 CSS px apart, three or more at 1280 px and one or more at 390 px; the chart is as tall under every cap;
    # the click on the cap leaves open the box that the click on the column opened, as a zoom does, the focus staying on
    # the cap (Spec change, Opus 5.5, 2026-11-23; dreeves: "could we kill more if-statements if the zoom-out button always worked unless you're already seeing the full x-range?", then "whatever has the least if-statements / is otherwise most anti-magic": it closed the box until then, a cap changing the columns); the click
    # on the largest cap shows every column again, as the reset button did, and a cap is pressed while the view is its
    # every column, none once + zooms in (Spec change, Opus 5.5, 2026-11-23; dreeves: "if you zoom with the + button, the cap buttons should all become unselected": the cap clicked last stayed pressed until then); and no script error
    # anywhere.
    # Resultata before: no caps: the chart ended at 1024 and a reset button showed every column.
    order = [64, 128, 256, 512, 1024, 4096, 2048]         # the one pressed as the page loads last: 1024 until 2026-11-12; 4096 since 2026-11-29 (dreeves, of it: "worth it")
    assert sorted(order) == [c for c, _, _ in caps()] and order[-1] == CAP, caps()
    for width, least in ((1280, 3), (390, 1)):
        got = columns_follow_the_controls(width, order)
        ncol = columns_as_stated(got, width, order, least)
        assert all(ncol[cap, (False,) * 4] == cap for cap in order), ncol
        assert got['capOpened'] and not got['capClosed'] and got['capFocus'] and got['zoomed'] and got['reset'], (
            got['capOpened'], got['capClosed'], got['capFocus'], got['zoomed'], got['reset'])
        # (Spec change, Opus 5.5, 2026-11-29; dreeves, of a cap at 4096: "worth it": with no box checked the view is every column, so the cap pressed, and the
        # one that resets a zoom, is the largest, the data's end: CAP, 2048, until then, which was the same.)
        assert (got['zoomedCaps'], got['resetCaps']) == (0, [DATA_NMAX]), (got['zoomedCaps'], got['resetCaps'])


def q_a_box_whose_statement_fails_says_so():
    # Replicata: the page 1280 px wide with made-up data (kinds_data), in which the odd n and the odd multiples of 2
    # have the orders their boxes state, and n = 12, an odd multiple of 4, has lo = 2 and hi = 3, not the 3 its box
    # states; then that box, the third, clicked.
    # Expectata: the page loads with no error, since the boxes checked then leave out only n whose orders are as
    # stated; the click fails loudly, as broken data does when the page loads: the readout ends with the error, which
    # quotes column 12 as JSON, and the error is uncaught.
    # Resultata before: no boxes.
    got = framed(1280, """
  const errors = []; addEventListener('error', e => errors.push(String(e.message)));
  const ro = document.getElementById('mstar-readout'), R = {before: ro.textContent, tall: document.getElementById('mstar-chart').height > 0};
  document.querySelectorAll('#mstar-omit input')[2].click();
  await sleep(50);
  parent.postMessage(JSON.stringify({...R, after: ro.textContent, errors}), '*');""", kinds_data(), BEFORE[2])
    quoted = "[12,[2,3,['join',4,4,4],['two']]]"   # (the join 4 + 8 until 2026-11-18)
    assert got['tall'] and 'Error' not in got['before'], got['before']
    assert got['after'].endswith(f'Error: {quoted}') and got['errors'] == [f'Uncaught Error: {quoted}'], (got['after'], got['errors'])


def q_mstar_grid_lines_come_with_zoom():
    # Replicata: the light and phone runs: row 1 (exists in every column) of the full view, of every view of the
    # sweep (columns about 30 CSS px wide at 1280 px) and of the first view, zooming in from the full view step by
    # step, whose columns are wider than 4 CSS px (3 steps in at 1280 px, about 6).
    # Expectata (dreeves, 2026-10-29, of a full grid on this chart: "maybe when zoomed in enough the full grid could
    # become visible", then of the powers-of-2 chart's: "this with hairline grid looks great to me"): a line of paper one
    # device px wide at each boundary of whole columns, over the cells at opacity (w - 4) / 4 from 0 up to 1, w a
    # column's width in CSS px: none at the full view (columns under 2 px wide), part at 3 steps in, solid in the sweep.
    # Each line's zone, a device px either side, holds exactly one pixel off exists, that blend of paper over exists
    # within 3 per channel; zones under a ring are the ring's (q_chart_rings_the_smallest_lengths_in_gold), and zones
    # crossing the plot's left or right edge reach into its margins, so they are passed over.
    for name in ('light', 'phone'):
        R = valid_run(name)
        assert R['lineBad'] == [], (name, len(R['lineBad']), R['lineBad'][:5])
        assert 4 < R['midWidth'] < 8 and R['midZones'] > 0, (name, R['midWidth'], R['midZones'])
        sweep = sum(len(range(math.floor(v['u0']) + 1, math.ceil(v['u0'] + v['span']))) for v in R['views'][1:])
        assert R['lineZones'] >= sweep + R['midZones'] - 4 * len(R['views']), (name, R['lineZones'], sweep, R['midZones'])
        assert R['rowOneLines'] >= 3 * (sweep - 4 * len(R['views'])), (name, R['rowOneLines'], sweep)


def q_chart_rings_the_smallest_lengths_in_gold():
    # Replicata: the light and phone runs: the cells the chart rings, with their roles (R's rings), the ring checks of
    # the sweep, and the token --record.
    # Expectata (dreeves's README, 2026-10-30: "[GLT] ... Or, better: match the "smallest length known" table:
    # green+gold is the smallest *known* n (resp. 2^k) for a give m (resp. delta) and black+gold is the smallest n (resp.
    # 2^k) not ruled out. but then maybe we want an additional visual indicator for when those coincide (the smallest
    # known is proven to be the smallest)?"; from 2026-10-19 until then, dreeves: "in the chart can you highlight the
    # known values for a(m-1)? maybe make those green with gold trim", the proven ones alone): the ringed cells are
    # exactly smallest_rings of mstar.js, the chart's own least columns, the cells of the table of smallest lengths up to
    # 1024 (from 2026-10-31 until 2026-11-03 its rows 14 and 15 gave products beyond the chart, 1920 and 3840): today the proven ones, (2, 1), (4,
    # 2), …, (432, 11), (480, 12), SMALLEST_PROVEN by order ((480, 12) known and (432, 12) not ruled out until 2026-11-03), and (960, 15); then (912, 13) known and
    # (480, 13) not ruled out; (960, 14) known and (480, 14) not ruled out (until 2026-11-03, with no length known (dreeves, 2026-10-30: "why isn't 480:14 highlighted in the
    # chart?"), (480, 14) and (960, 15) not ruled out).  Each is ringed in --record, #ffb300 (the validator's pick against the chart's three
    # colors and the paper), just outside its left and right and below it, in each view of the sweep that checks it,
    # and every one is checked; at its middle a proven one is gold, a dot (Claude's proposal for when the two coincide),
    # and the others keep their cell's color.  (Their readouts' notes: q_hover_reads_out_cells.)
    # Resultata before: only the 11 proven cells were ringed.
    cols = mstar_data()['cols'][:FULL]            # the chart as the harness opens it, up to its cap (1024 until 2026-11-12, 2048 until 2026-11-29)
    want = smallest_rings(cols)
    assert [c for c, role in want.items() if role == 3] == a323395_cells(cols) == PROVEN_CELLS, want
    for name in ('light', 'phone'):
        R = valid_run(name)
        assert {(n, m): role for n, m, role in R['rings']} == want, (name, R['rings'])
        assert R['tokens']['record'] == '#ffb300', (name, R['tokens'])
        assert R['ringChecks'] >= len(want) and R['ringBad'] == [], (name, R['ringChecks'], R['ringBad'][:5])
        assert sorted(tuple(map(int, c.split(','))) for c in R['ringed']) == sorted(want), (name, R['ringed'])


def q_readout_reports_columns_only():
    # Replicata: the light and phone runs: every hover of the harness (the full view, every view of the sweep, the
    # searches for column edges, which probe within a millionth of a px of them, and the interactions), and a hover at
    # the middle of every device px across row 1 of the full view.
    # Expectata: no readout reports an n without a column (odd, or 2 mod 4 but 2; only odd before 2026-10-29); across
    # the full view the readout goes through n = 2, 4, 8, 12, …, 1024, each once, in order from left to right.
    for name in ('light', 'phone'):
        R = valid_run(name)
        assert R['hiddenReadouts'] == [] and R['readouts'] > 2 * NCOL, (name, R['readouts'], R['hiddenReadouts'][:5])
        assert R['across'] == COLUMNS, (name, R['across'][:20])


def q_n_labels_are_round_multiples_of_4():
    # Replicata: the strings drawn below the rows, right of the plot's left edge, in one draw in each of the full view,
    # every view of the sweep, and the view zoomed in as far as it goes: the draw of a hover over the first whole
    # column in view; in the light and phone runs.
    # Expectata: the n labels, and then (since 2026-11-02, dreeves's README: "[HOV] ...") the tag of the cell read out,
    # the n of that first column, centered on its middle to within a device px (q_axes_tag_the_cell_read_out).  The
    # labels are the multiples of one step s of ladder(COLUMNS, FULL) (so every label is an n with a column), whose
    # columns' middles are in view, in order, each centered on its column's middle to within a device px; s is the
    # first of those steps that puts any two of its columns next to each other at least 48 CSS px apart.  (Until
    # 2026-10-29 the steps were 2, 10, 20, 50, ... and every even n had a column; then 4, 20, 40, 100, 200, 500 with
    # the columns n = 2 and the multiples of 4; since 2026-11-12, every box checked as the page loads, 16, 80, 160,
    # 400, 800 and 2000.)
    for name in ('light', 'phone'):
        R = valid_run(name)
        (PL, PR), dpr = R['plot'], R['dpr']
        assert len(R['labelDraws']) == len(R['views']) + 1, (name, len(R['labelDraws']))
        for d in R['labelDraws']:
            v, (*got, tag) = d['v'], d['labels']
            s, at = next((s, at) for s, at, gap in ladder(COLUMNS, FULL) if gap * (PR - PL) / dpr / v['span'] >= 48)
            want = [COLUMNS[c] for c in at if v['u0'] - 1e-6 <= c + 0.5 <= v['u0'] + v['span'] + 1e-6]
            assert [t for t, _ in got] == [str(n) for n in want], (name, v, s, got)
            for t, x in got:
                assert close(x, PL + (COLUMNS.index(int(t)) + 0.5 - v['u0']) * (PR - PL) / v['span'], 1), (name, v, t, x)
            j = math.ceil(v['u0'] - 1e-3) + 1                      # the first whole column in view, the harness's first(v)
            assert tag[0] == str(COLUMNS[j - 1]) and close(tag[1], PL + (j - 0.5 - v['u0']) * (PR - PL) / v['span'], 1), (name, v, tag)


def q_zoom_buttons_sit_beside_show_all():
    # Replicata: the chart's section.
    # Expectata: a zoom-out button labelled − and then, with only blank space and comments between, a zoom-in button
    # labelled + (math, not English), each with an aria-label.  Until 2026-11-10 they stood right before the reset
    # button, whose place the caps took (dreeves's README, [BOU]: q_caps_follow_the_zoom_buttons).
    s = section()
    tags = {i: re.search(rf'<button type="button" id="{i}"([^>]*)>([^<]*)</button>', s)
            for i in ('mstar-zoom-out', 'mstar-zoom-in')}
    assert all(tags.values()), {i: bool(t) for i, t in tags.items()}
    out, zin = tags.values()
    assert re.fullmatch(r'(?:\s|<!--.*?-->)*', s[out.end():zin.start()], re.S), s[out.end():zin.start()]
    for t, label in ((out, '−'), (zin, '+')):
        attrs, text = t.groups()
        assert text == label, (t.group(0), label)
        assert re.search(r"\baria-label='[^']+'", attrs), attrs


# The reset buttons that each chart's script hands to panZoom, as its source has them: the chart of powers of 2 its ↺,
# the m*(n) chart none since 2026-11-10, when its caps took that button's place ([BOU]).
def q_both_charts_share_one_pan_and_zoom():
    # Replicata: index.html: its scripts, the sections of the two charts (mstar and pow2) and its stylesheet (the
    # scripts and the stylesheet files in page/ since 2026-10-31, inline before).
    # Expectata (dreeves's README, 2026-10-30: "[ZOO] For anti-magic/consistency, have the same zoom controls on both
    # charts"): one script, the first after </main>, defines function panZoom, the pan and zoom of both charts; it
    # also defines gridChart, the drawing of both charts, which calls panZoom once, with no reset button, and each
    # chart's script calls gridChart once, with its own chart (#mstar-chart, #pow2-chart), its own buttons and its own
    # caps (Spec change, Opus 5.5, 2026-11-23; dreeves: "please DRY up as much as possible between the 2 figures": until
    # then each chart's script called panZoom itself, and the chart of powers of 2 handed it its reset button ↺); each
    # section holds a div of class zoom that starts with the same two buttons, − and +, the same but for their ids'
    # prefixes (mstar- and pow2-), and then has the caps (the m*(n) chart's since 2026-11-10 at dreeves's word, README
    # [BOU]: "replace the reset-zoom button with "cap:" and then buttons", the chart of powers of 2's since 2026-11-23,
    # in place of its ↺); one rule styles those buttons, .zoom button (one their grayed-out look, and one the cap
    # pressed); and each chart takes the keys (tabindex 0).  Which of the two charts each zooms is quals_pow2_page's
    # q_zoom_controls_zoom_their_own_chart; how the m*(n) chart pans and zooms is the browser quals here.
    # Resultata before: only the m*(n) chart could zoom, from code of its own.
    text = page()
    body = text[text.index('</main>'):]
    own = page_scripts(body)
    shared = re.fullmatch(r'(?://[^\n]*\n)*function panZoom\(\{[^\n]*\}\) \{\n.*\n\}\n', own[0], re.S)
    assert shared and sum('function panZoom(' in js for js in own) == 1, own[0][:400]
    assert re.findall(r'panZoom\(\{el: cv, out: zoomOut, in: zoomIn, resets: \[\],', own[0]) != [] and sum(js.count('panZoom({el:') for js in own) == 1, 'panZoom'
    for chart, prefix in (('mstar-chart', 'mstar'), ('pow2-chart', 'pow2')):
        [js] = [s for s in own if f"getElementById('{chart}')" in s]
        calls = re.findall(r'gridChart\(\{cv, ro, panel[^,]*, zoomIn: document\.getElementById\(\'([\w-]+)\'\),\s*'
                           r'zoomOut: document\.getElementById\(\'([\w-]+)\'\),\s*caps: document\.querySelectorAll\(\'#([\w-]+) button\'\)', js)
        assert js.count('gridChart(') == 1 and len(calls) == 1, (chart, calls)
        assert calls[0] == (f'{prefix}-zoom-in', f'{prefix}-zoom-out', f'{prefix}-caps'), (chart, calls)
        assert re.search(rf'\bcv = document\.getElementById\(\'{chart}\'\)', js), chart
    groups = []
    for prefix in ('mstar', 'pow2'):
        sec = re.search(rf'<section class="{prefix}" .*?</section>', text, re.S).group(0)
        [z] = re.findall(r'<div class="zoom">(.*?)</div>', sec, re.S)
        z = ' '.join(re.sub(r'<!--.*?-->', '', z, flags=re.S).split()).replace(f'id="{prefix}-', 'id="')
        assert re.findall(r'<button type="button" id="([\w-]+)"[^>]*>([^<]*)</button>', z) == [
            ('zoom-out', '−'), ('zoom-in', '+')], (prefix, z)
        assert f'<span class="caps" id="{prefix}-caps">' in sec, prefix
        groups.append(z[:z.index('</button>', z.index('zoom-in'))])
        assert re.search(rf'<(?:canvas|div) id="{prefix}-chart"[^>]* tabindex="0"', sec), prefix
    assert groups[0] == groups[1], groups
    style = re.sub(r'/\*.*?\*/', '', page_css(), flags=re.S)
    selectors = [s.strip() for sel in re.findall(r'([^{}]+)\{', style) for s in sel.split(',')]
    assert [s for s in selectors if re.search(r'\bbutton\b', s)] == [
        '.zoom button', '.zoom button:disabled', '.zoom button[aria-pressed="true"]'], selectors


def q_zoom_buttons_zoom_about_the_middle():
    # Replicata: the light run: the zoom buttons at load; a click of each from a view zoomed in 3 steps; then, from the
    # full view, clicks of + until it is disabled and then of − until it is disabled, the view measured after each; and
    # the buttons after every interaction step (keys, wheels, drags, pinches, gestures, reset).
    # Expectata: + zooms in by 1.5 and − out by 1.5 about the middle (the u at the middle stays), as the + and − keys do,
    # stopping at 12 and NCOL columns: 8 clicks each way with the 270 columns of the cap of 4096, which the light run presses since 2026-11-29 (7 with the 142 as the page loads, 2026-11-12
    # to then; 8 with 257 before, 10 with 512 before 2026-10-29).  + is disabled
    # exactly when the view is 12 columns and − exactly when it is all NCOL: at load (− only), after every click and after every step (so − after the reset
    # button).  A disabled button is grayed out, not hidden: opacity at most 0.5 but displayed, visible and as big as
    # the other, whose opacity is 1.
    R = valid_run('light')
    assert 'buttonsError' not in R, R['buttonsError']
    S = R['steps']
    for name, f in (('zoomInButton', 1 / 1.5), ('zoomOutButton', 1.5)):
        a, b = S[name]['a'], S[name]['b']
        assert close(b['span'], a['span'] * f, 1e-3) and close(b['u0'] + b['span'] / 2, a['u0'] + a['span'] / 2, 1e-3), (name, S[name])
    clicks = R['clicks']
    zooms = math.ceil(math.log(NCOL / MIN_SPAN, 1.5))           # the clicks from all the columns to 12 of them
    # (Spec change, Opus 5.5, 2026-11-29; dreeves, of a cap at 4096: "worth it": 8 clicks, 7 until then; NOW's note.)
    assert zooms == 8 and [k for k, *_ in clicks] == ['start'] + ['in'] * zooms + ['out'] * zooms, [k for k, *_ in clicks]
    for (_, a, _), (kind, b, _) in zip(clicks, clicks[1:]):
        want = min(max(a['span'] * (1 / 1.5 if kind == 'in' else 1.5), MIN_SPAN), NCOL)
        assert close(b['span'], want, 1e-3) and close(b['u0'] + b['span'] / 2, a['u0'] + a['span'] / 2, 1e-3), (a, kind, b)
    states = [(v, d) for _, v, d in clicks] + [(s['b'], s['disabled']) for s in S.values()] + [(R['views'][0], R['disabled0'])]
    for v, d in states:
        assert d == [close(v['span'], MIN_SPAN, 0.01), close(v['span'], NCOL, 0.05)], (v, d)
    zin, zout = R['looks0']
    assert zin['opacity'] == 1 and zout['opacity'] <= 0.5 and zout['display'] != 'none' and zout['visibility'] == 'visible', R['looks0']
    assert all(close(a, b, 2) for a, b in zip(zout['size'], zin['size'])) and min(zout['size']) > 10, R['looks0']


def q_light_run_uses_the_theme_tokens():
    # Replicata: the light run.
    # Expectata: the chart's colors, paper and ink are the theme block's values (the pixel checks of
    # q_drawn_cells_match_data compare against these).  (A dark run did the same for the dark blocks until 2026-10-12.)
    light, = theme_blocks()
    tokens = valid_run('light')['tokens']
    assert all(tokens[t[2:]] == light[t].lower() for t in TOKENS + ('--paper', '--ink')), tokens


def q_hover_reads_out_cells():
    # Replicata: the light run's hovers: the middle of cells lo, lo + 1 and hi + 1 of every column, in the full view
    # and zoomed in; and the kinds run's, on made-up data with every kind of reason.
    # Expectata: each readout is "n = N, m = M · BOUNDS · REASONS" for the hovered cell, BOUNDS being "m*(N) = lo"
    # when lo = hi and "lo ≤ m*(N) ≤ hi" otherwise; REASONS, joined by " · ": for a green cell (m ≤ lo) one that
    # names order lo, for a red cell (m > hi) one that names order hi + 1, for a gray cell both; and for a cell ringed
    # in gold one more, a note naming order m: a proven one's (a323395_cells, since 2026-10-19) naming a(m − 1) too, a
    # known one's and a not-ruled-out one's (smallest_rings, since 2026-10-30) each the same for every m but for its
    # numbers, and the three notes different.  (Until 2026-10-30 each was pinned as a Claude: "…" string starting
    # "order …", and the gold one as ring_note.)  Every column, n = 2, 4, 8, 12, …, 1024, is read out in both runs.
    for name in ('kinds', 'light'):                                 # light last: its notes are checked after the loop
        R = valid_run(name)
        data = json.loads(kinds_data()[len('const MSTAR = '):-2]) if name == 'kinds' else mstar_data()
        cols, ifsym = data['cols'], data['ifsym']
        assert {n for n, _, _ in R['hovers']} == set(state(name)[1]), name
        rings, notes = smallest_rings(cols), {}
        for n, m, text in R['hovers']:
            lo, hi = cols[n - 1][:2]
            bounds = f'm*({n}) = {lo}' if lo == hi else f'{lo} ≤ m*({n}) ≤ {hi}'
            # (spec change, 2026-11-09: an order named is its number, whole; until then the word "order" before it)
            named = lambda k: rf'(?<![\d.]){k}(?![\d.])'
            note = {1: named(m), 2: named(m), 3: rf'{named(m)}.*{re.escape(f"a({m - 1})")}'}
            # (spec change, Fable 5.2, 2026-11-11, for dreeves's README item [SYC]: a cell red if BGPW's Symmetry
            # Conjecture holds, above its column's ifsym bound h and at or below hi, is a gray cell with a third reason,
            # after its two, that names the order h + 1 and the program that checks the proofs)
            h = {k: v for k, v, _ in ifsym}.get(n, hi)
            reasons = ([named(lo)] * (m <= hi) + [named(hi + 1)] * (m > lo)
                       + [rf'{named(h + 1)}.*{re.escape(IFSYM_FILE)}'] * (h < m <= hi)
                       + [note[r] for r in [rings.get((n, m), 0)] if r])
            got = re.fullmatch(r'n = (\d+), m = (\d+) · (.*?) · (.*)', text)
            assert got and (int(got[1]), int(got[2]), got[3]) == (n, m, bounds), (name, n, m, text)
            parts = got[4].split(' · ')
            assert len(parts) == len(reasons) and all(re.search(r, p, re.I) for p, r in zip(parts, reasons)), (name, n, m, text)
            if (n, m) in rings: notes.setdefault(rings[(n, m)], set()).add(re.sub(r'\d+', '#', parts[-1]))
        assert all(len(v) == 1 for v in notes.values()) and len(set.union(*notes.values())) == len(notes), (name, notes)
    assert set(notes) == {1, 2, 3}, notes                           # the light run reads out all three


def q_hover_swatch_matches_gold_trim():
    # Replicata: the light and kinds runs' hover sweeps, sampling the readout swatch after each cell selection.
    # Expectata: every ringed cell (smallest_rings, since 2026-10-30; the 11 proven ones alone before) has a 2 px gold
    # ring on its swatch, and a proven one also a gold dot at its middle (a radial gradient of --record; Claude's
    # proposal, 2026-10-30), every other swatch has neither, and its fill retains the cell's exists/open/impossible
    # color.  The sweeps include both directions of transition between ringed and ordinary cells, so a ring cannot
    # persist after leaving one.
    # Resultata: each assertion reports the hovered cell and its expected and computed CSS values.
    rgb = lambda h: 'rgb(' + ', '.join(str(int(h[i:i + 2], 16)) for i in (1, 3, 5)) + ')'
    assert a323395_cells(mstar_data()['cols'][:FULL]) == PROVEN_CELLS        # the chart as the harness opens it, up to its cap
    for name in ('light', 'kinds'):
        R = valid_run(name)
        cols = json.loads(kinds_data()[len('const MSTAR = '):-2])['cols'] if name == 'kinds' else mstar_data()['cols']
        rings = smallest_rings(cols[:state(name)[0]])              # the chart as it loads, up to its cap
        swatches = R['swatches']
        assert set(rings) <= {(n, m) for n, m, *_ in swatches}, (name, rings, swatches)
        assert {(False, True), (True, False)} <= {
            (tuple(a[:2]) in rings, tuple(b[:2]) in rings) for a, b in zip(swatches, swatches[1:])}, name
        assert {0, 1, 2} == {(m <= cols[n - 1][0]) + (m <= cols[n - 1][1])
                            for n, m, *_ in swatches if (n, m) not in rings}, name
        shadows = {False: 'none', True: rgb(R['tokens']['record']) + ' 0px 0px 0px 2px'}
        # Since 2026-11-11 ([SYC]): a cell red if the Symmetry Conjecture holds (kind ifsym) has an open cell's fill under
        # a gradient that holds the impossible color and no gold: its swatch as the chart draws the cell.
        ifsym = json.loads(kinds_data()[len('const MSTAR = '):-2])['ifsym'] if name == 'kinds' else mstar_data()['ifsym']
        split = {(n, m) for n, m, *_ in swatches if kind_of(cols, n, m, ifsym) == 'ifsym'}
        assert split, (name, ifsym)                                  # some such cell is hovered: the ringed one at the least
        for n, m, fill, shadow, image in swatches:
            kind = kind_of(cols, n, m, ifsym)
            dot = rings.get((n, m)) == 3
            want = (rgb(R['tokens'][UNDER[kind]]), shadows[(n, m) in rings], dot)
            got = (fill, shadow, image.startswith('radial-gradient(') and rgb(R['tokens']['record']) in image)
            corner = image.startswith('linear-gradient(') and rgb(R['tokens']['impossible']) in image and rgb(R['tokens']['record']) not in image
            assert got == want and (dot or corner or image == 'none') and corner == ((n, m) in split), (name, n, m, 'expected', want, 'computed', (fill, shadow, image))


def q_canvas_draws_only_numbers():
    # Replicata: every string the kinds and light runs drew on the canvas.
    # Expectata: each is a number or the single letter n or m, the axes' names: the chart's words are in its HTML.
    for name in ('kinds', 'light'):
        R = valid_run(name)
        assert R['texts'] and all(re.fullmatch(r'\d+|[nm]', t) for t in R['texts']), (name, R['texts'])


def q_keys_pan_and_zoom():
    # Replicata: from a view zoomed in 3 steps, with the canvas focused: one keydown each of ArrowRight, ArrowLeft, +,
    # =, -, ArrowDown, ctrl and +, cmd and ArrowRight.
    # Expectata: the arrows pan by an eighth of the view (u0 ± span/8) without zooming; + and = zoom in by 1.5 and -
    # out by 1.5, about the middle; those keys' default actions are prevented.  ArrowDown, ctrl + and cmd ArrowRight
    # change nothing and keep their default actions (page scroll, browser zoom, history).
    S = valid_run('light')['steps']
    for name, sign in (('right', 1), ('left', -1)):
        a, b, prevented = S[name]['a'], S[name]['b'], S[name]['x']
        assert prevented and close(b['span'], a['span'], 1e-3) and close(b['u0'] - a['u0'], sign * a['span'] / 8, 1e-3), (name, S[name])
    for name, f in (('plus', 1 / 1.5), ('equals', 1 / 1.5), ('minus', 1.5)):
        a, b, prevented = S[name]['a'], S[name]['b'], S[name]['x']
        assert prevented and close(b['span'], a['span'] * f, 1e-3), (name, S[name])
        assert close(b['u0'] + b['span'] / 2, a['u0'] + a['span'] / 2, 1e-3), (name, S[name])
    for name in ('down', 'ctrlPlus', 'metaRight'):
        a, b, prevented = S[name]['a'], S[name]['b'], S[name]['x']
        assert not prevented and close(b['u0'], a['u0'], 1e-3) and close(b['span'], a['span'], 1e-3), (name, S[name])


def q_wheel_zooms_and_pans_but_lets_the_page_scroll():
    # Replicata: from a view zoomed in 3 steps, at about 30% of the plot's width (Chrome rounds a synthetic wheel's
    # position to a whole px): ctrl + wheel up 100 px; cmd + wheel down 50 px; ctrl + wheel up 3 lines; a wheel 60 px
    # right and 5 down; a wheel 100 px down and 2 right.
    # Expectata: ctrl and cmd zoom by 2^(delta in px / 100) (a line is 16 px) about the pointer: the u under it stays;
    # the mostly-sideways wheel pans by its 60 px; all four have their default prevented.  The mostly-down wheel changes
    # nothing and is not prevented, so the page scrolls.
    S = valid_run('light')['steps']
    for name, f in (('ctrlWheel', 0.5), ('metaWheel', 2 ** 0.5), ('lineWheel', 2 ** -0.48)):
        a, b, (prevented, x) = S[name]['a'], S[name]['b'], S[name]['x']
        assert prevented and close(b['span'], a['span'] * f, 1e-3) and close(x, 0.3, 0.01), (name, S[name])
        assert close(a['u0'] + x * a['span'], b['u0'] + x * b['span'], 1e-3), (name, S[name])
    a, b, (prevented, _) = S['sideWheel']['a'], S['sideWheel']['b'], S['sideWheel']['x']
    R = valid_run('light')
    W = (R['plot'][1] - R['plot'][0]) / R['dpr']
    assert prevented and close(b['span'], a['span'], 1e-3) and close(b['u0'] - a['u0'], 60 * a['span'] / W, 1e-3), S['sideWheel']
    a, b, (prevented, _) = S['upWheel']['a'], S['upWheel']['b'], S['upWheel']['x']
    assert not prevented and close(b['u0'], a['u0'], 1e-6) and close(b['span'], a['span'], 1e-6), S['upWheel']


def q_drag_and_touch_pan_and_pinch():
    # Replicata: from a view zoomed in 3 steps: a mouse drag 100 px left; a one-finger touch swipe 20% of the plot left;
    # a two-finger pinch from 40% and 60% of the plot's width out to 30% and 70%; then the canvas's touch-action.
    # Expectata: the drag and the swipe pan by their distance (content follows the pointer); the pinch zooms in about
    # the fingers' midpoint by (d0 + 1) / (d + 1), d0 and d the fingers' spread in px before and after, and the u under
    # the midpoint stays; touch-action is pan-y, so vertical swipes still scroll the page.
    R = valid_run('light')
    S, W = R['steps'], (R['plot'][1] - R['plot'][0]) / R['dpr']
    for name in ('drag', 'swipe'):
        a, b, dx = S[name]['a'], S[name]['b'], S[name]['x']
        assert close(b['span'], a['span'], 1e-3) and close(b['u0'] - a['u0'], dx * a['span'] / W, 1e-3), (name, S[name])
    a, b, (d0, d, xm) = S['pinch']['a'], S['pinch']['b'], S['pinch']['x']
    assert close(b['span'], a['span'] * (d0 + 1) / (d + 1), 1e-3), S['pinch']
    assert close(a['u0'] + xm * a['span'] / W, b['u0'] + xm * b['span'] / W, 1e-3), S['pinch']
    assert R['touchAction'] == 'pan-y', R['touchAction']


def q_safari_gestures_zoom_unless_touching():
    # Replicata: from a view zoomed in 3 steps: Safari's gesturestart, gesturechange (scale 2) and gestureend at 25% of
    # the plot's width; then the same while a touch pointer is down.
    # Expectata: the first zooms in by 2 about the pointer, with gesturestart's and gesturechange's defaults prevented;
    # the second changes nothing (the pointer events own a touch pinch), defaults still prevented.
    R = valid_run('light')
    S, W = R['steps'], (R['plot'][1] - R['plot'][0]) / R['dpr']
    a, b, (p1, p2, _, x) = S['gesture']['a'], S['gesture']['b'], S['gesture']['x']
    assert p1 and p2 and close(b['span'], a['span'] / 2, 1e-3), S['gesture']
    assert close(a['u0'] + x * a['span'] / W, b['u0'] + x * b['span'] / W, 1e-3), S['gesture']
    a, b, (p1, p2) = S['gestureWhileTouching']['a'], S['gestureWhileTouching']['b'], S['gestureWhileTouching']['x']
    assert p1 and p2 and close(b['span'], a['span'], 1e-6) and close(b['u0'], a['u0'], 1e-6), S['gestureWhileTouching']


def q_view_stays_within_limits():
    # Replicata: from a view zoomed in 3 steps: 40 presses of +; of -; 300 of ArrowRight; ctrl + wheel down 5000 px;
    # and (separately) ArrowRight, +, then the reset button.
    # Expectata: zooming in stops at 12 columns and out at all NCOL; panning stops with the last column, n = CAP, at the
    # right edge; the reset button (the cap pressed) shows all NCOL columns (142 up to 2048 since 2026-11-12; 257 up to
    # 1024 before).
    S = valid_run('light')['steps']
    assert close(S['zoomInFar']['b']['span'], MIN_SPAN, 0.01), S['zoomInFar']
    for name in ('zoomOutFar', 'wheelOutFar', 'reset'):
        assert close(S[name]['b']['span'], NCOL, 0.05) and close(S[name]['b']['u0'], 0, 0.01), (name, S[name])
    b = S['panFar']['b']
    assert close(b['u0'] + b['span'], NCOL, 0.01), S['panFar']


def q_tap_and_outline():
    # Replicata: in a zoomed view, a touch tap at 37% of the plot's width in row 1 (after hovering elsewhere), then a
    # pointerup with no pointerdown, then a mouse click (down and up, no move) at 63% in row 1 (after hovering
    # elsewhere); and, in a view zoomed in 5 steps, a hover over the middle of the middle column's cell in row 2.
    # Expectata: the tap and the click each read out the cell under them (an even n) and the stray pointerup changes
    # nothing; the hovered cell keeps its color in the middle and is outlined in ink just outside its left and right
    # edges.
    R = valid_run('light')
    n, m = R['tap']['want']
    assert R['tap']['text'].startswith(f'n = {n}, m = {m} · ') and R['tap']['after'] == R['tap']['text'], R['tap']
    n, m = R['click']['want']
    assert R['click']['text'].startswith(f'n = {n}, m = {m} · '), R['click']
    o = R['outline']
    assert R['outlineText'].startswith(f'n = {o["n"]}, m = {o["m"]} · '), R['outlineText']
    assert o['middle'] == o['want'] and o['left'] == o['ink'] and o['right'] == o['ink'], o


def q_axes_tag_the_cell_read_out():
    # Replicata: the light and phone runs: the canvas at load; then hovers, each with the draw it makes: in the full
    # view, its four corners (n = 2 and 4096, in rows 1 and T; 2048 until 2026-11-29, 1024 until 2026-11-12) and a cell in the middle; in a
    # view zoomed in 7 steps and panned right ten eighths of it (3 steps and three eighths until 2026-11-29, 5 steps and
    # an eighth until 2026-11-12, as the harness says), its corners at the plot's very ends, where its columns are cut (the first's middle
    # out of view, the last's in), a cell in the middle and its first whole column in row 2; then that view panned
    # right by a whole view with the keys alone, the last press's draw.
    # Expectata (dreeves's README, 2026-11-02: "[HOV] When hovering/clicking on cells in the charts it'd be nice to
    # highlight the values of m and n (resp., delta and k) on the axes of the chart"): the cell read out, as the readout
    # names it, is tagged on both axes in paper on ink (the outline's ink), each draw writing nothing else in paper: its
    # m over its row's m label, left of the plot, the ink exactly that row's colored part and reaching past the label's
    # right end, so no other row's label is touched; and its n on the n axis, below the plot, written on its column's
    # middle to within a device px and the ink centered there to within 2, while that middle is in view, as an n
    # label's must be, and no ink there otherwise.  At load, before any cell is read out, nothing is tagged: no ink in
    # either place, nothing written in paper.  Panning with the keys alone keeps the cell read out, as the readout keeps
    # it: its m stays tagged and its n goes with its column's middle.  (quals_pow2_page's q_axes_tag_the_cell_read_out
    # is the same for the chart of powers of 2.)
    # Resultata before: no tags.
    for name in ('light', 'phone'):
        R = valid_run(name)
        (PL, PR), dpr = R['plot'], R['dpr']
        assert R['tags0'] == {'paper': [], 'left': None, 'below': None}, (name, R['tags0'])
        seen = []
        for s in R['tagHovers'] + [R['tagAway']]:
            n, m = map(int, re.match(r'n = (\d+), m = (\d+) · ', s['text']).groups())
            v, j = s['v'], COLUMNS.index(n) + 1
            mid = PL + (j - 0.5 - v['u0']) * (PR - PL) / v['span']
            shown = v['u0'] - 1e-6 <= j - 0.5 <= v['u0'] + v['span'] + 1e-6
            seen.append((n, m, shown))
            # Row m's colored part, in device px: [top, bottom), among the rows of the view of this hover (since
            # 2026-11-10 the rows follow the view); the m tag is as tall as the colored part of a row 14 CSS px tall,
            # which the rows of a view of 16 rows are, or as its own row's where that is shorter, on its row's middle (as
            # tall as its row, whatever the view, until 2026-11-10; then 14 CSS px tall whatever its row, until
            # 2026-11-12, when the chart came to open with 19 rows, under 14 CSS px each, and the tag of row 1 reached
            # past the plot's bottom).
            # (Spec change, Opus 5.5, 2026-11-29; dreeves, of a cap at 4096: "worth it": a view of the 4096 data may hold 26 rows, 8.6 CSS px each, under a label's room, which the tag is as
            # tall as since 2026-11-23 at least; Figure 2's rows were that short then, Figure 1's not.  Where its box would reach past the plot's top or bottom it is moved in; a box of no
            # whole number of device px ends in a part of one, which is not ink alone.  Until then: as tall as its row's colored part or a 14 px row's, whichever is shorter, on its middle.)
            top, bottom = s['rows'][len(s['rows']) - m]
            plot_top, plot_bottom = s['rows'][0][0], s['rows'][-1][1] + 1
            tall = min(math.floor(14 * dpr + 0.5), max(bottom + 1 - top, R['room'])) - 1
            center = min(max((top + bottom) / 2, plot_top + tall / 2), plot_bottom - tall / 2)
            first = math.floor(center - tall / 2 + 0.5)
            ms = [(t, x, y) for t, x, y in s['paper'] if y < R['axisTop']]
            ns = [(t, x, y) for t, x, y in s['paper'] if y >= R['axisTop']]
            assert [t for t, _, _ in ms] == [str(m)] and ms[0][1] < PL and close(ms[0][2], center, 1), (name, n, m, s['paper'])
            assert [t for t, _, _ in ns] == [str(n)] * shown and all(close(x, mid, 1) for _, x, _ in ns), (name, n, m, mid, s['paper'])
            assert s['left'] is not None, (name, n, m, s['left'])
            X0, X1, Y0, Y1 = s['left']
            assert (Y0, Y1 + 1) == (first, math.floor(first + tall)) and PL - 7 * dpr <= X1, (name, n, m, s['left'], top, bottom)
            assert (s['below'] is not None) == shown, (name, n, m, shown, s['below'])
            assert not shown or close((s['below'][0] + s['below'][1] + 1) / 2, mid, 2), (name, n, m, mid, s['below'])
        T = len(R['rows'])                                         # the full view's rows
        corners = {(2, 1, True), (2, T, True), (COLUMNS[-1], T, True), (COLUMNS[-1], 1, True)}
        assert corners <= set(seen) and {True, False} <= {shown for *_, shown in seen[5:-1]}, (name, seen)
        away = R['tagAway']
        assert away['text'] == away['before'] and not seen[-1][2], (name, away['text'], away['before'], seen[-1])


def q_strips_read_out_their_column_or_row():
    # Replicata: the light and phone runs, in the full view: a hover on the cell in row 3 at the plot's middle, of column
    # N; then straight down onto the strip of the n labels, 10 CSS px below the plot; then onto the strip of the m labels
    # at row 12, 10 CSS px left of the plot.  After each, the readout, the tags (what each draw wrote in paper, and the
    # boxes of ink left of the plot and below it: q_axes_tag_the_cell_read_out's), and the pixels where the outlines go:
    # above the cell in its column, left of column N in rows 1 and T, and above row 12 a quarter and three quarters across.
    # Expectata (dreeves, 2026-11-19, of clicks on the strips: "you have to first get the mouse in the interior and then
    # carefully move it left or down before clicking for row or column"): a hover reads out what a click at the same
    # place opens.  On the strip of the n labels, column N: the readout "n = N · BOUNDS", BOUNDS as a cell's readout
    # writes them (its box's heading in the readout's words, no new words); N alone tagged, below the plot; the column
    # outlined from row 1 to row T, and the cell no longer.  On the strip of the m labels, row 12: the readout "m = 12";
    # 12 alone tagged, left of the plot; the row outlined across the plot, and the column no longer.  Control: on the
    # cell, its outline is drawn, and the column's and the row's are not.
    # Resultata before: a hover on a strip changed nothing: the cell first hovered stayed read out, outlined and tagged,
    # so the mouse had to cross the plot to show which column or row a click on a strip would open.
    for name in ('light', 'phone'):
        R = valid_run(name)
        S, ink, cols = R['strips'], R['tokens']['ink'], mstar_data()['cols']
        n, (lo, hi) = S['n'], cols[S['n'] - 1][:2]
        assert S['cell']['cell'] == [ink, ink] and ink not in S['cell']['column'] + S['cell']['row'], (name, S['cell'])
        C, W = S['column'], S['row']
        assert C['text'] == f'n = {n} · ' + (f'm*({n}) = {lo}' if lo == hi else f'{lo} ≤ m*({n}) ≤ {hi}'), (name, C['text'])
        assert [p[0] for p in C['paper']] == [str(n)] and C['left'] is None and C['below'] is not None, (name, C)
        assert C['column'] == [ink, ink] and C['cell'][0] != ink and ink not in C['row'], (name, C)
        assert W['text'] == 'm = 12', (name, W['text'])
        assert [p[0] for p in W['paper']] == ['12'] and W['left'] is not None and W['below'] is None, (name, W)
        assert W['row'] == [ink, ink] and W['cell'][0] != ink and ink not in W['column'], (name, W)


def q_phone_has_no_sideways_scroll():
    # Replicata: index.html with the real mstar.js, 390 px wide at 3 device px per CSS px.
    # Expectata: no errors; the page is no wider than the window; the canvas is as wide as main's content.
    R = valid_run('phone')
    assert R['scrollW'] <= R['innerW'] and close(R['canvasCss'][0], R['mainContentW'], 1), R


def q_missing_data_says_so():
    # Replicata: index.html with no mstar.js beside it.
    # Expectata: the canvas stays 0 px tall and the readout gives the error, which names MSTAR; the failed script load
    # and the uncaught error are recorded (the chart fails loudly).
    R = run('missing')
    assert 'harnessError' not in R, R['harnessError']
    assert R['canvasDev'][1] == 0 and R['canvasCss'][1] == 0, R
    assert re.search(r'\bMSTAR\b', R['readout0']), R['readout0']
    assert any('script failed to load' in e for e in R['errors']) and any('MSTAR' in e for e in R['errors']), R['errors']


def q_malformed_data_fails_loudly():
    # Replicata: made-up data whose column 100 has lo = 5 > hi = 3.
    # Expectata: the canvas stays 0 px tall; the readout gives the error, which quotes column 100 as JSON; the error is
    # uncaught (recorded).
    R = run('violates lo above hi')
    assert 'harnessError' not in R, R['harnessError']
    assert R['canvasDev'][1] == 0 and R['canvasCss'][1] == 0, R
    assert '[100,[5,3,' in R['readout0'], R['readout0']
    assert any('[100,[5,3,' in e for e in R['errors']), R['errors']


def q_contract_violations_fail_loudly():
    # Replicata: made-up data broken in one way each (VIOLATIONS): lo above hi; an unknown kind of reason; a reason with too few
    # arguments; a join of lengths that do not add up to n; a join or product claiming more than its parts give; "two"
    # with the wrong hi; "norm" for a prime dividing n, and for a composite; "table2" at an n not in Table 2; "page" for
    # a provenance the page does not use; an example with an empty label; "none" or "odd" at an even n; an example at
    # an odd n; a column of five entries; hi at mtop; mtop above max hi + 1; nmax not the number of columns; mtopAt not past nmax, or falling
    # (since 2026-11-04); a row of past not past nmax.
    # Expectata: in each case the canvas stays 0 px tall and the readout ends with the error, which quotes the
    # offending column as JSON (or mtop, or nmax and mtop), and the error is uncaught.  It is the page's one error,
    # but with nmax broken (999): since 2026-11-10 the chart of powers of 2 reads the m*(n) chart's last n from
    # mstar.js (page/pow2-section.js; a number of its own until then), and 2^10, whose upper bound it takes from the
    # m*(n) chart's column 1024, is past 999, so that chart fails loudly too, quoting its column 10.  Spec change (Opus
    # 5.5, 2026-11-18): the appendix, which takes every length's facts from both charts' scripts (page/appendix.js),
    # fails loudly too, last, naming the charts that gave theirs: the powers-of-2 chart's alone, or none with nmax broken.
    for v, (_, quoted) in VIOLATIONS.items():
        R = run(f'violates {v}')
        assert 'harnessError' not in R and R['canvasDev'][1] == 0 and R['canvasCss'][1] == 0, (v, R)
        assert R['readout0'].endswith(f'Error: {quoted}'), (v, R['readout0'])
        assert R['errors'][0] == f'error: Uncaught Error: {quoted}' and len(R['errors']) == 2 + (v == 'nmax'), (v, R['errors'])
        assert all(e.startswith('error: Uncaught Error: [10,') for e in R['errors'][1:-1]), (v, R['errors'])
        facts = '[]' if v == 'nmax' else "['pow2']"
        assert R['errors'][-1] == f"error: Uncaught Error: ['the facts of each chart',{facts}]", (v, R['errors'])


def q_made_up_data_draws():
    # Replicata: made-up data that uses every kind of reason (kinds_data).
    # Expectata: no errors; the chart is drawn with one row per m up to mtop.
    R = valid_run('kinds')
    assert R['canvasDev'][1] > 0 and len(R['rows']) == 8, R['rows']


# ---------------------------------------------------------------------------------------------------------------------
# The panels of the charts' columns (dreeves's spec [REO]; Claude's design of 2026-11-03, which dreeves approved: "those
# sound like good precedents. go ahead"): a click or a tap on a cell, or the page's fragment nN, opens under the m*(n)
# chart the full explanation of column n, one template per kind of reason filled with the column's numbers.

def entry_lengths():
    """{n: the id the page's script gives the remarks entry that lists n}: each p.entry's lengths, its TeX's n = ...,
    with 2^{k} as its digits, and the id entry-N, N the first of them."""
    out = {}
    for ns in re.findall(r'<p class="entry">\\\(n = (.*?)\\\): ', page()):
        lengths = [2 ** int(x[3:-1]) if x.startswith('2^{') else int(x) for x in ns.split(', ')]
        out.update({n: f'entry-{lengths[0]}' for n in lengths})
    return out


def code_ids():
    """The ids N:M of the page's codes."""
    return set(re.findall(r'<code id="(\d+:\d+)">', page()))


def entry_order():
    """The ids of the entries in the list's order, as the page's script names them (entry-N, N the first length each
    lists): the order of the list, to which every entry a panel showed goes back ([REO] step 2, 2026-11-03).  Since
    2026-11-18 the appendix's list, an entry for every length (panel_entries' id of each length, at its first length);
    until then the remarks' list, the entries by hand alone, in the page's order."""
    hand = entry_lengths()
    return list(dict.fromkeys(hand.get(n) or f'entry-{CLASS_FIRST.get(class_of(n), n)}'
                              for n in appendix_lengths(len(pow2_data()['cols']))))


def panel_whys(cols, n, rows=(), ifsym=()):
    """The kinds of the parts of the box of the m*(n) chart's column n, in order, or of its cell (n, m) for rows [m]
    (box_parts).  Spec change (2026-11-04, dreeves's README items [CEL] and [ROC]): until then the kinds of text of the
    column's one panel, for the cells clicked in rows: a status per cell, its lower bound's reason and, for an example,
    its code where the page shows it, and its upper bound's (and its entry's link, the template "entry", until [REO]
    step 2, 2026-11-03, which moved the entry itself into the panel: panel_entries)."""
    return box_parts(cols, n, *rows, ifsym=ifsym)


def panel_entries(n):
    """The ids of the entries that the panel of the length n shows ([REO] step 2, 2026-11-03): until 2026-11-18 the
    remarks' entry that lists n, if any; since, its entry in the appendix, which every length has (Opus 5.5; dreeves:
    "we want an entry for every n"), entry-N, N the first length of that entry: its class's first (CLASS_FIRST), its
    entry by hand's first (entry_lengths), or n itself."""
    return [entry_lengths().get(n) or f'entry-{CLASS_FIRST.get(class_of(n), n)}']


CLASS_FIRST = {'odd': 1, 'singly-even': 2}                  # each class's first length, whose id its entry takes
# What a class's entry says (Opus 5.5, 2026-11-18), its facts stated for any n: that n is odd; alternating signs, and
# the 2-adic bound with n = 2^1 u
CLASS_SAID = {'odd': ['\\(m^*(n) \\le 0\\): \\(n \\equiv 1 \\pmod 2\\)'],
              'singly-even': ['\\(m^*(n) \\ge 1\\): \\(f_i = (-1)^i\\)', '\\(m^*(n) \\le 1\\):', '\\(n = 2^{1} \\cdot u\\)',
                              '\\(m \\le 2^{1} - 1 = 1\\)']}


TABLE2 = 'https://arxiv.org/html/1912.03491v1#S3.T2'       # BGPW's Table 2, which a box that cites it links (its words until 2026-11-09)
PROP44 = 'https://arxiv.org/html/1912.03491v1#S4.Thmthm4'  # BGPW's Proposition 4.4, which a box that cites it links (2026-11-11)


def panel_says(data, n, P):
    """What the box of the m*(n) chart's column n, P, must say, by data (mstar.js's, or made up: since 2026-11-18 its
    cols and its codes), by its reasons' arguments, as [(what, found)].  Spec change
    (2026-11-04, [CEL]; dreeves: "so many pointless words in the implementation so far"): its bounds as math, each
    leading its part; an example's label; a join's or a product's construction, a button claiming n:lo; each proof's
    numbers; and the copy of the page's code of the length n and the order lo, unless its entry, which the box shows,
    holds that code (since 2026-11-18 an example's code, mstar.js's, page code or not: witness_codes).  Until then: the
    sentences of 2026-11-03, each part linked to its own column's panel and an example to its code."""
    cols = data['cols']
    lo, hi, lw, hw = cols[n - 1]
    t = P['text']
    heading = ('heading', P['heading'] == (f'\\(n = {n}\\): \\(m^*({n}) = {lo}\\)' if lo == hi else
                                            f'\\(n = {n}\\): \\({lo} \\le m^*({n}) \\le {hi}\\)'))
    # Spec change (Opus 5.5, 2026-11-18): a length of a class shows its class's entry, its facts stated for any n
    # (CLASS_SAID), and no copy of a code
    if class_of(n):
        return [heading, ('class', all(x in t for x in CLASS_SAID[class_of(n)])), ('copy', P['copies'] == []),
                ('entry', P['entries'] == panel_entries(n))]
    says = [heading, ('lower', f'\\(m^*({n}) \\ge {lo}\\):' in t), ('upper', f'\\(m^*({n}) \\le {hi}\\):' in t)]
    a, b = (lw + [0, 0])[1:3]
    arg, harg = (lw + [None])[1], (hw + [None])[1]                  # the first argument of each reason, if any
    built = lambda tex: [f'{n}:{lo}', 'button', f'\\({tex}\\)'] in P['constructions']
    says += {'example': [('label', f'\\(m^*({n}) \\ge {lo}\\): {arg}' in t)],
             'join': [('construction', built(' \\vee '.join(f'p_{{{k}}}' for k in lw[1:])))],   # (any parts since 2026-11-18)
             'product': [('construction', built(f'p_{{{a}}} \\mathbin{{\\#}} p_{{{b}}}'))],
             'table2': [('cited', TABLE2 in P['links'])], 'page': [('who', legend_labels(page()).get(arg, '\0') in t)]}[lw[0]]
    t2 = (n & -n).bit_length() - 1
    says += {'two': [('t', f'\\(n = 2^{{{t2}}} \\cdot {n >> t2}\\)' in t and f'\\(m \\le 2^{{{t2}}} - 1 = {hi}\\)' in t)],
             'norm': [('p', f'\\(p = {harg} \\nmid n\\)' in t)],
             # (spec change, 2026-11-16 evening, dreeves's "ok go": until then the modulus and mstar.py, linked, in
             # every residue box; since, at the single modulus 3, Stan Wagon's numbers or the line of Mathematica)
             'residue': [('M', residue_said(n, str(n), hi, str(harg), 'mstar.py', t))],
             # (2026-11-11) n factored, the power of 2 that order hi + 1 would need of |f(-1)|, and the citation's link
             'prop44': [('t', f'\\(n = 2^{{{t2}}} \\cdot {n >> t2}\\)' in t and f'2^{{{hi + 1}}} = ' in t),
                        ('cited', PROP44 in P['links'])],
             # (2026-11-12, when the chart came to open up to 2048, with 1248 and 1456 in it) the program, linked
             'proof': [('file', f'{REPO}{harg}' in P['links'])],
             'table2': [('cited', TABLE2 in P['links'])], 'page': [('who', legend_labels(page()).get(harg, '\0') in t)]}[hw[0]]
    copies = [x for x in witness_codes(data, n) if x[0] not in entry_codes(n)]
    says += [('copy', P['copies'] == copies)]
    says += [('entry', P['entries'] == panel_entries(n))]      # the entry itself since [REO] step 2 (2026-11-03), not its link
    return says


REPO = 'https://github.com/dreeves/equipow/blob/main/'       # where the page links the repository's files


def panel_link_lands(href):
    """Whether a panel's link lands: on a column's panel (#nN, N a column of the m*(n) chart), a code (#N:M), an entry
    of the remarks (#entry-N, as the page's script names them), a file of this repository, which must be one here
    (since 2026-11-10: the residue panels' links to mstar.py and pow2.py still went to the repository's root, where
    [REF] had left neither that day), or another page outside (https); since 2026-11-18, when every box of 480 shows its
    entry with the bound that holds if the Symmetry Conjecture does, also an element of the page by an id it has in
    index.html (that part's #symmetry-title)."""
    return (href.startswith(REPO) and os.path.isfile(os.path.join(HERE, href[len(REPO):]))
            or href.startswith('https://') and not href.startswith(REPO)
            or href[1:] in code_ids() or href[1:] in set(entry_lengths().values())
            or href.startswith('#') and page().count(f' id="{href[1:]}"') == 1
            or re.fullmatch(r'#entry-(\d+)', href) is not None and int(href[7:]) in appendix_lengths(len(pow2_data()['cols']))   # (2026-11-18: an example's label)
            or re.fullmatch(r'#n(\d+)', href) is not None and int(href[2:]) in COLUMNS)


def q_panel_works_out_the_mod_3_argument_at_1024():
    # Replicata: the page loaded with the fragment #n1024, which opens the panel of n = 1024; its upper bound is the
    # residue condition mod 3 (mstar.js: [11, 11, ["example", "equipow p1024"], ["residue", 3]]).
    # Expectata (Fable 5.2, 2026-11-16; dreeves, of Stan Wagon's "standard mod-3 argument" that m*(1024) <= 11, with no
    # root of unity: "ok, go ahead with breaking ties in favor of the mod-3 argument", then "i approve the
    # corresponding qual changes"): the box gives the class sizes mod 3, 342, 341 and 341, and at m = 12 the condition
    # in closed form, D_0 + D_1 + D_2 = 0, D_0 = D_1 = D_2 mod 3^6 and 3^5 dividing each D_r, with 3^6 = 729 and
    # 3^5 = 243 in digits.  That is Stan's argument: two sums differ by 342 + 341 = 683 at most, which is below 729, so
    # the congruence makes them equal, and the classes of 342 and of 341 have sums of different parities.
    # Spec change (that day): until then q_panel_works_out_the_norm_bound_at_1024, for the norm bound for p = 3, which
    # held column 1024 (the coordinator's spec, 2026-11-03: "For n = 1024, p = 3, a qual must find classes 342, 341,
    # 341, 3^12 = 531,441 and the cap 524,289 (= 2^19 + 1), so order 12 fails by 1.4%"; since 2026-11-04, [CEL], the
    # one inequality p^m <= the cap with those numbers).  The norm bound gives the same 11 there, and the residue
    # condition mod 3, which implies it, now comes first.
    # Spec change (2026-11-16 evening; dreeves, of Stan's note: "could you use stan's exact words (mutatis mutandis)
    # from the screenshot above?", then "ok go"): the box gives Stan's own argument, his numbers: m*(1024) >= 12 supposed
    # (his "= 12", a bound above, as his argument needs only order 12), 12 = s(p - 1) + r = 2s + r with s = 6 and
    # r = 0, the modulus 3^6 = 729, the range [0, 1023], the sizes (342, 341, 341), d_3,0 even as a + b = 342, and
    # d_3,2 odd.  Until then the closed form's numbers: the sizes and, at m = 12, D_0 + D_1 + D_2 = 0,
    # D_0 = D_1 = D_2 mod 3^6 and 3^5 dividing each D_r, with 3^6 = 729 and 3^5 = 243.
    # Spec change (Opus 5.5, 2026-11-18; Stan Wagon's shorter proof, relayed by dreeves: "For web page.  Here it is,
    # shorter now. No need for any Mathematica code. The 342 bound means that the congruence is equality, contradicting
    # parity."): the box gives his new numbers: m*(1024) >= 12 supposed, with d_3,i; p = 3, Proposition 4.3, s = 6 and
    # r = 0, so d_3,0 = d_3,1 mod 729; the classes 0 and 1 in [0, 1023] of sizes 342 and 341, so d_3,0 and d_3,1 of
    # opposite parity; |d_3,i| <= 342, so the mod-729 congruence is an equality.  Until then his note of 2026-11-16 (the
    # numbers above: 12 = s(p - 1) + r = 2s + r, 3^6 = 729, (342, 341, 341), d_3,0 even as a + b = 342, d_3,2 odd), and
    # after it, from later that evening (dreeves: "why no mathematica code for the 1024:12 cell?", then "yeah, add the
    # mathematica line"), his check of all pairs as a line of Mathematica, Reduce[{x - y == 3^6 k, k != 0,
    # -342 <= x <= 342, -341 <= y <= 341}, {x, y, k}, Integers], which his bound |d_3,i| <= 342 now does in words.
    # Resultata before: no panel.
    R = valid_run('fragment')
    t = R['fragment']['text']
    assert mstar_data()['cols'][1024 - 1][3] == ['residue', 3] and stan_holds(1024, 12)
    assert 342 + 341 == 683 < 3 ** 6 == 729 and (342 - 341) % 2 == 1 and mod3_sums(1024, 12) == [] != mod3_sums(1024, 11)
    said = ['\\(m^*(1024) \\ge 12\\) with \\(d_{3,i}\\)',
            '\\(p = 3\\) and apply Proposition 4.3 of [BGPW] to get \\(s = 6\\) and \\(r = 0\\), which gives '
            '\\(d_{3,0} \\equiv d_{3,1}\\) (mod 729)',
            '0 and 1 mod-3 residue class sizes in [0, 1023] are 342 and 341, respectively, so \\(d_{3,0}\\) and '
            '\\(d_{3,1}\\) have opposite parity. But \\(|d_{3,i}| \\le\\) 342, so the mod-729 congruence']
    for x in said:
        assert among(x, t), (x, t)
    assert stan_said(1024, 12, '1024') == said


def q_every_column_s_panel_shows_exactly_its_reasons():
    # Replicata: the panel of each of the m*(n) chart's NCOL columns as the page loads (142 since 2026-11-12, 257 before),
    # opened in turn by its fragment, nN (the panels run).
    # Expectata: each opens (not hidden, the fragment its own, the focus on its heading) with no error and no KaTeX
    # error mark; it shows exactly the data's reasons, the kinds of its texts in order (panel_whys: the lower bound's,
    # the code's where the page shows the example's code, the upper bound's; the entry's link where the remarks list n
    # until [REO] step 2, 2026-11-03, which moved the entry itself in); its heading gives n and the bounds; and each
    # text names its reason's arguments (panel_says), with links to the parts' own panels and the example's code, and
    # the entry that lists n shown (q_panel_shows_its_entry_and_gives_it_back).
    # Resultata before: no panel.
    R = valid_run('panels')
    cols, ifsym = mstar_data()['cols'], mstar_data()['ifsym']
    assert [P['n'] for P in R['panels']] == COLUMNS, [P['n'] for P in R['panels']][:5]
    for P in R['panels']:
        n = P['n']
        assert not P['hidden'] and P['hash'] == f'#n{n}' and P['focus'] and P['errors'] == 0, (n, P)
        assert P['whys'] == panel_whys(cols, n, ifsym=ifsym), (n, P['whys'], panel_whys(cols, n, ifsym=ifsym))   # (ifsym since 2026-11-18: box_parts)
        bad = [what for what, found in panel_says(mstar_data(), n, P) if not found]
        assert bad == [], (n, bad, P['text'])
        assert all(panel_link_lands(href) for href in P['links']), (n, P['links'])
    kinds = {w for P in R['panels'] for w in P['whys']}
    # Spec change (2026-11-04, [CEL] and [ROC]): the parts' kinds are a witness's and a proof's; until then the
    # explanations lo-example, lo-code, lo-join, lo-product, hi-two, hi-norm, hi-residue, hi-table2 and hi-page (and
    # 'entry', the link to the remarks' entry, until [REO] step 2, 2026-11-03, when the entry moved into the panel)
    # (2026-11-12: with the chart open up to 2048, its columns 1200, 1392, … by Proposition 4.4 and 1248 and 1456 by a
    # program, proof-prop44 and proof-file too)
    # (2026-11-16: proof-norm no longer among them: the residue condition mod 3 comes before the norm bound since that
    # day and holds every column that the norm bound for 3 held, the only norm bound the page's columns used)
    # (2026-11-16 evening, dreeves's "ok go": proof-stan, Stan Wagon's words, at the residue condition mod 3 where his
    # argument holds, box_parts; and after it proof-pairs, his check of all pairs in Mathematica, until 2026-11-18, when
    # his shorter proof took its place: "No need for any Mathematica code")
    # (2026-11-18, Opus 5.5: the appendix's entries in the boxes: at 2 the singly even n's, witness-alternating; at 480
    # the bound if the Symmetry Conjecture holds, proof-ifsym, which only an ifsym cell's box had until then)
    assert {'witness-example', 'witness-construction', 'witness-alternating', 'proof-two', 'proof-residue', 'proof-stan', 'proof-table2',
            'proof-page', 'proof-prop44', 'proof-file', 'proof-ifsym'} <= kinds <= {*WITNESSES.values(), 'witness-code', 'witness-alternating',
                                                                                   *PROOF_PARTS.values(), 'proof-stan', 'proof-ifsym'} - {'proof-odd'}, kinds


def q_norm_panels_work_out_their_numbers():
    # Replicata: the kinds panels run, on made-up data (kinds_data): the panel of each column whose upper bound is the
    # norm bound for a prime p (4 for p = 3, 32 for 5, 48 for 7).
    # Expectata: at m = hi + 1 the box gives p^m and the cap, each the exact integer its formula says (Python's own
    # arithmetic), and so are the class sizes and their squares' sum.
    # Spec change (2026-11-16; q_panel_works_out_the_mod_3_argument_at_1024 has dreeves's words): until then
    # q_norm_panels_hold_their_claims, on the page's own data (the panels run), which also held p^m to be more than
    # the cap at each such column.  No column of the page's data has the norm bound as its reason any more, since the
    # residue condition mod 3 comes before it, so the box's arithmetic is held on the made-up columns, whose bounds
    # are made up (at 48 the cap is the larger).  Spec change (2026-11-04, [CEL]): until then also both sides of
    # p^(2m) (p - 1)^(p - 1) <= (p sum s_r^2)^(p - 1), the left more than the right.
    R = valid_run('kinds panels')
    cols = json.loads(kinds_data()[len('const MSTAR = '):-2])['cols']
    found = []
    for P in R['panels']:
        n = P['n']
        lo, hi, lw, hw = cols[n - 1]
        if hw[0] != 'norm': continue
        p, m = hw[1], hi + 1
        sizes = [len(range(r, n, p)) for r in range(p)]
        S = sum(x * x for x in sizes)
        cap = (p * S) ** ((p - 1) // 2) // (p - 1) ** ((p - 1) // 2)
        for said in ('= ' + ', '.join(f'{x:,}' for x in sizes) + ' and', f'\\(\\sum s_r^2 =\\) {S:,};',
                     f'\\(p^m = {p}^{{{m}}} =\\) {p ** m:,} \\(>\\) {cap:,}'):
            assert among(said, P['text']), (n, said, P['text'])
        found.append((n, p))
    assert found == [(4, 3), (32, 5), (48, 7)], found


def mod3_form(n, a, b):
    """The residue sums mod 3, (D_0, D_1, D_2), of a length n that meet a closed form with the exponents a and b:
    D_0 + D_1 + D_2 = 0, |D_r| at most its class's size s_r and of its parity, D_0 = D_1 = D_2 mod 3^a, and 3^b
    dividing each D_r; sorted."""
    q, Q = 3 ** b, 3 ** a
    s = [(n - r + 2) // 3 for r in range(3)]          # len(range(r, n, 3)), which overflows past 2^63
    d0s, d1s = ([d for d in range(-(x // q) * q, x + 1, q) if (d - x) % 2 == 0] for x in s[:2])
    assert len(d0s) * len(d1s) <= 10 ** 7, (n, a, b)  # the multiples of 3^b within the sizes: few near a bound
    return [(d0, d1, -d0 - d1) for d0 in d0s for d1 in d1s
            if abs(d0 + d1) <= s[2] and (d0 + d1 - s[2]) % 2 == 0 and (d0 - d1) % Q == 0 and (d0 + 2 * d1) % Q == 0]


def mod3_sums(n, m):
    """The residue sums mod 3 that the closed form of the page's residue boxes allows a sequence of length n and order
    m (2026-11-16): mod3_form with a = floor(m/2) and b = floor((m - 1)/2).  For an even m the divisibility follows
    from the congruence and the zero sum, for an odd m the congruence from the divisibility; both are in the box at
    every m, so that it has one form.  quals_mstar's q_residue_condition_mod_3_has_its_closed_form holds this to the
    lattice L(3, m) that the generators enumerate."""
    return mod3_form(n, m // 2, (m - 1) // 2)


def mod3_said(n, m):
    """What a residue box of the single modulus 3 says past the words it shares with every residue box, for the length
    n at the order m, as [its class sizes, its closed form]: after s_r's definition the three sizes, in digits, and
    after m, in parentheses, the closed form with its powers of 3 as exponents, and then each of them once in digits."""
    a, b = m // 2, (m - 1) // 2
    return ['= ' + ', '.join(f'{(n - r + 2) // 3:,}' for r in range(3)) + ';',
            f'\\(m = {m}\\) (\\(\\Leftrightarrow D_0 + D_1 + D_2 = 0\\), \\(D_0 \\equiv D_1 \\equiv D_2 \\pmod{{3^{{{a}}}}}\\), '
            f'\\(3^{{{b}}} \\mid D_r\\); ' + ', '.join(f'\\(3^{{{e}}} =\\) {3 ** e:,}' for e in dict.fromkeys([a, b])) + ')']


def mod3_line(n, m):
    """The line of Mathematica that a residue box of the single modulus 3 ends with where Stan Wagon's argument does not
    decide its order (2026-11-16; dreeves: "are you still referring to "an exhaustive search" and linking to a python
    program when you could instead give a couple lines of mathematica like stan did?"), for the length n at the order
    m: s the class sizes; the multiples of 3^b within each size, every triple of them, and of those the triples of zero
    sum, each of its class size's parity, all congruent to the first mod 3^a, for a = floor(m/2) and b = floor((m - 1)/2):
    mod3_said's closed form, so that it gives {} exactly when mod3_sums(n, m) is empty, as mathematica_sums runs it."""
    a, b = m // 2, (m - 1) // 2
    s = [(n - r + 2) // 3 for r in range(3)]
    return (f's = {{{s[0]}, {s[1]}, {s[2]}}}; Select[Tuples[3^{b} Range[-Quotient[s, 3^{b}], Quotient[s, 3^{b}]]], '
            f'Total[#] == 0 && Mod[# - s, 2] == {{0, 0, 0}} && Mod[# - #[[1]], 3^{a}] == {{0, 0, 0}} &]')


def mathematica_values(lines):
    """What each line of Mathematica in lines gives, as InputForm text, all in one wolframscript run (a licensed local
    kernel; about 2 s for 290 lines)."""
    with tempfile.NamedTemporaryFile('w', suffix='.wl', delete=False) as f:
        f.write(''.join(f'Print[ToString[InputForm[({line})]]]\n' for line in lines))
    try:
        p = subprocess.run(['wolframscript', '-file', f.name], capture_output=True, text=True, timeout=600)
    finally:
        os.unlink(f.name)
    assert p.returncode == 0 and p.stderr.strip() == '', (p.returncode, p.stderr[-2000:])
    out = p.stdout.splitlines()
    assert len(out) == len(lines), (len(out), len(lines), out[:3])
    return out


def mathematica_sums(cases):
    """What mod3_line(n, m) gives in Mathematica for each (n, m) of cases (mathematica_values): for each, its triples,
    as a sorted list of tuples."""
    return [sorted(tuple(t) for t in json.loads(line.replace('{', '[').replace('}', ']')))
            for line in mathematica_values([mod3_line(n, m) for n, m in cases])]


def stan_holds(n, m):
    """Whether Stan Wagon's argument (his note of 2026-11-16 that m*(1024) <= 11) rules out the order m at the length n,
    as the page's boxes take it (dreeves: "could you use stan's exact words (mutatis mutandis)", then "ok go" to them
    where they hold): m even, so that BGPW's Proposition 4.3 (r = 0) makes the three class sums congruent mod 3^(m/2);
    classes 0 and 2 of sizes of different parities, so sums of different parities; and those sizes adding to less
    than 3^(m/2), the most the two sums can differ by, so that the congruence makes them equal."""
    s0, s2 = (n + 2) // 3, n // 3
    return m % 2 == 0 and (s0 + s2) % 2 == 1 and s0 + s2 < 3 ** (m // 2)


def stan_said(n, m, name):
    """The numbers of Stan Wagon's argument for the length n, named name in TeX, at the order m, which a box that gives
    his words holds (among, so his words themselves are not held).  Since 2026-11-18, his shorter proof ("For web page.
    Here it is, shorter now. No need for any Mathematica code."): the supposition m*(n) >= m, with d_3,i; p = 3, s = m/2
    and r = 0, so d_3,0 = d_3,j mod 3^s, 3^s in digits; the classes 0 and j of [0, n - 1], their sizes, so d_3,0 and
    d_3,j of opposite parity; |d_3,i| at most class 0's size, the largest, so the mod-3^s congruence.  His j is 1 at
    1024; here it is n mod 3, which is 1 there and 2 where n = 2 mod 3, whose classes 0 and 1 have sizes of one parity
    (class j's size is class 2's at every n that 3 does not divide).  Until then his note of 2026-11-16: m split as
    s(p - 1) + r = 2s + r, the modulus as 3^s = its digits, the three sizes, and the even one of the classes 0 and 2
    with its size, then the odd one."""
    s, j, sizes = m // 2, n % 3, [(n - r + 2) // 3 for r in range(3)]
    return [f'\\(m^*({name}) \\ge {m}\\) with \\(d_{{3,i}}\\)',
            f'\\(p = 3\\) and apply Proposition 4.3 of [BGPW] to get \\(s = {s}\\) and \\(r = 0\\), which gives '
            f'\\(d_{{3,0}} \\equiv d_{{3,{j}}}\\) (mod {3 ** s})',
            f'0 and {j} mod-3 residue class sizes in [0, {n - 1}] are {sizes[0]} and {sizes[j]}, respectively, so '
            f'\\(d_{{3,0}}\\) and \\(d_{{3,{j}}}\\) have opposite parity. But \\(|d_{{3,i}}| \\le\\) {sizes[0]}, so the '
            f'mod-{3 ** s} congruence']


def residue_said(n, name, hi, moduli, source, t):
    """Whether a residue box's text t says its proof's arguments, for the length n named name in TeX, the bound hi, the
    chain's moduli (as the box writes them, '3' or '3, 9') and its program, source: since 2026-11-16, Stan Wagon's
    argument with n's numbers where it holds (stan_said), else for the single modulus 3 the modulus and the closed
    form's line of Mathematica (mod3_line), else the moduli and the program that searched them."""
    m = hi + 1
    return (all(among(x, t) for x in stan_said(n, m, name)) if moduli == '3' and stan_holds(n, m)
            else f'\\(M = {moduli}\\)' in t and (mod3_line(n, m) if moduli == '3' else source) in t)


def q_residue_panels_at_3_give_stan_s_words_where_they_hold():
    # Replicata: the panels run: the panel of each column whose upper bound is the residue condition of the single
    # modulus 3 and whose order hi + 1 Stan Wagon's argument rules out (stan_holds).
    # Expectata (dreeves, 2026-11-16, of Stan's note proving m*(1024) <= 11: "could you use stan's exact words (mutatis
    # mutandis) from the screenshot above?", then "ok go" to his words where they hold and a line of Mathematica
    # elsewhere): the box's proof is one part, proof-stan, not of Claude's English, a quotation (OPENING): his argument
    # with its column's numbers (stan_said).  And the argument holds there: m = hi + 1 is even, so the class sums are
    # congruent mod 3^(m/2); the classes 0 and 2 differ in size by 1, so their sums differ in parity; and their sizes add
    # to less than 3^(m/2), the most those sums can differ by, so the congruence makes them equal.  The control: every
    # other column of that modulus fails one of those (q_residue_panels_at_3_give_a_mathematica_line_elsewhere).
    # Spec change (2026-11-16, later that evening; dreeves: "why no mathematica code for the 1024:12 cell?", then
    # "yeah, add the mathematica line"): after his part, a part of Claude's English, proof-pairs, quoted by itself, gives
    # his check of all pairs as a line of Mathematica (stan_line), which, run, gives False; the control: one power of 3
    # lower, the same line does not.
    # Spec change (Opus 5.5, 2026-11-18; Stan Wagon's shorter proof, relayed by dreeves: "For web page.  Here it is,
    # shorter now. No need for any Mathematica code. The 342 bound means that the congruence is equality, contradicting
    # parity."): the proof is his one part again, proof-stan, with his new numbers (stan_said), and no line of
    # Mathematica: his bound |d_3,i| <= class 0's size makes the congruence an equality in words.  The control: the
    # numbers one power of 3 lower (stan_said at m - 2) are not in the box, and there the argument fails (the two sizes
    # add to 3^(m/2 - 1) or more), which the line of Mathematica showed until then by finding pairs.
    # Resultata before: each such box gave the closed form and "an exhaustive search (pagegen/mstar.py) finds none".
    R = valid_run('panels')
    cols = mstar_data()['cols']
    stan = []
    for P in R['panels']:
        n = P['n']
        lo, hi, lw, hw = cols[n - 1]
        if hw != ['residue', 3] or not stan_holds(n, hi + 1): continue
        m, s0, s2 = hi + 1, (n + 2) // 3, n // 3
        assert m % 2 == 0 and s0 - s2 == 1 and s0 + s2 < 3 ** (m // 2) and not stan_holds(n, m - 2), (n, m)
        part = [(why, t, c) for why, t, c in P['parts'] if why == 'proof-stan']
        assert [(why, c) for why, _, c in part] == [('proof-stan', False)], (n, P['parts'])
        assert re.match(BOUND + OPENING, part[0][1]) and part[0][1].endswith('”'), (n, part)   # (Spec change, Opus 5.5, 2026-11-18; dreeves: "so many formatting and other inconsistencies": every part starts with its bound, its quotation after it.)
        for said in stan_said(n, m, str(n)):
            assert among(said, P['text']), (n, said, P['text'])
        assert not any(among(said, P['text']) for said in stan_said(n, m - 2, str(n))), (n, P['text'])
        stan.append((n, m))
    assert [n for n, _ in stan] == [n for n in COLUMNS if cols[n - 1][3] == ['residue', 3] and stan_holds(n, cols[n - 1][1] + 1)], stan
    assert (1024, 12) in stan, stan


def q_residue_panels_at_3_give_a_mathematica_line_elsewhere():
    # Replicata: the panels run: the panel of each column whose upper bound is the residue condition of the single
    # modulus 3 and whose order hi + 1 Stan Wagon's argument does not rule out; and Mathematica (wolframscript), which
    # runs each box's line.
    # Expectata (dreeves, 2026-11-16: "are you still referring to "an exhaustive search" and linking to a python program
    # when you could instead give a couple lines of mathematica like stan did?", then "ok go"): the box ends with the
    # line of Mathematica for its length at hi + 1 (mod3_line), which gives {} when run; and the control: the same line
    # at hi gives exactly the residue sums that Python's enumeration of the closed form finds (mod3_sums), never none.
    # Stan's argument fails at each of these: an odd hi + 1, or classes 0 and 2 of sizes adding to 3^((hi + 1)/2) or
    # more (at 40, order 6: 14 + 13 = 27).
    # Resultata before: those boxes ended "an exhaustive search (pagegen/mstar.py) finds none".
    R = valid_run('panels')
    cols = mstar_data()['cols']
    lines = []
    for P in R['panels']:
        n = P['n']
        lo, hi, lw, hw = cols[n - 1]
        if hw != ['residue', 3] or stan_holds(n, hi + 1): continue
        assert (hi + 1) % 2 or (n + 2) // 3 + n // 3 >= 3 ** ((hi + 1) // 2), (n, hi)
        assert mod3_line(n, hi + 1) in P['text'], (n, mod3_line(n, hi + 1), P['text'])
        lines.append((n, hi))
    assert len(lines) > 20 and 40 in [n for n, _ in lines], lines
    got = mathematica_sums([(n, m) for n, hi in lines for m in (hi + 1, hi)])
    for i, (n, hi) in enumerate(lines):
        assert got[2 * i] == [] and got[2 * i + 1] == sorted(mod3_sums(n, hi)) != [], (n, hi, got[2 * i:2 * i + 2])


def q_residue_panels_at_3_give_the_closed_form():
    # Replicata: the panels run: the panel of each column whose upper bound is the residue condition of the single
    # modulus 3 (mstar.js: ["residue", 3]; 44 of the chart's columns as the page loads).
    # Expectata (dreeves, 2026-11-16, of that condition in closed form, each such box then a check by hand as the norm
    # bound's is: "yes to mod-3 boxes"): the box gives the three class sizes s_r, in digits, and at m = hi + 1 the
    # condition in closed form, the math alone (mod3_said): D_0 + D_1 + D_2 = 0, D_0 = D_1 = D_2 mod 3^floor(m/2) and
    # 3^floor((m - 1)/2) dividing each D_r, with those powers of 3 in digits.  And the bound is that closed form's own
    # (Python's enumeration, mod3_sums): no residue sums meet it at hi + 1, and some do at hi.
    # Resultata before: the condition as (x - 1)^m dividing sum D_r x^r mod x^M - 1 alone and no class sizes, which
    # leaves a reader the search to repeat.
    # Spec change (2026-11-16, later; dreeves: "could you use stan's exact words (mutatis mutandis)", then "ok go"): only
    # the boxes whose order Stan Wagon's argument does not rule out (stan_holds) give the closed form; the others give
    # his words (q_residue_panels_at_3_give_stan_s_words_where_they_hold).
    R = valid_run('panels')
    cols = mstar_data()['cols']
    found = 0
    for P in R['panels']:
        n = P['n']
        lo, hi, lw, hw = cols[n - 1]
        if hw != ['residue', 3] or stan_holds(n, hi + 1): continue
        assert mod3_sums(n, hi + 1) == [] and mod3_sums(n, hi) != [], (n, hi)
        for said in mod3_said(n, hi + 1):
            assert among(said, P['text']), (n, said, P['text'])
        found += 1
    assert found == sum(1 for n in COLUMNS if cols[n - 1][3] == ['residue', 3] and not stan_holds(n, cols[n - 1][1] + 1)) > 20, found


def q_tap_opens_its_cell_s_box():
    # Replicata: the light run's mouse click on a cell of row 1 (R.click), in a view zoomed in 3 steps.
    # Expectata: the box of the clicked cell opens, its fragment nNm1 set and its heading focused, a green cell's (its
    # kind exists), the heading the cell's n and m and the legend's words for its swatch, m <= m*(n); its parts its
    # column's witness alone (panel_whys).
    # Spec change (2026-11-04, [CEL]: "the info box for a cell should focus on that cell"; until then
    # q_tap_opens_its_column_s_panel): the panel of the cell's column opened, its fragment nN, starting with the cell's
    # status: "The cell clicked, order 1, is known".
    R = valid_run('light')
    P, n = R['clickPanel'], R['click']['want'][0]
    assert not P['hidden'] and P['hash'] == f'#n{n}m1' and P['focus'] and P['kind'] == 'exists', P
    assert P['heading'] == f'\\(n = {n}\\), \\(m = 1\\): \\(m \\le m^*(n)\\)', P['heading']
    assert P['whys'] == panel_whys(mstar_data()['cols'], n, [1]), P['whys']


def q_fragment_opens_its_panel_and_focus_comes_back():
    # Replicata: the page loaded with the fragment #n1024; then Escape in the panel's heading; then the fragment #n512;
    # then a click on the panel's close button.
    # Expectata (the design of 2026-11-03: "Loading the page with such a fragment opens that panel"; "On open, focus
    # moves to the panel's heading; close or Escape returns focus to the chart"): the panel of n = 1024 is open at load,
    # its heading focused; Escape hides it, its default prevented, the fragment gone and the focus on the chart; #n512
    # opens 512's panel; its close button hides it, the fragment gone, the focus on the chart.
    R = valid_run('fragment')
    F, E, O, C = R['fragment'], R['escaped'], R['reopened'], R['closed']
    assert not F['hidden'] and F['hash'] == '#n1024' and F['focus'] and F['heading'].startswith('\\(n = 1024\\)'), F
    assert E['hidden'] and E['prevented'] and E['hash'] == '' and E['active'] == 'mstar-chart', E
    assert not O['hidden'] and O['hash'] == '#n512' and O['focus'] and O['heading'].startswith('\\(n = 512\\)'), O
    assert C['hidden'] and C['hash'] == '' and C['active'] == 'mstar-chart', C


def q_panels_fit_a_phone():
    # Replicata: 390 px wide: every column's panel opened in turn (the phone panels run); and the page loaded there
    # with #n1024.
    # Expectata: with each panel open, the page is no wider than the window.
    R = valid_run('phone panels')
    wide = [(P['n'], P['scrollW']) for P in R['panels'] if P['scrollW'] > R['innerW']]
    assert R['innerW'] == 390 and wide == [] and len(R['panels']) == NCOL, wide[:5]
    F = valid_run('phone fragment')
    assert not F['fragment']['hidden'] and F['fragment']['scrollW'] <= 390, F['fragment']
    # and (since 2026-11-04, [CEL] and [ROC]) the boxes of the phone boxes run, each target's box opened by a click there
    B = valid_run('phone boxes')['boxes']
    assert len(B) >= 15 and [(P['target'], P['scrollW']) for P in B if P['hidden'] or P['scrollW'] > 390] == [], [(P['target'], P['scrollW']) for P in B]


def q_made_up_data_opens_every_kind_of_panel():
    # Replicata: made-up data that uses every kind of reason (kinds_data): every column's panel opened in turn.
    # Expectata: no errors; each panel opens and shows exactly its data's reasons; between them they use every kind of
    # lower and upper bound of the data contract (but none and odd, which odd n have, with no column).
    R = valid_run('kinds panels')
    made = json.loads(kinds_data()[len('const MSTAR = '):-2])
    cols = made['cols']
    assert len(R['panels']) == len(state('kinds panels')[1]), len(R['panels'])
    for P in R['panels']:
        assert not P['hidden'] and P['errors'] == 0 and P['whys'] == panel_whys(cols, P['n'], ifsym=made['ifsym']), (P['n'], P)   # (ifsym since 2026-11-18)
    kinds = {w for P in R['panels'] for w in P['whys']}
    # (spec change, 2026-11-04, [CEL]: the parts' kinds are a witness's and a proof's, lo-KIND and hi-KIND until then)
    # ('prop44' since 2026-11-11: BGPW's Proposition 4.4, the made-up column 40)
    assert set(WITNESSES.values()) | {f'proof-{k}' for k in ('two', 'norm', 'residue', 'prop44', 'table2', 'page')} <= kinds, kinds
    for P in R['panels']:
        bad = [what for what, found in panel_says(made, P['n'], P) if not found and what in ('t', 'cited')]
        assert cols[P['n'] - 1][3] != ['prop44'] or bad == [], (P['n'], bad, P['text'], P['links'])
    assert [n for n, c in enumerate(cols, 1) if c[3] == ['prop44']] == [40]


# ---------------------------------------------------------------------------------------------------------------------
# The remarks' entries in the panels ([REO] step 2; dreeves, 2026-11-03: "how can we reduce the redundancy and clutter?
# we want everything to appear in this box -- the box shouldn't ever refer to "remarks below". but also it would be
# nice to be able to grep the page and find everything?", and the main session's design of that day): a column's panel
# shows the remarks' entry of its length, the entry itself moved in, not a copy, and it goes back to its place in the
# list when the panel closes or opens another column; the list, the entries' source text, stays in the page in one
# fold, closed until clicked, which find in page opens; and no entry repeats a sentence of its panel's generated text.

def q_panel_shows_its_entry_and_gives_it_back():
    # Replicata: the fragment runs (1280 and 390 px): the page loaded with #n1024; Escape; #n512; its close button;
    # #n1024 again; the powers-of-2 chart's #k10 (n = 1024 there too); that panel's close button; #n512, then #n1024
    # while it is open; Escape.  And the panels runs: every column's panel by its fragment in turn, then the last closed.
    # Expectata (the design, 2026-11-03: "When a column panel opens, its length's remarks entry ... is moved into the
    # panel, below the generated reasons. It is not cloned ... When the panel closes, or another column's panel opens,
    # the entry goes back to its exact place in the list"; "If an entry lists several lengths (e.g. 320 and 352), it
    # moves into whichever of their panels opens"; "A column with no entry shows its generated reasons only"): each
    # open panel shows exactly the entry that lists its length, if any (panel_entries), and the list holds the others in
    # their order (entry_order); the powers-of-2 chart's panel of 2^10 takes 1024's entry from the m*(n) chart's, which
    # stays open, showing none; once a panel closes or switches, every entry it showed is back in its place, and with
    # both panels closed the list is whole, in order.
    # Spec change (Opus 5.5, 2026-11-18): the list is the appendix's, with an entry for every length (entry_order), so
    # every panel shows one (panel_entries); the rest as before.
    # Spec change (later that night, for dreeves's sign-off; his "yes, please fix that!", of a link into an entry that
    # landed in the box showing it: q_links_into_an_entry_land_in_the_appendix_while_a_box_shows_it): a panel shows a
    # copy of the entry, so the list stays whole, in order, at every step (until then it lacked the entries shown,
    # held), and the m*(n) chart's panel keeps showing 1024's entry when the powers-of-2 chart's panel of 2^10 shows it
    # too (until then it showed none, the entry taken from it).
    # Resultata before: panels linked their entries ("Its entry in the remarks below"), which stayed in the list.
    order = entry_order()
    assert len(order) == len(set(order)) > 500 and 'entry-1024' in order and 'entry-512' in order, order[:10]
    for name in ('fragment', 'phone fragment'):
        R = valid_run(name)
        steps = [('fragment', R['fragment'], ['entry-1024']), ('escaped', R['escaped'], []), ('reopened', R['reopened'], ['entry-512']),
                 ('closed', R['closed'], []), ('again', R['again'], ['entry-1024']),
                 ('crossed mstar', R['crossed']['mstar'], ['entry-1024']), ('crossed pow2', R['crossed']['pow2'], ['entry-1024']),
                 ('crossClosed mstar', R['crossClosed']['mstar'], ['entry-1024']), ('crossClosed pow2', R['crossClosed']['pow2'], []),
                 ('switched', R['switched'], ['entry-1024']), ('allClosed', R['allClosed']['mstar'], [])]
        for step, P, want in steps:
            assert P['entries'] == want, (name, step, P['entries'], want)
        for step, P, _ in steps:
            assert P['listed'] == order, (name, step, sorted(set(order) ^ set(P['listed'])))
        assert not R['crossed']['mstar']['hidden'] and not R['crossed']['pow2']['hidden'], R['crossed']
        assert R['crossClosed']['pow2']['hidden'] and not R['crossClosed']['mstar']['hidden'], R['crossClosed']
        assert R['allClosed']['mstar']['hidden'] and R['allClosed']['pow2']['hidden'], R['allClosed']
    for name in ('panels', 'phone panels'):
        R = valid_run(name)
        for P in R['panels']:
            assert P['entries'] == panel_entries(P['n']) and P['listed'] == order, (name, P['n'], P['entries'])
        assert R['after']['hidden'] and R['after']['entries'] == [] and R['after']['listed'] == order, (name, R['after']['entries'])
    assert {P['n'] for P in valid_run('panels')['panels'] if P['entries']} >= {320, 352, 416, 512, 1024}


def q_entry_ids_stay_unique_and_codes_expand_in_a_panel():
    # Replicata: the fragment runs: 1024's panel opened by its fragment, a click on its code there, 1024:11, then the
    # powers-of-2 chart's panel of 2^10, which takes the entry, then both closed; and the panels runs, each column's
    # panel in turn.
    # Expectata (the design, 2026-11-03: "It is not cloned: the entry holds ids (codes' N:M ids) that must stay unique,
    # and codes.js's expanders must keep working"): no id is on two elements of the page at any step; the click expands
    # the code in the panel (aria-expanded true), its box right there, shown, inside the entry: the power sums for k = 0
    # to 11, equal below 11 and unequal at 11; the box moves with the entry into the other panel, still shown, and back
    # into the list with it.
    # Spec change (Opus 5.5, 2026-11-18, for dreeves's sign-off; his "yes, please fix that!", of a link into an entry
    # that landed in the box showing it): a panel shows a copy of the entry, with no id, so no id is on two elements
    # still; the click is on the copy's code, data-code 1024:11, which expands in the panel as before; the powers-of-2
    # chart's panel shows a copy of its own, so the expanded one stays in the m*(n) chart's panel, shown; and with both
    # panels closed the copy is gone from the page, its box with it.
    # Resultata before: the code was in the list, and its box opened there, outside the panel.
    for name in ('fragment', 'phone fragment'):
        R = valid_run(name)
        reports = [R[k] for k in ('fragment', 'escaped', 'reopened', 'closed', 'again', 'switched')] + [
            R[k][c] for k in ('crossed', 'crossClosed', 'allClosed') for c in ('mstar', 'pow2')]
        assert all(P['dups'] == [] for P in reports), (name, [P['dups'] for P in reports])
        shown = {'expanded': 'true', 'connected': True, 'inEntry': True, 'inMstar': True, 'inPow2': False, 'shown': True,
                 'ks': [str(k) for k in range(12)], 'relations': ['='] * 11 + ['≠']}
        for step, want in (('expanded', shown), ('crossed', shown), ('allClosed', {'connected': False, 'inMstar': False, 'inPow2': False})):
            B = R[step] if step == 'expanded' else R[step]['box']
            assert {k: B[k] for k in want} == want, (name, step, B)
    for name in ('panels', 'phone panels'):
        assert all(P['dups'] == [] for P in valid_run(name)['panels']), name


def q_no_panel_mentions_the_remarks_below():
    # Replicata: the panels runs, every column's panel of the m*(n) chart, its generated text and the entry it shows;
    # and the panel templates of index.html.
    # Expectata (dreeves, 2026-11-03: "we want everything to appear in this box -- the box shouldn't ever refer to
    # "remarks below""): no panel's text says "remarks below", and no template says it; the template "entry" ("Its
    # entry in the remarks below") is gone.
    # Resultata before: every panel of a length with an entry ended "Its entry in the remarks below: ...".
    for name in ('panels', 'phone panels'):
        said = [P['n'] for P in valid_run(name)['panels'] if 'remarks below' in ' '.join([P['text'], *P['entryText']])]
        assert said == [], (name, said[:10])
    # (spec change, 2026-11-04, [CEL]: the boxes' 14 templates, some marked data-claude, in place of 2026-11-03's 16)
    templates = re.findall(r'<template data-panel="([^"]+)"[^>]*>(.*?)</template>', page(), re.S)
    assert len(templates) >= 14 and 'entry' not in {t for t, _ in templates}, [t for t, _ in templates]
    assert not [t for t, body in templates if 'remarks below' in body], [t for t, body in templates if 'remarks below' in body]


def appendix_fold():
    """The appendix's fold, from index.html (2026-11-18; until then the remarks section's, which this read the same way):
    (its summary's text, the text it holds after the summary), asserting it is the section's one outermost <details>,
    without open, with nothing else in the section, and that its first element is a <summary>."""
    # Spec change (2026-11-07; dreeves chose "Allow nested disclosures" over moving the inline proofs out of the remarks):
    # the fold is the section's one outermost <details>; closed disclosures nested inside its entries (Astra's typeset
    # 512 proof and complete 384 proof, which quals_inline384 and quals_proof_layout require to be native <details>) are
    # allowed.  Before, the section had to hold exactly one <details>, and its first </details> closed the fold.
    section = re.search(r'<section class="appendix"[^>]*>(.*?)</section>', page(), re.S)[1]
    tags = list(re.finditer(r'<details([^>]*)>|</details>', section))
    depth, top, nested = 0, [], []
    for x in tags:
        if x.group(0).startswith('</'):
            depth -= 1
            if depth == 0: top[-1].append(x)
        else:
            (top.append([x]) if depth == 0 else nested.append(x))
            depth += 1
    assert depth == 0 and len(top) == 1 and len(top[0]) == 2, [len(f) for f in top]
    opening, closing = top[0]
    assert 'open' not in opening.group(1) and not any('open' in x.group(1) for x in nested), (opening.group(1), [x.group(1) for x in nested])
    assert section[:opening.start()].strip() == '' and section[closing.end():].strip() == '', 'the fold is the whole section'
    fold = re.fullmatch(r'\s*<summary>(.*?)</summary>(.*)', section[opening.end():closing.start()], re.S)
    assert fold, section[opening.end():opening.end() + 300]
    return fold.group(1), fold.group(2)


def q_appendix_list_folds_closed_under_its_summary():
    # Replicata: index.html's section "Appendix: Everything Known About Every Length"; and the light run, as the page loads.
    # Expectata (the design, 2026-11-03, for the list of entries, then in the section "Where the new results come
    # from": "The remarks list ... stays in the HTML exactly as written, as the source text. Fold it into one closed
    # <details> with a summary line ... styled like the Search progress section's folds"; "Without JavaScript the page
    # reads as before, with the list foldable"): the list of entries, every <p class="entry"> of the page with it, is in
    # one <details> without open, after its <summary>, which has words.  As the page loads the fold is closed, its summary
    # shown and its list not.  A summary is a pointer in the stylesheet, as the Search progress section's are.
    # Spec change (Opus 5.5, 2026-11-18; dreeves: "how about an appendix section right above Search Progress: Appendix:
    # Everything Known About Every Length ... move that section to the appendix, default collapsed"): the fold is the
    # appendix section, its summary the section's heading, his words (held by q_appendix_has_an_entry_for_every_length),
    # its list in a div.remarks, styled as the boxes' entries are, last, after what the codes and constructions of its
    # entries use (that evening: "the human text starting "The hex codes shown below" also belongs somewhere else, right?
    # the top of the appendix?").  Until then it was in the section "Where the new
    # results come from", its summary Opus 5.5's words, after that section's paragraphs on how the upper bounds are
    # proven, which stay there, visible ("Keep the section's introduction ... visible above the fold").
    # Resultata before: the list stood open, with no fold.
    summary, inside = appendix_fold()
    assert re.fullmatch(r'<h2 id="appendix-title">[^<]+</h2>', summary), summary
    top, list_, rest = inside.partition('<div class="remarks"><ul class="entries">\n')
    assert list_ and '<p class="entry">' not in top and re.fullmatch(r'.*\n    </ul></div>\s*', rest, re.S) \
        and rest.count('<p class="entry">') == page().count('<p class="entry">'), inside[:300]
    assert '.appendix > details > summary { cursor: pointer; }' in page_css(), 'no pointer on the summary'
    assert valid_run('light')['fold'] == {'there': True, 'open': False, 'summary': True, 'list': False}, valid_run('light')['fold']


def panel_reasons(n, cols, pcols):
    """[lo, hi, loWhy, hiWhy] of each panel that shows the length n, by the columns cols of mstar.js and pcols of
    pow2.js: the m*(n) chart's column n, if it has one, and the powers-of-2 chart's column k for n = 2^k, its hiWhy
    ["mstar", why] read as why."""
    k = n.bit_length() - 1
    return ([cols[n - 1] for _ in [0] if n in COLUMNS]
            + [[lo, hi, lw, hw[1] if hw[0] == 'mstar' else hw] for lo, hi, lw, hw in pcols[k - 1:k] if n == 2 ** k])


def repeated_reasons(reasons, n):
    """The sentences that would repeat, in a panel of the length n with the reasons [lo, hi, loWhy, hiWhy], what its
    generated text states, in the forms the remarks used for them, as regexes over an entry's HTML: the upper bound's
    reason, the residue condition mod M (a chain's last modulus) or the norm bound for the residue sums mod p, as the
    entries of the m*(n) chart's lengths said it and as those of the powers of 2 did ("as in the powers-of-2 chart
    above"); Thue–Morse's order, where Thue–Morse is the lower bound's reason; and a doubling with the upper bound's
    reason, where those are the panel's two reasons."""
    lo, hi, lw, hw = reasons
    M = hw[1][-1] if isinstance((hw + [None])[1], list) else (hw + [None])[1]
    said = {'residue': f'the residue condition mod {M}', 'norm': f'the norm bound for the residue sums mod {M}'}.get(hw[0])
    forms = ([rf'Order {hi + 1} is ruled out by {said}\.', rf'The upper bound is {said}, as in the powers-of-2 chart above\.'] * bool(said)
             + [rf'The Thue–Morse polynomial \\\(\\tau_\{{?{lo}\}}?\\\) has order {lo}\.'] * (lw in (['thue-morse'], ['example', 'Thue–Morse']))
             + [rf'Order {lo} from examples above, doubled \(\\\({n} = 2\\cdot {lw[-1]}\\\)\); order {hi + 1} is ruled out by {said}\.']
             * (lw[:2] == ['product', 2] and bool(said)))
    return [re.compile(f) for f in forms]


def entry_lis():
    """[(the lengths it lists, its HTML with comments blanked)] for each entry written by hand, an li of the appendix's
    list (the remarks' list until 2026-11-18), in page order."""
    section = blank_comments(re.search(r'<section class="appendix"[^>]*>(.*?)</section>', page(), re.S)[1])
    # (the entries' own list, ul.entries, since 2026-11-18, when dreeves's list of the product's and the join's
    # properties came to be in the appendix's opening; every li of the section until then)
    lis = re.findall(r'<li[ >].*?</li>', section[section.index('<ul class="entries">'):], re.S)
    lengths = [re.search(r'<p class="entry">\\\(n = (.*?)\\\): ', li)[1].split(', ') for li in lis]
    return [([2 ** int(x[3:-1]) if x.startswith('2^{') else int(x) for x in ns], li) for ns, li in zip(lengths, lis)]


def q_no_entry_repeats_its_panel_s_reasons():
    # Replicata: each entry of the remarks' list and, for each length it lists, the reasons of every panel that shows
    # that length (panel_reasons: the m*(n) chart's column, and the powers-of-2 chart's at a power of 2).
    # Expectata (the design, 2026-11-03: "No sentence shown twice. Delete from the entries each sentence that a
    # generated reason now states with the same content, for example "Order 12 is ruled out by the norm bound for the
    # residue sums mod 3." and "Order 13 is ruled out by the residue condition mod 5." Keep everything the templates do
    # not say: provenance, credit ..., history, methods, links and codes"; "Delete them only where the generated text
    # says exactly the same thing"): no entry has a sentence in the forms that state one of those panels' reasons
    # (repeated_reasons), which the panel's generated text states; a sentence that says more (a credit, a chain of
    # moduli, several lengths' reasons) is not in those forms.  The forms catch sentences of the entries as they stood
    # (controls).
    # Resultata before: 544's entry said "Order 11 is ruled out by the norm bound for the residue sums mod 3.", as its
    # panel's norm bound worked out does, and so did 63 other sentences, one in each of 63 other entries.
    reasons, cols, pcols = {}, mstar_data()['cols'], pow2_data()['cols']
    lis = entry_lis()
    # (Spec change, Opus 5.5, 2026-11-18: the entries by hand are some of the appendix's, which has one for every length,
    # 82 of them since the two that listed several lengths, 320 to 464 and 640 to 736, were split, one length each; 88
    # since 2026-11-19, the entries of the new firsts 2^22, 2^35, 2^42, 2^50, 2^55 and 2^63 added: spec change, Opus 5.5,
    # q_sequences_past_the_chart_move_seven_firsts.)
    # (Fable 5.2, 2026-11-21, with q_powers_of_2_on_the_page_follow_pow2_js: however many entries by hand there are, 88 until then.)
    assert lis and {f'entry-{lengths[0]}' for lengths, _ in lis} <= set(entry_order()), len(lis)
    found = []
    for lengths, li in lis:
        for n in lengths:
            reasons.setdefault(n, panel_reasons(n, cols, pcols))
            found += [(n, f.pattern) for r in reasons[n] for f in repeated_reasons(r, n) if f.search(li)]
    assert found == [], (len(found), found[:8])
    assert all(reasons[n] for n in reasons), [n for n in reasons if not reasons[n]]
    # (2026-11-16: 544's panel states the residue condition mod 3, which comes before the norm bound since that day, so
    # the sentence that would repeat it is of that form; its entry said "... ruled out by the norm bound for the
    # residue sums mod 3." until 2026-11-03, the control here until now)
    controls = {544: 'Claude: “A symmetric example of order 10, found by a lattice search. Order 11 is ruled out by the residue condition mod 3.”',
                864: 'Order 12 from examples above, doubled (\\(864 = 2\\cdot 432\\)); order 15 is ruled out by the residue condition mod 5.',
                512: 'The Thue–Morse polynomial \\(\\tau_9\\) has order 9.',
                2 ** 30: 'That beats Thue–Morse by 3. The upper bound is the residue condition mod 3, as in the powers-of-2 chart above.'}
    for n, said in controls.items():      # sentences of the entries as they stood, which the forms must catch
        assert [n for r in panel_reasons(n, cols, pcols) for f in repeated_reasons(r, n) if f.search(said)], (n, said)


def q_find_in_page_opens_the_fold():
    # Replicata: index.html loaded on its own (not in the harness's frame) with the text fragment #:~:text=Berend and
    # Golan, words of 432's entry, and then with the fragment #lemma432, an element of that entry, in the closed fold.
    # Expectata (the design, 2026-11-03: "Browser find-in-page opens a closed <details> on a match; check that the find
    # still works"): Chrome opens the fold to show the match, as the HTML standard's ancestor revealing algorithm has
    # it for find in page, text fragments and fragments: each load ends with the fold open and the entry's lemma shown.
    # (Chrome's find bar has no headless form; a text fragment is Chrome's other text search that reveals what it finds.
    # window.find finds the words in the fold but opens nothing: scratch/reo-step2-20261103/findprobe/.)  Spec change
    # (Opus 5.5, 2026-11-18; dreeves: "part of the point of having everything fully spelled out in the appendix is so
    # that you can grep for anything on the page"): the fold is the appendix's, which holds the entries since that day.
    # Resultata before: no fold.
    # words to search for, taken from the page (until 2026-11-09: "Berend and Golan"): three plain words in a row of
    # the lemma that stand nowhere else in the page's text
    seen = ' '.join(re.sub(r'<!--.*?-->|<script\b.*?</script>|<[^>]+>', ' ', page(), flags=re.S).split())
    start = page().index('<div id="lemma432">')                 # the lemma, up to the first element that closes inside it
    lemma = ' '.join(re.sub(r'<!--.*?-->|<[^>]+>', ' ', page()[start:page().index('</div>', start)], flags=re.S).split())
    phrase = next(p for p in re.findall(r'(?<![^ ])[A-Za-z]{3,} [A-Za-z]{3,} [A-Za-z]{3,}(?![^ ])', lemma) if seen.count(p) == 1)
    for frag in ('#:~:text=' + phrase.replace(' ', '%20'), '#lemma432'):
        d = tempfile.mkdtemp(prefix='index-quals-')
        probe = ('<script>addEventListener("load", () => setTimeout(() => { const f = document.querySelector("section.appendix details"),'
                 ' t = document.getElementById("lemma432"); document.documentElement.dataset.fold = JSON.stringify({there: f !== null,'
                 ' open: f?.open ?? null, shown: t.checkVisibility()}); }, 1500));</script>')
        text = page()
        assert text.count('</body>') == 1
        open(os.path.join(d, 'index.html'), 'w', encoding='utf-8').write(text.replace('</body>', probe + '</body>'))
        copy_page_dir(d)
        shutil.copy(DATA, data_file(d, 'mstar.js'))
        shutil.copy(POW2, data_file(d, 'pow2.js'))
        dom = chrome(d, ['--window-size=1280,1000', '--virtual-time-budget=10000', '--dump-dom', 'file://' + os.path.join(d, 'index.html') + frag])
        shutil.rmtree(d)
        m = re.search(r'<html[^>]* data-fold="([^"]*)"', dom)
        assert m, (frag, dom[:300])
        assert json.loads(html.unescape(m[1])) == {'there': True, 'open': True, 'shown': True}, (frag, m[1])


# ---------------------------------------------------------------------------------------------------------------------
# The boxes of the charts' cells, columns and rows (dreeves's README, 2026-11-03: "[CEL] For the info box you see when
# clicking a cell, color-code it to match the cell. And the info box for a cell should focus on that cell. If the cell
# is green, just give the partition (expandable hex code) for the highest green cell in that cell's column. If the cell
# is red, show the proof for the lowest red cell in that cell's column. If the cell is black... maybe just summarize the
# search efforts so far?", and "[ROC] Only if it's straightforward and if it makes sense and isn't a nighmare to make it
# anti-magic and DRY: in addition to clicking individual cells, allow clicking the column number or the row number";
# in chat: "so many pointless words in the implementation so far ... think through what the user will want to see and
# making the correspondence between the clicked cell and the info box visually obvious"; the main session's design of
# 2026-11-04): a click on a cell of the m*(n) chart, on the strip of its n labels or on the strip of its m labels opens,
# under the chart, the box of that cell, column or row (the boxes runs, the harness's boxes).

WITNESSES = {'example': 'witness-example', 'file': 'witness-example', 'join': 'witness-construction', 'product': 'witness-construction',
             'table2': 'witness-table2', 'page': 'witness-page'}    # a box's part of a lower bound, by its reason's kind
# A box's part of an upper bound, by its reason's kind: proof-KIND, but proof-file for a program of proofs/ (the kind
# proof, since 2026-11-10; written down here on 2026-11-12, when the chart came to open up to 2048, with 1248 and 1456)
PROOF_PARTS = {k: f'proof-{k}' for k in ('odd', 'two', 'norm', 'residue', 'table2', 'page', 'prop44')} | {'proof': 'proof-file'}
SHOWS = {'exists': (True, False), 'open': (True, True), 'ifsym': (True, True), 'impossible': (False, True)}   # (witness, proof),
# by the kind of cell of a box (a column's, None, until 2026-11-18: box_parts)
# The token of a cell's own color, by its kind: an ifsym cell (2026-11-11, [SYC]: red if BGPW's Symmetry Conjecture
# holds) is an open cell with a corner in the impossible color, and its box's frame and its swatch's fill are open's
UNDER = {'exists': 'exists', 'open': 'open', 'ifsym': 'open', 'impossible': 'impossible'}
BOX_WORDS = 24    # a cell's box's words of Claude's English, at most (q_cell_box_words_stay_within_budget)
# The boxes' templates of Claude's English (dreeves, 2026-11-04: "we don't need claude attribution for blurbs without
# words like these"): the others hold math, codes, the data's labels and citations alone
# (since 2026-11-16 evening, dreeves's "ok go", also the residue box's two endings: an exhaustive search by the chain's
# program, and the line of Mathematica of the single modulus 3; proof-stan holds Stan Wagon's words, not Claude's; and
# later that evening proof-pairs, the line of Mathematica after his words, until 2026-11-18, when his shorter proof
# took its place: "No need for any Mathematica code")
CLAUDE_TEMPLATES = {'witness-page', 'witness-thue-morse', 'proof-two', 'proof-norm', 'proof-residue', 'proof-page',
                    'check-search', 'check-mathematica'}


def entry_codes(n):
    """The ids of the codes that the remarks' entry that lists the length n holds (none if no entry lists n)."""
    return {c for lengths, li in entry_lis() if n in lengths for c in re.findall(r'<code id="(\d+:\d+)">', li)}


def code_digits(id_):
    """The hex digits of the page's code of the id N:M."""
    return re.search(rf'<code id="{id_}">([0-9A-F]+)</code>', page()).group(1)


def kind_of(cols, n, m, ifsym=()):
    """The kind of the m*(n) chart's cell (n, m): exists, open or impossible; or, with the data's ifsym given
    (2026-11-11, [SYC]), ifsym: open, and above the column's upper bound if BGPW's Symmetry Conjecture holds."""
    lo, hi = cols[n - 1][:2]
    h = {k: v for k, v, _ in ifsym}.get(n, hi)
    return 'exists' if m <= lo else 'open' if m <= h else 'ifsym' if m <= hi else 'impossible'


def box_parts(cols, n, m=None, ifsym=()):
    """The kinds of the parts of the box of the m*(n) chart's cell (n, m), or of its column n's (m None), in order (since
    2026-11-04): of its column's lower bound, its witness (WITNESSES, then a copy of the page's code of the length n and
    the order lo, where the page has one: witness-code), for a green cell, a black one and a column; of its upper bound,
    its proof (proof-KIND), for a red cell, a black one and a column; and a black cell's searches.  A copy goes where the
    box shows the code itself, in the entry that lists n, which a column's box shows, and a cell's whose bound shown is
    one of the page's own (page).  An ifsym cell's (2026-11-11, [SYC]; kind_of with the data's ifsym) is a black cell's
    with, after the proof, the bound that holds if the Symmetry Conjecture does (proof-ifsym).  Spec change (2026-11-16
    evening; dreeves: "could you use stan's exact words (mutatis mutandis)", then "ok go"): the proof of the residue
    condition of the single modulus 3 is Stan Wagon's words, proof-stan, where his argument holds (stan_holds), and
    after them (later that evening: "yeah, add the mathematica line") his check of all pairs as a line of Mathematica,
    proof-pairs, until 2026-11-18 (Opus 5.5; his shorter proof, relayed by dreeves: "No need for any Mathematica
    code"): since then his words alone.  Spec change (Opus 5.5, 2026-11-18; dreeves: "Appendix: Everything Known About
    Every Length", and of that afternoon's version, in which every cell's box showed its column's entry whole: "the
    whole point was to show just the information for the cell (unless you click the number for the whole column)"): a
    column's box shows its length's entry of the appendix, with its facts (fact_kinds: a class's for a length of a
    class, and the bound that holds if the Symmetry Conjecture does where ifsym lists the length); a cell's box is as
    before, the entry it shows for a bound of the page's own with its facts hidden (page/style.css)."""
    if m is None: return fact_kinds(cols[n - 1], n, ifsym)
    lo, hi, lw, hw = cols[n - 1]
    kind = kind_of(cols, n, m, ifsym)
    witness, proof = SHOWS[kind]
    upper = ['proof-stan'] if hw == ['residue', 3] and stan_holds(n, hi + 1) else [PROOF_PARTS[hw[0]]]
    # (Spec change, Opus 5.5, 2026-11-18, dreeves's point 10: a witness's codes are in its part, on its line, and no part
    # of their own, witness-code, as they were; the copies report holds them: witness_codes.)
    return ([WITNESSES[lw[0]]] * witness + upper * proof + ['proof-ifsym'] * (kind == 'ifsym')
            + ['searches'] * (kind in ('open', 'ifsym')))


def coded(lw, n, lo):
    """Whether a witness of the lower bound lo of the length n, of the reason lw, shows a code (witness-code): an
    example's, always, its code from mstar.js's codes (Opus 5.5, 2026-11-18; dreeves: "there should be no "found
    here". what does "here" mean? totally ambiguous. show the expandable hex code for everything"); a join's or a
    product's, always, the code of the sequence it builds (that night; dreeves: "witnesses are a top-level thing,
    conceptually", and, of every witness made (-1)^lo-symmetric so that a code in BGPW's convention holds it: "making
    all witnesses conforming sounds great"; until then such a witness's code was behind its construction, in its
    derivation's box); any other's, a copy of the page's code n:lo where the page has one (until 2026-11-18 every
    witness's, examples' too)."""
    return lw[0] in ('example', 'join', 'product') or f'{n}:{lo}' in code_ids()


def column_signs(data, n, memo=None):
    """The signs of the sequence behind column n's lower bound, by data (mstar.js's, or made up), built as its reason
    says (2026-11-18): an example's from its code (the data's examples, BGPW's convention: the code's bits, 1 as +1,
    begin the left half, and the left half reversed, times (-1)^lo, is the right half); a join's, its parts' one after
    the other; a product f # g's, block j f times g_j; none's, n ones."""
    memo = {} if memo is None else memo
    if n not in memo:
        lo, _, lw, _ = data['cols'][n - 1]
        part = lambda k: column_signs(data, k, memo)
        rule = {'none': lambda: [1] * n,
                'example': lambda: (lambda left: left + [(-1) ** lo * t for t in reversed(left)])(
                    [2 * int(b) - 1 for b in bin(int({x: c for x, c, _ in data['examples']}[n], 16))[2:].zfill(4 * -(-n // 8))[:n // 2]]),
                'join': lambda: [t for k in lw[1:] for t in part(k)],
                'product': lambda: [s * t for t in part(lw[2]) for s in part(lw[1])]}
        memo[n] = rule[lw[0]]()
    return memo[n]


def code_of(signs, lo):
    """The code, in BGPW's convention, of a (-1)^lo-symmetric sequence (asserted): the bits of its left half, 1 for +1,
    padded with 0 to whole hex digits."""
    n = len(signs)
    assert n % 2 == 0 and all(signs[-1 - i] == (-1) ** lo * t for i, t in enumerate(signs)), (n, lo)
    bits = ''.join('1' if t == 1 else '0' for t in signs[:n // 2])
    bits += '0' * (-len(bits) % 4)
    return f'{int(bits, 2):0{len(bits) // 4}X}'


def witness_codes(data, n):
    """The codes the witness of column n's lower bound shows, by data (mstar.js's, or made up), as the harness reports
    them (copies): [n:lo, lo, the role button, its digits], the data's code for an example (2026-11-18), the code of
    the sequence it builds for a join or a product (that night: code_of), the page's for any other reason."""
    lo, _, lw, _ = data['cols'][n - 1]
    if not coded(lw, n, lo): return []
    digits = {'example': lambda: {x: code for x, code, _ in data['examples']}[n],
              'join': lambda: code_of(column_signs(data, n), lo), 'product': lambda: code_of(column_signs(data, n), lo)
              }.get(lw[0], lambda: code_digits(f'{n}:{lo}'))()
    return [[f'{n}:{lo}', str(lo), 'button', digits]]


def class_of(n):
    """The class of lengths whose one entry of the appendix holds the length n, or None (Opus 5.5, 2026-11-18; dreeves:
    "combine entries for odd n", then "odd multiples of 2 are all essentially the same"): odd, or singly-even, n = 2
    mod 4; with each class's facts, stated for any n (CLASS_FACTS): that n is odd; alternating signs and the 2-adic bound
    at t = 1."""
    return 'odd' if n % 2 else 'singly-even' if n % 4 == 2 else None


CLASS_FACTS = {'odd': ['proof-odd'], 'singly-even': ['witness-alternating', 'proof-two']}


def fact_kinds(row, n, ifsym=()):
    """The kinds of the facts of the length n of the m*(n) chart's data, of its row [lo, hi, loWhy, hiWhy] (a column's,
    or since 2026-11-19 one of past's: mstar_rows), in its entry of the appendix, in order (Opus 5.5, 2026-11-18): its
    class's (CLASS_FACTS) for a length of a class; else the witness of its lower bound (WITNESSES), then
    a copy of the page's code of the length n and the order lo where the page has one and the entry does not hold it
    itself (witness-code); the proof of its upper bound (PROOF_PARTS, or Stan Wagon's words, proof-stan, where his
    argument holds); and where ifsym (the data's) lists n, the bound that holds if BGPW's Symmetry Conjecture does."""
    lo, hi, lw, hw = row
    upper = ['proof-stan'] if hw == ['residue', 3] and stan_holds(n, hi + 1) else [PROOF_PARTS[hw[0]]]
    return CLASS_FACTS.get(class_of(n)) or ([WITNESSES[lw[0]]] + upper   # (no witness-code since 2026-11-18: its codes in its part)
                                            + ['proof-ifsym'] * any(x == n for x, _, _ in ifsym))


def pow2_fact_kinds(pcols, k):
    """The kinds of the facts of the length 2^k past the m*(n) chart (k from 12) in its entry of the appendix, as the
    powers-of-2 chart has them (pow2.js's cols, pcols, or made-up ones): the witness of its lower bound, Thue–Morse or a
    construction of joins and products, then a copy of the page's code of that length and order where the page has one
    and the entry does not hold it; and the proof of its upper bound, proof-KIND, but Stan Wagon's words where his
    argument holds at the residue condition of the single modulus 3 (the page's data: joins and that residue condition
    at every such k)."""
    lo, hi, lw, hw = pcols[k - 1]
    upper, code = hw[1][0] if hw[0] == 'mstar' else hw[0], f'{2 ** k}:{lo}'
    return ([{'thue-morse': 'witness-thue-morse', 'joins': 'witness-construction'}[lw[0]]]
            + ['proof-stan' if hw in (['residue', [3]], ['mstar', ['residue', 3]]) and stan_holds(2 ** k, hi + 1) else f'proof-{upper}'])


def mstar_rows(data):
    """The m*(n) chart's data by length, {n: [lo, hi, loWhy, hiWhy]}: each column's, n from 1 to its nmax, and since
    2026-11-19 each row of past's, [n, lo, hi, loWhy, hiWhy], a length past the chart that the page has a sequence of
    (dreeves: "yes, full anti-magic, add the new entries")."""
    return {**dict(enumerate(data['cols'], 1)), **{n: c for n, *c in data['past']}}


def appendix_lengths(kmax):
    """The lengths the appendix has an entry for (dreeves, 2026-11-18: "we want an entry for every n from 1 thru 2048,
    plus 2^12 thru 2^72"): every n of the m*(n) chart, 1 to DATA_NMAX, then each 2^k past it up to 2^kmax, the
    powers-of-2 chart's last.  Spec change (Opus 5.5, 2026-11-19; dreeves, of entries for the sequences longer than the
    chart: "yes, full anti-magic, add the new entries"): every length of the chart's data, its columns' and past's
    (mstar_rows), so the seven lengths of past too, between 2048 and 2^12."""
    # (Fable 5.2, 2026-11-21: a length of both, a power of 2 past the chart that the page has a sequence of, as 2^13 since that day, is one length.)
    return sorted({*mstar_rows(mstar_data()), *(2 ** k for k in range(DATA_NMAX.bit_length(), kmax + 1))})


def q_appendix_has_an_entry_for_every_length():
    # Replicata: the light run: the page as it loads, before anything is clicked, its section "Appendix: Everything
    # Known About Every Length" (the harness's appendixReport).
    # Expectata (Opus 5.5, 2026-11-18; dreeves: "how about an appendix section right above Search Progress: Appendix:
    # Everything Known About Every Length ... move that section to the appendix, default collapsed, and extend and
    # consitent-ify it so that the title of the appendix is true. this means we want an entry for every n from 1 thru
    # 2048, plus 2^12 thru 2^72. combine entries for odd n since there's literally no witness for any odd n and the
    # proof that m*(n)=0 is exactly the same for all odd n. for even n, i believe every even n should have a separate
    # entry because the witnesses are different", and "part of the point of having everything fully spelled out in the
    # appendix is so that you can grep for anything on the page"): the section right before the Search progress
    # section, its fold closed, its title his words; at load, so that find in page reaches every one, one entry for the
    # odd n, first, its one fact the proof that n is odd, and one for the singly even n, n = 2 mod 4, second (that
    # afternoon: "odd multiples of 2 are all essentially the same: same exact proof that the order is 1 ... and the
    # witness ... is just any bipartition with 2 equal-sized sets"; CLASS_FACTS), then every other length
    # (appendix_lengths) in an entry of its own, in order (that evening: "no multi-length entries. just duplicate them
    # and add TODOs for me to consider how to change the human words accordingly"); each length's facts in its entry
    # (fact_kinds, pow2_fact_kinds); and no entry left in the section "Where
    # the new results come from".  Its math is drawn when the fold first opens, not as the page loads (page/math.js):
    # none drawn at load, then at least the two formulas of each entry's heading, with no error of KaTeX's.
    # Resultata before: no such section; 75 entries in a fold of "Where the new results come from", which a column's
    # box alone showed.
    O = valid_run('light')['appendixOpened']
    A = valid_run('light')['appendix']
    assert A is not None, 'no section.appendix'
    assert (A['prev'], A['next'], A['open'], A['remarks']) == ('symmetry', 'progress', False, 0), {k: A[k] for k in ('prev', 'next', 'open', 'remarks')}
    assert A['title'] == 'Appendix: Everything Known About Every Length', A['title']
    # Spec change (Opus 5.5, 2026-11-19; dreeves: "yes, full anti-magic, add the new entries"): the lengths of past's
    # rows have their entries too (appendix_lengths), each with its row's facts, as a column's (fact_kinds).
    data, pcols = mstar_data(), pow2_data()['cols']
    rows, ifsym, kmax = mstar_rows(data), data['ifsym'], len(pcols)
    lengths = [[int(x) for x in e['lengths'].split()] for e in A['entries']]
    classes = [[n for n in appendix_lengths(kmax) if class_of(n) == c] for c in CLASS_FACTS]
    assert lengths[:2] == classes and [e['facts'] for e in A['entries'][:2]] == [[[k, c] for k in CLASS_FACTS[c]] for c in CLASS_FACTS], \
        ([ls[:4] for ls in lengths[:2]], [e['facts'] for e in A['entries'][:2]])
    assert sorted(n for ls in lengths for n in ls) == appendix_lengths(kmax), 'each length in exactly one entry'
    assert [ls[0] for ls in lengths] == sorted(ls[0] for ls in lengths), [ls[0] for ls in lengths][:20]
    assert all(len(ls) == 1 for ls in lengths[2:]), [ls for ls in lengths[2:] if len(ls) > 1]
    for ls, e in zip(lengths[2:], A['entries'][2:]):
        want = [[kind, str(n)] for n in ls
                # (Fable 5.2, 2026-11-21: a power of 2 past the chart has the powers-of-2 chart's facts, as page/appendix.js gives it them, also when the
                # m*(n) chart's data have a row for it, as for 2^13 since that day; until then every length with a row had its row's.)
                for kind in (pow2_fact_kinds(pcols, n.bit_length() - 1) if n > DATA_NMAX and n & (n - 1) == 0 else fact_kinds(rows[n], n, ifsym))]
        assert e['facts'] == want, (ls, e['facts'], want)
    assert O['before'] == 0 and O['after'] >= 2 * len(A['entries']) and O['errors'] == 0, O


def words(text, codes=()):
    """The words of a box's text outside its math, its codes and its numbers: its runs of letters.  Its codes are the
    page's hex codes and, since 2026-11-16 evening (the residue boxes' line of Mathematica), the texts of its code
    elements, given as codes (the harness's codes)."""
    for code in codes:
        text = text.replace(code, ' ')
    return re.findall(r'[A-Za-z]+', re.sub(r'[0-9A-F]{16,}', ' ', re.sub(r'\\\(.*?\\\)', ' ', text)))


def boxes_run(name='boxes'):
    """The boxes run (or another configuration's), with each box's report by its target, as a tuple."""
    R = valid_run(name)
    return R, {tuple(B['target']): B for B in R['boxes']}


def q_cell_box_takes_its_cell_s_color():
    # Replicata: the boxes run (1280 px): a click on each cell of BOX_TARGETS in the m*(n) chart's full view, the pointer
    # then moved off to cell (4, 1); and on the strip of the n labels under column 1024, and on the strip of the m labels
    # left of rows 12, 13 and 16.
    # Expectata ([CEL]: "color-code it to match the cell"; the design of 2026-11-04: "the box's frame or header band in
    # the clicked cell's own color (use the charts' own CSS tokens, not new colors), with a swatch identical to the cell
    # (gold ring included when the cell is ringed)"): each cell's box open, its fragment nNmM, its kind the cell's, its
    # frame the very color of the cell's pixels, its heading led by a swatch of that color, ringed in gold where the
    # cell is ringed (record), and dotted where it is proven the least of its order (proven, a(m − 1)), the swatch of the
    # legend's item whose words follow it; a column's and a row's box framed in ink, its heading without a swatch.
    # Resultata before: each click on a cell opened its column's panel, in a frame of ink whatever the cell, with no
    # swatch; a click on a strip opened nothing.
    # Since 2026-11-11 ([SYC]): a cell red if the Symmetry Conjecture holds (kind ifsym; (480, 14) among the targets) is
    # an open cell with a corner: its frame and its swatch's fill are open's (UNDER), which is its pixel's color three
    # quarters down its middle, and its swatch's classes are its own kind's.
    R, B = boxes_run()
    cols, rings, ifsym = mstar_data()['cols'], smallest_rings(mstar_data()['cols']), mstar_data()['ifsym']
    cells = [t for t in B if None not in t]
    assert len(cells) >= 10, cells
    for n, m in cells:
        P, kind, role = B[(n, m)], kind_of(cols, n, m, ifsym), rings.get((n, m), 0)
        assert not P['hidden'] and P['hash'] == f'#n{n}m{m}' and P['kind'] == kind, (n, m, P['hidden'], P['hash'], P['kind'])
        assert P['own'] == R['tokens'][UNDER[kind]] and P['frame'] == P['own'] and P['swatch']['color'] == P['own'], (n, m, P['own'], P['frame'], P['swatch'])
        assert P['swatch']['cls'] == f"swatch {kind}{['', ' record', ' record', ' record proven'][role]}", (n, m, P['swatch'])
        assert (P['swatch']['ring'] != 'none') == (role > 0), (n, m, P['swatch'])
    assert {rings.get(t, 0) for t in cells} == {0, 1, 2, 3}, 'not every role of ring among the cells clicked'
    assert {kind_of(cols, n, m, ifsym) for n, m in cells} == set(UNDER), 'not every kind of cell among the cells clicked'
    for t in [t for t in B if None in t]:
        P = B[t]
        assert not P['hidden'] and P['kind'] == ('row' if t[0] is None else 'column') and P['frame'] == R['tokens']['rule'], (t, P['kind'], P['frame'])
        assert P['swatch'] is None, (t, P['swatch'])


def q_outline_goes_when_the_mouse_leaves_the_chart():
    # Replicata: the boxes run (1280 px), after the box of (528, 12) is closed: the mouse onto cell (1024, 8), then off the
    # chart (the events a browser sends as a mouse leaves the canvas: pointerout, pointerleave, mouseout, mouseleave);
    # then a click on cell (528, 12), the mouse off the chart again, as on its way to the close button of the box that
    # opened, and a click on that button: after each step, the pixels where that cell's outline goes.
    # Expectata (dreeves, 2026-11-19: "closing the popup box should also remove the black-rim highlighting from the
    # figure. relatedly: when you move the mouse away from the figure, the black-rim highlighting should go away"): the
    # hovered cell is outlined in ink until the mouse leaves the chart, and then not; the clicked cell stays outlined
    # while its box is open, the mouse gone (the box's target, q_box_outline_stays_while_open_and_goes_with_it), and not
    # once its box is closed.
    # Resultata before: the cell read out kept its outline once the mouse had left the chart, and so after its box closed.
    R, _ = boxes_run()
    ink, L = R['tokens']['ink'], R['left']
    assert L['hovered'] == [ink, ink] and L['open'] == [ink, ink], L
    assert ink not in L['left'] and ink not in L['closed'], L


def q_box_outline_stays_while_open_and_goes_with_it():
    # Replicata: the boxes run: each target's box opened by its click, then the pointer moved off to cell (4, 1), so that
    # the cell read out, outlined in ink, is elsewhere; and the box of cell (528, 12), opened again, then closed by its
    # button.
    # Expectata (the design of 2026-11-04: "the clicked cell keeps an outline while its box is open ... Column box: the
    # column is outlined; row box: the row"): while a box is open, the chart's pixels just outside its target are ink: a
    # cell's left and right of it in its row, a column's left of it in rows 1 and 16, a row's above it at the plot's
    # middle and a quarter of the way in; once the box is closed, none of them is.
    # Resultata before: only the cell read out was outlined, so with the pointer off at (4, 1) no target was.
    R, B = boxes_run()
    ink = R['tokens']['ink']
    bad = [(t, P['outline']) for t, P in B.items() if P['outline'] != [ink, ink]]
    assert bad == [], bad
    assert R['closed']['hidden'] and ink not in R['closed']['outline'], R['closed']


def q_box_caret_points_at_its_target():
    # Replicata: the boxes run, each target's box.
    # Expectata (the design of 2026-11-04: "a caret on the box's top edge at the clicked column's x (clamped)"): the
    # middle of the caret on the box's top edge (its ::before, a triangle) within 2 CSS px of the middle of the target's
    # column, for a cell's box and a column's, or of the strip of the m labels, for a row's.
    # Resultata before: no caret.
    R, B = boxes_run()
    bad = [(t, P['caret'], P['column']) for t, P in B.items() if P['caret'] is None or abs(P['caret'] - P['column']) > 2]   # None: no caret
    assert bad == [], bad


def q_green_box_gives_the_witness_and_its_code():
    # Replicata: the boxes run: the boxes of the green cells (1024, 8), (672, 13), (480, 12), (36, 2) and (80, 3); then the
    # box of (1024, 8) again and a click on its code, and the box of (36, 2) and a click on its construction.
    # Expectata ([CEL]: "If the cell is green, just give the partition (expandable hex code) for the highest green cell
    # in that cell's column"): each shows its column's witness alone (box_parts), led by the bound m*(n) >= lo; an
    # example's with its label and a copy of the page's code of length n and order lo (data-join its id, data-order lo),
    # a button with the code's digits, which, clicked, opens in the box the code's partition, its power sums for k = 0
    # to 11, equal below 11 and unequal at 11; a join's or a product's with its construction, a button claiming n:lo,
    # whose derivation, clicked, opens in the box: p_8 and p_28, then the join of length 36 and order 3.
    # Spec change (Opus 5.5, 2026-11-18; dreeves: "there should be no "found here". what does "here" mean? totally
    # ambiguous. show the expandable hex code for everything"): an example's code is mstar.js's, data-code n:lo, a
    # button, whether or not the page shows that code (witness_codes); (16, 4), Thue–Morse's, whose code the page shows
    # nowhere else, among them.  Until then a copy of the page's code alone, so that an example the page did not show,
    # such as Thue–Morse's or BGPW's Table 4's, had its label alone.
    # Spec change (that night, for dreeves's sign-off; his "witnesses are a top-level thing, conceptually" and "making all
    # witnesses conforming sounds great"): a join's or a product's witness shows the code of the sequence it builds too
    # (witness_codes), every witness being (-1)^lo-symmetric; and 36's is the product p_3 # p_12 (each sign of p_12
    # three times), not the join p_8 v p_28, neither symmetric nor antisymmetric, so its derivation's rows are p_3 and
    # p_12, then the product of length 36 and order 3.
    # Resultata before: a click opened the column's panel: the cell's status, both bounds' sentences, and a link to the
    # code, in the list below.
    R, B = boxes_run()
    cols = mstar_data()['cols']
    for t in ((1024, 8), (672, 13), (480, 12), (36, 2), (80, 3), (16, 4)):
        n, m = t
        P, (lo, hi, lw, hw) = B[t], cols[n - 1]
        assert kind_of(cols, n, m) == 'exists' and P['whys'] == box_parts(cols, n, m), (t, P['whys'], box_parts(cols, n, m))
        assert P['said'].startswith(f'\\(m^*({n}) \\ge {lo}\\):') and '“' not in P['said'], (t, P['said'])   # no English to attribute
        assert P['copies'] == witness_codes(mstar_data(), n), (t, P['copies'], witness_codes(mstar_data(), n))
    assert cols[16 - 1][2][0] == 'example' and '16:4' not in code_ids() and B[(16, 4)]['copies'][0][3] == '96', B[(16, 4)]['copies']
    assert B[(1024, 8)]['said'].startswith('\\(m^*(1024) \\ge 11\\): equipow p1024'), B[(1024, 8)]['said']
    assert R['expanded'] == {'expanded': 'true', 'inBox': True, 'shown': True, 'ks': [str(k) for k in range(12)],
                             'relations': ['='] * 11 + ['≠']}, R['expanded']
    assert B[(36, 2)]['constructions'] == [['36:3', 'button', '\\(p_{3} \\mathbin{\\#} p_{12}\\)']], B[(36, 2)]['constructions']
    assert B[(80, 3)]['constructions'] == [['80:6', 'button', '\\(p_{2} \\mathbin{\\#} p_{40}\\)']], B[(80, 3)]['constructions']
    # (Spec change, 2026-11-18, the derivation redone at dreeves's word, "the first table is confusing and looks
    # misaligned": its parts' n and m, its three lines and its own n and m, in place of its rows and its bound)
    assert R['derived'] == {'expanded': 'true', 'inBox': True, 'shown': True, 'parts': [['3', '0'], ['12', '3']],
                            'lines': ['order(p3) = 0, order(p12) = 3', 'length = 3 · 12 = 36', 'order = 0 + 3 = 3'],
                            'claim': ['36', '3']}, R['derived']


def q_a_partition_that_fits_does_not_scroll():
    # 2026-11-18 (Opus 5.5; dreeves, of 36's partition in the appendix: "the partitions have some kind of faint
    # scrollbars and in fact scroll very slightly").
    # Replicata: the light run (1280 px): the appendix opened and the code 12:3 in the entry of 12 clicked (the
    # harness's openAppendix): its partition's two parts, six numbers each, one line, and their boxes' heights, client
    # and scroll (CSS px).
    # Expectata: each part's box, which scrolls only past four and a half lines, as tall as its numbers: no scroll.
    # Resultata before: each scrolled by a pixel, with a faint scrollbar: the line's text stood a pixel below its box.
    T = valid_run('light')['appendixOpened']['twelve']
    assert len(T['heights']) == 2 and all(0 < client == scroll for client, scroll in T['heights']), T['heights']


def q_example_codes_expand_in_the_appendix():
    # Replicata: the light run: the appendix opened, and in the entry of 12 its code 12:3, BGPW's Table 4 example, 12
    # not a multiple of 8, clicked (the harness's openAppendix).
    # Expectata (Opus 5.5, 2026-11-18; dreeves: "show the expandable hex code for everything"): the code is mstar.js's
    # code of 12, two digits, the first 6 bits the left half and the last 2 bits 0, padding, as BGPW's Table 4 pads its
    # codes; it expands into its partition: the positions of +1 and of −1 in the signs that convention gives it, the
    # left half then its mirror times (−1)^3, with power sums equal for k = 0 to 2 and unequal at 3.
    # Resultata before: the entry of 12 had no code, its witness the label BGPW Table 4 alone.
    T = valid_run('light')['appendixOpened']['twelve']
    code = {x: c for x, c, _ in mstar_data()['examples']}[12]
    bits = bin(int(code, 16))[2:].zfill(4 * len(code))
    left = [1 if b == '1' else -1 for b in bits[:6]]
    a = left + [-t for t in reversed(left)]
    assert mstar_data()['cols'][12 - 1][:2] == [3, 3] and len(code) == 2 and bits[6:] == '00', code
    assert T['digits'] == code and T['expanded'] == 'true' and T['shown'], T
    assert T['parts'] == [', '.join(str(i) for i in range(12) if a[i] == s) for s in (1, -1)], (T['parts'], a)
    assert T['ks'] == ['0', '1', '2', '3'] and T['relations'] == ['=', '=', '=', '≠'], T


def q_red_box_works_out_the_proof():
    # Replicata: the boxes run: the boxes of the red cells (1024, 12), the residue condition mod 3; (1020, 4), the 2-adic
    # bound; (56, 6), BGPW's Table 2; and (240, 11), a proof of the page's own.
    # Expectata ([CEL]: "If the cell is red, show the proof for the lowest red cell in that cell's column"): each shows
    # its column's proof alone (box_parts), its bound m*(n) <= hi, worked out with n's numbers: for 1024, the class
    # sizes 342, 341 and 341 and, at m = 12, the condition's closed form with 3^6 = 729 and 3^5 = 243 (mod3_said;
    # since 2026-11-16, when the residue condition mod 3 came before the norm bound, whose numbers they were until
    # then: p = 3, the squares' sum 349,526, and 3^12 = 531,441, more than the floor 524,289:
    # q_panel_works_out_the_mod_3_argument_at_1024 has dreeves's words; since 2026-11-16 evening Stan Wagon's argument,
    # its numbers stan_said, in his words: dreeves's "ok go"); for 1020 = 2^2 * 255, m <= 2^2 - 1 = 3, with BGPW's Theorem 4.1 linked; for 56, BGPW's Table 2,
    # linked; for 240, who proved it, and the remarks' entry of 240 shown in the box, which holds the proof; no witness
    # and no searches.
    # Resultata before: the column's panel, its status sentence, both bounds' sentences and the norm bound's paragraph
    # "below".
    R, B = boxes_run()
    cols = mstar_data()['cols']
    for t, quoted in (((1024, 12), True), ((1020, 4), True), ((56, 6), False), ((240, 11), True)):   # BGPW's, cited, no English
        assert kind_of(cols, *t) == 'impossible' and B[t]['whys'] == box_parts(cols, *t), (t, B[t]['whys'])
        # (Spec change, Opus 5.5, 2026-11-18; dreeves: "so many formatting and other inconsistencies": every part starts with its bound, its quotation after it.)
        said, start = B[t]['said'], f'\\(m^*({t[0]}) \\le {cols[t[0] - 1][1]}\\): '
        assert said.startswith(start) and bool(re.match(re.escape(start) + OPENING, said)) == quoted, (t, said)
    assert cols[1024 - 1][3] == ['residue', 3] and mod3_sums(1024, 12) == [] != mod3_sums(1024, 11) and stan_holds(1024, 12)
    for said in stan_said(1024, 12, '1024'):
        assert among(said, B[(1024, 12)]['said']), (said, B[(1024, 12)]['said'])
    assert '\\(n = 2^{2} \\cdot 255\\)' in B[(1020, 4)]['said'] and '\\(m \\le 2^{2} - 1 = 3\\)' in B[(1020, 4)]['said'], B[(1020, 4)]['said']
    assert 'https://arxiv.org/html/1912.03491v1#S4.Thmthm1' in B[(1020, 4)]['links'], B[(1020, 4)]['links']
    assert TABLE2 in B[(56, 6)]['links'], B[(56, 6)]
    assert legend_labels(page())[cols[240 - 1][3][1]] in B[(240, 11)]['said'] and B[(240, 11)]['entries'] == ['entry-240'], B[(240, 11)]
    assert all(B[t]['entries'] == [] for t in ((1024, 12), (1020, 4), (56, 6))), [B[t]['entries'] for t in B]


def q_black_box_shows_both_bounds_and_the_searches():
    # Replicata: the boxes run, with BOX_PROGRESS as progress.js: two runs at 528:12, PROGRESS_CAMPAIGN, a tracked
    # search that a campaign runs, with its odds, and an overnight_v5.py run, aborted; and one at 64:7.  The box of the
    # black cell (528, 12), once its searches had loaded (searched); and the boxes of the black cells (480, 13).
    # Expectata ([CEL]: "If the cell is black... maybe just summarize the search efforts so far?"; the design of
    # 2026-11-04: "the two bracketing facts in compact form (the order-lo witness, the order hi + 1 proof), plus the
    # search efforts"): each shows its column's witness and proof (box_parts) and then its searches: the heading of the
    # Search progress section, and below it each run of that section at the cell's n and m, its question, program and
    # state as that section's fold names them, with its time so far, and then its status line as that section states
    # it (the campaign's 0.2 h so far + 0.0–3.2 h to go = 0.2–3.3 h and its finish times, the other's 2.0 h of running);
    # nothing of 64:7; for (480, 13), with no run, a dash.
    # Spec change (Claude, 2026-11-06; dreeves: "everything here seems useless, kill it unless you have a good argument
    # for salvaging anything. the up-to-date probability that a bipartition exists is great."; the coordinator: "Make
    # every other run brief its status line (time so far + to go)"): each run's status line, in place of the campaign's
    # chance line (within 6 h 0.91%, within 24 h 2.8%, 2.1 CPU-hours) and nothing for the other run.
    # Resultata before: the column's panel, with its status sentence and no searches.
    # Spec change (Claude, 2026-11-07; dreeves: "1. show elapsed time with full granularity like so: 3d 4h 5m 6s ... 3. no
    # need for the "so far" ... 4. sane number of sigfigs for everything else based in a principled way on the amount of
    # uncertainty"): the times so far 10m 0s and 2h 0m 0s, with no "so far", and the campaign's figures to its band's
    # uncertainty, half its width, 1.58 h: 0–3 h to go, 0–3 h in all, and its finish times to the hour.
    R, B = boxes_run()
    cols = mstar_data()['cols']
    S = R['searched']
    # (Spec change, Opus 5.5, 2026-11-18, dreeves's point 10: 528's code in its witness's part, on its line, not a part
    # of its own, witness-code.)
    assert S['whys'] == box_parts(cols, 528, 12) == ['witness-example', 'proof-residue', 'searches'], S['whys']
    assert S['copies'] == witness_codes(mstar_data(), 528), S['copies']
    assert S['said'].startswith('\\(m^*(528) \\ge 11\\): equipow p528') and S['said'].endswith('”'), S['said']
    assert '\\(m^*(528) \\le 12\\):' in S['said'] and '\\(M = 5\\)' in S['said'], S['said']
    made, to_go = BOX_PROGRESS['made'], PROGRESS_CAMPAIGN['to_go']
    status = f'10m 0s + 0–3 h to go = 0–3 h ({finish(made, made + to_go["lo"], made + to_go["hi"], (to_go["hi"] - to_go["lo"]) / 2)})'
    assert [figures(t) for t in S['searches']] == [figures(f'Search progress m*(528) ≥ 12? probe_seed.py running 10m 0s {status} m*(528) ≥ 12? '
                                                           'overnight_v5.py aborted 2h 0m 0s Aborted after running for 2h 0m 0s.')], S['searches']
    # Since 2026-11-13 (480:13 is red if the Symmetry Conjecture holds, by the kept proof cells/480_13_antisym): the
    # parts of (480, 13)'s box are those of such a cell (box_parts with the data's ifsym), its searches as before.
    assert B[(480, 13)]['whys'] == box_parts(cols, 480, 13, mstar_data()['ifsym']) and [figures(t) for t in B[(480, 13)]['searches']] == ['—'], B[(480, 13)]


def q_column_box_opens_from_its_n_label():
    # Replicata: the boxes run: a click on the strip of the n labels under column 1024, 10 CSS px below the plot.
    # Expectata ([ROC]: "allow clicking the column number ... For a column, the info box would explain the known bounds
    # for that value of n -- both the witness for the highest green cell in the column and the proof for the lowest red
    # cell"): the box of the column opens, its fragment n1024, its heading n and m*(1024) = 11, its parts the witness and
    # the proof (box_parts: no copy of 1024:11, whose own code its entry shows) and the remarks' entry of 1024.
    # Resultata before: nothing opened.
    R, B = boxes_run()
    P = B[(1024, None)]
    assert not P['hidden'] and P['hash'] == '#n1024' and P['focus'] and P['kind'] == 'column', P
    assert P['heading'] == '\\(n = 1024\\): \\(m^*(1024) = 11\\)' and P['whys'] == box_parts(mstar_data()['cols'], 1024), (P['heading'], P['whys'])
    assert P['entries'] == ['entry-1024'] and P['copies'] == [], (P['entries'], P['copies'])


def q_symmetry_table_and_the_exact_cutoff_explanation_link_to_each_other():
    # Replicata: start at Table 6's new E_m column or at the exact-cutoffs fragment.
    # Expectata: the column leads to the definition, and the explanation leads to the table.
    # Resultata before: Table 6 had no E_m column. The explanation had a second lookup table.
    source = blank_comments(page())
    table = source.split('id="symmetry-table"', 1)[1].split('</table>', 1)[0]
    header = table.split('<thead>', 1)[1].split('</thead>', 1)[0]
    cells = re.findall(r'<th\b[^>]*>(.*?)</th>', header, re.S)
    assert len(cells) == 3, cells
    definition, = re.findall(r'<a\b[^>]*href="#([^"]+)"[^>]*>', cells[2])
    assert re.search(rf'<dfn\b[^>]*id="{re.escape(definition)}"[^>]*>[^<]*E_m', source), cells[2]
    explanation = source.split('id="exact-cutoffs"', 1)[1].split('<h4', 1)[0]
    assert 'href="#symmetry-table"' in explanation


def q_symmetry_table_fits_a_narrow_phone():
    # Replicata: render Table 6 at 320 CSS pixels, including its formulas and longest cutoff.
    # Expectata: all three columns fit inside the section's text area.
    # Resultata before: the table was 338 pixels wide in a 288-pixel text area.
    left, right, section_left, section_right, formulas = framed(320, """
  await document.fonts.ready;
  const table = document.getElementById('symmetry-table').closest('table');
  const r = table.getBoundingClientRect(), s = table.parentElement.getBoundingClientRect();
  parent.postMessage(JSON.stringify([r.left, r.right, s.left, s.right,
    table.querySelectorAll('.katex').length]), '*');""")
    assert formulas and section_left - 0.5 <= left < right <= section_right + 0.5, (left, right, section_left, section_right, formulas)


def q_row_box_is_its_row_of_the_smallest_lengths():
    # Replicata: the boxes run: clicks on the strip of the m labels, left of the plot, at rows 12, 13 and 16; and the
    # page's own table of smallest lengths and its Table 5, as drawn.
    # Expectata ([ROC]: "For a row, it would be like a row in [the table of smallest lengths], giving the smallest n not
    # ruled out and the smallest known n, mention the A323395 sequence"): the box of the row opens, its fragment mM,
    # its heading m = M; its first part a table, that table's head and its row for the order M, as the page's table
    # has them, and the term a(M − 1) of OEIS A323395, linked, the order's smallest length: a(11) = 480, proven; 480 <=
    # a(12) <= 672; a(15) = 1440, proven.
    # Spec change (Opus 5.5, 2026-11-18; dreeves: "clicking the m for a whole row in a chart should gather up all the
    # relevant things for that row, including what we know conditional on the symmetry conjecture being true", and of
    # the design: "for the rows: i think that's right, if you can't think of anything else relevant"): then the term
    # a(M − 1) if BGPW's Symmetry Conjecture holds, after a link to the conjecture's section (the chart's upper bounds
    # lowered where mstar.js's ifsym lowers them: a(12) = 672); Table 5's head and its row of the order M, the last
    # whose first order is at most M, its caption a link to it; and each open cell of the row, above its column's lower
    # bound and at or below its upper bound, in order of n: its swatch, of its kind (ifsym, red if the conjecture holds,
    # where it is) and gold ring, as its own box's heading has it, and n, linked to its box.  Until then the first part
    # alone.  Spec change (that night; dreeves: "for the box when it's quoting table 5, can we have the following
    # webcopy, using m=13 as an example: The Symmetry Conjecture is proven to hold for n>=3665. "proven" can be an
    # anchor link to the proof ... i think the above sentence can be instead of that"): in place of Table 5's head and
    # row, a sentence that ends with that row's N, its link the proof that the row names (data-proof: the Symmetry
    # section's first quote, symsmall, through order 14; Fable 5.2's proof, symlarge, from 15).  Spec change (later that
    # night; dreeves's README, [SOG]: "It should be clearer that that's specific to the order. So like this: For order 13,
    # the Symmetry Conjecture is proven to hold for n>=3665."): the sentence names the row's order M first.
    # Resultata before: nothing opened.
    R, B = boxes_run()
    table, table5, data = R['table3'], R['table5'], mstar_data()
    cols = data['cols']
    firsts = [int(re.search(r'\d+', row[0])[0]) for row in table5[1:]]
    assert firsts[0] == 1 and firsts == sorted(set(firsts)), firsts         # the orders of Table 5's rows, from 1 up
    # each row's proof: the first quote of the Symmetry section through order 14, Fable 5.2's proof from 15 (2026-11-18)
    # The constructive thresholds (2026-11-26, dreeves: "get all that on the page") have their own linked proofs.
    # 2026-11-30: dreeves approved adding E_m. The box still cites N's proof from the second column.
    # 2026-12-02 (Opus 5.5): order 16's row cites the center calculation, symcenters, whose centers of order 16 gave
    # 20033 that day (sym15, the transport proof's 21473, until then).
    proofs = (dict.fromkeys(range(1, 15), 'symsmall') | dict.fromkeys((15,), 'sym15')
              | dict.fromkeys(range(16, 20), 'symcenters') | dict.fromkeys(range(20, 32), 'cutoff-reflection')
              | {32: 'uniform-base'})
    assert R['table5proofs'] == [proofs[first] for first in firsts], R['table5proofs']
    for m, term, ifterm in ((12, '\\(a(11) = 480\\)', '\\(a(11) = 480\\)'), (13, '\\(480 \\le a(12) \\le 672\\)', '\\(a(12) = 672\\)'),
                            (16, '\\(a(15) = 1440\\)', '\\(a(15) = 1440\\)')):
        P = B[(None, m)]
        opened = [n for n in range(1, DATA_NMAX + 1) if cols[n - 1][0] < m <= cols[n - 1][1]]
        five = [row for row, first in zip(table5[1:], firsts) if first <= m][-1]
        assert not P['hidden'] and P['hash'] == f'#m{m}' and P['kind'] == 'row' and P['heading'] == f'\\(m = {m}\\)', (m, P)
        assert P['whys'] == ['row-smallest', 'row-ifsym', 'row-symmetry'] + ['row-cell'] * len(opened), (m, P['whys'], opened)
        proof = [p for p, first in zip(R['table5proofs'], firsts) if first <= m][-1]
        assert P['tables'] == [[table[0], table[m]]], (m, P['tables'], table[0], table[m])
        said = {why: t for why, t, _ in P['parts']}
        assert said['row-smallest'].endswith(f'A323395: {term}') and said['row-ifsym'].endswith(ifterm), (m, said)
        assert figures(said['row-symmetry']) == figures(f'{m}, \\(n \\ge\\) {five[1]}.'), (m, said['row-symmetry'], five)   # M, then n >= N, N Table 5's
        assert P['links'] == ['https://oeis.org/A323395', '#symmetry-title', f'#{proof}'] + [f'#n{n}m{m}' for n in opened], (m, P['links'])
        assert [(cls.split()[1], href) for cls, href in P['cells']] == [(kind_of(cols, n, m, data['ifsym']), f'#n{n}m{m}') for n in opened], (m, P['cells'])
    # (Spec change, Opus 5.5, 2026-11-29; dreeves, of a cap at 4096: "worth it": the row's open cells go on past 2048, where the loop above holds the box's list to the chart's, so here
    # those up to 2048, 480 and 864, as they were; Astra's review that night: until 2026-11-29 the line held only those, all there were, and for some hours that evening the first alone.)
    assert [n for n in range(1, CAP + 1) if cols[n - 1][0] < 13 <= cols[n - 1][1]] == [480, 864], 'the open cells of row 13 up to 2048'
    assert B[(None, 13)]['cells'][0] == [B[(480, 13)]['swatch']['cls'], '#n480m13'] and B[(480, 13)]['swatch']['cls'] == 'swatch ifsym record', B[(None, 13)]['cells']


def q_row_box_tables_look_as_their_tables_do():
    # Replicata: the boxes run: the boxes of the rows 12, 13 and 16 of the m*(n) chart; and the page's own table of
    # smallest lengths and its Table 5, as drawn (the harness's look of each).
    # Expectata (dreeves, 2026-11-18, of the box of row 15 with Table 5's row unruled and stretched across the box:
    # "this box looks terrible. i guess the borders for table 5 are missing? got quals for that?"): each table of a row's
    # box looks as the page's table it is a row of: its borders collapsed, it set at the start of its grid, its head's
    # and its body's cells ruled, padded, aligned and weighted alike, the first the table of smallest lengths' and the
    # second Table 5's.  Spec change (later that night; dreeves: "i think the above sentence can be instead of that"):
    # Table 5's row gave way to his sentence (q_row_box_is_its_row_of_the_smallest_lengths), so the box has one table.
    # Resultata before: Table 5's row in the box had no rules, and spread across the box's width.
    R, B = boxes_run()
    for m in (12, 13, 16):
        assert B[(None, m)]['looks'] == [R['looks']['smallest']], (m, B[(None, m)]['looks'], R['looks'])
    assert R['looks']['symmetry'][2][1] == 'solid' and R['looks']['symmetry'][1] == 'start', R['looks']


def q_boxes_word_a_credit_as_the_legend_does():
    # Replicata: a copy of the page reworded (reworded: the titles of the new results' cells and the labels of their
    # legend, each word's letters reversed), beside the real page/, mstar.js and pow2.js, loaded at #n240m11: the box of
    # the cell (240, 11), whose upper bound mstar.js cites from the page, ["page", who].
    # Expectata (dreeves, 2026-11-09: "probably yes to the decoupling"): the box opens, and its proof's part names the
    # credit by the reworded label of the legend's item of the cell's class, which is no label of the real page.  So a
    # credit is renamed on the page alone: mstar.py, mstar.js, the scripts and the quals hold none of its words.
    # Spec change (Opus 5.5, 2026-11-18): every length's entry in the appendix holds its facts, each marked with its
    # length (data-n), so the page names a credit wherever a length's bound is the page's own; the words looked at are
    # those of the box's own parts, the parts with no data-n.
    # Resultata before: the box named the credit by mstar.js's words, the real page's label, whatever the legend said.
    text = page()
    [cls] = re.findall(r'<td class="(\w+)" title=\'[^\']*\'>240</td>', text)
    assert mstar_data()['cols'][240 - 1][3] == ['page', cls], mstar_data()['cols'][240 - 1]
    d = tempfile.mkdtemp(prefix='index-quals-')
    try:
        open(os.path.join(d, 'index.html'), 'w', encoding='utf-8').write(reworded(text))
        copy_page_dir(d)
        for src, name in ((DATA, 'mstar.js'), (POW2, 'pow2.js')): shutil.copy(src, data_file(d, name))
        dom = chrome(d, ['--window-size=1280,1000', '--virtual-time-budget=10000', '--dump-dom',
                         'file://' + os.path.join(d, 'index.html') + '#n240m11'])
    finally:
        shutil.rmtree(d)
    said = [w for w in re.findall(r'<div data-why="(?:witness|proof)-page"(?![^>]*data-n=)[^>]*>.*?<span data-slot="who">([^<]*)</span>', dom, re.S) if w]
    want = legend_labels(reworded(text))[cls]
    assert said == [html.unescape(want)] and want not in legend_labels(text).values(), (said, want)


def q_box_fragments_name_cells_and_rows():
    # Replicata: the page loaded with the fragment #n1024m12 (the box fragment run); and, in the boxes run, the fragment
    # set to #m16 and then to #n1024m12.
    # Expectata (the design of 2026-11-04, as of 2026-11-03 for a column's: every box has a fragment, which opens it as
    # the page loads or moves to it): the box of cell (1024, 12) open at load, its heading focused, red, its proof; the
    # box of row 16 after #m16; the box of cell (1024, 12) again after #n1024m12.
    # Resultata before: only a column's fragment opened anything.
    F = valid_run('box fragment')['atLoad']
    # (proof-norm until 2026-11-16, then proof-residue until that evening, when Stan Wagon's words took the box, and
    # then his check of all pairs in Mathematica after them, until 2026-11-18, when his shorter proof took the box
    # alone: box_parts)
    assert not F['hidden'] and F['hash'] == '#n1024m12' and F['focus'] and F['kind'] == 'impossible' and F['whys'] == ['proof-stan'], F
    R, _ = boxes_run()
    row, cell = R['hashed']
    assert not row['hidden'] and row['kind'] == 'row' and row['heading'] == '\\(m = 16\\)', row
    assert not cell['hidden'] and cell['kind'] == 'impossible' and cell['whys'] == ['proof-stan'] and cell['hash'] == '#n1024m12', cell


def q_boxes_say_nothing_about_elsewhere():
    # Replicata: the boxes' templates in index.html, and the parts of Claude's words in every box of the boxes run and
    # in every column's box of the panels run.
    # Expectata (dreeves, 2026-11-03: "we want everything to appear in this box -- the box shouldn't ever refer to
    # "remarks below""; the design of 2026-11-04: "No box refers to anything outside itself ("below", "above", "on this
    # page", "the paragraph on ...")"): none of them says below, above, this page, paragraph or remarks.
    # Resultata before: the norm bound's sentence said "the paragraph on the norm bound below derives it", and others
    # "at the top of this page" and "the new results above".
    elsewhere = re.compile(r'\b(?:below|above|this page|paragraph|remarks)\b', re.I)
    templates = re.findall(r'<template data-panel="([^"]+)"[^>]*>(.*?)</template>', page(), re.S)
    assert len(templates) >= 14 and [t for t, body in templates if elsewhere.search(body)] == [], templates
    said = [(P['target'], P['said']) for P in valid_run('boxes')['boxes']]
    said += [(P['n'], text) for P in valid_run('panels')['panels'] for why, text, _ in P['parts'] if why.startswith(('witness', 'proof'))]
    assert [(t, s) for t, s in said if elsewhere.search(s)] == [], [(t, s) for t, s in said if elsewhere.search(s)][:3]


def quoted_right(parts):
    """Whether a box's parts, [(kind, text, whether of Claude's English)], quote Claude once around its parts of Claude's
    English, from the start of the first to the end of the last, and not at all without any.  Spec change (Claude,
    2026-11-05): a box's searches, its copy of the Search progress section's runs, are left out, since they carry that
    section's own quotations (Astra's in the chance line, from 2026-11-05 until that line went on 2026-11-06), as the
    word budget leaves them out.  Spec change (2026-11-16 evening; dreeves: "ok go" to Stan Wagon's words in the boxes
    where his argument holds, which carry his name): a box's part proof-stan, his quotation, is left out too.  And
    (later that evening; "yeah, add the mathematica line" after his words, a part of Claude's English) his part ends
    a run: the parts before it and those after it each quote Claude once, as above, so that no quote of Claude's holds
    his; a box without his part is one run, as before."""
    runs = [[]]
    for p in parts:
        if p[0] == 'proof-stan': runs.append([])
        elif p[0] != 'searches': runs[-1].append(p)
    return all(quoted_run_right(run) for run in runs)


def quoted_run_right(parts):
    """Whether parts, [(kind, text, whether of Claude's English)], quote Claude once around their parts of Claude's
    English, from the start of the first to the end of the last, and not at all without any (quoted_right's runs)."""
    claude, text = [i for i, (_, _, c) in enumerate(parts) if c], ''.join(t for _, t, _ in parts)
    return (text.count('“') == text.count('”') == min(1, len(claude))   # (the opening after the bound since 2026-11-18)
            and all(re.match(BOUND + OPENING, parts[i][1]) for i in claude[:1]) and all(parts[i][1].endswith('”') for i in claude[-1:]))


def q_box_quotes_claude_around_its_english_alone():
    # Replicata: index.html's boxes' templates; every box of the boxes run, and every column's box of the panels run.
    # Expectata (dreeves, 2026-11-04, of «Claude: “m*(480) ≥ 12: equipow p480 <code>”»: "we don't need claude
    # attribution for blurbs without words like these"; the design of 2026-11-04: "every generated English word sits
    # under one Claude attribution per box ... with a TODO comment above each template giving a recap of what the copy
    # conveys"): the templates marked data-claude are exactly CLAUDE_TEMPLATES, each with a TODO recap right above it,
    # and no other template has a TODO recap; a box's parts of those (data-claude) sit in one quote, its Claude: “ at
    # the start of the first and its ” at the end of the last, where it has any, and a box with none has no quote.
    # Resultata before: every box had Claude: “ … ” around all of its witness's and its proof's parts, those of math,
    # codes and labels alone too, such as 480's “m*(480) ≥ 12: equipow p480 <code>”.
    templates = re.findall(r'(<!--(?:(?!-->).)*-->)\n  <template data-panel="([^"]+)"( data-claude)?>', page(), re.S)
    assert len(templates) == len(re.findall(r'<template data-panel=', page())) >= 14, len(templates)
    assert {name for _, name, claude in templates if claude} == CLAUDE_TEMPLATES, [(name, claude) for _, name, claude in templates]
    # Spec change (2026-11-09): no longer that each of those templates, and no other, has a TODO recap right above it:
    # dreeves took the "TODO:" off those comments in his commit b5ce25c, and the comments are his to word.
    boxes = [(P['target'], P['parts']) for P in valid_run('boxes')['boxes']] + [(P['n'], P['parts']) for P in valid_run('panels')['panels']]
    bad = [(t, parts) for t, parts in boxes if not quoted_right(parts)]
    assert bad == [], bad[:3]
    assert {bool(sum(c for _, _, c in parts)) for _, parts in boxes} == {True, False}, 'boxes with and without English'


def q_legend_has_an_item_for_every_kind_of_cell():
    # Replicata: the legend of the m*(n) chart's section; mstar.js and the made-up data; the kinds panels run's boxes.
    # Expectata (dreeves, 2026-11-11, of a cell that is ringed in gold and also red if the Symmetry Conjecture holds:
    # "can we just have a legend entry for every combination?"): the legend's swatches are, in order, a cell's four
    # kinds, exists, open, ifsym and impossible, and then each kind that a gold ring can be on, with its ring: exists
    # (the smallest n known for its m), open and ifsym (the smallest n not ruled out), and exists proven the least,
    # dotted.  Those are all the combinations a cell can be: a ring of role 1 or 3 is on a cell at or below its
    # column's lower bound, one of role 2 on a cell above it and at or below its upper bound, which is open or ifsym.
    # And every cell of the real chart and of the made-up one is one of them.
    # Resultata before: six items, none for ifsym, which no cell was.
    legend = re.search(r'<ul class="legend">(.*?)</ul>', section(), re.S).group(1)
    want = ['swatch exists', 'swatch open', 'swatch ifsym', 'swatch impossible', 'swatch exists record', 'swatch open record',
            'swatch ifsym record', 'swatch exists record proven']
    assert re.findall(r'<span class="(swatch[^"]*)" aria-hidden="true">', legend) == want, re.findall(r'<span class="(swatch[^"]*)"', legend)
    assert legend.count('<li>') == len(want) and all(re.search(r'<li><span class="swatch[^"]*" aria-hidden="true"></span>\s*\S', x)
                                                     for x in legend.split('</li>')[:-1]), legend       # each with words after its swatch
    suffix = ['', ' record', ' record', ' record proven']
    seen = set()
    for data in (mstar_data(), json.loads(kinds_data()[len('const MSTAR = '):-2])):
        rings = smallest_rings(data['cols'])
        for n in range(1, len(data['cols']) + 1):
            for m in range(1, data['mtop'] + 1):
                seen.add(f"swatch {kind_of(data['cols'], n, m, data['ifsym'])}{suffix[rings.get((n, m), 0)]}")
    assert seen == set(want), (seen - set(want), set(want) - seen)


def q_ifsym_cells_are_open_with_an_impossible_corner():
    # Replicata: the light run (the real chart, whose ifsym is [[480, 12, ...]] since 2026-11-13: the cells (480, 13) and
    # (480, 14), both ringed; [[480, 13, ...]] and (480, 14) alone until then) and the
    # kinds run (made-up: (24, 5), ringed, and (48, 7), not ringed): the harness's checks of every cell's pixels down
    # its middle column, zoomed in, and of every ringed cell's.
    # Expectata (dreeves's README, [SYC]: "a different styling on the chart (like striped or half-and-half black vs
    # red, split diagonally) for cells for which we know they're red conditional on the Symmetry Conjecture being
    # true"; the prototype he saw, scratch/syc-20261111): such a cell is an open cell with its upper right triangle in
    # the color of an impossible one, so down its middle column it is impossible a quarter of the way down and open
    # three quarters down, under any gold ring it has; no check of either run finds another color, and each run's
    # checks fell on such a cell.
    # Resultata before: every cell was of one color; with the data's ifsym in place and the page as it was, the cell
    # (480, 14) was open all over.
    for name, least in (('light', 1), ('kinds', 2)):
        R = valid_run(name)
        assert R['pixelBad'] == [] and R['ringBad'] == [], (name, R['pixelBad'][:5], R['ringBad'][:5])
        assert R['ifsymChecks'] >= least, (name, R['ifsymChecks'])


def q_box_of_a_cell_red_if_the_conjecture_holds():
    # Replicata: the boxes run: a click on the cell (480, 14), which mstar.js's ifsym makes red if BGPW's Symmetry
    # Conjecture holds (m*(480) <= 13 then, by the kept proof that no symmetric sequence of length 480 has order 14).
    # Expectata: its box is a black cell's (the witness of the lower bound 12, the proof of the upper bound 14, the
    # searches) with one more part after the proof, proof-ifsym: the bound m*(480) <= 13, the conjecture named and
    # linked to the page's section on it, and the program that checks the proof, linked, a file of the repository; no
    # English of a model's in that part.  Its kind is ifsym, its fragment n480m14, its swatch the legend's item for a
    # ringed ifsym cell.  The readout of that cell, hovered, says so too and names the program.
    # Resultata before: the cell was open and its box a black cell's.
    # Spec change (Fable 5.2, 2026-11-13: the antisymmetric search at 480:13 closed, and its proof is kept as
    # searches/formtree/cells/480_13_antisym): mstar.js's ifsym is [[480, 12, ...]], so the cell (480, 13) is of that
    # kind too, and each of the two boxes states m*(480) <= 12 in its part proof-ifsym.  The cell below them, (480, 12),
    # is green, and its box and readout have nothing of the conjecture.  Until then: ifsym [[480, 13, ...]], the
    # bound m*(480) <= 13 in the box of (480, 14), and (480, 13) open, with no such part.
    # Spec change (Opus 5.5, 2026-11-17: the unconditional form tree at 480:14 closed, kept as
    # searches/formtree/cells/480_14; quals_mstar's q_kept_form_trees_bound_the_chart): the column is 12 to 13, so the
    # cell (480, 14) is impossible with no conjecture and its box has no part proof-ifsym, nor does its readout name the
    # program; (480, 13) alone is of the kind, its box stating m*(480) <= 12 if the conjecture holds and the chart's
    # m*(480) <= 13.  Until then both cells were of the kind, their boxes stating the chart's m*(480) <= 14.
    R, B = boxes_run()
    data = mstar_data(); cols, ifsym = data['cols'], data['ifsym']
    assert ifsym == [[480, 12, IFSYM_FILE]] and [kind_of(cols, 480, m, ifsym) for m in (12, 13, 14, 15)] == ['exists', 'ifsym', 'impossible', 'impossible'], ifsym
    for m in (13,):
        P = B[(480, m)]
        assert not P['hidden'] and P['hash'] == f'#n480m{m}' and P['kind'] == 'ifsym', (m, P['hidden'], P['hash'], P['kind'])
        assert P['whys'] == box_parts(cols, 480, m, ifsym) and P['whys'][-2:] == ['proof-ifsym', 'searches'], (m, P['whys'])
        assert '\\(m^*(480) \\le 12\\)' in P['said'] and '\\(m^*(480) \\le 13\\)' in P['said'] and '\\(m^*(480) \\ge 12\\)' in P['said'], (m, P['said'])
        files = [href for href in P['links'] if href.endswith('/' + IFSYM_FILE)]
        assert files and all(panel_link_lands(href) for href in files), (m, P['links'])        # the program: a file of the repository that is here
        assert '#symmetry-title' in P['links'] and page().count('id="symmetry-title"') == 1, (m, P['links'])   # the conjecture's section: an anchor of the page
        assert P['swatch']['cls'] == 'swatch ifsym record', (m, P['swatch'])
    assert [(B[(480, m)]['kind'], 'proof-ifsym' in B[(480, m)]['whys']) for m in (12, 14)] == [('exists', False), ('impossible', False)], [B[(480, m)]['whys'] for m in (12, 14)]
    hovers = valid_run('light')['hovers']
    hovered = [(m, t) for n, m, t in hovers if n == 480 and m in (12, 13, 14)]
    assert {m for m, _ in hovered} == {12, 13, 14} and {m for m, t in hovered if IFSYM_FILE in t} == {13}, hovered


def q_cell_box_words_stay_within_budget():
    # Replicata: the boxes run's boxes of cells, the text of their parts but their searches (which are the Search
    # progress section's); and every column's box of the m*(n) chart (the panels run), its witness's and its proof's
    # parts, a cell's box of its column showing its witness, its proof, or both (a black cell's).
    # Expectata (dreeves, 2026-11-03: "so many pointless words in the implementation so far"; spec, Claude's proposal of
    # 2026-11-04 for dreeves to review): a cell's box has at most BOX_WORDS, 24, words outside its math, codes and
    # numbers (words), the attribution "Claude", where it has one, and the data's labels among them; the most on
    # 2026-11-04, 19, is a black cell's at 480, 528 and 720, an example's label and the residue condition's proof.
    # Resultata before: the panel that a click on (1024, 12) opened had 121 such words (scratch/reo-step3-20261103/red/).
    # Spec change (2026-11-16 evening; dreeves: "ok go" to a line of Mathematica in the residue boxes of the modulus 3
    # and Stan Wagon's words in those his argument settles, both proposed with this change): the words of a box's code
    # elements are not counted (words' codes), which the budget's "codes" already meant of the hex codes, and nor are
    # Stan's, his part proof-stan, a person's words and not Claude's English, as its searches are not.  The line alone
    # has 12 runs of letters (Select, Tuples, …), which took the box of (1024, 12) to 27.
    cols, most = mstar_data()['cols'], []
    for P in valid_run('panels')['panels']:
        n, parts = P['n'], P['parts']
        lo, hi = cols[n - 1][:2]
        text = {k: ' '.join(unquoted(t) for why, t, _ in parts if why.startswith(k) and why != 'proof-stan') for k in ('witness', 'proof')}
        claude = {k: any(c for why, _, c in parts if why.startswith(k)) for k in ('witness', 'proof')}
        for kind in [k for k, present in (('exists', lo >= 1), ('open', hi > lo), ('impossible', hi < mstar_data()['mtop'])) if present]:
            shows = SHOWS[kind]                    # the attribution, Claude, is a word where the box has one
            count = ((claude['witness'] and shows[0]) or (claude['proof'] and shows[1])) + len(words(text['witness'], P['codes'])) * shows[0] + len(words(text['proof'], P['codes'])) * shows[1]
            most.append((count, n, kind))
    most += [(len(words(' '.join(text for why, text, _ in P['parts'] if why not in ('searches', 'proof-stan')), P['codes'])), tuple(P['target']), 'clicked')
             for P in valid_run('boxes')['boxes'] if None not in P['target']]
    assert max(c for c, *_ in most) <= BOX_WORDS, sorted(most, key=lambda x: x[0])[-5:]


# ---------------------------------------------------------------------------------------------------------------------
# The section "Search progress" (dreeves, 2026-10-17: "make it a collapsible section of index.html -- no separate
# progress page -- and have it do something less crude than reloading the page every minute"), which draws
# progress.py's data file, progress.js (its contract: progress.js_text).

STATUSES = ('settled', 'open', 'split', 'pending', 'running')
# a run's odds as progress.js gives them for a run with no model of its search (progress.py's run_data, 2026-11-06:
# IGNORANT's prior with no history; dreeves: "go with 50% as the ignorant prior when there's no model or whatever"),
# which every made-up run without odds of its own carries, as every real one does since then
ODDS_IGNORANT = dict(prior=0.5, since=None, exists=[])
# made-up data: one running run, three groups, every status, three recorded ETAs an hour apart, and the odds of a run with
# no model of its search
PROGRESS_DATA = {'made': 1792200000, 'runs': [{
    'program': 'overnight_v5.py', 'n': 64, 'order': 7, 'state': 'running', 'outcome': None, 'so_far': 7200.0, 'to_go': {'median': 3600.0, 'lo': 1800.0, 'hi': 10800.0},
    'etas': [[1792192800, 0.0, 10800.0, 7200.0, 14400.0], [1792196400, 3600.0, 7200.0, 3600.0, 10800.0],
             [1792200000, 7200.0, 3600.0, 1800.0, 10800.0]],
    'statuses': list(STATUSES), 'depth': 1, 'keys': ['3:[0,0,3]', '3:[1,1,1]', '3:[2,1,0]'],
    'groups': ['0123', '4', '00110'], 'counts': {'settled': 4, 'open': 3, 'split': 1, 'pending': 1, 'running': 1},
    'odds': ODDS_IGNORANT,
    # its CPU (2026-11-07): the search, other processes and idle over its first hour of running and its second, beside
    # its ETA records at 0, 1 and 2 h
    'cpu': [[0.0, 1.0, 1792196400, 0.5, 0.3, 0.2], [1.0, 2.0, 1792200000, 0.25, 0.25, 0.5]]}]}
# progress.html's ETA chart case (quals_progress.eta_chart_case): 13.2 h of running, ended, ETAs of [2, 1, 4] h at
# its start and [1, 0.5, 3] h at its end
PROGRESS_ETA_DATA = {'made': 1792200000, 'runs': [dict(PROGRESS_DATA['runs'][0], state='ended', so_far=47520.0, to_go=None,
                                                       etas=[[1792100000, 0.0, 7200.0, 3600.0, 14400.0],
                                                             [1792192160, 47520.0, 3600.0, 1800.0, 10800.0]])]}
# two runs, the second the first as boxsplit.py's pass with no ETA recorded yet (dreeves, 2026-10-17: a second block for
# 240@11's boxsplit pass)
PROGRESS_TWO = {'made': 1792200000, 'runs': [PROGRESS_DATA['runs'][0], dict(PROGRESS_DATA['runs'][0], program='boxsplit.py', to_go=None, etas=[])]}
# two long runs (dreeves, 2026-10-23: "this would be more helpful as days or years when over like 48 or maybe 72h, and
# the parenthetical needs disambiguation when >1week"): 480:14's of that day, 14.2 h so far and 3596.5–56401.4 h to go
# (median 7500 h), its last two ETAs an hour apart; and a run 100 h along with 0.5–3.0 h to go
HOURS = 3600.0
PROGRESS_LONG = {'made': 1792200000, 'runs': [
    dict(PROGRESS_DATA['runs'][0], so_far=14.2 * HOURS, to_go={'median': 7500 * HOURS, 'lo': 3596.5 * HOURS, 'hi': 56401.4 * HOURS},
         etas=[[1792196400, 13.2 * HOURS, 7400 * HOURS, 3550 * HOURS, 55000 * HOURS],
               [1792200000, 14.2 * HOURS, 7500 * HOURS, 3596.5 * HOURS, 56401.4 * HOURS]]),
    dict(PROGRESS_DATA['runs'][0], so_far=100 * HOURS, to_go={'median': 1 * HOURS, 'lo': 0.5 * HOURS, 'hi': 3 * HOURS},
         etas=[[1792196400, 99 * HOURS, 2 * HOURS, 1 * HOURS, 4 * HOURS], [1792200000, 100 * HOURS, 1 * HOURS, 0.5 * HOURS, 3 * HOURS]])]}
# a run whose band stays within the y axis's cap (2026-10-23): 10 h so far and 1.5–2.5 h to go (median 2 h), so the
# projected finish is 12 h and the cap 13.2 h, above elapsed + ETA's band top, 12.5 h
PROGRESS_NARROW = {'made': 1792200000, 'runs': [dict(PROGRESS_DATA['runs'][0], so_far=10 * HOURS,
    to_go={'median': 2 * HOURS, 'lo': 1.5 * HOURS, 'hi': 2.5 * HOURS},
    etas=[[1792196400, 9 * HOURS, 2 * HOURS, 1.5 * HOURS, 2.5 * HOURS], [1792200000, 10 * HOURS, 2 * HOURS, 1.5 * HOURS, 2.5 * HOURS]])]}
PROGRESS_EARLY = '<script>window.PROGRESS_POLL_MS = 1000;</script>\n'      # a 1 s poll, for the quals
# the page's clock standing at its snapshot's time, so that a running run's time so far, which goes on with the clock
# (2026-11-07; dreeves: "make it update second by second"), is its data's, and the snapshot's age 0s, in the quals
PROGRESS_FROZEN = '<script>window.PROGRESS_CLOCK = () => window.progressView.data.made;</script>\n'
# a browser that last left the section open (dreeves, 2026-10-17: "i keep having to re-expand the search progress
# section", Live Server reloading the page as files change), set before the page's scripts run
PROGRESS_REMEMBERED = '<script>localStorage.setItem("progress-open", "1");</script>\n'
NNBSP = '\u202f'                               # the narrow no-break space between a number and its unit h (2026-10-17)
EMSP = '\u2003'                                # the em space after a snapshot line's time (dreeves, 2026-10-17: "some whitespace")


def stamp(t):
    """A time as the section gives a snapshot's: local, YYYY-MM-DD HH:MM:SS."""
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t))


def hms(sec):
    """An elapsed time as the section gives it (HMSFORMAT, dreeves, 2026-11-07: "3d 4h 5m 6s"): its days, hours, minutes
    and seconds from the largest unit it reaches down to the second, each number with its letter, narrow no-break
    spaces between them."""
    s = int(sec // 1)
    parts = [(s // 86400, 'd'), (s // 3600 % 24, 'h'), (s // 60 % 60, 'm'), (s % 60, 's')]
    return NNBSP.join(f'{v}{u}' for v, u in parts[next(i for i, k in enumerate((86400, 3600, 60, 0)) if s >= k):])


def step_of(u):
    """The step a clock time is rounded to for an uncertainty of u seconds (2026-11-07): the largest of the hour, ten
    minutes and the minute that u reaches, the minute at least."""
    return next(s for s in (3600, 600, 60) if s <= max(u, 60))


def ampm(t, u):
    """A time as the section's status line gives it, for an uncertainty of u seconds: local, to the nearest step
    (step_of), 12-hour hours without a leading zero, the minutes but to the hour, am or pm."""
    step = step_of(u)
    lt = time.localtime(t + step / 2)
    minutes = f':{lt.tm_min // (step // 60) * (step // 60):02d}' if step < 3600 else ''
    return f'{lt.tm_hour % 12 or 12}{minutes}{"am" if lt.tm_hour < 12 else "pm"}'


WEEK = 7 * 86400                               # seconds; a finish time a week or more on is a date (dreeves, 2026-10-23)


def moment(t, t1, u):
    """A finish time of a snapshot at t, for an uncertainty of u seconds: its weekday and its 12-hour time (ampm); but a
    week or more after t its local date, YYYY-MM-DD (dreeves, 2026-10-23: "the parenthetical needs disambiguation when
    >1week")."""
    return f'{time.strftime("%a", time.localtime(t1 + step_of(u) / 2))} {ampm(t1, u)}' if t1 - t < WEEK else time.strftime('%Y-%m-%d', time.localtime(t1))


def finish(t, t1, t2, u):
    """The status line's finish times, of a snapshot at t, for an uncertainty of u seconds: the first (moment), a spaced
    en dash, the second's weekday only when its date differs, the second; but an end a week or more after t as its local
    date."""
    near = lambda s: s + step_of(u) / 2            # a time's rounding falls within the step it is in, past its half
    day = lambda s: time.strftime('%a', time.localtime(near(s)))
    date = lambda s: time.strftime('%Y-%m-%d', time.localtime(near(s)))
    second = f'{"" if date(t1) == date(t2) else day(t2) + " "}{ampm(t2, u)}' if t2 - t < WEEK else time.strftime('%Y-%m-%d', time.localtime(t2))
    return f'{moment(t, t1, u)} – {second}'
# The harness: notes what has loaded, opens the section, waits 3.5 s, reads each dot's middle pixel, the key's counts,
# the state line and the times, the subtrees' blocks and the ETA chart (its markup at rest), hovers over the third
# group's first dot and over the ETA chart's second record, gives progressData a changed snapshot (one dot running ->
# open), then closes the section and waits 3.5 s more; its report goes into <pre id="harness-out">.
PROGRESS_HARNESS = """<script>
(async () => {
  const out = {};
  const sleep = ms => new Promise(r => setTimeout(r, ms));
  const section = document.querySelector('section.progress'), details = section.querySelector('details');
  const view = () => window.progressView;
  const pixel = (gi, j) => {
    const [x, y, size] = view().layouts[0].place(gi, j);
    const p = section.querySelector('canvas').getContext('2d').getImageData(x + (size >> 1), y + (size >> 1), 1, 1).data;
    return [p[0], p[1], p[2]];
  };
  try {
    window.harnessMarker = 'kept';
    out.before = {open: details.open, loads: view().loads, renders: view().renders,
                  scripts: [...document.scripts].filter(s => /progress[.]js/.test(s.getAttribute('src') || '')).length};
    out.stored = {before: localStorage.getItem('progress-open')};
    details.open = true;
    await sleep(3500);
    out.opened = {loads: view().loads, renders: view().renders};
    out.stored.opened = localStorage.getItem('progress-open');
    const run = view().data.runs[0];
    out.dots = run.groups.flatMap((g, gi) => [...g].map((c, j) => [+c, pixel(gi, j)]));
    const css = getComputedStyle(section);
    out.colors = run.statuses.map(s => css.getPropertyValue('--progress-' + s).trim());
    const squeeze = t => t.replace(/[ \\t\\n\\r]+/g, ' ').trim();       // ASCII whitespace only: U+202F, before a unit, is text
    out.state = [...section.querySelectorAll('[data-state]')].filter(e => !e.hidden).map(e => squeeze(e.textContent));
    out.made = section.querySelector('[data-made]').textContent;
    out.heads = [...section.querySelectorAll('.progress-runs h3')].map(h => h.textContent.replace(/\\s+/g, ' ').trim());
    out.etaDisplays = [...section.querySelectorAll('.progress-runs .progress-eta')].map(e => getComputedStyle(e).display);
    out.age = section.querySelector('[data-age]').textContent;
    const canvas = section.querySelector('canvas'), L = view().layouts[0], [hx, hy] = L.place(2, 0);
    const box = canvas.getBoundingClientRect(), dpr = canvas.width / box.width;
    canvas.dispatchEvent(new MouseEvent('mousemove', {clientX: box.left + (hx + L.size / 2) / dpr, clientY: box.top + (hy + L.size / 2) / dpr, bubbles: true}));
    out.readout = section.querySelector('[data-readout]').textContent.replace(/\\s+/g, ' ').trim();
    out.blocks = {rects: L.rects, cols: L.cols, rows: L.rows};
    const fig = section.querySelector('.progress-eta'), svg = fig.querySelector('svg');
    const text = sel => squeeze(fig.querySelector(sel).textContent);
    out.eta = {hidden: fig.hidden, widths: [svg.getBoundingClientRect().width, section.querySelector('canvas').getBoundingClientRect().width],
               togo: fig.querySelector('[data-togo]').getAttribute('points').trim().split(/\\s+/).length,
               labels: svg.querySelectorAll('text.label').length};
    out.etaSvg = svg.outerHTML;
    out.etaTextStrokes = [...svg.querySelectorAll('text')].map(t => [t.getAttribute('class'), t.textContent, getComputedStyle(t).stroke, getComputedStyle(t).paintOrder]);
    const status = section.querySelector('.progress-run [data-state]').parentElement, shown = [...status.children].find(e => !e.hidden);
    out.status = {afterChart: !fig.contains(status) && !!(fig.compareDocumentPosition(status) & Node.DOCUMENT_POSITION_FOLLOWING),
                  colors: [...shown.querySelectorAll('.spent, .togo, .total')].map(e => [e.className, getComputedStyle(e).color]),
                  ink: getComputedStyle(shown).color,
                  legends: section.querySelectorAll('.progress-eta-keys').length};
    const tipEl = fig.querySelector('[data-tip]');
    out.tipRest = {visibility: getComputedStyle(tipEl).visibility, height: tipEl.getBoundingClientRect().height};
    const top0 = status.getBoundingClientRect().top;
    const sb = svg.getBoundingClientRect();
    svg.dispatchEvent(new MouseEvent('mousemove', {clientX: sb.left + L.etaXs[1] * sb.width / svg.viewBox.baseVal.width, clientY: sb.top + sb.height / 2, bubbles: true}));
    out.eta.tip = getComputedStyle(tipEl).visibility === 'visible' ? text('[data-tip]') : null;
    out.jump = status.getBoundingClientRect().top - top0;
    svg.dispatchEvent(new MouseEvent('mousemove', {clientX: sb.left + L.etaXs[L.etaXs.length - 1] * sb.width / svg.viewBox.baseVal.width, clientY: sb.top + sb.height / 2, bubbles: true}));
    out.eta.tipLast = text('[data-tip]');
    out.eta.sameMarkup = tipEl.innerHTML === status.querySelector('[data-state="running"]').innerHTML;
    out.eta.projectedAtRecord = tipEl.classList.contains('projected');
    const xAt = h => L.etaXs[0] + h * (L.etaXs[1] - L.etaXs[0]);      // viewBox x at h hours: PROGRESS_DATA's records sit at 0, 1, 2 h
    svg.dispatchEvent(new MouseEvent('mousemove', {clientX: sb.left + xAt(2.5) * sb.width / svg.viewBox.baseVal.width, clientY: sb.top + sb.height / 2, bubbles: true}));
    out.eta.tipAhead = text('[data-tip]');
    out.eta.stampAhead = fig.querySelector('[data-stamp] text').textContent;   // the time on the x axis (2026-11-12)
    out.eta.ahead = {projected: tipEl.classList.contains('projected'), style: getComputedStyle(tipEl).fontStyle,
                     cross: Number(fig.querySelector('[data-cross]').getAttribute('x1')), want: xAt(2.5)};
    out.jumpAhead = status.getBoundingClientRect().top - top0;
    const cfig = section.querySelector('.progress-run .progress-cpu');
    out.cpu = cfig && {bands: [...cfig.querySelectorAll('[data-cpu-bands] polygon')].map(p => [p.getAttribute('class'), p.getAttribute('points')]),
                       shares: Object.fromEntries([...cfig.querySelectorAll('[data-cpu-share]')].map(e => [e.dataset.cpuShare, squeeze(e.textContent)])),
                       after: !!(fig.compareDocumentPosition(cfig) & Node.DOCUMENT_POSITION_FOLLOWING),
                       afterStatus: !!(status.compareDocumentPosition(cfig) & Node.DOCUMENT_POSITION_FOLLOWING),
                       trackLineAfter: !!(cfig.compareDocumentPosition(section.querySelector('.progress-run [data-track-line]')) & Node.DOCUMENT_POSITION_FOLLOWING),
                       widths: [cfig.querySelector('svg').getBoundingClientRect().width, svg.getBoundingClientRect().width],
                       etaXs: L.etaXs};
    const d2 = JSON.parse(JSON.stringify(view().data));
    d2.made += 60; d2.runs[0].groups[1] = '1'; d2.runs[0].counts.running -= 1; d2.runs[0].counts.open += 1;
    window.progressData(d2);
    out.changed = {renders: view().renders, pixel: pixel(1, 0), marker: window.harnessMarker};
    details.open = false;
    await sleep(100);
    const atClose = view().loads;
    await sleep(3500);
    out.closed = {atClose, loads: view().loads};
    out.stored.closed = localStorage.getItem('progress-open');
  } catch (e) { out.harnessError = String(e && e.stack || e); }
  const pre = document.createElement('pre');
  pre.id = 'harness-out';
  pre.textContent = JSON.stringify(out);
  document.body.appendChild(pre);
})();
</script>
"""
PROGRESS_RUNS = {}                             # progress_run's reports, by case, made once per process


def progress_run(case='main'):
    """The harness's report on index.html with the case's data (main: PROGRESS_DATA; eta: PROGRESS_ETA_DATA; two:
    PROGRESS_TWO; long: PROGRESS_LONG; narrow: PROGRESS_NARROW; remembered: PROGRESS_DATA, with PROGRESS_REMEMBERED's stored state) as progress.js
    beside it, made on first use."""
    if case not in PROGRESS_RUNS:
        data = {'main': PROGRESS_DATA, 'eta': PROGRESS_ETA_DATA, 'two': PROGRESS_TWO, 'long': PROGRESS_LONG,
                'narrow': PROGRESS_NARROW, 'remembered': PROGRESS_DATA}[case]
        early = PROGRESS_EARLY + PROGRESS_FROZEN + (PROGRESS_REMEMBERED if case == 'remembered' else '')
        d = tempfile.mkdtemp(prefix='index-quals-')
        text = page()
        assert text.count('<head>\n') == 1 and text.count('</body>') == 1
        text = text.replace('<head>\n', '<head>\n' + early).replace('</body>', PROGRESS_HARNESS + '</body>')
        open(os.path.join(d, 'index.html'), 'w', encoding='utf-8').write(text)
        copy_page_dir(d)
        open(data_file(d, 'progress.js'), 'w', encoding='utf-8').write(progress_text(data))
        shutil.copy(DATA, data_file(d, 'mstar.js'))
        shutil.copy(POW2, data_file(d, 'pow2.js'))
        dom = chrome(d, ['--window-size=1000,1100', '--force-device-scale-factor=2', '--virtual-time-budget=20000',
                         '--dump-dom', 'file://' + os.path.join(d, 'index.html')])
        m = re.search(r'<pre id="harness-out">(.*?)</pre>', dom, re.S)
        assert m, dom[-3000:]
        PROGRESS_RUNS[case] = json.loads(html.unescape(m.group(1)))
        shutil.rmtree(d)
    R = PROGRESS_RUNS[case]
    assert 'harnessError' not in R, R['harnessError']
    return R


def rgb(hexcolor): return [int(hexcolor[i:i + 2], 16) for i in (1, 3, 5)]


def q_theorem_states_pow2_s_thresholds():
    # Replicata: the powers-of-2 section's theorem, its first paragraph stating bounds m*(2^k) ≥ v, and its alternative
    # form, the first paragraph saying "1, 2, …, E", their numbers read off; and pow2.js (pow2_data).
    # Expectata: the theorem's bounds are m*(2^k) ≥ k + e for e = 1, …, E in turn, E the most any power reaches in pow2.js (8 until
    # 2026-10-25, 9 since: dreeves, 2026-10-25: "yes please"), each k the least power whose known lower bound
    # reaches k + e in pow2.js, so that a new result that moves a threshold fails here until the theorem changes with
    # it; then m*(2^9) = 9, pow2.js's bounds at 2^9 both 9; and the alternative form's count is E and its values are
    # those same ks.
    sec = re.search(r'<section class="pow2".*?</section>', page(), re.S).group(0)
    paras = re.findall(r'<p>.*?</p>', sec, re.S)
    theorem = next(p for p in paras if re.search(r'\(2\^\{?\d+\}?\) \\ge \d+', p))
    alt = next(p for p in paras if '1, 2, \\ldots, ' in p)
    bounds = [(int(k), op, int(v)) for k, op, v in re.findall(r'\(2\^\{?(\d+)\}?\) (\\ge|=) (\d+)', theorem)]
    cols = pow2_data()['cols']
    E = max(c[0] - k for k, c in enumerate(cols, 1))
    firsts = [next(k for k in range(1, len(cols) + 1) if cols[k - 1][0] - k >= e) for e in range(1, E + 1)]
    # Spec change (Claude, 2026-11-05): dreeves's 6000eaa (2026-11-04) puts m*(2^9) = 9 first and states m*(2^{10}) = 11
    # as an equality, which pow2.js settles; so the bounds are compared as a set, and a bound may say = where pow2.js's
    # two bounds there are equal.
    assert sorted((k, v) for k, _, v in bounds) == sorted([(9, 9)] + [(k, k + e) for e, k in enumerate(firsts, 1)]), (bounds, firsts)
    assert all(op == '\\ge' or cols[k - 1][:2] == [v, v] for k, op, v in bounds), [(b, cols[b[0] - 1][:2]) for b in bounds]
    assert (9, '=', 9) in bounds and cols[8][:2] == [9, 9], (bounds, cols[8][:2])
    assert f'1, 2, \\ldots, {E}' in alt and ', '.join(map(str, firsts)) in alt, (alt, firsts)


def q_smallest_section_sits_between_the_remarks_and_the_counts():
    # Replicata: index.html's section "The smallest length known for each order".
    # Expectata: a <section class="smallest" aria-labelledby="smallest-title"> (anywhere since 2026-10-30, when
    # dreeves moved it after the m*(n) chart; between the remarks and the counts before), holding its heading, a link to OEIS
    # A323395, and a table whose body is empty in the HTML: the script fills it from mstar.js; and not of class block,
    # so that the page keeps the twelve tables of that class that mstar.py reads as Table 2's and the new results'
    # (their count asserted there until 2026-10-27, which a tenth broke on 2026-10-17; nine until 2026-10-26, when the
    # powers of 2 took a third row, and ten until 2026-10-27, when the new results took in Table 2 and reached 1024 in
    # six upper rows).
    text = page()
    filler = r'(?:\s|<!--.*?-->)*'
    m = re.search(r'(<section class="smallest" aria-labelledby="smallest-title">\n.*?\n</section>)', text, re.S)
    assert m, 'no section "smallest"'
    body = m.group(1)
    assert '<h2 id="smallest-title">' in body, body[:300]
    assert 'href="https://oeis.org/A323395"' in body, body
    assert '<table>' in body and '<tbody data-smallest></tbody>' in body, body
    # Spec change (Opus 5.5, 2026-11-19; q_sequences_past_the_chart_move_seven_firsts): thirteen since then, the powers of 2 in four rows of 12 cells, the
    # new firsts' cells having made the three rows 15 to 17 cells wide, wider than the column (twelve until then).
    # (Fable 5.2, 2026-11-21, with q_powers_of_2_on_the_page_follow_pow2_js: the count of the page's block tables, thirteen until then, is no longer asked here: fourteen since the powers of 2 took a fifth.)


DRAWN = []    # the page's DOM once its scripts ran, dumped once per process (drawn_rows)
# In the page whose DOM drawn_rows dumps: once the page has loaded and KaTeX has drawn its math, each formula is put
# back as its TeX between \( and \), as the harnesses' boxes do, so that a cell's text is its words and its formulas.
TEX_BACK = """<script>addEventListener('load', () => setTimeout(() => document.querySelectorAll('.katex').forEach(k =>
  k.replaceWith(`\\\\(${k.querySelector('annotation').textContent}\\\\)`)), 300));</script>"""


def drawn_rows(attr):
    """The rows of the page's table whose body carries the attribute attr, each as the texts of its cells, a formula as
    its TeX between \\( and \\) (TEX_BACK): index.html in headless Chrome beside page/, mstar.js and pow2.js, its DOM
    dumped once its scripts ran and its math was drawn; the dump made once per process.  (Until 2026-11-27
    smallest_table alone, of the one table a script filled, whose cells hold no formula.)"""
    if not DRAWN:
        d = tempfile.mkdtemp(prefix='index-quals-')
        text = page()
        assert text.count('</body>') == 1
        with open(os.path.join(d, 'index.html'), 'w', encoding='utf-8') as f: f.write(text.replace('</body>', TEX_BACK + '</body>'))
        for src, name in ((DATA, 'mstar.js'), (POW2, 'pow2.js')): shutil.copy(src, data_file(d, name))
        copy_page_dir(d)
        DRAWN.append(chrome(d, ['--virtual-time-budget=5000', '--dump-dom', 'file://' + os.path.join(d, 'index.html')]))
        shutil.rmtree(d)
        assert 'class="katex"' not in DRAWN[0] and '\\(m\\)' in DRAWN[0], 'the dump keeps drawn formulas, or the page drew none'
    body = re.search(rf'<tbody {attr}="">(.*?)</tbody>', DRAWN[0], re.S)
    assert body, (attr, DRAWN[0][-2000:])
    return [[html.unescape(re.sub(r'<[^>]+>', '', c)) for c in re.findall(r'<td>(.*?)</td>', tr, re.S)]
            for tr in re.findall(r'<tr>(.*?)</tr>', body.group(1), re.S)]


def smallest_table():
    """The rows of the table of smallest lengths, as the page draws it."""
    return drawn_rows('data-smallest')


def tails_table():
    """The rows of the table of each order's lengths (BGPW's Table 1, carried on), as the page draws it, read back from
    its two cells, m and L_m in the form of BGPW's Table 1, as [m, g, start, others]: "start + g N" (others empty) or
    "{others} ∪ (start + g N)", each of the others a length, with its question mark where the page puts one."""
    def read(m, lengths):
        tex = re.sub(r'\\[()]|\\,|\s', '', lengths)                # the formulas' TeX less their delimiters and spaces
        # ("{(" and ")}" around the progression after a union: a TeX group, which KaTeX does not break across lines)
        got = re.fullmatch(r'(?:\\\{([\d,?]+)\\\}\\cup\{\((?=.*\)\}$))?(\d+)\+(\d+)\\mathbb\{N\}(?:\)\})?', tex)
        assert got and tex.endswith(')}') == (got.group(1) is not None), lengths
        return [int(m), int(got.group(3)), int(got.group(2)), [x for x in (got.group(1) or '').split(',') if x]]
    return [read(*row) for row in drawn_rows('data-tails')]


def q_page_statements_agree_with_the_chart():
    # Replicata: the page's math, its comments aside: every statement m^*(N) = V, \le V, \ge V or \in \{A, ..., B\}
    # with N in digits or 2^k, N up to mstar.js's last n; and mstar.js's column [lo, hi] at N.
    # Spec change (Opus 5.5, 2026-11-19; dreeves: "yes, full anti-magic, add the new entries"): N a length of mstar.js's
    # rows, its columns' or past's (mstar_rows), each statement held to N's row: the lengths past the chart that the
    # page has a sequence of are stated in their entries and the changelog since then.
    # Expectata (dreeves, 2026-11-10, of the chart's column 1456, open at order 12 while the changelog and the section
    # on asymptotics state m*(1456) = 11: "first get the chart in sync with all the known results"): the chart knows
    # what the page states: lo = hi = V, hi <= V, lo >= V, or A <= lo and hi <= B (a range of an earlier day may be
    # wider than the chart's); and the statements are a hundred or more.
    # Resultata before: at 1456 the chart had [11, 12], its upper bound the norm lemma's.
    rows, said = mstar_rows(mstar_data()), []
    for n, rel, v in re.findall(r'm\^\*\((\d+|2\^\{?\d+\}?)\)\s*(=|\\le|\\ge|\\in)\s*(\\\{[\d, ]+\\\}|\d+)', blank_comments(page())):
        n = int(n) if n.isdigit() else 2 ** int(re.sub(r'\D', '', n[1:]))
        if n in rows: said.append((n, rel, [int(x) for x in re.findall(r'\d+', v)]))
    holds = {'=': lambda lo, hi, vs: lo == hi == vs[0], '\\le': lambda lo, hi, vs: hi <= vs[0],
             '\\ge': lambda lo, hi, vs: lo >= vs[0], '\\in': lambda lo, hi, vs: min(vs) <= lo and hi <= max(vs)}
    bad = [(n, rel, vs, rows[n][:2]) for n, rel, vs in said if not holds[rel](*rows[n][:2], vs)]
    assert len(said) >= 100 and bad == [], (len(said), bad)


def q_smallest_table_matches_mstar():
    # Replicata: the table of smallest lengths as the page draws it (smallest_table); and smallest_rows of MSTAR
    # (mstar_data), computed here.
    # Expectata: the table's body holds exactly smallest_rows' rows, in order, through the largest order some n's upper
    # bound allows (since 2026-10-30) and the orders past the chart through mstar.MMAX (one more since 2026-11-03, [LIN]; through 17 since 2026-11-04, [M17]),
    # with a product of lesser orders' lengths where that is less than the chart's, as
    # beyond the chart (since 2026-10-31, [MIN]; until then — where no n up to NMAX was known to reach m); the first
    # twelve orders' smallest lengths are SMALLEST_PROVEN, each marked proven (480 added on 2026-11-03 after the pin tree of 432:12; 432 added on 2026-10-20 after
    # proof384.py).
    got = smallest_table()
    want = smallest_rows(mstar_data())
    assert got == want, (got, want)
    proven = got[:len(SMALLEST_PROVEN)]
    assert [r[2] for r in proven] == [str(n) for n in SMALLEST_PROVEN] and all(r[3] == '✓' for r in proven), proven


# The smallest lengths past the chart (dreeves's README, 2026-10-31: "[MIN] In the "smallest length known for each
# order" table, we currently have no entries for the smallest known n for orders 14 and 15. But we know from Thue-Morse
# that 2^14 has order at least 14 and in fact from the chart below the table, we know 2^13 has order 14. Similarly for
# 2^14 having order at least 15.").

def least_columns(cols):
    """[(m, the least n whose lower bound is at least m, or None, the least n whose upper bound is)] for each order m from
    1 while some n's upper bound allows m: the chart's own least n known to reach m and least n not ruled out."""
    least = lambda test: next((n for n, c in enumerate(cols, 1) if test(c)), None)
    out, m = [], 1
    while least(lambda c: c[1] >= m):
        out.append((m, least(lambda c: c[0] >= m), least(lambda c: c[1] >= m)))
        m += 1
    return out


def products_least(cols, m, past=()):
    """By brute force over the chart's data: the least product n_1 n_2 ... n_k (k >= 1) of lengths of the chart, and of
    the examples past it in past (mstar.js's past, [n, order, ...]; since 2026-11-04, its rows [n, lo, hi, loWhy, hiWhy]
    since 2026-11-19), whose lower bounds sum to at least m, a product f(x) g(x^n) (f of length n) having order at least
    the sum of its factors'.  A depth-first search over the multisets of lengths with a lower bound of at least 1, in
    rising order, cut off where the product already exceeds the least found."""
    lengths = sorted([(n, c[0]) for n, c in enumerate(cols, 1) if c[0] >= 1] + [(n, k) for n, k, *_ in past])
    best = math.inf
    def go(start, product, order):
        nonlocal best
        if order >= m:
            best = min(best, product)
            return
        for j in range(start, len(lengths)):
            n, lo = lengths[j]
            if product * n > best: break
            go(j, product * n, order + lo)
    go(0, 1, 0)
    return best


def q_smallest_lengths_go_past_the_chart():
    # Replicata: the table of smallest lengths as the page draws it (smallest_table).
    # Expectata ([MIN]): every order has a smallest known length, a number; orders 14 and 15 are reached at 960 by its example of order 15 (2026-11-03), 960 proven least at
    # order 15, the least n not ruled out being 480 and 960.  (From 2026-10-31 until then no n up to 1024 was known to reach them, and they had products: 1920 = 960 · 2
    # (960 = 480 · 2, the chart's least n of order 13, and 480 of order 12) and 3840 = 1920 · 2, each less than [MIN]'s 2^13 and 2^14, and neither proven least.)
    # Resultata before: — at orders 14 and 15.
    # And since 2026-11-03 ([LIN]: "Add one more line for m=16", then "yes, 1440 instead of ">1024" if that's all we
    # know so far"), order 16, which no n up to 1024 allows: not ruled out first at 1440 (mstar.js's mtopAt), and
    # reached at 1920 = 960 · 2, its example of order 15 times Thue–Morse's of order 1 at 2, until 2026-11-04, when the example of order 16 at 1440 reached
    # it at the least n not ruled out (q_example_at_1440_settles_a_15).
    # And since 2026-11-04 (dreeves's README: "[M17] Let's add m=17 to the "smallest length known" table; no need for much
    # search, just whatever bounds we can find quickly"), order 17: not ruled out first at 1440 either (mstar.js's
    # mtopAt; quals_mstar's q_order_17_is_open_first_at_1440), and reached at 2880 = 1440 · 2, the example of order 16
    # times Thue–Morse's of order 1 at 2, not proven least.  (Resultata before: the table stopped at order 16.)
    # And since 2026-11-10 (dreeves's README: "[BOU] Let's try having Figure 1 go up to 2048") the orders 16 to 18 are
    # the chart's own, 1440 and 1920 being columns: order 18 is not ruled out first at 1920 and reached at 5760 =
    # 1440 · 4; and order 19, which no n up to 2048 allows, is not ruled out first at 2400 (mstar.js's mtopAt) and
    # reached at 11520 = 1440 · 8.  (Resultata before: the table stopped at order 17.)
    # Spec change (Opus 5.5, 2026-11-17: the unconditional form tree at 480:14 closed, m*(480) <= 13): order 14 is not
    # ruled out first at 720, so 720 <= a(13) <= 960 in OEIS A323395 (480 until then).
    rows = smallest_table()
    assert all(re.fullmatch(r'\d+', r[2]) for r in rows), rows
    # (Spec change, Opus 5.5, 2026-11-29; dreeves, of a cap at 4096: "worth it": the chart's columns reach 4096, and the table the orders 20 to 25 that they allow,
    # which q_smallest_table_matches_mstar holds to the data, so this keeps the orders 14 to 19 as they were, the rest not pinned.)
    # 2026-11-29, dreeves: "make sure all that's on the page". The order-19
    # contradiction at 2400 moves the first possible length in three rows.
    # Spec change (Opus 5.5, 2026-12-01; dreeves: "B", a no-regression check in place of the rows of orders 14 to 21 as
    # they were, which 2400:17 moved that day at orders 17 to 21, 2880 ... 46080 to 2400 ... 38400): the table against
    # its own rows at 38cb052, that morning, computed here from that commit's mstar.js.  At every order of both, the
    # first length not ruled out is no smaller, the smallest length known no larger, and every check mark still there.
    # Control: the same comparison run backwards, that commit's table held to today's, fails (at order 17 that day,
    # 2880 against 2400).
    then = smallest_rows(mstar_of(at_commit(BEFORE_BATCH, 'pagedata/mstar.js')))
    worse = lambda a, b: [y[0] for x, y in zip(a, b)        # the orders at which b's rows are worse than a's
                          if not (x[0] == y[0] and int(y[1]) >= int(x[1]) and int(y[2]) <= int(x[2]) and (y[3] or not x[3]))]
    assert worse(then, rows) == [], (worse(then, rows), then, rows)
    assert worse(rows, then), (then, rows)


def q_smallest_known_is_the_least_product_of_the_chart_s_lengths():
    # Replicata: the table of smallest lengths as the page draws it (smallest_table), and mstar.js's columns.
    # Expectata ([MIN]): each order m's smallest known length is products_least(cols, m), the least product of lengths
    # of the chart whose lower bounds sum to at least m, found by brute force.
    # Resultata before: — at orders 14 and 15, whose least products are 1920 and 3840.
    # Since 2026-11-04 an example past the chart (mstar.js's past) competes with them: order 16's 1440 against its least product, 1920.
    # Since 2026-11-04 ([M17]) its length is a factor too: order 17's 2880 = 1440 · 2 against the chart's own 3840 = 960 · 4.
    # Since 2026-11-10 ([BOU]) 1440 is a column of the chart, which reaches 2048, and past is empty: the columns up to
    # 1024 and the example at 1440 give what they gave.
    cols, past = mstar_data()['cols'], mstar_data()['past']
    rows = smallest_table()
    assert [products_least(cols[:NMAX], m, p) for m in (16, 17) for p in ((), [[1440, 16, 'equipow p1440']])] == [1920, 1440, 3840, 2880]
    assert [r[2] for r in rows] == [str(products_least(cols, m, past)) for m in range(1, len(rows) + 1)], rows


def q_smallest_rows_the_chart_decides_are_unchanged():
    # Replicata: the table of smallest lengths as the page draws it (smallest_table), mstar.js's columns, and as a
    # control a table made by a wrong rule, 2^m (Thue–Morse) at every order.
    # Expectata ([MIN]): products fill only rows that the chart does not decide: at each order m that some n up to 1024
    # is known to reach (today 1 to 13), the row is the chart's own, as before 2026-10-31: m, the least n whose lower
    # bound is at least m, ✓ when that is also the least n whose upper bound is, and that n (least_columns); and the
    # control fails this.
    # Resultata before: (none: this holds before and after, as it must; the control is what fails.)
    cols = mstar_data()['cols']
    def check(rows):
        want = [[str(m), str(p), str(k), '✓' if k == p else ''] for m, k, p in least_columns(cols) if k is not None]
        assert len(want) >= 13 and rows[:len(want)] == want, (rows[:len(want)], want)
    check(smallest_table())
    wrong = [[str(m), str(p), str(2 ** m), '✓' if 2 ** m == p else ''] for m, k, p in least_columns(cols)]
    try: check(wrong)
    except AssertionError: return
    # TODO: error copy; says the check passed a table made by a wrong rule
    raise AssertionError('Claude: "the check passed the wrong table"')


def q_smallest_columns_follow_the_chart():
    # Replicata: the table of smallest lengths: its header in index.html, and its rows as the page draws them
    # (smallest_table).
    # Expectata (dreeves's README, 2026-10-31: "[FLP] I think the smallest-known and smallest-not-ruled-out columns
    # should be swapped, so the numbers in that table are in the same order they're in in the chart. And then I think
    # the checkmarks should be the last column"): the columns are the order, the smallest n not ruled out, the smallest
    # known n, then whether that is proven smallest; so in every row the n not ruled out is at most the n known, as
    # they stand left to right in the chart, and the check mark stands last, exactly where the two agree.
    # Resultata before: the smallest known n second, the check mark third, the n not ruled out last.
    head = re.search(r'<section class="smallest".*?<thead><tr>(.*?)</tr></thead>', page(), re.S)
    assert head, 'no header for the table of smallest lengths'
    assert len(re.findall(r'<th>(.*?)</th>', head.group(1))) == 4, head.group(1)       # four columns, whatever their headers' words (2026-11-09)
    rows = smallest_table()
    assert all(int(r[1]) <= int(r[2]) and r[3] == ('✓' if r[1] == r[2] else '') for r in rows), rows


# BGPW's Table 1, the lengths L_m of each order m up to 8, as their paper prints it (2 + 2N, 4 + 4N, 8 + 4N, 16 + 8N,
# 32 + 8N, {48} with 64 + 8N, {96, 112, 128, 144, 160, 176} with 192 + 8N, {144} with 192 + 16N): [m, the difference of
# the progression, its start, the other lengths].
BGPW_TABLE1 = [(1, 2, 2, []), (2, 4, 4, []), (3, 4, 8, []), (4, 8, 16, []), (5, 8, 32, []), (6, 8, 64, [48]),
               (7, 8, 192, [96, 112, 128, 144, 160, 176]), (8, 16, 192, [144])]


def tails_rows(cols):
    """The rows of the table of each order's lengths, computed here from the chart's columns cols, [lo, hi, ...] each: for
    each order m from 1, [m; g, the least power of 2 above m, which every length that reaches order m (has a sequence of
    order at least m) is a multiple of (BGPW's Theorem 4.1); the least multiple t of g such that every multiple of g
    from t to below t + a is known to reach order m, a the least length known to reach it (two sequences of order at
    least m, one after the other, are one of order at least m, so from that stretch on every multiple of g reaches it:
    a length of the stretch plus copies of a); and the multiples of g below t that order m is not ruled out at, as
    texts, those not known to reach it with a question mark].  An order with no such stretch inside
    the chart has no row."""
    def row(m):
        g = 1 << m.bit_length()
        known = lambda n: cols[n - 1][0] >= m
        a = next(n for n in range(g, len(cols) + 1, g) if known(n))
        return m, g, next((t for t in range(g, len(cols) - a + g + 1, g) if all(known(n) for n in range(t, t + a, g))), None)
    rows = [r for r in map(row, range(1, max(c[0] for c in cols) + 1)) if r[2] is not None]
    return [[m, g, t, [str(n) + '?' * (cols[n - 1][0] < m) for n in range(g, t, g) if cols[n - 1][1] >= m]] for m, g, t in rows]


def q_tails_table_matches_mstar():
    # Replicata: the table of each order's lengths as the page draws it (tails_table); tails_rows of MSTAR's columns,
    # computed here; BGPW's Table 1 as printed; and the columns with one bound changed, three times.
    # Expectata (dreeves, 2026-11-27, of Stan Wagon's table of the lengths of orders 9 to 11, with a conjecture for 11:
    # "do we already have all this on equipow? should we add a table like in the screenshot from stan?"; then, of its
    # first form, four columns in Stan's phrasing: "why not follow the format of BGPW's Table 1?"): a table after the
    # table of smallest lengths whose body the script fills from mstar.js, two cells a row as BGPW's Table 1 has them:
    # m, and L_m as "start + g N" or "{lengths} ∪ (start + g N)" (tails_table reads them back, and stops on any other
    # form).  Its rows are tails_rows', in order, the orders 1, 2, 3, ... with none left out; the first eight are
    # BGPW's Table 1; and each row is a theorem of the chart's bounds: every multiple of g from start to below that
    # plus the order's least known length is known to reach the order, the multiple below start is not, the braces
    # list exactly the smaller multiples that the order is not ruled out at, a question mark on those not known to
    # reach it, and the order is ruled out at every length that is no multiple of g.  The rule answers to the data:
    # with m*(528) >= 12 the question mark at 528 in row 12 goes; with m*(784) >= 11 row 11 starts at 768 (784 joins
    # the stretch, 768 was known, and 752 is ruled out) and its braces end at 720; with order 11 unknown at 800, it
    # starts later and 800 is listed with a question mark.
    # Resultata before: the page had each cell (Figure 1) and each order's least length (the table above), and the
    # starts 192, 320 and 528 inside the Symmetry section's reductions, but no statement of which lengths have a
    # sequence of order m.
    cols = mstar_data()['cols']
    got, want = tails_table(), tails_rows(cols)
    assert got == want and len(got) >= 11 and [r[0] for r in got] == list(range(1, len(got) + 1)), (got, want)
    assert [(m, g, t, [int(x) for x in also]) for m, g, t, also in got[:8]] == BGPW_TABLE1, got[:8]
    for m, g, t, also in got:
        known, open_ = (lambda n: cols[n - 1][0] >= m), (lambda n: cols[n - 1][1] >= m)
        a = min(n for n in range(g, len(cols) + 1, g) if known(n))
        assert g == 1 << m.bit_length() and t % g == 0 and t + a - g <= len(cols), (m, g, t, a)
        assert all(known(n) for n in range(t, t + a, g)) and not (t > g and known(t - g)), (m, t, a)
        assert also == [str(n) + '?' * (not known(n)) for n in range(g, t, g) if open_(n)], (m, also)
        assert not any(open_(n) for n in range(1, len(cols) + 1) if n % g), (m, g)
    changed = lambda n, lo: [[lo, max(lo, c[1])] + list(c[2:]) if i == n - 1 else c for i, c in enumerate(cols)]
    row = lambda data, m: tails_rows(data)[m - 1]
    assert '528?' in row(cols, 12)[3] and '528' in row(changed(528, 12), 12)[3], row(cols, 12)
    assert row(cols, 11)[2:] == [800, ['432', '480', '528', '576', '624', '672', '720', '768']], row(cols, 11)
    assert row(changed(784, 11), 11)[2:] == [768, ['432', '480', '528', '576', '624', '672', '720']], row(changed(784, 11), 11)
    lost = [[10, c[1]] + list(c[2:]) if i == 799 else c for i, c in enumerate(cols)]
    assert row(lost, 11)[2] > 800 and '800?' in row(lost, 11)[3], row(lost, 11)


def q_tables_and_figures_are_numbered():
    # Replicata: index.html: the labels of its own tables and charts, and every mention of a numbered table or figure
    # in its visible text, its tags' attribute values, its scripts (page/) and mstar.js's hover labels.
    # Expectata (dreeves's README, 2026-11-03: "[NUM] Number the tables and charts for easier reference. To avoid
    # confusion with BGPW's Table 2 I guess we could just omit "Table 1" and start with our extended results as "Table
    # 3"?", then "alternatively we could just always be clear about the BGPW prefix and have our own tables/figures/charts
    # numbered normally from 1", then "can you do this more like latex does it? the numbers don't belong in the section
    # headers", and "the powers-of-two table should have it's own number, right? if there's prose in between two tables
    # that's not a caption, they can't be considered the same table"): the page's own tables and charts are numbered from
    # 1 in page order, each by a small-caps label in its caption, as in LaTeX and as BGPW's Table 2 above them is: a
    # table's caption above it, a figure's below it. Table 1 the extended results other than powers of 2 (a caption above
    # them, with dreeves's words "Extended results since BGPW"), Table 2 the powers of 2 (a caption right above their
    # frame), Figure 1 the m*(n) chart (a caption after its readout), Table 3 the smallest lengths (its caption), Figure 2
    # the powers-of-2 chart (a caption after its readout), Table 4 the record gaps (its caption); no section heading holds
    # a label; each label once; and every other numbered table or figure the
    # page names is the paper's, named as such just before it ("BGPW" or "paper's" among the 40 visible characters
    # before it) or right after it ("of BGPW", "of the paper", as in dreeves's "Table 2 of the paper by Buhler, ...").
    # Resultata before: no labels; and Claude's "the upper value in Table 2's entry for 288" named BGPW's Table 2 bare.
    text, seen = page(), visible_text()
    # Spec change (2026-11-09): a label is one word and a number in small capitals, and what the word is ("Table",
    # "Figure") is the page's.  The six floats are found by their places, the second right above the frame of the powers
    # of 2; the tables' labels share a word, the figures' another, and each kind is numbered from 1 in the page's
    # order.  Until then the six labels were asked for by their words.
    LABEL = r'([^<\d\s]+) (\d+)\.</span>'
    # Spec change (2026-11-10; dreeves: "quals that don't let Figure and Table numbers get out of sync sounds valuable.
    # are we doing that the sensible way?", then "latex-style label&ref sounds good"): as LaTeX's \label and \ref.
    #   label      a small-caps "Word N." (LABEL); each kind's labels count 1, 2, 3, ... in the page's order, however
    #              many there are.
    #   float id   the id of a caption that holds a label: <p class="float-caption" id="..."> or <caption id="...">.
    #   reference  a link to a float id; its text ends with its float's number.
    # So a float added, dropped or moved turns this red until the labels count again and every reference names its
    # float's number.  Until then the six floats were found by their places and their kinds by position, which made
    # adding a float on purpose red, no label could stand in a section heading, and a mention was tied to no float.
    labels = list(re.finditer(r'<span class="sc">' + LABEL, text))
    assert labels, 'no label'
    at, kinds, numbers = [m.start(1) for m in labels], [m.group(1) for m in labels], [m.group(2) for m in labels]
    counted = {kind: [n for k, n in zip(kinds, numbers) if k == kind] for kind in kinds}
    assert all(ns == [str(i + 1) for i in range(len(ns))] for ns in counted.values()), counted
    number_of = dict(re.findall(r'<(?:p class="float-caption"|caption) id="([^"]+)"><span class="sc">[^<\d\s]+ (\d+)\.</span>', text))
    references = [(i, re.sub(r'<[^>]*>', '', said).strip()) for i, said in re.findall(r'<a href="#([^"]+)"[^>]*>(.*?)</a>', blank_comments(text), re.S)
                  if i in number_of]
    stale = [(i, said, number_of[i]) for i, said in references if not re.search(r'(?<!\d)' + number_of[i] + '$', said)]
    assert not stale, stale
    mention, after = r'\b(?:Tables?|Figures?) \d+', r' of (?:BGPW|the paper)\b'
    # Spec change (2026-11-10): dreeves's own "Eyeballing the Figures 1 and 2, it looks like maybe" (d67f6dd) names the
    # page's two charts bare, and this qual took every bare mention for the paper's without its prefix.  By his rule
    # above ("always be clear about the BGPW prefix and have our own tables/figures/charts numbered normally from 1") a
    # bare mention is one of the page's own, so it passes when the page has that float (own: its kind, in the singular,
    # and its number); a bare mention of a float the page lacks still fails.  No qual reads his words (2026-11-07).
    own = {f'{kind} {number}' for kind, number in zip(kinds, numbers)}
    lacks = lambda said: re.sub(r's(?= \d)', '', said) not in own
    bare = [seen[m.start():m.end()] for m in re.finditer(mention, seen) if m.start() not in at and lacks(m.group(0))
            and not re.search(r"BGPW|paper's", seen[:m.start()].replace('\0', '')[-40:])
            and not re.match(after, seen[m.end():].replace('\0', ''))]
    tags = [v for t in re.findall(r'<[a-zA-Z][^>]*>', text) for v in re.findall(r"""=(?:'([^']*)'|"([^"]*)")""", t) for v in v if v]
    others = tags + page_scripts(text) + [open(DATA, encoding='utf-8').read()]
    bare += [o[max(0, m.start() - 40):m.end()] for o in others for m in re.finditer(mention, o) if lacks(m.group(0))
             and not re.search(r"BGPW|paper's", o[max(0, m.start() - 40):m.start()]) and not re.match(after, o[m.end():])]
    assert not bare, bare


# In the page, loaded at a caption's id, once its fonts are in: where the caption and the chart of its section (the
# section's element of role img: a canvas, or a div that a script fills) stand in the window, and the window's height
LANDING = """<script>
addEventListener('load', () => document.fonts.ready.then(() => setTimeout(() => {
  const caption = document.getElementById(location.hash.slice(1)), chart = caption.closest('section').querySelector('[role="img"]');
  const c = caption.getBoundingClientRect(), f = chart.getBoundingClientRect();
  parent.postMessage(JSON.stringify({captionTop: c.top, captionBottom: c.bottom, chartTop: f.top, innerH: innerHeight}), '*');
}, 1200)));
</script>
"""


def q_a_reference_to_a_figure_lands_with_the_figure_in_view():
    # Replicata: each caption of index.html that stands below its float, right after a chart's readout (the two
    # figures'), and the page 1280 px wide in a frame 1000 px tall, loaded at that caption's id, as a click on a
    # reference to it loads it.
    # Expectata (dreeves, 2026-11-10: "latex-style label&ref sounds good"): the window then holds the figure: its
    # chart's top is at or below the window's top, and its caption's bottom at or above the window's bottom.
    # Resultata before: the caption stood at the window's top, with its chart above it, out of sight.
    text = page()
    below = re.findall(r'<p id="[^"]+" aria-live="polite">[^\n]*</p>\n\s*<p class="float-caption" id="([^"]+)">', text)
    for i in below:
        d = tempfile.mkdtemp(prefix='index-quals-')
        try:
            assert text.count('</body>') == 1
            open(os.path.join(d, 'index.html'), 'w', encoding='utf-8').write(text.replace('</body>', LANDING + '</body>'))
            copy_page_dir(d)
            for data in (DATA, POW2): shutil.copy(data, data_file(d, os.path.basename(data)))
            open(os.path.join(d, 'host.html'), 'w').write(HOST.replace('__WIDTH__', '1280').replace('src="index.html"', f'src="index.html#{i}"'))
            dom = chrome(d, ['--window-size=1320,1100', '--virtual-time-budget=10000', '--dump-dom', 'file://' + os.path.join(d, 'host.html')])
        finally:
            shutil.rmtree(d)
        m = re.search(r'<pre id="harness-out">(.*?)</pre>', dom, re.S)
        assert m, (i, dom[-1500:])
        R = json.loads(html.unescape(m.group(1)))
        assert R['chartTop'] >= 0 and R['captionBottom'] <= R['innerH'], (i, R)


ERRORS_LOOK = """<script>
addEventListener('load', () => setTimeout(() => {
  const b = document.getElementById('page-errors'), r = b && b.getBoundingClientRect(), css = b && getComputedStyle(b);
  const pre = document.createElement('pre'); pre.id = 'harness-out';
  pre.textContent = JSON.stringify(b && {shown: b.checkVisibility(), text: b.textContent, role: b.getAttribute('role'), position: css.position,
                                         top: r.top, width: r.width, height: r.height, color: css.backgroundColor, viewport: document.documentElement.clientWidth});   // the width inside the scrollbar
  document.body.appendChild(pre);
}, 1500));
</script>
"""


def error_run(case):
    """What the page shows of its errors (ERRORS_LOOK) in case: load, an inline script at the end of the body throwing an
    Error as the page loads; later, one throwing a TypeError 300 ms after; promise, a promise rejected and never handled;
    stale, the Search progress section's script replaced by one that sets the text of an element the page does not have
    (as an old script cached with a new page did on 2026-11-12); nostyle, load without page/style.css; clean, nothing."""
    inject = dict(load="<script>throw new Error('qual: thrown as the page loads')</script>\n",
                  later="<script>setTimeout(() => { throw new TypeError('qual: thrown later'); }, 300)</script>\n",
                  promise="<script>Promise.reject(new Error('qual: rejected'))</script>\n",
                  nostyle="<script>throw new Error('qual: thrown as the page loads')</script>\n").get(case, '')
    d = tempfile.mkdtemp(prefix='index-quals-')
    try:
        open(os.path.join(d, 'index.html'), 'w', encoding='utf-8').write(page().replace('</body>', inject + ERRORS_LOOK + '</body>'))
        copy_page_dir(d)
        for name, path in (('mstar.js', DATA), ('pow2.js', POW2)): shutil.copy(path, data_file(d, name))
        open(data_file(d, 'progress.js'), 'w', encoding='utf-8').write(progress_text(PROGRESS_DATA))
        if case == 'stale':
            open(os.path.join(d, 'page', 'progress-section.js'), 'w').write("document.querySelector('[data-no-such-element]').textContent = 'x';\n")
        if case == 'nostyle':
            os.remove(os.path.join(d, 'page', 'style.css'))
        dom = chrome(d, ['--window-size=390,800', '--virtual-time-budget=8000', '--dump-dom', 'file://' + os.path.join(d, 'index.html')])
        m = re.search(r'<pre id="harness-out">(.*?)</pre>', dom, re.S)
        assert m, dom[-2000:]
        return json.loads(html.unescape(m.group(1)))
    finally:
        shutil.rmtree(d)


def q_an_error_shows_at_the_top_of_the_window():
    # Replicata: index.html at 390 px in each of error_run's cases: an Error thrown by an inline script as the page
    # loads; a TypeError thrown 300 ms after; a promise rejected and never handled; the Search progress section's script
    # replaced by one that sets the text of an element the page does not have; the first case with no page/style.css;
    # and the page as it is.
    # Expectata (Opus 5.5, 2026-11-12; dreeves: "is there something simpler we can do to make it fail louder? see
    # anti-postel in AGENTS.md", after his phone ran an old cached script with the new page and the Search progress
    # section stayed silently empty): every error the page's scripts do not catch shows at once, at the top of the
    # window, over the page, across its width (a box with the role alert, fixed, its top at 0, in the impossible red):
    # its message, and for a script's error the file it came from ("index.html", "progress-section.js"); with no
    # stylesheet the same, its look its own; and with no error, nothing (the box hidden, empty).  Resultata before: no
    # box; the stale case's section empty, and the other errors only in the console.
    want = dict(load=('qual: thrown as the page loads', 'index.html'), later=('qual: thrown later', 'index.html'),
                promise=('qual: rejected', ''), stale=('textContent', 'progress-section.js'), nostyle=('qual: thrown as the page loads', 'index.html'))
    for case, (message, source) in want.items():
        got = error_run(case)
        assert got is not None and got['shown'] and got['role'] == 'alert' and got['position'] == 'fixed' and got['top'] == 0, (case, got)
        assert abs(got['width'] - got['viewport']) < 1 and got['height'] > 10 and got['color'] == 'rgb(168, 40, 63)', (case, got)
        assert message in got['text'] and source in got['text'], (case, got['text'])
    clean = error_run('clean')
    assert clean is not None and not clean['shown'] and clean['text'] == '', clean


def q_contents_links_reach_every_main_section():
    # Replicata: the real page at desktop and phone widths; click each link in the header's navigation.
    # Expectata (dreeves, 2026-11-11): a contents list above the introduction, one link per main section in page
    # order, using that section's own heading. Each click brings its heading into view; links fit the viewport,
    # formulas render, and visiting the progress summary does not open its fold or load its data.
    # Resultata before: no navigation in the header, hence no links to the page's twelve main sections.
    # Approved 2026-12-02: keep every heading link and add Table 6 beside the Symmetry heading, using its caption.
    # Its through-order-11 heading gave no direct route to the table of all-orders bounds.
    harness = r'''<script>
addEventListener('load', async () => {
  await document.fonts.ready;
  const nav = document.querySelector('header nav'), links = [...(nav?.querySelectorAll('a') ?? [])];
  const headings = [...document.querySelectorAll('main > section')].map(s => s.querySelector('h2'));
  const caption = document.querySelector('section.symmetry caption#symmetry-table');
  const symmetry = nav.querySelector('a[href="#symmetry-title"]'), table = nav.querySelector('a[href="#symmetry-table"]');
  const intro = document.querySelector('header > p:not(.lede)'), landed = [];
  const fits = links.every(a => [...a.getClientRects()].every(r => r.left >= 0 && r.right <= innerWidth));
  for (const a of links) {
    a.click();
    await new Promise(resolve => setTimeout(resolve, 100));
    const target = document.getElementById(a.hash.slice(1)), r = target?.getBoundingClientRect();
    landed.push({hash: location.hash, visible: !!r && r.top >= -1 && r.bottom <= innerHeight});
  }
  parent.postMessage(JSON.stringify({
    headings: headings.map(h => [h.id, h.textContent]),
    caption: caption.textContent, beside: !!table && table.closest('li') === symmetry.closest('li'),
    links: links.map(a => [a.getAttribute('href'), a.textContent]), landed, fits,
    named: !!nav && !!document.getElementById(nav.getAttribute('aria-labelledby'))?.textContent.trim(),
    above: !!nav && !!(nav.compareDocumentPosition(intro) & Node.DOCUMENT_POSITION_FOLLOWING),
    unique: headings.every(h => h.id && document.querySelectorAll(`[id="${h.id}"]`).length === 1),
    math: nav?.querySelectorAll('.katex').length ?? 0, errors: nav?.querySelectorAll('.katex-error').length ?? 0,
    progressOpen: document.querySelector('section.progress > details').open, loads: progressView.loads
  }), '*');
});
</script>'''
    for width in (320, 390, 1280):
        with tempfile.TemporaryDirectory(prefix='contents-quals-') as d:
            open(os.path.join(d, 'index.html'), 'w', encoding='utf-8').write(page().replace('</body>', harness + '</body>'))
            copy_page_dir(d)
            for data in (DATA, POW2): shutil.copy(data, data_file(d, os.path.basename(data)))
            open(os.path.join(d, 'host.html'), 'w').write(HOST.replace('__WIDTH__', str(width)))
            dom = chrome(d, ['--window-size=1320,1100', '--virtual-time-budget=10000', '--dump-dom',
                             'file://' + os.path.join(d, 'host.html')])
        match = re.search(r'<pre id="harness-out">(.*?)</pre>', dom, re.S)
        assert match, (width, dom[-1500:])
        got = json.loads(html.unescape(match[1]))
        expected = [['#' + i, label] for i, label in got['headings']]
        symmetry = next(i for i, link in enumerate(expected) if link[0] == '#symmetry-title')
        expected.insert(symmetry + 1, ['#symmetry-table', got['caption']])
        assert got['links'] == expected and got['beside'], (width, got)
        assert got['unique'] and got['named'] and got['above'] and got['fits'], (width, got)
        assert all(r['visible'] and r['hash'] == link[0] for r, link in zip(got['landed'], got['links'])), (width, got)
        assert got['math'] > 0 and got['errors'] == 0, (width, got)
        assert not got['progressOpen'] and got['loads'] == 0, (width, got)


def q_smallest_script_passes_node_check():
    # Replicata: the script that fills the table of smallest lengths (page/smallest-section.js since 2026-10-31, an
    # inline script before), saved as a .js file, through node --check.
    # Expectata: exit 0: it parses as a classic script.
    js = next(js for js in page_scripts(page()) if '[data-smallest]' in js)
    d = tempfile.mkdtemp(prefix='index-quals-')
    path = os.path.join(d, 'smallest.js')
    open(path, 'w', encoding='utf-8').write(js)
    p = subprocess.run(['node', '--check', path], capture_output=True, text=True, timeout=60)
    shutil.rmtree(d)
    assert p.returncode == 0, p.stderr


def q_progress_section_starts_closed():
    # Replicata: index.html's section "Search progress".
    # Expectata: a <section class="progress" aria-labelledby="progress-title"> after the lattice section (after the
    # sets' section, until it left the page on 2026-10-31) and before the
    # footer: after any comments, a <details> without open, so it starts closed, whose <summary> is the heading
    # progress-title, with a key of the five statuses; and in its run template one more <details>, also without open,
    # each run's fold (dreeves, 2026-10-23; since 2026-10-25 each stays as this browser left it); no <script> on the
    # page names progress.js, which the section's script (page/progress-section.js since 2026-10-31) loads only once it
    # is opened.
    text = page()
    sec = re.search(r'<section class="progress" aria-labelledby="progress-title">\n(.*?)\n</section>\n', text, re.S)
    assert sec and text.index('<section class="lattice"') < sec.start() < text.index('<footer>'), sec
    body = sec.group(1)
    assert re.match(r'(?:\s*<!--.*?-->)*\s*<details>', body, re.S), body[:300]
    assert '<details open' not in body and body.count('</details>') == 2, body[:300]
    run = re.search(r'<template class="progress-run">(.*?)</template>', body, re.S).group(1)
    assert run.count('<details>') == 1 and run.count('</details>') == 1, run[:300]
    assert '<summary><h2 id="progress-title">' in body
    assert not re.search(r'<script[^>]*progress\.js', text)


def q_progress_classes_meet_only_its_own_css():
    # Replicata: the classes the section "Search progress" uses, and the page's CSS rules whose selectors start neither
    # with its own classes (.progress, .progress-*) nor with another section's class or a chart's id (they match only
    # inside that section).
    # Expectata: no such rule names one of the section's classes but nw (the page's no-wrap span, used on purpose).
    # (2026-10-17: the ETA chart's legend took the page's legend rule for .key, which drew its line swatches as
    # boxes.)
    text = page()
    sec = re.search(r'<section class="progress".*?</section>', text, re.S).group(0)
    classes = {c for attr in re.findall(r'\bclass="([^"]*)"', sec) for c in attr.split()} - {'nw'}
    others = set(re.findall(r'<section class="([\w-]+)"', text)) - {'progress'}
    style = re.sub(r'/\*.*?\*/', '', page_css(), flags=re.S)
    selectors = [s.strip() for sel in re.findall(r'([^{}]+)\{', style) for s in sel.split(',')]
    scoped = r'(\.progress(-[\w-]+)?|\.(' + '|'.join(map(re.escape, others)) + r')|#(pow2|mstar)[\w-]*)(?![\w-])'
    foreign = [s for s in selectors if not re.match(scoped, s)]
    bad = [(s, c) for s in foreign for c in classes if re.search(rf'\.{re.escape(c)}(?![\w-])', s)]
    assert classes and not bad, bad


def q_progress_css_names_only_what_the_section_has():
    # Replicata: the page's CSS rules whose selectors start with the section's classes (.progress, .progress-*); the
    # section's markup with its script (the page's last, page/progress-section.js since 2026-10-31, which makes the
    # chart's and the tip's marks).
    # Expectata: every class and element such a selector names occurs in them, so no rule of the section's matches
    # nothing.  (2026-10-17: dreeves took the section out of its block quote, which left .progress blockquote and
    # .progress .attrib matching nothing.)
    text = page()
    sec = re.search(r'<section class="progress".*?</section>', text, re.S).group(0)
    js = page_scripts(text)[-1]
    style = re.sub(r'/\*.*?\*/', '', page_css(), flags=re.S)
    selectors = [s.strip() for sel in re.findall(r'([^{}]+)\{', style) for s in sel.split(',')]
    ours = [re.sub(r'\[[^\]]*\]|::?[\w-]+(\([^)]*\))?', '', s) for s in selectors
            if re.match(r'\.progress(-[\w-]+)?(?![\w-])', s)]
    named = {(kind, name) for s in ours for kind, name in re.findall(r'(\.|(?:^|(?<=[\s>+~])))([a-z][\w-]*)', s)}
    def present(kind, name):
        if kind == '.':
            return re.search(rf'(?<![\w-]){re.escape(name)}(?![\w-])', sec + js)
        return re.search(rf'<{name}\b', sec) or re.search(rf"""['"]{name}['"]""", js)
    missing = sorted((kind or '<') + name for kind, name in named if not present(kind, name))
    assert len(ours) > 40 and ('.', 'progress') in named and ('', 'canvas') in named and not missing, missing


def q_progress_script_passes_node_check():
    # Replicata: the section's script (the page's last, page/progress-section.js since 2026-10-31, an inline script
    # before), saved as a .js file, through node --check.
    # Expectata: exit 0: it parses as a classic script.
    js = page_scripts(page())[-1]
    d = tempfile.mkdtemp(prefix='index-quals-')
    path = os.path.join(d, 'progress-section.js')
    open(path, 'w', encoding='utf-8').write(js)
    p = subprocess.run(['node', '--check', path], capture_output=True, text=True, timeout=60)
    shutil.rmtree(d)
    assert 'progressData' in js and p.returncode == 0, p.stderr


def q_progress_loads_only_while_open():
    # Replicata: progress_run: index.html in headless Chrome with PROGRESS_DATA as progress.js, the poll 1 s.
    # Expectata: closed at load, with nothing loaded or drawn and no script naming progress.js; opened, it loads
    # progress.js, again each second (at least 3 loads in 3.5 s), and draws once, since the snapshot did not change;
    # closed again, it loads nothing more.
    R = progress_run()
    assert R['before'] == {'open': False, 'loads': 0, 'renders': 0, 'scripts': 0}, R['before']
    assert R['opened']['loads'] >= 3 and R['opened']['renders'] == 1, R['opened']
    assert R['closed']['loads'] == R['closed']['atClose'], R['closed']


def q_progress_eta_text_is_not_outlined():
    # Replicata: progress_run's ETA chart (PROGRESS_DATA's run), the computed stroke of each of its text elements.
    # Expectata: none for the tick labels; for the three labels at the record's end (ETA, total, elapsed), which share
    # their lines' classes (togo, total, spent), only the page's paper color painted under the letters (paint-order
    # stroke first), a halo that hides the lines behind a label (the red dotted line runs from the red marker through
    # its label) and draws no outline.  The lines' rules outranked the text rule until 2026-10-17 and outlined the
    # labels in their lines' colors (dreeves: "the messed up font/bolding").  Since 2026-10-17 (dreeves: "comment it out
    # for now") the labels are commented out, so there are only ticks; the labels' checks stay for their return.
    R = progress_run()
    strokes = R['etaTextStrokes']
    # Spec change (Opus 5.5, 2026-11-12; dreeves: "what if we showed the timestamp more subtly and showed it floating on
    # the x-axis matched up with the dashed vertical line on the graph marking the timestamp in question that we're
    # hovering over?"): the chart's
    # texts are its ticks and one more, the time under the pointer (class time), none outlined.
    labels = [s for s in strokes if s[0].split()[0] == 'label']
    ticks = [s for s in strokes if s[0] in ('ytick', 'xtick', 'time')]
    assert len(labels) == 0 and len(ticks) == len(strokes) and [s[0] for s in strokes].count('time') == 1, strokes
    # With the labels (until 2026-10-17; back with them):
    # assert len(labels) == 3 and len(labels) + len(ticks) == len(strokes), strokes
    assert all(stroke == 'rgb(255, 255, 255)' and order.startswith('stroke') for _, _, stroke, order in labels), labels
    assert all(stroke == 'none' for _, _, stroke, _ in ticks), ticks


def q_progress_remembers_it_was_left_open():
    # Replicata: progress_run with no stored state (main), and with this browser's stored state saying it last left the
    # section open (remembered, PROGRESS_REMEMBERED); in each, the stored state as the harness begins, after it opens
    # the section and after it closes it.
    # Expectata (dreeves, 2026-10-17: reloads kept closing the section; "2": remember it in the browser): main starts
    # closed with nothing stored, stores "1" once opened and nothing once closed; remembered starts open, its data
    # loading already (a progress.js script and at least one load before the harness touched it), then the same.
    main, kept = progress_run(), progress_run('remembered')
    assert main['before']['open'] is False and main['stored'] == {'before': None, 'opened': '1', 'closed': None}, main['stored']
    assert kept['before']['open'] is True and kept['before']['loads'] >= 1 and kept['before']['scripts'] >= 1, kept['before']
    assert kept['stored'] == {'before': '1', 'opened': '1', 'closed': None}, kept['stored']


def q_progress_draws_each_dot_in_its_status_color():
    # Replicata: progress_run, the middle pixel of every dot after opening, and the CSS custom properties
    # --progress-<status> (STATUSES).
    # Expectata: one dot per status digit of the data, in its order, each pixel exactly its status's color; the key's
    # counts are the data's.
    R = progress_run()
    want = [(int(c), STATUSES[int(c)]) for g in PROGRESS_DATA['runs'][0]['groups'] for c in g]
    assert [s for s, _ in R['dots']] == [s for s, _ in want], R['dots']
    assert all(len(c) == 7 and c.startswith('#') for c in R['colors']), R['colors']
    assert all(px == rgb(R['colors'][s]) for s, px in R['dots']), (R['dots'], R['colors'])


def q_progress_states_times_and_hours():
    # Replicata: progress_run's state line, snapshot time and age after opening.
    # Expectata: only the running state's line shows, in dreeves's form of 2026-10-17 ("Running: 11.4 h so far +
    # 34.2–50.6 h to go = 45–62 h (Mon 6:27am – 10:58pm)", then for "Running:" his '"@2026-10-17 20:40:59" (in black)
    # and then some whitespace, no colon'): an @ and the snapshot's time (the data's made: stamp), in the page's ink, an
    # em space, then 2.0 h so far + a 0.5–3.0 h band to go (PROGRESS_DATA's so_far and to_go) = 2.5–5.0 h in all, each
    # number and its h apart by a narrow no-break space (his "thin space"), then in parentheses the local times that
    # band ends between (finish: the weekday once unless the dates differ, 12-hour times with am or pm), no period; the
    # snapshot time above the runs is the data's made in
    # local time (YYYY-MM-DD HH:MM:SS), and its age a duration in digits.  And since dreeves's request of 2026-10-17, the
    # status line sits below the ETA chart, where its legend was, outside the chart's box (so that it shows when the
    # chart has no record), its parts in the chart's colors: the hours so far blue (spent), the hours to go red (togo),
    # the hours in all and the clock times purple (total: #7b1fa2 since dreeves's "blue+red=purple", 2026-10-17; the
    # page's ink before).
    # Spec change (Claude, 2026-11-06; dreeves: "i don't think we need "@2026-11-06 19:12:49" under the graph since the
    # search progress line above the progress bar shows the freshness"): the line's text is checked as its template
    # gives it (its textContent), which the ETA chart's tip shows whole; the status line hides its @, its time and the
    # em space (q_progress_status_line_has_no_time_but_its_tip_does), so the time's ink is read in the tip.
    # Spec change (Claude, 2026-11-07; dreeves: "1. show elapsed time with full granularity like so: 3d 4h 5m 6s ... 3. no
    # need for the "so far" ... 4. sane number of sigfigs for everything else based in a principled way on the amount of
    # uncertainty"): the time so far 2h 0m 0s, with no "so far" (hms; q_progress_elapsed_is_days_hours_minutes_seconds_and_ticks),
    # and the rest to the band's uncertainty, half its width, 1.25 h (q_progress_rounds_figures_to_their_uncertainty):
    # 1–3 h to go, 3–5 h in all, and the finish times to the hour; the age in the same form, 0s, the page's clock in
    # the quals standing at the snapshot's time (PROGRESS_FROZEN).
    R = progress_run()
    made, go, h = PROGRESS_DATA['made'], PROGRESS_DATA['runs'][0]['to_go'], NNBSP + 'h'
    # Spec change (Opus 5.5, 2026-11-12; dreeves: "could you improve the consistency of the graphs a little? font sizes
    # and whether graphs are labeled above or below the graph. ... what if we showed the timestamp more subtly and showed
    # it floating on the x-axis matched up with the dashed vertical line on the graph marking the timestamp in question
    # that we're hovering over?"): the line has no
    # time of its own, which floats on the ETA chart's x axis while the pointer is over it
    # (q_progress_lines_have_no_time_the_axis_does).
    want = f'{hms(7200)} + 1–3{h} to go = 3–5{h} ({finish(made, made + go["lo"], made + go["hi"], 4500)})'
    assert [figures(s) for s in R['state']] == [figures(want)], (R['state'], want)
    at = lambda d, hh, mm: time.mktime((2026, 10, d, hh, mm, 0, 0, 0, -1))        # local times; 2026-10-19 is a Monday
    assert finish(at(19, 6, 0), at(19, 6, 27), at(19, 17, 38), 0) == 'Mon 6:27am – 5:38pm', finish(at(19, 6, 0), at(19, 6, 27), at(19, 17, 38), 0)
    assert finish(at(19, 6, 0), at(19, 6, 27), at(20, 0, 18), 0) == 'Mon 6:27am – Tue 12:18am', finish(at(19, 6, 0), at(19, 6, 27), at(20, 0, 18), 0)
    # to ten minutes and to the hour (2026-11-07)
    assert finish(at(19, 6, 0), at(19, 6, 27), at(19, 17, 38), 600) == 'Mon 6:30am – 5:40pm', finish(at(19, 6, 0), at(19, 6, 27), at(19, 17, 38), 600)
    assert finish(at(19, 6, 0), at(19, 6, 27), at(19, 17, 38), 3600) == 'Mon 6am – 6pm', finish(at(19, 6, 0), at(19, 6, 27), at(19, 17, 38), 3600)
    # a week on, a weekday is ambiguous: a date (dreeves, 2026-10-23; 'Mon 12:05pm – Mon 12:05pm' until then)
    assert finish(at(19, 12, 5), at(19, 12, 5), at(26, 12, 5), 0) == 'Mon 12:05pm – 2026-10-26'
    want = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(PROGRESS_DATA['made']))
    assert R['made'] == want, (R['made'], want)
    assert R['age'] == '0s', R['age']
    assert R['status']['afterChart'] is True, R['status']
    assert R['status']['colors'] == [['spent', 'rgb(42, 120, 214)'], ['togo', 'rgb(227, 73, 72)'], ['total', 'rgb(123, 31, 162)']], R['status']
    assert R['status']['ink'] == 'rgb(27, 29, 34)', R['status']


def q_progress_lines_have_no_time_the_axis_does():
    # Replicata: index.html with two running runs as progress.js, each fold open: PROGRESS_DATA's, its data fresh, and
    # the same with its data stale, from an hour before the snapshot; then a hover over the first run's ETA chart at its
    # last record.
    # Expectata (dreeves, 2026-11-06: "i don't think we need "@2026-11-06 19:12:49" under the graph since the search
    # progress line above the progress bar shows the freshness"): each status line under the ETA chart shows its hours
    # so far + to go = in all and its finish times (the stale run's from its stale time), and no @, time or em space
    # before them; the tip above the chart, over the last record, still shows the @, the snapshot's time and an em
    # space, then the status line's text; the stale run's summary still shows its stale time as the section's stamp
    # writes it, the time its status line gave until then; and the section's line above the runs, the snapshot's time.
    # Resultata before: each status line began with an @, its time (the stale run's its stale time) and an em space.
    # Spec change (Claude, 2026-11-07; dreeves: "1. show elapsed time with full granularity like so: 3d 4h 5m 6s", "2.
    # make it update second by second", "3. no need for the "so far"" and "4. sane number of sigfigs for everything else
    # based in a principled way on the amount of uncertainty"): the lines in that form (q_progress_states_times_and_hours),
    # each running run's time so far going on with the clock from its data's time: the stale run's 3h 0m 0s at the
    # snapshot's time, an hour after its data's, where the fresh run's is 2h 0m 0s.
    made, go, h = PROGRESS_DATA['made'], PROGRESS_DATA['runs'][0]['to_go'], NNBSP + 'h'
    old = made - 3600
    got = progress_harness({'made': made, 'runs': [PROGRESS_DATA['runs'][0], dict(PROGRESS_DATA['runs'][0], stale=old)]}, """
  for (const r of runs()) r.querySelector('details').open = true;
  await sleep(200);
  const [fresh, stale] = runs(), squeeze = t => t.replace(/[ \\t\\n\\r]+/g, ' ').trim();
  const shown = r => squeeze(r.querySelector('.progress-status [data-state="running"]').innerText);
  const L = window.progressView.layouts[0], svg = fresh.querySelector('.progress-eta svg'), sb = svg.getBoundingClientRect();
  svg.dispatchEvent(new MouseEvent('mousemove', {clientX: sb.left + L.etaXs[L.etaXs.length - 1] * sb.width / svg.viewBox.baseVal.width, clientY: sb.top + sb.height / 2, bubbles: true}));
  out({status: [shown(fresh), shown(stale)], tip: squeeze(fresh.querySelector('[data-tip]').innerText),
       axis: fresh.querySelector('.progress-eta [data-stamp] text').textContent,
       mark: stale.querySelector('[data-stale]').checkVisibility() && stale.querySelector('[data-stale-at]').textContent,
       made: document.querySelector('section.progress [data-made]').textContent});""")
    line = lambda t, x: f'{hms(x)} + 1–3{h} to go = 3–5{h} ({finish(t, t + go["lo"], t + go["hi"], 4500)})'
    # Spec change (Opus 5.5, 2026-11-12; dreeves: "could you improve the consistency of the graphs a little? font sizes
    # and whether graphs are labeled above or below the graph. ... what if we showed the timestamp more subtly and showed
    # it floating on the x-axis matched up with the dashed vertical line on the graph marking the timestamp in question
    # that we're hovering over?"):
    # the tip has no time either, its line now the status line's; the time floats on the chart's x axis, the record's,
    # local, to the minute.  (Until then this qual was q_progress_status_line_has_no_time_but_its_tip_does: the tip
    # began with the @, the snapshot's time and an em space.)
    assert dict(got, status=[figures(s) for s in got['status']], tip=figures(got['tip'])) == dict(
        status=[figures(line(made, 7200)), figures(line(old, 10800))], tip=figures(line(made, 7200)),
        axis=time.strftime('%Y-%m-%d %H:%M', time.localtime(made)), mark=stamp(old), made=stamp(made)), got


def q_progress_writes_days_and_years_past_72_h_and_dates_past_a_week():
    # Replicata: progress_run('long'): PROGRESS_LONG's two running runs.
    # Expectata (dreeves, 2026-10-23: "this would be more helpful as days or years when over like 48 or maybe 72h, and
    # the parenthetical needs disambiguation when >1week"): each duration in hours below 72 h, in days below a year of
    # 365.25 d, in years from there, as before a tenth so far and to go and in all a tenth below 10 and whole from 10,
    # each with its own unit but a range's unit once when its ends share it: 14.2 h so far + 149.9 d–6.4 y to go =
    # 150 d–6.4 y, then 4.2 d so far + 0.5–3.0 h to go = 4.2–4.3 d; each finish time a week or more after the snapshot
    # as its local date, both of the first run's, YYYY-MM-DD; and the first run's ETA chart's axes each in the unit of
    # its largest value, hours of running in days, 0 to 400 d, and hours in all in days too, 0 to 300 d, as the y axis
    # stops a bit above the projected finish (dreeves, 2026-10-23; q_progress_caps_the_y_axis_above_the_projected_finish).
    # Spec change (Claude, 2026-11-06; dreeves: "i don't think we need "@2026-11-06 19:12:49" under the graph since the
    # search progress line above the progress bar shows the freshness"): the lines' text as their template gives it (its
    # textContent), its @, time and em space shown in the ETA chart's tip alone
    # (q_progress_status_line_has_no_time_but_its_tip_does).
    # Spec change (Claude, 2026-11-07; dreeves: "1. show elapsed time with full granularity like so: 3d 4h 5m 6s ... 3. no
    # need for the "so far" ... 4. sane number of sigfigs for everything else based in a principled way on the amount of
    # uncertainty"): the times so far 14h 12m 0s and 4d 4h 0m 0s, and every other figure to the uncertainty of its run's
    # band to go, half its width (q_progress_rounds_figures_to_their_uncertainty): the first's 3.0 y, so 150 d–6 y to go
    # and in all, the second's 1.25 h, so 1–3 h to go, 4.19–4.29 d in all (an hour is 0.04 d) and its finish times to
    # the hour; the dates as before.
    R = progress_run('long')
    made, (a, b) = PROGRESS_LONG['made'], [r['to_go'] for r in PROGRESS_LONG['runs']]
    h, d, y = NNBSP + 'h', NNBSP + 'd', NNBSP + 'y'
    date = lambda s: time.strftime('%Y-%m-%d', time.localtime(s))
    # Spec change (Opus 5.5, 2026-11-12; dreeves: "what if we showed the timestamp more subtly and showed it floating on
    # the x-axis matched up with the dashed vertical line on the graph marking the timestamp in question that we're
    # hovering over?"): the lines have no time of their own before them.
    want = [f'{hms(14.2 * HOURS)} + 150{d}–6{y} to go = 150{d}–6{y} ({date(made + a["lo"])} – {date(made + a["hi"])})',
            f'{hms(100 * HOURS)} + 1–3{h} to go = 4.19–4.29{d} ({finish(made, made + b["lo"], made + b["hi"], 1.25 * HOURS)})']
    assert [figures(s) for s in R['state']] == [figures(w) for w in want], (R['state'], want)
    parts = SvgParts()
    parts.feed(R['etaSvg'])
    ticks = lambda k: [text for tag, at, text in parts.items if at.get('class') == k]
    # (2026-11-12; dreeves: "could the graphs use more of the available horizontal space? no indenting, for one thing. ... how about end
    # the x-axis range right at the purple dashed vertical line?"): the x axis ends at the projected finish, 313 d, its round
    # ticks within it, the last with the unit; until then to the round tick past it, 400 d.
    assert ticks('xtick') == ['0', '100', '200', f'300{d}'], ticks('xtick')
    assert ticks('ytick') == ['0', '100', '200', f'300{d}', '6', f'8{y}'], ticks('ytick')   # then the top panel's


def q_progress_elapsed_is_days_hours_minutes_seconds_and_ticks():
    # Replicata: index.html with three runs as progress.js, each fold open, the page's clock (window.PROGRESS_CLOCK)
    # standing at the snapshot's time: PROGRESS_DATA's run, running, 273,905 s along, its last ETA record the snapshot's;
    # the same as a tracked search's (two runs, one running and one ended); and the same ended, 86,405 s along.  Then the
    # clock a second on, and then on to 4 d of running for the first two, each followed by a wait of 1.1 s, as the page
    # ticks each second; then a hover over the first run's ETA chart at its last record.
    # Expectata (dreeves, 2026-11-07, of 288:10's box: "redundant elapsed time here. let's keep the one in blue and nix
    # the one in black", "1. show elapsed time with full granularity like so: 3d 4h 5m 6s with spacing exactly like that
    # but the spaces are Narrow No-Break Spaces (unicode 8239)", "2. make it update second by second", "3. no need for
    # the "so far" -- the liveness make that obvious"; and "i do like the explicit hms better than colons, to help
    # distinguish from times-of-day"): each status line's time so far in days, hours, minutes and seconds, from the
    # largest unit it reaches down to the second, zeros between them shown, each number with its letter and a narrow no-
    # break space between them, and no "so far" in the line: 3d 4h 5m 5s for the running runs and 1d 0h 0m 5s for the
    # ended one; a second on, the running runs' 3d 4h 5m 6s, and at 4 d 4d 0h 0m 0s, the ended run's unchanged; the
    # snapshot's age in the same form, 0s, 1s, then 19h 54m 55s; the tip over the last record the snapshot's line, its
    # time so far 3d 4h 5m 5s however the clock goes on; and the tracked search's line of its runs with no time of its own.
    made, base = PROGRESS_DATA['made'], PROGRESS_DATA['runs'][0]
    running = dict(base, so_far=273905.0, etas=[[made - 3600, 270305.0, 7200.0, 3600.0, 14400.0], [made, 273905.0, 3600.0, 1800.0, 10800.0]])
    tracked = dict(running, tracked=True, work=dict(runs=2, running=1, frozen=0, ended=1, aborted=0, paused=0, found=0))
    ended = dict(base, state='ended', outcome=None, so_far=86405.0, to_go=None)
    got = progress_harness({'made': made, 'runs': [running, tracked, ended]}, """
  for (const r of runs()) r.querySelector('details').open = true;
  await sleep(200);
  const shown = r => [...r.querySelectorAll('.progress-status [data-state]')].filter(e => !e.hidden)[0];
  const read = () => ({lines: runs().map(r => shown(r).innerText), soFar: runs().map(r => shown(r).querySelector('[data-so-far]').textContent),
                       age: document.querySelector('section.progress [data-age]').textContent});
  const first = read();
  window.clockAt = 1;
  await sleep(1100);
  const second = read();
  window.clockAt = 4 * 86400 - 273905;
  await sleep(1100);
  const third = read();
  const [r] = runs(), L = window.progressView.layouts[0], svg = r.querySelector('.progress-eta svg'), sb = svg.getBoundingClientRect();
  svg.dispatchEvent(new MouseEvent('mousemove', {clientX: sb.left + L.etaXs[L.etaXs.length - 1] * sb.width / svg.viewBox.baseVal.width, clientY: sb.top + sb.height / 2, bubbles: true}));
  out({first, second, third, tip: r.querySelector('[data-tip] [data-so-far]').textContent,
       track: runs()[1].querySelector('[data-track-line]').textContent.replace(/\\s+/g, ' ').trim(),
       trackElapsed: runs()[1].querySelectorAll('[data-track-line] [data-elapsed]').length});""",
        before='<script>window.clockAt = 0; window.PROGRESS_CLOCK = () => window.progressView.data.made + window.clockAt;</script>\n')
    N = NNBSP
    assert got['first']['soFar'] == [f'3d{N}4h{N}5m{N}5s', f'3d{N}4h{N}5m{N}5s', f'1d{N}0h{N}0m{N}5s'], got['first']
    assert got['second']['soFar'] == [f'3d{N}4h{N}5m{N}6s', f'3d{N}4h{N}5m{N}6s', f'1d{N}0h{N}0m{N}5s'], got['second']
    assert got['third']['soFar'] == [f'4d{N}0h{N}0m{N}0s', f'4d{N}0h{N}0m{N}0s', f'1d{N}0h{N}0m{N}5s'], got['third']
    assert [got[k]['age'] for k in ('first', 'second', 'third')] == ['0s', '1s', f'19h{N}54m{N}55s'], got
    assert not any('so far' in line for k in ('first', 'second', 'third') for line in got[k]['lines']), got
    assert got['tip'] == f'3d{N}4h{N}5m{N}5s', got['tip']
    # (Spec change, 2026-11-13: the line counts the paused runs too, after the aborted; track.py pause.)
    assert got['trackElapsed'] == 0 and figures(got['track']) == figures('2 runs: 1 running, 0 frozen, 1 ended, 0 aborted, 0 paused; 0 found; running.'), got['track']


def q_progress_rounds_figures_to_their_uncertainty():
    # Replicata: index.html with three running runs as progress.js, made at 8:03pm on Saturday 2026-11-07, local time,
    # each fold open: the first 3d 4h 48m 0s along with 15.6 h to 74.2 h to go (to finish between 11:39am on Sunday
    # and 10:17pm on Tuesday: dreeves's example of that day); the second 2 h along with 2.3 to 2.6 h to go; the third 2 h
    # along with 40 to 100 min to go.
    # Expectata (dreeves, 2026-11-07: "4. sane number of sigfigs for everything else based in a principled way on the
    # amount of uncertainty. for example: * "Sun 11:39am - Tue 10:17pm" should instead be "Sun 12pm - Tue 10pm" *
    # "15.6h - 3.1d" should instead be "16h - 3d""): each figure but the time so far rounded to its uncertainty u, half
    # the width of the interval to go, which the time in all and the finish times share: a duration in its unit to the
    # place of u's first significant digit, but no coarser than a whole unit; a clock time to the largest of the hour,
    # ten minutes and the minute that u reaches, to the hour without its minutes.  The first run's u is 29.3 h: 16 h–3 d
    # to go, 4–6 d in all, Sun 12pm – Tue 10pm; the second's 9 min: 2.3–2.6 h to go, 4.3–4.6 h in all and its finish
    # times to the minute; the third's 30 min: 0.7–1.7 h to go, 2.7–3.7 h in all and its finish times to ten minutes.
    made, base, h = time.mktime((2026, 11, 7, 20, 3, 0, 0, 0, -1)), PROGRESS_DATA['runs'][0], 3600
    run = lambda x, lo, hi: dict(base, so_far=float(x), to_go=dict(median=(lo + hi) / 2, lo=float(lo), hi=float(hi)),
                                 etas=[[made, float(x), (lo + hi) / 2, float(lo), float(hi)]])
    data = {'made': made, 'runs': [run(3 * 86400 + 4 * h + 48 * 60, 15.6 * h, 74 * h + 14 * 60), run(2 * h, 2.3 * h, 2.6 * h), run(2 * h, 2400, 6000)]}
    got = progress_harness(data, """
  for (const r of runs()) r.querySelector('details').open = true;
  await sleep(200);
  out(runs().map(r => [...r.querySelectorAll('.progress-status [data-state]')].filter(e => !e.hidden)[0].innerText.replace(/[ \\t\\n\\r]+/g, ' ').trim()));""")
    N = NNBSP
    assert [figures(s) for s in got] == [figures(s) for s in (
        f'3d{N}4h{N}48m{N}0s + 16{N}h–3{N}d to go = 4–6{N}d (Sun 12pm – Tue 10pm)',
        f'2h{N}0m{N}0s + 2.3–2.6{N}h to go = 4.3–4.6{N}h (Sat 10:21pm – 10:39pm)',
        f'2h{N}0m{N}0s + 0.7–1.7{N}h to go = 2.7–3.7{N}h (Sat 8:40pm – 9:40pm)')], got


def q_progress_draws_cpu_aligned_with_the_eta_chart():
    # Replicata: the harness's run (PROGRESS_DATA), its ETA records at 0, 1 and 2 h of running, its cpu rows the search,
    # other processes and idle over 0-1 h (0.5, 0.3, 0.2) and 1-2 h (0.25, 0.25, 0.5).
    # Expectata (dreeves, 2026-11-07: "could we get a nice CPU usage graph on the search page? similar to what activity
    # monitor shows. three colors: one for the search, one for all other processes on the machine, and one for idle, if
    # any", then "maybe aligned with the ETA graph"): below the ETA chart, its status line and its notes on Lindy's rule
    # and the later stages (spec change, the same day: "let's keep the blue/red/purple line of numbers directly below the
    # ETA graph, not below the CPU graph", then "not the black text line though": a tracked search's counts of its runs,
    # [data-track-line], follow it; before it, right under the ETA chart), a CPU chart as wide, three bands stacked from the bottom in that order (classes band search, band other, band idle), each one
    # polygon over the two rows (one stretch, no gap), every band's left and right edges at the ETA chart's x of 0 and 2 h
    # (its records' xs: the same axis); the bands' tops the shares' sums on a 0-100% scale, the search's at 50% then 25%,
    # other processes' at 80% then 50%, idle's at 100%; and its key's readout, at rest, the latest row's shares at its
    # time: "search 25% · other processes 25% · idle 50%".
    # Resultata before: no CPU chart.
    # Spec change (Claude, 2026-11-08; dreeves: "might as well combine the percentages with the legend here"): the
    # latest row's shares are in the key's entries, search 25%, other processes 25%, idle 50%
    # (q_progress_cpu_key_carries_each_share), and the readout names its time; until then the readout gave both.
    R = progress_run()
    c = R['cpu']
    assert c is not None, 'no CPU chart'
    assert c['after'] and c['afterStatus'] and c['trackLineAfter'] and abs(c['widths'][0] - c['widths'][1]) < 0.5, c
    assert [k for k, _ in c['bands']] == ['band search', 'band other', 'band idle'], c['bands']
    x0, x2 = c['etaXs'][0], c['etaXs'][2]
    # (2026-11-12: its x axis labeled as the ETA chart's, the hours in a band at its foot as tall as that chart's, so
    # that the time under the pointer can float there: 98 high, 30 at the foot; 72 and 4 until then)
    # (2026-11-12; dreeves: "could the graphs use more of the available horizontal space? no indenting, for one thing. ... how about end
    # the x-axis range right at the purple dashed vertical line?"): its value labels inside it, "100%" over its top, so 16 at
    # the top (4 until then) and 110 high, the plot as tall as before.
    H, T, B = 110, 16, 30
    Y = lambda f: H - B - (H - B - T) * f
    for (_, points), tops in zip(c['bands'], ([0.5, 0.25], [0.8, 0.5], [1.0, 1.0])):
        ps = [tuple(map(float, p.split(','))) for p in points.split()]
        xs = [x for x, _ in ps]
        assert abs(min(xs) - x0) < 0.02 and abs(max(xs) - x2) < 0.02, (points, x0, x2)
        upper = [y for x, y in ps[:4]]
        want = [Y(tops[0]), Y(tops[0]), Y(tops[1]), Y(tops[1])]
        assert all(abs(a - b) < 0.02 for a, b in zip(upper, want)), (upper, want)
    assert c['shares'] == dict(search='25%', other='25%', idle='50%'), c


def q_progress_cpu_key_carries_each_share():
    # Replicata: index.html with PROGRESS_DATA's run as progress.js, its fold open: its CPU rows the search, other
    # processes and idle over 0-1 h (0.5, 0.3, 0.2, ending an hour before the snapshot) and 1-2 h (0.25, 0.25, 0.5,
    # ending at it); the CPU chart's key at rest, then with the pointer over the first hour.
    # Expectata (dreeves, 2026-11-08: "might as well combine the percentages with the legend here"): each of the key's
    # entries (search, other, idle) holds its own share of the latest row, 25%, 25% and 50%, and the readout after them
    # that row's time and no share; with the pointer over the first hour, the first row's shares, 50%, 30% and 20%, and
    # its time.
    # Resultata before: the key's entries held no shares; the readout gave the time and all three shares, in a line of
    # its own after the key.
    made = PROGRESS_DATA['made']
    got = progress_harness(PROGRESS_DATA, """
  for (const r of runs()) r.querySelector('details').open = true;
  await sleep(200);
  const fig = runs()[0].querySelector('.progress-cpu'), svg = fig.querySelector('svg');
  const read = () => {
    const shares = [...fig.querySelectorAll('[data-cpu-share]')];
    return {shares: Object.fromEntries(shares.map(e => [e.dataset.cpuShare, e.textContent.trim()])),
            inEntries: shares.length === 3 && shares.every(e => { const entry = e.closest('.progress-cpu-key > span'); return !!entry && entry.classList.contains(e.dataset.cpuShare); }),
            stamp: fig.querySelector('[data-stamp]').getAttribute('visibility') === 'visible' ? fig.querySelector('[data-stamp] text').textContent : null,
            key: fig.querySelector('.progress-cpu-key').textContent};
  };
  const rest = read();
  const L = window.progressView.layouts[0], sb = svg.getBoundingClientRect(), x = L.etaXs[0] + 0.5 * (L.etaXs[1] - L.etaXs[0]);
  svg.dispatchEvent(new MouseEvent('mousemove', {clientX: sb.left + x * sb.width / svg.viewBox.baseVal.width, clientY: sb.top + sb.height / 2, bubbles: true}));
  out({rest, hover: read()});""")
    rest, hover = got['rest'], got['hover']
    assert rest['shares'] == dict(search='25%', other='25%', idle='50%') and rest['inEntries'], got
    # Spec change (Opus 5.5, 2026-11-12; dreeves: "could you improve the consistency of the graphs a little? font sizes
    # and whether graphs are labeled above or below the graph. ... what if we showed the timestamp more subtly and showed
    # it floating on the x-axis matched up with the dashed vertical line on the graph marking the timestamp in question
    # that we're hovering over?"): the key has no
    # time; the row's floats on the chart's x axis at the cross while the pointer is over it, its end's, local, to the
    # minute, and at rest none shows.  (Until then the readout after the key gave the row's time, at rest the latest's.)
    assert rest['stamp'] is None and '@' not in rest['key'], got
    assert hover['shares'] == dict(search='50%', other='30%', idle='20%') and hover['inEntries'], got
    assert hover['stamp'] == time.strftime('%Y-%m-%d %H:%M', time.localtime(made - 3600)) and '@' not in hover['key'], got


def q_progress_cpu_chart_shows_no_paper_between_its_bands():
    # Replicata: index.html with one running run as progress.js, its fold open, 6 h along: its ETA records at 0 and 6
    # h, its CPU rows 480 one-minute-wide steps... over its first hour, so several to a pixel, the search's share
    # zigzagging between 45% and 85% (1 - 0.4 |sin|, a row apart), other processes' the rest, idle none; a screenshot
    # of its CPU chart alone, everything else hidden, at device scales 1 and 2.
    # Expectata (dreeves, 2026-11-07, of 288:10's CPU chart, idle 0% in its readout: "shouldn't that imply the CPU graph
    # is completely blue and brown? what's the white (gray?) i see between the blue and brown?"): in every column the
    # search's blue reaches, every pixel from the bands' lowest to their highest is the search's blue, other
    # processes' color (--cpu-other: brown until 2026-11-08, magenta since) or a blend of the two (within 40 of one in
    # RGB): no paper between them.
    # Resultata before: each band outlined by a hairline of paper (0.75 px), which traced every step of the border
    # between blue and brown, several to a pixel: about a fifth of those pixels paper or near it.
    made, base = PROGRESS_DATA['made'], PROGRESS_DATA['runs'][0]
    search = [1 - 0.4 * abs(math.sin(i)) for i in range(480)]
    cpu = [[i / 480, (i + 1) / 480, made - 5 * HOURS + 7.5 * (i + 1), s, 1 - s, 0.0] for i, s in enumerate(search)]
    run = dict(base, so_far=6 * HOURS, etas=[[made - 6 * HOURS, 0.0, 6 * HOURS, 3 * HOURS, 9 * HOURS], [made, 6 * HOURS, 1800.0, 900.0, 3600.0]],
               to_go=dict(median=1800.0, lo=900.0, hi=3600.0), cpu=cpu)
    color = lambda name: rgb(re.search(rf'{name}: (#[0-9a-f]{{6}});', page_css()).group(1))
    blue, other = color('--progress-spent'), color('--cpu-other')         # the search's (--cpu-search) and other processes'
    def apart(p):                                  # how far the color p is from every blend of the blue and the other
        d = [b - a for a, b in zip(blue, other)]
        t = max(0.0, min(1.0, sum((x - a) * e for x, a, e in zip(p, blue, d)) / sum(e * e for e in d)))
        return math.dist(p, [a + t * e for a, e in zip(blue, d)])
    from PIL import Image
    for scale in (1, 2):
        d = tempfile.mkdtemp(prefix='index-quals-')
        keep = ('<script>localStorage.setItem("progress-open", "1"); localStorage.setItem("progress-fold overnight_v5.py 64 7", "1");</script>\n'
                '<style>main > *:not(section.progress) { display: none !important; } body * { visibility: hidden !important; } '
                '.progress-cpu svg, .progress-cpu svg * { visibility: visible !important; } .progress-cpu .cross { visibility: hidden !important; } '
                # its hour labels (2026-11-12) and the time's box, which the rule above would show, hidden as the cross is
                '.progress-cpu text, .progress-cpu .stamp, .progress-cpu .stamp * { visibility: hidden !important; } '
                # and the page's error box (2026-11-12), outside the body: the m*(n) chart, hidden here, fails its own assert of
                # a width above 0, which the box shows; this qual is of the CPU chart's pixels alone
                '#page-errors { display: none !important; }</style>\n')
        open(os.path.join(d, 'index.html'), 'w', encoding='utf-8').write(page().replace('<head>\n', '<head>\n' + keep))
        copy_page_dir(d)
        open(data_file(d, 'progress.js'), 'w', encoding='utf-8').write(progress_text({'made': made, 'runs': [run]}))
        shutil.copy(DATA, data_file(d, 'mstar.js'))
        shutil.copy(POW2, data_file(d, 'pow2.js'))
        shot = os.path.join(d, 'shot.png')
        chrome(d, ['--window-size=1000,1400', f'--force-device-scale-factor={scale}', '--virtual-time-budget=8000',
                   '--run-all-compositor-stages-before-draw', f'--screenshot={shot}', 'file://' + os.path.join(d, 'index.html')])
        img = Image.open(shot).convert('RGB')
        shutil.rmtree(d)
        px, (w, h), bad, total = img.load(), img.size, 0, 0
        for x in range(w):
            ys = [y for y in range(h) if apart(px[x, y]) <= 40]
            # no search's blue in this column (until 2026-11-08 any blue channel above 150, which other processes' magenta
            # has too: the gray of the "100%" label's glyphs, near the blends of blue and magenta, then made a column)
            if not any(math.dist(px[x, y], blue) <= 40 for y in ys): continue
            span = range(min(ys), max(ys) + 1)
            total += len(span)
            bad += sum(apart(px[x, y]) > 40 for y in span)
        assert total > 2000 * scale * scale and bad == 0, (scale, bad, total)


def q_progress_breaks_the_y_axis_above_the_projected_finish():
    # Replicata: the ETA charts of progress_run('long') (480:14's bands, thousands of hours above its projected
    # finish), of progress_run('eta') (its purple band's top 0.6 h above the cap) and of progress_run('narrow') (bands
    # within the cap), as markup.
    # Expectata (dreeves, 2026-10-23: "truncate the y-axis a bit above the horizontal purple dashed line ... and
    # indicate visually in some way (no words) when the confidence bands go above the y-axis cap", then "can you do
    # something more canonical for the y-axis break? maybe something like this?", a two-panel plot with slashes at the
    # break): the main panel stops at the cap, 10% above the projected finish, the purple guide's level, its top edge a
    # cap line; anything above the cap, as long's and eta's band tops, gets a top panel 40 units tall, 10 above the
    # main one, linear from the round tick of its unit at or below the least such value (but no lower than the cap) to
    # the round tick at or above the greatest, labeled at the round ticks at its ends, the last with its unit (four
    # labels crowded 480's 40 units); no line at either panel's edge (dreeves, 2026-10-23: "why does this look so bad?
    # the excess horizontal lines": the edges sat a few units from gridlines), so no two horizontal lines within 4
    # units; the 10 units between clipped away; a y axis line at
    # the plot's left (dreeves, 2026-10-23: "i think we need a visible y-axis line for that to look reasonable"), up
    # from the x axis to the main panel's top and from the top panel's bottom to its top, broken at the gap, with a
    # slash across each end of the break (none at the right, where no line is); every band vertex in one panel or on an
    # edge of the gap; and narrow has one panel: its y axis whole, its slashes hidden, nothing clipped.
    # Spec change (dreeves, 2026-11-04, of a break whose band top sat just above the cap: "does the y-axis break in this
    # particular graph make sense?", then of a break only where it gives the main panel a larger scale than one axis up
    # to the tallest value would: "sounds like your principled fix should work. updating the quals is fine."): eta's
    # tallest value, its band top at 16.2 h, is 1.04 times the cap, under the 196/146 = 1.34 at which a break gains room,
    # so eta has one panel, up to that top, 16.2/14.2 times the projected finish; long's, 6.8 times, still breaks.
    # Until then eta's band top went to a top panel from 15.62 h to 20 h, labeled 20 h.
    for case, over, labels, ratio in (('long', True, ['6', '8\u202fy'], 1.1), ('eta', False, [], 16.2 / 14.2), ('narrow', False, [], 1.1)):
        parts = SvgParts()
        parts.feed(progress_run(case)['etaSvg'])
        pts = lambda a: [tuple(map(float, xy.split(','))) for xy in a['points'].split()]
        seg = lambda a: tuple(float(a[k]) for k in ('x1', 'y1', 'x2', 'y2'))
        [(x0, axis)] = [(float(a['x1']), float(a['y1'])) for tag, a, _ in parts.items if tag == 'line' and a.get('class') == 'axis']   # where the x axis starts, and its height
        [guide] = [pts(a) for tag, a, _ in parts.items if tag == 'polyline' and a.get('class') == 'guide']
        clip = SvgParts()                                    # the clip path's rects (the time's box, since 2026-11-12, is none of them)
        clip.feed(re.search(r'<clipPath.*?</clipPath>', progress_run(case)['etaSvg'], re.S).group(0))
        rects = [tuple(float(a[k]) for k in ('x', 'y', 'width', 'height')) for tag, a, _ in clip.items if tag == 'rect']
        yt, yb = rects[0][3], rects[1][1]                     # the top panel's bottom edge, the main panel's top
        assert abs((axis - yb) - ratio * (axis - guide[0][1])) < 0.05, (case, axis, yb, guide[0])
        assert not [a for tag, a, _ in parts.items if a.get('class') == 'cap'], case
        rows = sorted({round(seg(a)[1], 2) for tag, a, _ in parts.items if tag == 'line' and a.get('class') in ('grid', 'axis')})
        assert all(b - a >= 4 for a, b in zip(rows, rows[1:])), (case, rows)
        assert (yt, yb) == ((54.0, 64.0) if over else (14.0, 14.0)), (case, yt, yb)
        breaks = [(seg(a), a.get('visibility')) for tag, a, _ in parts.items if tag == 'line' and a.get('class') == 'break']
        # (2026-11-12; dreeves: "could the graphs use more of the available horizontal space? no indenting, for one thing. ... how about end
    # the x-axis range right at the purple dashed vertical line?"): the y axis at the chart's left edge, x 0 (48 until then),
        # and its value labels inside, 3 above their gridlines (4 below their values until then).
        # Spec change (Opus 5.5, 2026-11-12, later; dreeves, of those labels: "is that standard at all to put the [y]-axis
        # annotations to the right of the [y]-axis? or were you just taking me extremely literally?", then, of a proposal to
        # drop the y axis line: "i'm guessing the axis break slashes will make no visual sense without an axis line"): the y
        # axis's line where the x axis starts, x0, past a margin that holds the value labels, outside the plot again, each
        # right-aligned 6 short of the line and 4 below its value; the slashes across the line.
        assert x0 > 0 and sorted(s for s, _ in breaks) == sorted((x0 - 4, y + 4, x0 + 4, y - 4) for y in (yt, yb)), (case, x0, breaks)
        spine = sorted(seg(a) for tag, a, _ in parts.items if tag == 'line' and a.get('class') == 'yaxis')
        assert spine == sorted([(x0, axis, x0, yb), (x0, yt, x0, 14)]), (case, spine)
        assert all(v == ('visible' if over else 'hidden') for _, v in breaks), (case, breaks)
        ticks = [a for tag, a, _ in parts.items if tag == 'text' and a.get('class') == 'ytick']
        assert ticks and all(a.get('text-anchor') == 'end' and float(a['x']) == x0 - 6 for a in ticks), (case, ticks)
        top = [(float(a['y']) - 4, t) for tag, a, t in parts.items if tag == 'text' and a.get('class') == 'ytick' and float(a['y']) - 4 < yb - 0.05]
        assert [t for _, t in top] == labels and all(14 - 0.05 <= y <= yt + 0.05 for y, _ in top), (case, top)
        W = float(re.search(r'viewBox="0 0 ([0-9.]+) 240"', progress_run(case)['etaSvg']).group(1))   # its width in CSS px (2026-11-12; 640 units until then)
        assert rects == [(0, 0, W, yt), (0, yb, W, 240 - yb)], (case, rects)
        bands = [y for tag, a, _ in parts.items if tag == 'polygon' for _, y in pts(a)]
        assert all(14 - 0.05 <= y <= yt + 0.05 or yb - 0.05 <= y for y in bands), (case, sorted(bands))
        assert any(y < yb - 0.05 for y in bands) == over, case


def from_oklab(lab):
    """An OKLab color as #rrggbb, its sRGB clipped: the inverse of oklab(linear(h))."""
    L, a, b = lab
    l, m, s = [(L + x * a + y * b) ** 3 for x, y in ((0.3963377774, 0.2158037573), (-0.1055613458, -0.0638541728), (-0.0894841775, -1.2914855480))]
    lin = (4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
           -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s)
    enc = [12.92 * c if c <= 0.0031308 else 1.055 * c ** (1 / 2.4) - 0.055 for c in (min(1, max(0, c)) for c in lin)]
    return '#' + ''.join(f'{round(255 * v):02x}' for v in enc)


def q_progress_bands_overlap_visibly():
    # Replicata: the page's CSS: the ETA's band and elapsed + ETA's, each color-mix(in oklab, its color N%, the paper),
    # multiplied onto what is under them; so the three regions they make on the paper: the ETA's band alone, elapsed +
    # ETA's alone, and both.
    # Expectata (dreeves, 2026-10-23: "shouldn't we be able to visually distinguish between a region that both red and
    # purple confidence bands cover vs just the purple confidence band covering it?"; at 16% and 16% that pair was ΔE
    # 6.1, OKLab x 100): both at least ΔE 13 from purple alone and 11 from red alone, and red alone 7 from purple alone.
    style = page_css()
    color = lambda name: re.search(rf'--{name}: (#[0-9a-f]{{6}});', style).group(1)
    pct = lambda name: int(re.search(rf'\.progress-eta \.band\.{name} \{{ fill: color-mix\(in oklab, var\(--progress-{name}\) (\d+)%, var\(--paper\)\); \}}', style).group(1)) / 100
    paper = oklab(linear(color('paper')))
    def wash(name):
        c = oklab(linear(color(f'progress-{name}')))
        return from_oklab([pct(name) * x + (1 - pct(name)) * y for x, y in zip(c, paper)])
    red, purple = wash('togo'), wash('total')
    rgb = lambda h: [int(h[i:i + 2], 16) / 255 for i in (1, 3, 5)]
    both = '#' + ''.join(f'{round(255 * x * y):02x}' for x, y in zip(rgb(red), rgb(purple)))   # multiply, as the blend does
    got = (delta_e(purple, both), delta_e(red, both), delta_e(red, purple))
    assert got[0] >= 13 and got[1] >= 11 and got[2] >= 7, got


def q_progress_reloads_on_returning_to_the_tab():
    # Replicata: index.html with PROGRESS_DATA as progress.js, the section left open (PROGRESS_REMEMBERED) and the
    # minute's poll; after its first load, a visibilitychange event, as when the tab comes back into view.
    # Expectata (dreeves, 2026-10-23: "did you break auto-refresh yet again?", the page having polled nothing while its
    # tab was hidden): a load at once, not up to a minute later.
    d = tempfile.mkdtemp(prefix='index-quals-')
    harness = """<script>
(async () => {
  const sleep = ms => new Promise(r => setTimeout(r, ms));
  await sleep(1500);
  const before = window.progressView.loads;
  document.dispatchEvent(new Event('visibilitychange'));
  await sleep(50);
  const pre = document.createElement('pre'); pre.id = 'harness-out';
  pre.textContent = JSON.stringify({before, after: window.progressView.loads}); document.body.appendChild(pre);
})();
</script>
"""
    text = page().replace('<head>\n', '<head>\n' + PROGRESS_REMEMBERED).replace('</body>', harness + '</body>')
    open(os.path.join(d, 'index.html'), 'w', encoding='utf-8').write(text)
    copy_page_dir(d)
    open(data_file(d, 'progress.js'), 'w', encoding='utf-8').write(progress_text(PROGRESS_DATA))
    shutil.copy(DATA, data_file(d, 'mstar.js'))
    shutil.copy(POW2, data_file(d, 'pow2.js'))
    dom = chrome(d, ['--virtual-time-budget=5000', '--dump-dom', 'file://' + os.path.join(d, 'index.html')])
    shutil.rmtree(d)
    m = re.search(r'<pre id="harness-out">(.*?)</pre>', dom, re.S)
    assert m, dom[-2000:]
    got = json.loads(html.unescape(m.group(1)))
    assert got['before'] >= 1 and got['after'] == got['before'] + 1, got


FOLD = 'progress-fold '         # localStorage: "1" under this prefix and a run's program, n and order while its fold is open
# two runs whose folds have names of their own: PROGRESS_DATA's running one and PROGRESS_ETA_DATA's ended one as
# boxsplit.py's, with no outcome
PROGRESS_FOLDS = {'made': PROGRESS_DATA['made'],
                  'runs': [PROGRESS_DATA['runs'][0], dict(PROGRESS_ETA_DATA['runs'][0], program='boxsplit.py')]}
# The page with data as progress.js and harness (a script) run in it, the section open and before (a script) run before
# the page's own: what the harness put in <pre id="harness-out">, as JSON.
FOLD_LOOK = """
  const sleep = ms => new Promise(r => setTimeout(r, ms));
  const runs = () => [...document.querySelectorAll('.progress-runs .progress-run')];
  const look = () => runs().map(r => ({state: r.dataset.runState, open: r.querySelector('details').open,
    summary: !!r.querySelector('summary h3'), color: getComputedStyle(r.querySelector('summary')).color,
    status: r.querySelector('.progress-status').checkVisibility(), canvas: r.querySelector('canvas').width,
    label: [...r.querySelectorAll('summary [data-label]')].filter(e => e.checkVisibility()).map(e => e.dataset.label)}));
  const out = x => { const pre = document.createElement('pre'); pre.id = 'harness-out'; pre.textContent = JSON.stringify(x); document.body.appendChild(pre); };
"""


def progress_harness(data, harness, before=''):
    d = tempfile.mkdtemp(prefix='index-quals-')
    script = '<script>\n(async () => {' + FOLD_LOOK + '  await sleep(1500);\n' + harness + '\n})();\n</script>\n'
    text = page().replace('<head>\n', '<head>\n' + PROGRESS_REMEMBERED + PROGRESS_FROZEN + before).replace('</body>', script + '</body>')
    open(os.path.join(d, 'index.html'), 'w', encoding='utf-8').write(text)
    copy_page_dir(d)
    open(data_file(d, 'progress.js'), 'w', encoding='utf-8').write(progress_text(data))
    shutil.copy(DATA, data_file(d, 'mstar.js'))
    shutil.copy(POW2, data_file(d, 'pow2.js'))
    dom = chrome(d, ['--window-size=1000,1100', '--virtual-time-budget=5000', '--dump-dom', 'file://' + os.path.join(d, 'index.html')])
    shutil.rmtree(d)
    m = re.search(r'<pre id="harness-out">(.*?)</pre>', dom, re.S)
    assert m, dom[-2000:]
    return json.loads(html.unescape(m.group(1)))


def q_progress_folds_stay_as_left():
    # Replicata: index.html with PROGRESS_FOLDS as progress.js, the section open and no fold stored; then the running
    # run opened by hand, as by a click; a snapshot in which it has ended; then it closed by hand.
    # Expectata (dreeves, 2026-10-25: "i think there's some anti-magic violation with the collapsed/expanded state.
    # probably they should just remember in localstorage what their state is and just always stay that way until
    # explicitly clicked"): both runs listed, each folded under its heading (a summary) whatever its state, its status
    # line folded with its charts, its dots sized to the section's width though folded, the run not running grayed;
    # opened by hand, a run's fold is stored, "1" under FOLD and its program, n and order, and stays open across the
    # snapshot that ends the run; closed by hand, its stored fold is gone.
    # Resultata before (2026-10-23's design): the running run's fold opened by itself and the ended one's folded, and
    # a fold opened or closed by hand was kept in memory only, so a reload forgot it.
    got = progress_harness(PROGRESS_FOLDS, """
  const name = 'progress-fold overnight_v5.py 64 7', first = look();
  runs()[0].querySelector('details').open = true;
  await sleep(50);
  const stored = localStorage.getItem(name);
  const d2 = JSON.parse(JSON.stringify(window.progressView.data)); d2.made += 60; d2.runs[0].state = 'ended'; d2.runs[0].to_go = null;
  window.progressData(d2);
  await sleep(50);
  const after = look();
  runs()[0].querySelector('details').open = false;
  await sleep(50);
  out({first, stored, after, cleared: localStorage.getItem(name)});""")
    first, after = got['first'], got['after']
    assert [(r['state'], r['open'], r['summary'], r['status']) for r in first] == [('running', False, True, False), ('ended', False, True, False)], first
    assert first[1]['color'] != first[0]['color'], first                 # grayed: not the running heading's color
    assert first[1]['canvas'] == first[0]['canvas'] > 100, first        # sized to the section, folded or not
    assert got['stored'] == '1', got
    assert [(r['state'], r['open'], r['status']) for r in after] == [('ended', True, True), ('ended', False, False)], after
    assert got['cleared'] is None, got


def q_progress_folds_are_remembered_across_loads():
    # Replicata: index.html with PROGRESS_FOLDS as progress.js, the section open, and this browser having left the
    # ended run's fold open (stored before the page's scripts run) and the running run's never opened.
    # Expectata (dreeves, 2026-10-25, as for q_progress_folds_stay_as_left): the ended run open and the running run
    # folded, each as this browser left it, whatever its state.
    got = progress_harness(PROGRESS_FOLDS, '  out(look());',
                           before='<script>localStorage.setItem("progress-fold boxsplit.py 64 7", "1");</script>\n')
    assert [(r['state'], r['open'], r['status']) for r in got] == [('running', False, False), ('ended', True, True)], got


def q_progress_redraw_keeps_the_scroll_position():
    # Replicata: index.html with three runs as progress.js (PROGRESS_FOLDS's two and a third at n 72), the section
    # and every run's fold open, scroll anchoring off (overflow-anchor: none, as in a browser without it, like Safari),
    # the page scrolled to its bottom, where the section sits; then a new snapshot of the same runs, which redraws them.
    # Expectata (dreeves, 2026-10-26: "Every time the graph updates the page scrolls itself"): the redraw leaves the
    # page where it was, the scroll position and the page's height the same before and after.
    # Resultata before the fix: 715 px up. render emptied the runs and rebuilt them one by one, and each run's sea
    # measured the runs' width (runsBox.clientWidth), a layout of the page with only the runs rebuilt so far, shorter,
    # so the browser pulled the scroll position up to fit it, and there it stayed (Chrome's scroll anchoring put it
    # back, when its anchor survived the rebuild).
    data = {'made': PROGRESS_FOLDS['made'], 'runs': PROGRESS_FOLDS['runs'] + [dict(PROGRESS_FOLDS['runs'][0], n=72)]}
    opened = ''.join(f'localStorage.setItem("progress-fold {r["program"]} {r["n"]} {r["order"]}", "1");' for r in data['runs'])
    got = progress_harness(data, """
  window.scrollTo(0, document.documentElement.scrollHeight);
  await sleep(50);
  const before = {y: window.scrollY, h: document.documentElement.scrollHeight, open: look().map(r => r.open)};
  const d2 = JSON.parse(JSON.stringify(window.progressView.data)); d2.made += 60; window.progressData(d2);
  await sleep(50);
  out({before, after: {y: window.scrollY, h: document.documentElement.scrollHeight, renders: window.progressView.renders}});""",
                           before=f'<script>{opened}</script>\n<style>* {{ overflow-anchor: none; }}</style>\n')
    assert got['before']['open'] == [True, True, True], got
    assert got['before']['y'] > 0 and got['after']['renders'] == 2, got
    assert (got['after']['y'], got['after']['h']) == (got['before']['y'], got['before']['h']), got


def q_progress_summary_names_each_run_s_state():
    # Replicata: index.html with five runs as progress.js, the section open, every fold folded: running, paused,
    # frozen, ended with an outcome (excluded) and ended with none (its process gone without a finish, as a stopped or
    # crashed run).
    # Expectata (dreeves, 2026-10-25: "can these be clearer when collapsed about what's paused/completed/aborted/
    # running?"): each run's summary, folded, shows the label of its state, running, paused, frozen, completed or
    # aborted (data-label), and no other.
    # Resultata before: no word; a run not running was only grayed.
    base = dict(PROGRESS_DATA['runs'][0], to_go=None)
    runs = [dict(base, n=64 + 8 * i, state=state, outcome=outcome) for i, (state, outcome) in
            enumerate([('running', None), ('paused', None), ('frozen', None), ('ended', 'excluded'), ('ended', None)])]
    got = progress_harness({'made': PROGRESS_DATA['made'], 'runs': runs}, '  out(look());')
    assert [(r['state'], r['open'], r['label']) for r in got] == [
        ('running', False, ['running']), ('paused', False, ['paused']), ('frozen', False, ['frozen']),
        ('ended', False, ['completed']), ('ended', False, ['aborted'])], got


def q_progress_says_when_an_eta_is_lindy():
    # Replicata: index.html with three runs of 768:12 as progress.js: a tracked search running on Gott's rule alone
    # (lindy true), the same with its own estimate (lindy false), and an untracked run (no lindy field).
    # Expectata (dreeves, 2026-11-04: "i think the graph should say if it's just using lindy"): the first run's note
    # below its ETA chart shown, and not empty; the other two runs' notes hidden.  Its words are not pinned (dreeves
    # wrote his own the same day, and no qual pins wording since 2026-10-26).
    # Resultata before: no such note on the page.
    # Fixture change (Claude, 2026-11-06; dreeves: "go with 50% as the ignorant prior when there's no model or whatever",
    # and "for anti-magic i don't want to conditionally include or exclude graphs"): odds, as every run's data carries them.
    base, made = PROGRESS_DATA['runs'][0], PROGRESS_DATA['made']
    plain = dict(program='w12.py', n=768, order=12, state='running', outcome=None, so_far=600,
                 to_go=dict(median=600, lo=600 / 19, hi=19 * 600),
                 etas=[[made - 60, 540.0, 540.0, 28.4, 10260.0], [made, 600.0, 600.0, 31.6, 11400.0]],
                 statuses=base['statuses'], depth=0, keys=['768:12'], groups=['4'],
                 counts=dict(settled=0, open=0, split=0, pending=0, running=1), stale=None, odds=ODDS_IGNORANT,
                 cpu=[])   # (2026-11-07: every run's data carry its CPU series, none here)
    work = dict(runs=1, running=1, frozen=0, ended=0, aborted=0, paused=0, found=0)   # paused: a count of the form since 2026-11-13 (track.py pause)
    lindy, own = dict(plain, tracked=True, work=work, lindy=True), dict(plain, tracked=True, work=work, lindy=False)
    got = progress_harness({'made': made, 'runs': [lindy, own, plain]}, """
  const notes = runs().map(box => box.querySelector('[data-lindy]'));
  out(notes.map(e => e && {hidden: e.hidden, text: e.textContent.trim()}));""")
    assert all(got) and [n['hidden'] for n in got] == [False, True, True] and got[0]['text'], got


def q_progress_shows_a_tracked_search():
    # Replicata: index.html with two runs of 768:12 by w12.py as progress.js, alike but for the second being a tracked
    # search's (tracked, its runs' work: 4 runs, 3 running, 1 ended, none found; dots running, running, running,
    # settled), each in the form progress.js_text gives survey_track's survey since 2026-10-31: running, 600 s so far,
    # to go by Gott's rule (600 s at the median, from a 19th of it to 19 times it), and two recorded ETAs, at 540 s and
    # 600 s of running.
    # Expectata (dreeves, 2026-10-28: "can we rearchitect things so that always happens easily and automatically?"; the
    # coordinator, 2026-10-31: "Every run gets an ETA graph", tracked searches drawing the same ETA figure and status
    # line as every other run): its heading asks m*(768) ≥ 12? and names w12.py, its summary says running; its ETA chart
    # shown and drawn as the other run's (the same figure, but for its clip path's id); its status line the other's,
    # then its counts (template progress-track: 4 runs, 3 running, 0 frozen, 1 ended, 0 aborted, 0 found) with its
    # elapsed time filled in; its readout the tracked hint (template progress-track-hint); its key hidden.
    # Resultata before (2026-10-28's tracked view): its ETA chart hidden and its status line its counts alone.
    # Fixture change (Claude, 2026-11-06; dreeves: "go with 50% as the ignorant prior when there's no model or whatever",
    # and "for anti-magic i don't want to conditionally include or exclude graphs"): odds, as every run's data carries them.
    # Spec change (Claude, 2026-11-07; dreeves, of 288:10's box: "redundant elapsed time here. let's keep the one in blue
    # and nix the one in black"): the counts have no elapsed time of their own, the status line above them having it.
    base, made = PROGRESS_DATA['runs'][0], PROGRESS_DATA['made']
    plain = dict(program='w12.py', n=768, order=12, state='running', outcome=None, so_far=600,
                 to_go=dict(median=600, lo=600 / 19, hi=19 * 600),
                 etas=[[made - 60, 540.0, 540.0, 28.4, 10260.0], [made, 600.0, 600.0, 31.6, 11400.0]],
                 statuses=base['statuses'], depth=0, keys=['768:12'], groups=['4440'],
                 counts=dict(settled=1, open=0, split=0, pending=0, running=3), stale=None, odds=ODDS_IGNORANT,
                 cpu=[])   # (2026-11-07: every run's data carry its CPU series, none here)
    tracked = dict(plain, tracked=True, work=dict(runs=4, running=3, frozen=0, ended=1, aborted=0, paused=0, found=0))
    got = progress_harness({'made': made, 'runs': [plain, tracked]}, """
  const [plain, r] = runs();
  const tpl = name => document.querySelector('template.' + name);
  const fig = box => box.querySelector('.progress-eta');
  const drawn = box => fig(box).innerHTML.replace(/progress-clip-\\d+/g, 'progress-clip');
  const line = box => [...box.querySelectorAll('.progress-status [data-state]')].filter(e => !e.hidden).map(e => e.textContent);
  out({head: r.querySelector('h3').textContent,
       label: [...r.querySelectorAll('[data-label]')].filter(e => !e.hidden).map(e => e.dataset.label),
       hidden: [fig(plain).hidden, fig(r).hidden], same: drawn(plain) === drawn(r), drawn: drawn(r).length,
       lines: [line(plain), line(r)],
       counts: Object.fromEntries([...r.querySelectorAll('.progress-status [data-attempt-count]')].map(e => [e.dataset.attemptCount, e.textContent])),
       elapsed: (r.querySelector('.progress-status [data-elapsed]') || {}).textContent || '',
       readout: r.querySelector('[data-readout]').textContent.trim(),
       hint: tpl('progress-track-hint') ? tpl('progress-track-hint').content.textContent.trim() : null});""")
    assert got['head'] == 'm*(768) ≥ 12? w12.py' and got['label'] == ['running'], got
    assert got['hidden'] == [False, False] and got['same'] is True and got['drawn'] > 0, got
    assert got['lines'][0] == got['lines'][1] and len(got['lines'][1]) == 1 and got['lines'][1][0].strip(), got
    # (Spec change, 2026-11-13: the counts hold the paused runs too; dreeves: "go ahead and generalize track.py to record
    # pause vs abort or whatever".)
    assert got['counts'] == dict(runs='4', running='3', frozen='0', ended='1', aborted='0', paused='0', found='0'), got
    # (2026-11-11: the statuses' key, hidden for a tracked search, is gone from every box: the hint names the dots)
    assert got['elapsed'] == '' and got['hint'] is not None and got['readout'] == got['hint'], got


def q_asymptotics_states_the_records_in_the_data():
    # Replicata: index.html's section "Asymptotics" (class asymptotics), mstar.js (its columns' lower bounds and its
    # past examples) and pow2.js (its columns' lower bounds).
    # Expectata (dreeves, 2026-11-06: "Can you add an "Asymptotics" section that uses my words with your corrections?"):
    # the section names the record of m*(n)/log2 n among the known lower bounds, as N:M with the ratio to three
    # decimals, and the record of m*(2^k)/k, the lower end of c, as the fraction lo/k, so that a new record turns this
    # red until the section is updated.  Numbers only, no wording.
    # Resultata before: no such section.
    from fractions import Fraction
    found = re.search(r'<section class="asymptotics".*?</section>', page(), re.S)
    assert found, 'no section asymptotics'
    text = re.sub(r'<!--.*?-->', '', found.group(0), flags=re.S)   # what the reader sees, not the TODO recaps
    # 2026-11-29, dreeves: "make sure all that's on the page". Read the original
    # record explanation; the following fold proves the stronger asymptotic bound.
    text, quote = text.split('<blockquote class="claude">', 1)
    M = mstar_data()
    known = [(c[0] / math.log2(n), n, c[0]) for n, c in enumerate(M['cols'], 1) if c[0] > 0 and n > 1]
    known += [(m / math.log2(n), n, m) for n, m, *_ in M['past']]   # (past's rows, [n, lo, ...], since 2026-11-19)
    ratio, n, m = max(known)
    assert f'{n}:{m}' in text and f'{ratio:.3f}' in text, (n, m, ratio)
    # (Fable 5.2, 2026-11-21: the record at the first power of 2 that reaches it, 15/13 at 2^13 that day; until then at the last, which no two powers
    # had shared before 39/34 and 78/68 did the night before.)
    best = max(Fraction(c[0], k) for k, c in enumerate(pow2_data()['cols'], 1))
    lo, k = next((c[0], k) for k, c in enumerate(pow2_data()['cols'], 1) if Fraction(c[0], k) == best)
    assert f'{lo}/{k}' in text and f'{float(best):.3f}' in text, (lo, k, float(best))
    # Replicata: the same two records in the attributed explanation below the section's opening paragraphs.
    # Expectata: its lower end for c is the current fraction, and its inequality for U bounds U by the exact
    # record, with the three-decimal number as an approximation. Resultata before: 71/61 and U ≥ 1.525,
    # though 16/log2(1440) is strictly below 1.525.
    expected = {f'{lo}/{k}', rf'U \ge {m}/\log_2 {n} \approx {ratio:.3f}'}
    formulas = {' '.join(eq.split()) for eq in re.findall(r'\\\((.*?)\\\)', quote.split('</blockquote>')[0], re.S)}
    assert expected <= formulas, expected - formulas


def q_progress_lists_running_runs_first():
    # Replicata: index.html with three runs as progress.js, PROGRESS_DATA's run as an ended a.py, a running b.py and
    # an ended c.py, in that order.
    # Expectata (dreeves, 2026-11-06, asking for a Pareto improvement to the search progress display; the coordinator's
    # choice: the one live run was listed 10th of 22, under nine ended ones): the running run first, then the others
    # in the data's order, each run's box its own.
    # Resultata before: a.py, b.py, c.py, the data's order.
    base = PROGRESS_DATA['runs'][0]
    ended = dict(base, state='ended', to_go=None)
    data = {'made': PROGRESS_DATA['made'], 'runs': [dict(ended, program='a.py'), dict(base, program='b.py'),
                                                     dict(ended, program='c.py')]}
    got = progress_harness(data, """
  out(runs().map(r => [r.querySelector('[data-program]').textContent, r.dataset.runState]));""")
    assert got == [['b.py', 'running'], ['a.py', 'ended'], ['c.py', 'ended']], got


# A run's odds as progress.js carries them (progress.py's odds; since 2026-11-06 {prior, since, exists}): a campaign
# target's, its prior P(exists) 0.3, its history's origin 6 h before the data was made, and P(exists) at 9 quarter
# hours to then, falling from 0.3 (ODDS_CAMPAIGN); the same before its first measurement, with no point (ODDS_NONE);
# and the live 288:10 run's, its prior 0.01, its origin 3 h before, and P(exists) at three hours to then (ODDS_WORK).
# (Until 2026-11-06 odds carried a basis, the hours ahead and curves, and came with a chance, whose history the chance
# chart drew: dreeves, that day, "everything here seems useless, kill it unless you have a good argument for salvaging
# anything. the up-to-date probability that a bipartition exists is great.")
# Fixture correction, 2026-11-14: comparable graphs require one clock. The campaign is 600 s old and WORK is 2 h
# old, so their independent probability samples now lie within those same histories (previously 6 h and 3 h).
ODDS_SINCE = PROGRESS_DATA['made'] - 600
ODDS_CAMPAIGN = dict(prior=0.3, since=ODDS_SINCE, exists=[[PROGRESS_DATA['made'] - 75 * (8 - k), 0.3 * math.exp(-k / 20)] for k in range(9)])
ODDS_NONE = dict(prior=0.3, since=ODDS_SINCE, exists=[])
ODDS_WORK = dict(prior=0.01, since=PROGRESS_DATA['made'] - 2 * 3600,
                 exists=[[PROGRESS_DATA['made'] - 3600 * (2 - k), 0.01 - 0.002 * k] for k in range(3)])
# PROGRESS_CAMPAIGN: a tracked target a campaign searches, with its odds (PROGRESS_CHANCE until 2026-11-06, with its
# chance too).
PROGRESS_CAMPAIGN = dict(program='probe_seed.py', n=528, order=12, state='running', outcome=None, so_far=600,
                         to_go=dict(median=600, lo=600 / 19, hi=19 * 600), etas=[[PROGRESS_DATA['made'], 600.0, 600.0, 31.6, 11400.0]],
                         statuses=list(STATUSES), depth=0, keys=['528:12'], groups=['4440'],
                         counts=dict(settled=1, open=0, split=0, pending=0, running=3), stale=None, tracked=True,
                         work=dict(runs=4, running=3, frozen=0, ended=1, aborted=0, paused=0, found=0), odds=ODDS_CAMPAIGN,
                         cpu=[])   # (2026-11-07: every run's data carry its CPU series, none here)
# The boxes runs' progress.js (2026-11-04, [CEL]: a black cell's box summarizes the searches at its cell): two runs at
# 528:12, PROGRESS_CAMPAIGN and an overnight_v5.py run that ended with no outcome (aborted), and one at 64:7.
BOX_PROGRESS = {'made': PROGRESS_DATA['made'], 'runs': [PROGRESS_CAMPAIGN, dict(PROGRESS_DATA['runs'][0], n=528, order=12, state='ended',
                                                                                to_go=None), PROGRESS_DATA['runs'][0]]}


def odds_runs():
    """The runs of the quals of a run's prior and its P(exists) graph (2026-11-06), in this order: PROGRESS_CAMPAIGN, a
    campaign target with its odds; PROGRESS_DATA's overnight_v5.py run, which has no model of its search (ODDS_IGNORANT);
    PROGRESS_WORK, the live 288:10 run, with ODDS_WORK; and PROGRESS_CAMPAIGN at 672:13 before its first measurement
    (ODDS_NONE).  All running, so the section lists them in this order."""
    return [PROGRESS_CAMPAIGN, PROGRESS_DATA['runs'][0], dict(PROGRESS_WORK, odds=ODDS_WORK), dict(PROGRESS_CAMPAIGN, n=672, order=13, odds=ODDS_NONE)]


# Quals removed on 2026-11-06 (Claude; dreeves: "everything here seems useless, kill it unless you have a good argument
# for salvaging anything. the up-to-date probability that a bipartition exists is great."; "for anti-magic i don't want
# to conditionally include or exclude graphs."; then "after the ETA graph, explicitly state the prior probability a
# bipartition exists. we can go back to 1% or whatever makes sense for 288:10. then show the first probability graph,
# even though for 288:10 it's uninteresting. then kill everything below that."), with the graphs, lines and notes they
# specified: q_progress_draws_a_search_s_odds (in its place q_progress_every_run_has_one_probability_graph),
# q_progress_work_note_states_the_run_s_prior (in its place q_progress_states_each_run_s_prior),
# q_progress_draws_the_chance_after_the_odds and q_progress_draws_a_campaign_target_s_chance (the third graph and its
# line; in their place q_progress_has_none_of_the_removed_graphs_or_lines).


def q_progress_old_fixtures_preserve_their_probability_clock():
    # Replicata: the independently sampled campaign history and a run with no measured odds, whose ETA records
    # include a stopped gap (wall timestamps 0, 1, 3 h apart; active time 0, 1, 2 h).
    # Expectata: campaign times/probabilities retained with its explicit elapsed clock; synthesized prior points
    # use each ETA's own active seconds, so conversion never silently interpolates a stopped gap.
    # Resultata before: neither kind of probability row carried an active-time coordinate.
    campaign = uniform(PROGRESS_CAMPAIGN, PROGRESS_DATA['made'])
    assert campaign['odds']['exists'] == [[t, 75 * k, p] for k, (t, p) in enumerate(ODDS_CAMPAIGN['exists'])], campaign['odds']
    source = json.loads(json.dumps(PROGRESS_DATA['runs'][0]))
    source['etas'][-1][0] += 3600
    converted = uniform(source, PROGRESS_DATA['made'] + 3600)
    assert converted['odds']['exists'] == [[row[0], row[1], 0.5] for row in source['etas']], converted['odds']


def q_progress_every_run_has_one_probability_graph():
    # Replicata: index.html with odds_runs() as progress.js, every fold opened.
    # Expectata (dreeves, 2026-11-06: "for anti-magic i don't want to conditionally include or exclude graphs"; then
    # "show the first probability graph, even though for 288:10 it's uninteresting. then kill everything below that";
    # and "go with 50% as the ignorant prior when there's no model or whatever"; the coordinator: a run with no model of
    # its search has nothing to update its prior with, so its graph is the same frame grayed, with no line, by one
    # mechanism for all runs): every run's box has exactly one probability graph, its P(exists) graph, shown, a vertex
    # per point of its odds (9, none for the run without a model, 3, and none before the first measurement) and a dot
    # on its last; a graph with no point grayed (data-empty, its svg's opacity below 1) and no other, so that the run
    # without a model and the campaign target before its first measurement look alike but for the prior they state;
    # the run without a model's axes those of its time so far (0 to 2 h) and percent to 1%.  The campaign target's
    # line at its points' hours since its odds' since on the hour ticks' scale (0 to 6 h, every 2) and at their
    # P(exists) on the percent ticks' (0 to 30%, every 10).
    # Resultata before: the section threw at the first run with odds but no chance ("odds without a chance"); with
    # chances, a run without odds had its odds' figure hidden and a run with odds three graphs.
    # Spec change, 2026-11-14; dreeves: "yes, comparable graphs sounds good": each probability graph now shares
    # its ETA graph's running-time scale and projected-finish horizon, including the ticks and their positions.
    got = progress_harness({'made': PROGRESS_DATA['made'], 'runs': odds_runs()}, """
  for (const r of runs()) r.querySelector('details').open = true;
  await sleep(200);
  const vertices = e => (e.getAttribute('points') || '').trim().split(/\\s+/).filter(Boolean).map(p => p.split(',').map(Number));
  const ticks = (f, which, axis) => [...f.querySelectorAll(`[data-exists-ticks="${which}"] text`)].map(t => [t.textContent, +t.getAttribute(axis)]);
  out(runs().map(box => { const f = box.querySelector('.progress-odds');
    return {program: box.querySelector('[data-program]').textContent, graphs: f.querySelectorAll('svg').length, shown: f.checkVisibility(),
            empty: f.hasAttribute('data-empty'), opacity: +getComputedStyle(f.querySelector('svg')).opacity, line: vertices(f.querySelector('[data-exists-line]')),
            marks: [...f.querySelectorAll('[data-exists-marks] circle')].map(c => [+c.getAttribute('cx'), +c.getAttribute('cy')]),
            pticks: ticks(f, 'p', 'y'), tticks: ticks(f, 't', 'x'),
            etaTicks: [...box.querySelectorAll('.progress-eta text.xtick')].map(t => [t.textContent, +t.getAttribute('x')]),
            axis: ['x1', 'x2'].map(a => +f.querySelector('line.axis').getAttribute(a))}; }));""")
    assert [g['program'] for g in got] == ['probe_seed.py', 'overnight_v5.py', 'ftree.py', 'probe_seed.py'], got
    assert [(g['graphs'], g['shown']) for g in got] == [(1, True)] * 4, [(g['graphs'], g['shown']) for g in got]
    # Spec change (Fable 5.2, 2026-11-11; dreeves: "the search progress code seems like a shitshow; can you revamp it?
    # ... anti-magic anti-magic anti-magic"): every search has a history, since each of its estimates states its
    # P(exists) (a search that knows only its age its prior, each time: lindy.py), so no graph is grayed for want of
    # one: the run without a model has a point per recorded ETA, three, flat at its prior 0.5, on percent ticks to 50%,
    # and the campaign target before its first measurement its prior at its estimates' times; until then those two
    # drew no line, their graphs grayed (data-empty).
    assert [len(g['line']) for g in got] == [9, 3, 3, len(got[3]['line'])] and len(got[3]['line']) >= 1, [len(g['line']) for g in got]
    assert [len(g['marks']) for g in got] == [1, 1, 1, 1] and not any(g['empty'] for g in got) and all(g['opacity'] == 1 for g in got), got
    assert all(g['tticks'] == g['etaTicks'] for g in got), [(g['tticks'], g['etaTicks']) for g in got]
    assert [t for t, _ in got[1]['pticks']] == ['0', '10', '20', '30', '40', '50%'], got[1]
    assert len({y for _, y in got[1]['line']}) == 1, got[1]['line']
    camp = got[0]
    assert [t for t, _ in camp['pticks']] == ['0', '10', '20', '30%'], camp['pticks']
    x0, xend = camp['axis']
    (_, y0), (_, y3) = camp['pticks'][0], camp['pticks'][-1]
    X = lambda seconds: x0 + (xend - x0) * seconds / 1200  # 600 s elapsed + 600 s forecast, the ETA's horizon
    # a tick label sits 3 above its value's line, inside the chart (2026-11-12; dreeves: "could the graphs use more of the available horizontal space? no indenting, for one thing. ... how about end the x-axis range right at the purple dashed vertical line?"); 4 below it until then
    # and 4 below it again, in the margin left of the plot, later that day (Opus 5.5; dreeves: "i'm guessing the axis break slashes will make no visual sense without an axis line")
    Y = lambda v: y0 - 4 + (y3 - y0) * v / 0.3
    want = [(X(t - ODDS_SINCE), Y(p)) for t, p in ODDS_CAMPAIGN['exists']]
    assert all(abs(a - c) < 0.05 and abs(b - d) < 0.05 for (a, b), (c, d) in zip(camp['line'], want)), (camp['line'][:3], want[:3])
    assert all(abs(a - c) < 0.05 for a, c in zip(camp['marks'][0], want[-1])), (camp['marks'], want[-1])


def q_progress_has_none_of_the_removed_graphs_or_lines():
    # Replicata: the section's markup in index.html, its comments left out; the section's script, its comments left
    # out; the page's CSS rules; and the boxes of odds_runs() as progress.js, every fold opened.
    # Expectata (dreeves, 2026-11-06: "everything here seems useless, kill it unless you have a good argument for
    # salvaging anything. the up-to-date probability that a bipartition exists is great."; then "then show the first
    # probability graph ... then kill everything below that"): none of what was below the P(exists) graph anywhere: no
    # graph of P(found by t | exists) (data-found-*), no chance chart (progress-chance, data-chance-*), no template of
    # its tip (progress-chance-point), no chance line (the chances within 6 h and 24 h, its CPU-hours, nodes and rate),
    # no note on the odds' basis (data-odds-basis); the script draws none of them (chanceChart, chanceXs, curves, a
    # basis), and no CSS rule styles them (progress-chance, the curves' now and old, the now line); and no drawn box
    # holds one of those elements.
    # Resultata before: all of them, in the markup, the script and the CSS, and drawn in every box of a run with odds.
    text = page()
    sec = re.sub(r'<!--.*?-->', '', re.search(r'<section class="progress".*?</section>', text, re.S).group(0), flags=re.S)
    removed = r'data-found-|data-chance-|progress-chance|data-odds-basis'
    assert not re.findall(removed, sec), sorted(set(re.findall(removed, sec)))
    js = re.sub(r'/\*.*?\*/|//[^\n]*', '', page_scripts(text)[-1], flags=re.S)
    assert not re.findall(r'chanceChart|chanceXs|curves|data-found|data-chance|progress-chance|odds-basis|oddsBasis', js), sorted(set(re.findall(r'chanceChart|chanceXs|curves|data-found|data-chance|progress-chance|odds-basis|oddsBasis', js)))
    css = re.sub(r'/\*.*?\*/', '', page_css(), flags=re.S)
    assert not re.findall(r'progress-chance|polyline\.now|polyline\.old|\.nowline', css), sorted(set(re.findall(r'progress-chance|polyline\.now|polyline\.old|\.nowline', css)))
    got = progress_harness({'made': PROGRESS_DATA['made'], 'runs': odds_runs()}, """
  for (const r of runs()) r.querySelector('details').open = true;
  await sleep(200);
  out(runs().map(box => box.querySelectorAll('[data-found-curves], [data-found-now], .progress-chance, [data-chance-line], [data-chance-at], [data-chance-spent], [data-odds-basis]').length));""")
    assert got == [0, 0, 0, 0], got


def q_progress_states_each_run_s_prior():
    # Replicata: index.html with odds_runs() as progress.js, every fold opened.
    # Expectata (dreeves, 2026-11-06: "after the ETA graph, explicitly state the prior probability a bipartition exists.
    # we can go back to 1% or whatever makes sense for 288:10. then show the first probability graph"; and "go with 50%
    # as the ignorant prior when there's no model or whatever"; the coordinator: shown for every run, never "—"): in
    # every run's box a line stating its prior P(exists), shown, after its ETA chart and its status line, right before
    # its P(exists) graph's title, that graph the last of its figure: 0.3, 0.5 (the ignorant prior of the run without a
    # model), 0.01 and 0.3, as the page writes numbers.  Its words are dreeves's, unpinned (no qual pins wording,
    # dreeves's rule since 2026-10-26).
    # Resultata before: no such line; the prior was stated only in the work basis's note, below all three graphs, for a
    # run on that basis.
    got = progress_harness({'made': PROGRESS_DATA['made'], 'runs': odds_runs()}, """
  for (const r of runs()) r.querySelector('details').open = true;
  await sleep(200);
  const after = (a, b) => !!(a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING);
  out(runs().map(box => { const field = box.querySelector('.progress-odds [data-odds-prior]'), line = field && field.closest('p');
    const f = box.querySelector('.progress-odds'), title = f.querySelector('.progress-odds-title'), svg = f.querySelector('svg');
    return field && {prior: field.textContent, shown: line.checkVisibility(), afterEta: after(box.querySelector('.progress-eta'), line),
                     afterStatus: after(box.querySelector('.progress-status'), line),
                     // Spec change, 2026-11-27 (dreeves, of the search's own line, which stood over this one: "the line with the prior should come
                     // first"): the prior's line is the figure's first, the search's own line follows it, and the title follows that (until then
                     // the prior's line stood right before the title).
                     next: line === f.firstElementChild && line.nextElementSibling.matches('.progress-finds-title') && line.nextElementSibling.nextElementSibling === title,
                     graph: title.nextElementSibling === svg && svg === f.lastElementChild}; }));""")
    assert [g and g['prior'] for g in got] == ['0.3', '0.5', '0.01', '0.3'], got
    assert all(g['shown'] and g['afterEta'] and g['afterStatus'] and g['next'] and g['graph'] for g in got), got


def q_progress_brief_of_a_run_without_a_work_model_is_its_status_line():
    # Replicata: index.html with BOX_PROGRESS's runs as progress.js: at 528:12, PROGRESS_CAMPAIGN (running) and an
    # overnight_v5.py run that ended with no outcome (aborted); then want(528, 12), as the box of the m*(n) chart's black
    # cell (528, 12) asks for the runs at its target (page/shared.js's searches).
    # Expectata (the coordinator, 2026-11-06, with the chance line gone: "Make every other run brief its status line
    # (time so far + to go), with no new branch beyond a selector map like workView's"; dreeves: "everything here seems
    # useless, kill it unless you have a good argument for salvaging anything"): two rows a run, its summary line, then
    # its status line (p.progress-status) filled as the section fills that run's own: only its state's form shown, the
    # first's running one with its time so far, its range to go, in all and its finish times as in the section, the
    # second's aborted one with its 2.0 h.
    # Resultata before: the first run's second row was its chance line, and the second run had no second row.
    # Spec change (Claude, 2026-11-07; dreeves: "1. show elapsed time with full granularity like so: 3d 4h 5m 6s"): the
    # times so far 10m 0s and 2h 0m 0s (hms).
    got = progress_harness(BOX_PROGRESS, """
  const rows = await new Promise(put => window.progressView.want(528n, 12, put));
  const shown = row => [...row.querySelectorAll('[data-state]')].filter(e => !e.hidden);
  const fields = e => Object.fromEntries(['so-far', 'to-go', 'sum', 'done'].map(f => [f, (e.querySelector(`[data-${f}]`) || {}).textContent ?? null]));
  const section = runs().find(r => r.querySelector('[data-program]').textContent === 'probe_seed.py');
  out({rows: rows.length, status: rows.map(r => r.matches('p.progress-status')), states: rows.map(r => shown(r).map(e => e.dataset.state)),
       running: fields(shown(rows[1])[0]), section: fields(section.querySelector('.progress-status [data-state="running"]')),
       aborted: shown(rows[3])[0].textContent});""")
    assert got['rows'] == 4 and got['status'] == [False, True, False, True], got
    assert got['states'] == [[], ['running'], [], ['aborted']], got['states']
    assert got['running'] == got['section'] and got['running']['so-far'] == hms(600), (got['running'], got['section'])
    assert figures(got['aborted']) == figures(f'Aborted after running for {hms(7200)}.'), got['aborted']


def q_progress_status_line_names_an_ended_run_s_outcome():
    # Replicata: index.html with the five runs of q_progress_summary_names_each_run_s_state as progress.js: running,
    # paused, frozen, ended with an outcome (excluded) and ended with none.
    # Expectata (dreeves, 2026-10-26: "for the ended/aborted searches, they say either "completed" or "aborted" in the
    # collapsed version but the last line of the expanded version always just says "ended". can you change those
    # instances of "ended" to "aborted" or "completed" as appropriate?"): each run's status line, under its charts,
    # shows the one part (data-state) of the state its summary names: running, paused, frozen, completed, aborted.
    # Resultata before: both ended runs' status lines showed the part for "ended", which said "Ended after running for".
    base = dict(PROGRESS_DATA['runs'][0], to_go=None)
    runs = [dict(base, n=64 + 8 * i, state=state, outcome=outcome) for i, (state, outcome) in
            enumerate([('running', None), ('paused', None), ('frozen', None), ('ended', 'excluded'), ('ended', None)])]
    got = progress_harness({'made': PROGRESS_DATA['made'], 'runs': runs}, """
  out(runs().map(r => [...r.querySelectorAll('.progress-status > [data-state]')].filter(e => !e.hidden)
    .map(e => e.dataset.state)));""")
    assert got == [['running'], ['paused'], ['frozen'], ['completed'], ['aborted']], got


def q_progress_names_each_run_s_program():
    # Replicata: progress_run with two runs: PROGRESS_DATA's, then the same as boxsplit.py's pass (PROGRESS_TWO).
    # Expectata: two headings, in the data's order, each the run's question and its program, overnight_v5.py then
    # boxsplit.py (dreeves, 2026-10-17: a second block for the boxsplit pass over 240@11's open cases); both runs' ETA
    # charts show, the second's with no ETA recorded too (dreeves, 2026-10-23: "the search progress section should
    # always be clear about what's been running for how long"; hidden with no ETA from 2026-10-17 until then).
    R = progress_run('two')
    assert R['heads'] == ['m*(64) ≥ 7? overnight_v5.py', 'm*(64) ≥ 7? boxsplit.py'], R['heads']
    assert R['etaDisplays'] == ['grid', 'grid'], R['etaDisplays']


def q_progress_redraws_in_place_and_reads_out_a_subtree():
    # Replicata: progress_run: a hover over the third group's first dot; then progressData given a changed snapshot
    # (one minute later, the running dot open).
    # Expectata: the readout holds the third group's key; after the call the section has drawn again in the same
    # document (the harness's marker survives: no reload), that dot is open's color and the key counts it.
    R = progress_run()
    assert R['readout'].startswith(PROGRESS_DATA['runs'][0]['keys'][2]), R['readout']
    c = R['changed']
    assert c['marker'] == 'kept' and c['renders'] == 2, c
    assert c['pixel'] == rgb(R['colors'][STATUSES.index('open')]), (c['pixel'], R['colors'])



# a form-tree search with a work model (formtree_eta.attach's work_eta), the live 288:10 run's numbers of 2026-11-06:
# 468,750,102 nodes checked; the total, the nodes checked when the search ends, 780M to 2.5B, median 1.27B, at 90%
PROGRESS_WORK = dict(PROGRESS_DATA['runs'][0], program='ftree.py', n=288, order=10, work_eta=dict(
    source_time=1792199990, samples=1024, nodes=1.037e9, done=468750102, rate=1884.1, roots_done=10, roots_total=16,
    model='importance', interval='conditional', discrepancy_factor=2.117, root_discrepancy_factor=2.117, rate_log_sd=0.35,
    coverage=0.9, root_log_sd_posterior=dict(lo=0.35, median=0.52, hi=0.83), effective_samples=2273.9,
    forecast_samples=65536, total=dict(median=1270000000.0, lo=780000000.0, hi=2500000000.0)))


def q_progress_brief_of_a_work_model_run_is_its_bar_caption():
    # Replicata: index.html with PROGRESS_WORK as progress.js; then want(288, 10), as the box of the m*(n) chart's black
    # cell (288, 10) asks for the runs at its target (page/shared.js's searches).
    # Expectata (dreeves, 2026-11-06: "1. add nodes/s to the blue/purple line" and "2. kill the whole line with number
    # of samples"; the coordinator: the box keeps showing a work-model run's nodes checked, rate and range): two rows,
    # the run's summary line and then its bar's caption, filled as on the page: 468,750,102 nodes checked, then the
    # rate 1,884.1, and the total's range 780M–2.5B, shown; no field of the samples or the source time.
    # Resultata before: the second row was the work paragraph, with its samples and its source time.
    got = progress_harness({'made': PROGRESS_DATA['made'], 'runs': [PROGRESS_WORK]}, """
  const rows = await new Promise(put => window.progressView.want(288n, 10, put));
  const caption = rows[rows.length - 1], text = sel => (caption.querySelector(sel) || {}).textContent ?? null;
  out({rows: rows.length, caption: caption.matches('p.progress-bar-caption'), done: text('.spent [data-bar-done]'),
       rate: text('.spent [data-work-rate]'), range: text('.total [data-bar-range]'),
       purple: !!caption.querySelector('.total') && !caption.querySelector('.total').hidden,
       unshown: caption.querySelectorAll('[data-work-samples], [data-work-source_time]').length});""")
    assert got == dict(rows=2, caption=True, done='468,750,102', rate='1,884.1', range='780M–2.5B', purple=True, unshown=0), got


def q_progress_shows_runs_and_dots_for_every_run():
    # Replicata: index.html with three running runs as progress.js, each fold open: a tracked search with a work model
    # (ftree.py's 288:10 as survey_track and formtree_eta.attach give it: four launches of one proof search, 1 running
    # and 3 ended, and PROGRESS_WORK's model), a tracked search without one (w12.py's 768:12, as in
    # q_progress_shows_a_tracked_search), and PROGRESS_DATA's overnight_v5.py run.
    # Expectata (dreeves, 2026-11-06: "for anti-magic i don't want to conditionally include or exclude graphs"; the
    # coordinator: "Every run shows its sea and its runs line exactly as runs without a work model do"): the first and
    # the second each show the line of its runs, its dots and their readout, its key hidden as every tracked search's,
    # its status line, and the first its bar; the third its dots, their key and their readout, and no runs' line.
    # Spec change (the same request; until then this qual was q_progress_shows_runs_and_dots_only_without_a_work_model,
    # after dreeves, 2026-11-06, of 288:10's line "4 runs: 1 running, 0 frozen, 3 ended, 0 aborted; 0 found; elapsed …;
    # running." and its "One dot per run" dots: "sounds like noise?"): the first shows its runs' line and its dots
    # again, in place of neither.
    # Resultata before: the first showed neither the line of its runs nor its dots, their key or their readout.
    # Fixture change (Claude, 2026-11-06; dreeves: "go with 50% as the ignorant prior when there's no model or
    # whatever"): odds, as every run's data carries them.
    # Spec change (Claude, 2026-11-08; dreeves, of 288:10's dots, its tree's roots since 2026-11-07: "we used to have a
    # legend for this; why don't we have one here?"): the first shows its key, its hint having no swatches of its own
    # (q_progress_keys_a_search_s_roots); until then every tracked search's key was hidden.
    base, made = PROGRESS_DATA['runs'][0], PROGRESS_DATA['made']
    tracked = dict(program='w12.py', n=768, order=12, state='running', outcome=None, so_far=600,
                   to_go=dict(median=600, lo=600 / 9, hi=9 * 600),
                   etas=[[made - 60, 540.0, 540.0, 60.0, 4860.0], [made, 600.0, 600.0, 66.7, 5400.0]],
                   statuses=base['statuses'], depth=0, keys=['768:12'], groups=['4440'],
                   counts=dict(settled=1, open=0, split=0, pending=0, running=3), stale=None, tracked=True,
                   work=dict(runs=4, running=3, frozen=0, ended=1, aborted=0, paused=0, found=0), lindy=True, odds=ODDS_IGNORANT,
                   cpu=[])   # (2026-11-07: every run's data carry its CPU series, none here)
    worked = dict(tracked, program='ftree.py', n=288, order=10, keys=['288:10'], groups=['0004'],
                  counts=dict(settled=3, open=0, split=0, pending=0, running=1), lindy=False,
                  work=dict(runs=4, running=1, frozen=0, ended=3, aborted=0, paused=0, found=0), work_eta=PROGRESS_WORK['work_eta'])
    got = progress_harness({'made': made, 'runs': [worked, tracked, base]}, """
  for (const r of runs()) r.querySelector('details').open = true;
  await sleep(200);
  const shows = (r, sel) => { const e = r.querySelector(sel); return e && e.checkVisibility(); };
  out(runs().map(r => ({program: r.querySelector('[data-program]').textContent,
    runs: shows(r, '.progress-status [data-attempt-count="runs"]'), dots: shows(r, 'canvas'),
    readout: shows(r, '[data-readout]'), status: shows(r, '.progress-status [data-state="running"]'), bar: shows(r, '.progress-work')})));""")
    # Spec change (Fable 5.2, 2026-11-11; dreeves: "we used to have a progress bar. the search progress code seems like
    # a shitshow; can you revamp it? ... anti-magic anti-magic anti-magic"): every search's box has the same parts,
    # whatever the search: the line of its runs, its dots and their readout, its status line and its bar; until then
    # the bar showed for a search with a work model alone, the runs' line for a tracked one, and the statuses' key (gone
    # now: the hint names the dots) for the others.
    want = [dict(program=name, runs=True, dots=True, readout=True, status=True, bar=True) for name in ('ftree.py', 'w12.py', 'overnight_v5.py')]
    assert got == want, got



def q_progress_lays_out_each_subtree_as_a_block():
    # Replicata: progress_run's layout of the sea: a rectangle of cells per group (x, y, w, h), in a grid cols wide.
    # Expectata: each group's rectangle holds its dots (w h at least its count) inside the grid; no two rectangles
    # touch (a cell's gap at least between them); and they come in reading order, as the groups do.
    B = progress_run()['blocks']
    rects, sizes = B['rects'], [len(g) for g in PROGRESS_DATA['runs'][0]['groups']]
    assert len(rects) == len(sizes) and all(r['w'] * r['h'] >= n for r, n in zip(rects, sizes)), (rects, sizes)
    assert all(r['x'] >= 0 and r['y'] >= 0 and r['x'] + r['w'] <= B['cols'] and r['y'] + r['h'] <= B['rows'] for r in rects), B
    apart = lambda a, b: a['x'] + a['w'] < b['x'] or b['x'] + b['w'] < a['x'] or a['y'] + a['h'] < b['y'] or b['y'] + b['h'] < a['y']
    assert all(apart(a, b) for i, a in enumerate(rects) for b in rects[i + 1:]), rects
    assert [(r['y'], r['x']) for r in rects] == sorted((r['y'], r['x']) for r in rects), rects


def q_progress_draws_the_eta_chart():
    # Replicata: progress_run's ETA chart (progress.html's, ported: dreeves, 2026-10-09 and 10-10), from
    # PROGRESS_DATA's three recorded ETAs; a hover over the second, then over the last.
    # Expectata: shown, as wide as the sea (2026-10-17: as a figure, the page's figure rule shrank it to its content); the
    # ETA's line has a point per record; no direct labels at the last record (they gave its ranges and the elapsed time
    # until dreeves's "comment it out for now", 2026-10-17: the status line below says the same, in the same colors), so
    # no x tick gives way to the elapsed time's label: 0, 1, 2 and 3 h; the tip, laid out but invisible at rest (a line
    # of its own, so that showing it moves nothing: the page jumped on hover until 2026-10-17), is the status line's
    # running form for the record under the pointer (dreeves, 2026-10-17: "the same as the line below, just an earlier
    # snapshot thereof and with the datetimestamp prefix"): over the second record, an @ and its time, an em space, 1.0 h
    # so far + 1.0–3.0 h to go = 2.0–4.0 h, and in parentheses the local times its band ends between; over the last (the
    # snapshot's own), the status line exactly, markup and all; and the hover moved the status line not at all.
    # Spec change (Claude, 2026-11-06; dreeves: "i don't think we need "@2026-11-06 19:12:49" under the graph since the
    # search progress line above the progress bar shows the freshness"): the status line's markup and text still the
    # tip's, but the status line hides the @, the time and the em space, which the tip shows
    # (q_progress_status_line_has_no_time_but_its_tip_does).
    # Spec change (Claude, 2026-11-07; dreeves: "1. show elapsed time with full granularity like so: 3d 4h 5m 6s ... 3. no
    # need for the "so far" ... 4. sane number of sigfigs for everything else based in a principled way on the amount of
    # uncertainty"): over the second record 1h 0m 0s + 1–3 h to go = 2–4 h, its band's uncertainty an hour, so its finish
    # times to the hour.
    R = progress_run()
    E = R['eta']
    assert not E['hidden'] and E['togo'] == 3 and abs(E['widths'][0] - E['widths'][1]) <= 1, E
    h = NNBSP + 'h'
    assert E['labels'] == 0, E
    # With the labels (until 2026-10-17; back with them):
    # assert (E['labelTogo'], E['labelTotal'], E['labelSpent']) == (f'0.5–3.0{h}', f'2.5–5.0{h}', f'2.0{h}'), E
    parts = SvgParts()
    parts.feed(R['etaSvg'])
    assert [text for tag, a, text in parts.items if a.get('class') == 'xtick'] == ['0', '1', '2', f'3{h}'], R['etaSvg']
    t = PROGRESS_DATA['runs'][0]['etas'][1][0]
    # Spec change (Opus 5.5, 2026-11-12; dreeves: "what if we showed the timestamp more subtly and showed it floating on
    # the x-axis matched up with the dashed vertical line on the graph marking the timestamp in question that we're
    # hovering over?"): the tip has no time before its line.
    assert figures(E['tip']) == figures(f'{hms(3600)} + 1–3{h} to go = 2–4{h} ({finish(t, t + 3600, t + 10800, 3600)})'), E['tip']
    assert E['tipLast'] == R['state'][0] and E['sameMarkup'] is True, (E['tipLast'], R['state'], E['sameMarkup'])
    assert R['tipRest']['visibility'] == 'hidden' and R['tipRest']['height'] > 0 and R['jump'] == 0, (R['tipRest'], R['jump'])


def q_progress_tip_projects_past_the_last_record():
    # Replicata: progress_run: hovers over the ETA chart's records, then at 2.5 h of running, half an hour past its last
    # record (PROGRESS_DATA's, at 2 h: 0.5–3.0 h to go).
    # Expectata (dreeves, 2026-10-18: "the hover feature of showing the historical ETA might as well work for the whole
    # graph, right? i guess what we'd need is a way to make the distinction clear between historical vs projected";
    # then 2026-10-30: "maybe when showing the italicized hovertext for hovering over future points, that blurb should
    # have just the median, not ranges?"): past its last record the chart draws the median's course alone, the dashed
    # ideal line down to the projected finish, and no band, so there the tip reads out that course, in italics (class
    # projected): the clock and the hours so far half an hour on, 2.5 h so far, the median half an hour lower and no
    # lower than 0, 0.5 h to go, so 3.0 h in all and the median's finish time, the record's time plus its median
    # (moment); the cross line at the pointer; over a record, no italics; and the status line below the chart did not
    # move.  (From 2026-10-18 until then the band, carried on the same way.)
    # Spec change (Claude, 2026-11-07; dreeves: "1. show elapsed time with full granularity like so: 3d 4h 5m 6s ... 3. no
    # need for the "so far" ... 4. sane number of sigfigs for everything else based in a principled way on the amount of
    # uncertainty"): 2h 30m 0s, and the median's figures to the uncertainty of the last record's band, half its width,
    # 1.25 h: 1 h to go (0.5 h rounded), 3 h in all, and its finish time to the hour.
    R = progress_run()
    E, h = R['eta'], NNBSP + 'h'
    t = PROGRESS_DATA['made'] + 1800
    # Spec change (Opus 5.5, 2026-11-12; dreeves: "could you improve the consistency of the graphs a little? font sizes
    # and whether graphs are labeled above or below the graph. ... what if we showed the timestamp more subtly and showed
    # it floating on the x-axis matched up with the dashed vertical line on the graph marking the timestamp in question
    # that we're hovering over?"): the tip
    # without its time, which floats on the x axis at the cross: the projected clock time, local, to the minute.
    want = f'{hms(9000)} + 1{h} to go = 3{h} ({moment(t, t + 1800, 4500)})'
    assert figures(E['tipAhead']) == figures(want), (E['tipAhead'], want)
    assert E['stampAhead'] == time.strftime('%Y-%m-%d %H:%M', time.localtime(t)), (E['stampAhead'], t)
    A = E['ahead']
    assert A['projected'] is True and A['style'] == 'italic' and abs(A['cross'] - A['want']) < 0.05, A
    assert E['projectedAtRecord'] is False and R['jumpAhead'] == 0, (E['projectedAtRecord'], R['jumpAhead'])


class SvgParts(html.parser.HTMLParser):
    """An svg's elements in document order, each [tag, attributes, text], an element's text with its children's."""
    def __init__(self):
        super().__init__()
        self.items, self.open = [], []
    def handle_starttag(self, tag, attrs):
        item = [tag, dict(attrs), '']
        self.items.append(item)
        self.open.append(item)
    def handle_endtag(self, tag):
        while self.open and self.open.pop()[0] != tag: pass
    def handle_data(self, data):
        for item in self.open: item[2] += data


def q_progress_eta_chart_keeps_progress_html_s_spec():
    # Replicata: progress_run('eta'): the section's ETA chart of PROGRESS_ETA_DATA, progress.html's case (13.2 h of
    # running; ETAs [2, 1, 4] h at 0 h and [1, 0.5, 3] h at 13.2 h), as markup; and the section's CSS.
    # Expectata, progress.html's (quals_progress's q_page_draws_the_eta_chart until 2026-10-17, when index.html's
    # section took the chart over): it knows nothing of passes (dreeves, 2026-10-10); round ticks every 5 h from 0 to
    # 15 h on both axes, labeled, the top one with its unit, a gridline at each y tick but 0, which is the axis; the
    # diagonal of elapsed time (spent) from (0, 0) to (13.2, 13.2) h, carried on ahead, dashed, to (14.2, 14.2); the
    # band along the ETAs' tops left to right and their bottoms back; the ETA (togo) and elapsed + ETA (total) with a
    # point per ETA; at the last, a vertical range line across its band, markers on both lines, and dreeves's direct
    # labels (2026-10-10; ranges since 2026-10-12): "ETA 0.5–3.0 h" just right of the red marker, "14–16 h" just right
    # of the black one, and "13 h" in blue on the x axis under it; a cross line hidden at rest; no other line; the
    # black stroke the widest; the palette's blue (#2a78d6) and red (#e34948) and the page's ink; the legend in
    # dreeves's words: elapsed time, ETA, elapsed + ETA.  And since 2026-10-17 (dreeves: "1. yes"), the projected finish
    # marked: a hollow marker (finish) where the dashed elapsed time meets elapsed + ETA, at (14.2, 14.2) h, and a guide
    # from the black marker across to it and down to the x axis, (13.2, 14.2), (14.2, 14.2), (14.2, 0) h.  Then, at
    # dreeves's request (2026-10-17): the ETA's ideal course, a red dotted line (ideal) from the red marker down to the x
    # axis at the finish, (13.2, 1) to (14.2, 0) h; the red label without its "ETA", "0.5–3.0 h"; and no legend: the
    # status line below the chart says what each color is (q_progress_states_times_and_hours); and, since dreeves's
    # "comment it out for now" (2026-10-17), no direct labels, nor their rules among the live CSS.  Then, at dreeves's
    # request (2026-10-17: "1. shouldn't the black line also have a confidence band? 2. shouldn't there be a blue dot for
    # consistency? 3. ooh, how about purple instead of black, because blue+red=purple?"): elapsed + ETA's band too, the
    # ETAs' band raised by each record's elapsed time, (0, 4), (13.2, 16.2), (13.2, 13.7), (0, 1) h, with its own range
    # line at the last, (13.2, 13.7) to (13.2, 16.2) h; a blue marker at the last record's elapsed time, (13.2, 13.2) h,
    # where the dashed elapsed time starts; elapsed + ETA purple, #7b1fa2 (the validator's numbers are in the CSS), in
    # its line, band, range line, marker, label and the finish marker's ring, the black ink no more; and the y axis
    # taller, to the top of elapsed + ETA's band (16.2 h), so its ticks run from 0 to 20 h.  The two bands can overlap,
    # and so can the two range lines (not here; in boxsplit.py's chart of 2026-10-17, from 46 to 51 h), so both bands
    # and both range lines multiply onto what is under them: neither hides the other (the purple range line hid the red
    # one's top until they did, 2026-10-17).  And the guide purple too, as it carries elapsed + ETA's level across to the
    # finish and down to it on the x axis (dreeves, 2026-10-18: "that looks black and should be purple"; the page's
    # muted gray before).  And no finish marker since 2026-10-18 (dreeves: "remove the hollow purple dot at the upper
    # right; that might look cleaner"): the guide alone marks the projected finish.  And since 2026-10-23 (dreeves:
    # "truncate the y-axis a bit above the horizontal purple dashed line ... and indicate visually in some way (no words)
    # when the confidence bands go above the y-axis cap", then "can you do something more canonical for the y-axis
    # break?"), the main panel stops 10% above the projected finish, at 15.62 h, in place of 20 h: its gridlines at 5, 10
    # and 15 h and its top edge at 15.62 h; and elapsed + ETA's band top (16.2 h) and range line's go to a top panel,
    # 15.62 to 20 h, labeled 20 h (q_progress_breaks_the_y_axis_above_the_projected_finish).  And since 2026-11-04
    # (dreeves, of a break only where it gives the main panel a larger scale than one axis up to the tallest value
    # would: "sounds like your principled fix should work. updating the quals is fine."), no break here: the band top,
    # 16.2 h, is only 1.04 times that cap, so one axis runs up to it, gridlines at 5, 10 and 15 h, labeled to 15 h, its top
    # edge at 16.2 h, with nothing in a top panel, the slashes hidden and the y axis's line whole.  And since 2026-11-15
    # (Opus 5.5; dreeves, of the strip the range lines made at the live 480:14 chart's end: "what's up with this darker
    # vertical band slightly to the left of the purple/blue/red dots?", then "what makes most logical sense?"), no range
    # lines: they drew the last record's ranges, which the bands' right edges already draw (DRY), and since the bands
    # went past the lines' 30% tints (2026-10-23) the two copies could not match, the half of each line over the bands
    # multiplying to that strip.  A run with one record draws its range in the status line alone, as its lines too are
    # dots alone.
    R = progress_run('eta')
    parts = SvgParts()
    parts.feed(R['etaSvg'])
    els = [(tag, a, re.sub(r'[ \t\n\r]+', ' ', text).strip()) for tag, a, text in parts.items]   # U+202F stays: it is text
    def pts(text): return [tuple(map(float, xy.split(','))) for xy in text.split()]
    polys = {a['class']: pts(a['points']) for tag, a, _ in els if tag == 'polyline'}
    assert sorted(polys) == ['guide', 'spent', 'togo', 'total'], polys.keys()
    (x0, y0), (x1, y1) = polys['spent'][0], polys['spent'][-1]          # blue at 0 h and at 13.2 h
    def X(h): return x0 + (x1 - x0) * h / 13.2
    def Y(h): return y0 + (y1 - y0) * h / 13.2
    def near(p, q): return abs(p[0] - q[0]) < 0.05 and abs(p[1] - q[1]) < 0.05
    cap = 16.2                                                           # the one panel's cap, h: the tallest value
    YB = YT = Y(cap)                                                     # its top edge, the plot's: no top panel
    def Ys(h): return Y(h)
    def check(got, want, what): assert len(got) == len(want) and all(near(g, (X(a), Ys(b))) for g, (a, b) in zip(got, want)), (what, got, [(X(a), Ys(b)) for a, b in want])
    for k, w in (('spent', [(0, 0), (13.2, 13.2)]), ('togo', [(0, 2), (13.2, 1)]), ('total', [(0, 2), (13.2, 14.2)]),
                 ('guide', [(13.2, 14.2), (14.2, 14.2), (14.2, 0)])): check(polys[k], w, k)
    bands = {a['class']: pts(a['points']) for tag, a, _ in els if tag == 'polygon'}
    assert sorted(bands) == ['band togo', 'band total'], bands.keys()
    check(bands['band togo'], [(0, 4), (13.2, 3), (13.2, 0.5), (0, 1)], 'band togo')
    check(bands['band total'], [(0, 4), (13.2, 16.2), (13.2, 13.7), (0, 1)], 'band total')   # within the one panel (2026-11-04)
    lines = [(a['class'], tuple(float(a[k]) for k in ('x1', 'y1', 'x2', 'y2')), a) for tag, a, _ in els if tag == 'line']
    assert sorted(c for c, _, _ in lines) == sorted(['axis', 'ahead', 'ideal', 'cross'] + ['grid'] * 3 + ['break'] * 2 + ['yaxis'] * 2), [c for c, _, _ in lines]   # no range lines since 2026-11-15
    assert all(a.get('visibility') == 'hidden' for c, _, a in lines if c == 'break'), lines
    seg = {c: s for c, s, _ in lines if c not in ('grid', 'break', 'yaxis')}
    check([seg['ahead'][:2], seg['ahead'][2:]], [(13.2, 13.2), (14.2, 14.2)], 'ahead')
    check([seg['ideal'][:2], seg['ideal'][2:]], [(13.2, 1), (14.2, 0)], 'ideal')
    assert abs(seg['axis'][1] - Y(0)) < 0.05 and seg['axis'][1] == seg['axis'][3], seg['axis']
    grid = [s for c, s, _ in lines if c == 'grid' and s[1] > YB]       # the main panel's
    hours = sorted((y0 - g[1]) / (y0 - Y(1)) for g in grid)              # to 0.01 h: positions are written to 0.01 units
    assert len(hours) == 3 and all(abs(h - t) < 0.01 for h, t in zip(hours, (5, 10, 15))) and all(g[1] == g[3] for g in grid), grid
    assert [s[1] for c, s, _ in lines if c == 'grid' and s[1] < YB] == [], lines       # no top panel (2026-11-04)
    assert sorted(round(y, 2) for c, s, _ in lines if c == 'yaxis' for y in (s[1], s[3])) == sorted([round(YT, 2), round(YB, 2), 14, round(Y(0), 2)]), lines   # its y axis's ends at the break
    cross = next(a for c, _, a in lines if c == 'cross')
    assert cross.get('visibility') == 'hidden', cross
    yt = [(float(a['y']), text) for tag, a, text in els if tag == 'text' and a.get('class') == 'ytick']
    # (2026-11-12; dreeves: "could the graphs use more of the available horizontal space? no indenting, for one thing. ... how about end
    # the x-axis range right at the purple dashed vertical line?"): the value labels inside the chart, 3 above their
    # gridlines (4 below them until then); the x axis ends at the projected finish, 14.2 h, its round ticks within it, so
    # its labels 0, 5 and 10 h (to 15 h until then).  And later that day (Opus 5.5; dreeves, of those labels: "is that
    # standard at all to put the [y]-axis annotations to the right of the [y]-axis?", then "i'm guessing the axis break
    # slashes will make no visual sense without an axis line"): the value labels in a margin left of the plot again, 4
    # below their values.
    assert [v for _, v in yt] == ['0', '5', '10', '15\u202fh'] and all(abs(y - 4 - Ys(int(v.split()[0]))) < 0.05 for y, v in yt), yt   # up to the cap, 16.2 h (2026-11-04; to the cap 15.62 h, then the top panel's 20 h, from 2026-10-23; to 20 h before)
    xt = [(float(a['x']), text) for tag, a, text in els if tag == 'text' and a.get('class') == 'xtick']
    assert [v for _, v in xt] == ['0', '5', '10\u202fh'] and all(abs(x - X(int(v.split()[0]))) < 0.05 for x, v in xt), xt
    now = {a['class'].split()[1]: (float(a['cx']), float(a['cy'])) for tag, a, _ in els if tag == 'circle'}
    assert sorted(now) == ['spent', 'togo', 'total'], now
    check([now['spent'], now['togo'], now['total']], [(13.2, 13.2), (13.2, 1), (13.2, 14.2)], 'now')
    labels = {a['class'].split()[1]: (float(a['x']), float(a['y']), text) for tag, a, text in els
              if tag == 'text' and a.get('class', '').startswith('label ')}
    assert labels == {}, labels
    # With the labels (until 2026-10-17; back with them):
    # assert {k: v for k, (_, _, v) in labels.items()} == {'togo': '0.5–3.0\u202fh', 'total': '14–16\u202fh', 'spent': '13\u202fh'}, labels
    # for k, h in (('togo', 1), ('total', 14.2)):
    #     x, y, _ = labels[k]
    #     assert X(13.2) < x < X(13.2) + 20 and abs(y - Y(h)) < 16, (k, labels[k], X(13.2), Y(h))
    # x, y, _ = labels['spent']
    # assert abs(x - X(13.2)) < 0.05 and y > Y(0), (labels['spent'], X(13.2), Y(0))
    style = re.sub(r'/\*.*?\*/', '', page_css(), flags=re.S)   # live rules only
    assert re.search(r'--progress-spent: #2a78d6;', style) and re.search(r'--progress-togo: #e34948;', style) and re.search(r'--progress-total: #7b1fa2;', style)
    widths = {k: float(w) for k, w in re.findall(r'\.progress-eta \.(spent|togo|total) \{[^}]*stroke-width: ([\d.]+)', style)}
    assert set(widths) == {'spent', 'togo', 'total'} and widths['total'] > max(widths['spent'], widths['togo']), widths
    fills = dict(re.findall(r'\.progress-eta \.label\.(togo|total|spent) \{ fill: var\(--([\w-]+)\); \}', style))
    assert fills == {}, fills
    # With the labels (until 2026-10-17; back with them):
    # assert fills == {'togo': 'progress-togo', 'total': 'progress-total', 'spent': 'progress-spent'}, fills
    tints = dict(re.findall(r'\.progress-eta \.band\.(togo|total) \{ fill: color-mix\(in oklab, var\(--progress-(togo|total)\) \d+%', style))
    assert tints == {'togo': 'togo', 'total': 'total'}, tints
    dots = dict(re.findall(r'\.progress-eta \.now\.(spent|togo|total) \{ fill: var\(--progress-([\w-]+)\);', style))
    assert dots == {'spent': 'spent', 'togo': 'togo', 'total': 'total'}, dots
    assert not re.search(r'\.finish\b', style), 'a rule for the finish marker'
    assert re.search(r'\.progress-eta \.guide \{ stroke: var\(--progress-total\);', style), 'the guide not purple'
    assert re.search(r'\.progress-eta \.band \{[^}]*mix-blend-mode: multiply;', style), 'an overlap hidden'
    assert R['status']['legends'] == 0, R['status']

AI_QUOTE = re.compile(r'(?:Claude )?' + WRITERS + r': “')


def q_ai_text_starts_folded():
    # Replicata: index.html as written: every passage a model wrote, each quote "Model: “…”" outside an HTML comment and
    # each <blockquote class="claude">, with the folds and fold lines around it.
    # Expectata (dreeves, 2026-11-13: "i'm thinking maybe all ai-generated text should be default collapsed?", and of
    # folding each behind the model's name: "we want more context than just the model's name, so the reader knows what
    # they're expanding"): each is inside a <details> that starts closed (no open attribute), or is a fold's line itself
    # (inside a <summary>, as the remarks' list's and the proof expositions' lines are); and each fold made for such text
    # (details.ai) has a line that names a model and says more than the name, or is its section's heading (the contents
    # links' target, moved out of the quote).
    # Spec change (that afternoon; dreeves, of the OEIS notes' folds: "small anti-magic/consistency violation but this is
    # too annoying to click to expand something that's a single line. with that exception can we get more consistency with
    # all this?"): a one-line note, a quote "Model: “…”" that shares its line with other words (each OEIS note follows its
    # entry's number), stays in its line, in no fold; every other passage is folded as before, and each fold made for a
    # model's text holds one thing past its line, a block quote (class claude) whose last paragraph signs it "— Model",
    # the model its line names where the line is "Model on …" (a heading line is not read: dreeves's words).  Every block
    # quote of a model's is signed so.
    # Resultata before: 19 passages shown as the page opens, from Opus 5.5's account of the upper bounds to Fable 5.2's
    # proof for large lengths.  Before the spec change: the ten OEIS notes each in a fold; two folds holding paragraphs
    # "Model: “…”" (the 1440 note, the partitions' counts), one an unsigned block quote (the asymptotics'), one signed
    # "— Claude Opus 5.5" under the line "Opus 5.5 on …".
    s = blank_comments(page())
    def around(pos):
        stack, summary = [], 0
        for m in re.finditer(r'<details\b[^>]*>|</details>|<summary\b[^>]*>|</summary>', s[:pos]):
            t = m.group()
            if t.startswith('<details'): stack.append(t)
            elif t == '</details>': stack.pop()
            else: summary += 1 if t.startswith('<summary') else -1
        return stack, summary > 0
    BLOCK = r'<(?:p|li|td|th|dd|dt|h[1-6]|div|blockquote|details|summary|figcaption|section)\b[^>]*>'
    def note(text, pos):
        """whether the quote at pos in text shares its line with other words: words since the block that holds it began"""
        start = [m.end() for m in re.finditer(BLOCK, text[:pos])][-1]
        return re.sub(r'<[^>]+>|\s', '', text[start:pos]) != ''
    # the control: a quote after an entry's number is a note; one that begins its paragraph is not
    li, para = '<ul><li><a href="#">A000069</a>. Claude: “Its other part.”</li></ul>', '<p>Claude: “Its other part.”</p>'
    assert note(li, li.index('Claude')) and not note(para, para.index('Claude'))
    quotes = [m.start() for m in AI_QUOTE.finditer(s)]
    places = quotes + [m.start() for m in re.finditer(r'<blockquote class="claude"', s)]
    shown, notes = [], []
    for pos in places:
        stack, in_line = around(pos)
        if in_line or any(not re.search(r'\sopen\b', d) for d in stack): continue
        (notes if pos in quotes and note(s, pos) else shown).append(re.sub(r'<[^>]+>', ' ', s[pos:pos + 90]).strip())
    assert len(places) > 50 and shown == [], (len(shown), shown[:5])
    # each details.ai: its line, and what it holds past its line, to its own </details> (folds may nest)
    folds = []
    for m in re.finditer(r'<details class="ai"[^>]*>\s*<summary>(.*?)</summary>', s, re.S):
        depth, i = 1, m.end()
        for t in re.finditer(r'<details\b[^>]*>|</details>', s[m.end():]):
            depth += 1 if t.group().startswith('<details') else -1
            if depth == 0: i = m.end() + t.start(); break
        folds.append((m.group(1), s[m.end():i].strip()))
    named = [l for l, _ in folds if re.match(r'(Opus 5\.5|Fable 5\.2|Astra|Claude|Gemini Neon) \S+ \S+', l) or re.fullmatch(r'\s*<h2 id="[^"]+">[^<].*</h2>\s*', l, re.S)]
    assert folds and named == [l for l, _ in folds], [l for l, _ in folds if l not in named][:5]
    SIGNED = r'<blockquote class="claude">.*<p class="attrib">— (Opus 5\.5|Fable 5\.2|Astra|Claude|Gemini Neon)</p>\s*</blockquote>'
    unlike = []
    for line, held in folds:
        q = re.fullmatch(SIGNED, held, re.S)
        one = q and held.count('<blockquote') == 1
        label = re.match(r'(Opus 5\.5|Fable 5\.2|Astra|Claude|Gemini Neon) on ', line)
        if not one or (label and label.group(1) != q.group(1)): unlike.append((re.sub(r'<[^>]+>', ' ', line).strip()[:60], held[:70]))
    assert unlike == [], (len(unlike), unlike[:4])
    bqs = re.findall(r'<blockquote class="claude">.*?</blockquote>', s, re.S)
    unsigned = [b[:120] for b in bqs if not re.search(r'<p class="attrib">— (Opus 5\.5|Fable 5\.2|Astra|Claude|Gemini Neon)</p>\s*</blockquote>$', b)]
    assert bqs and unsigned == [], unsigned


def q_preview_png_is_current():
    # Replicata: preview.png as it is, and the image pagegen/preview.py draws now from the page (index.html, page/ and
    # the data files the page loads, as they are), into a directory of the qual's.
    # Expectata (dreeves, 2026-11-13: "i guess that would be a reasonable qual, sure, to keep the preview image from
    # getting stale"): the two are the same, pixel for pixel, so that a shared link shows the page as it is.  When they
    # differ, rerun `python3 -B pagegen/preview.py` and look at the image.  The builder draws the same pixels run after
    # run (2026-11-13: renders in parallel and in turn, byte for byte); a new Chrome or new fonts from Google could move
    # pixels too, and the same rerun answers that.  When the page does not load whole (without the network its fonts and
    # KaTeX are missing), the builder fails on its own and leaves preview.png as it is.  preview.png's pixels are those
    # of dreeves's Mac, its Chrome and fonts, so elsewhere this fails.  The builder's Chrome is the quals' (CHROME) and
    # starts with the quals' flags (HEADLESS), in their order.
    # Resultata before: the preview.png of 2026-11-09 (rebuilt 2026-11-13) differed from the page in the cells of 2^30,
    # 2^33, 2^34, 2^51 and 2^52 and in the legend.
    from PIL import Image, ImageChops
    import preview
    assert preview.CHROME == CHROME and preview.FLAGS[:len(HEADLESS)] == HEADLESS, (preview.CHROME, preview.FLAGS, HEADLESS)
    d = tempfile.mkdtemp(prefix='index-quals-')
    try:
        fresh = Image.open(preview.render(os.path.join(d, 'preview.png'))).convert('RGB')
        held = Image.open(PREVIEW).convert('RGB')
        assert held.size == fresh.size == preview.SIZE, (held.size, fresh.size, preview.SIZE)
        where = ImageChops.difference(held, fresh).getbbox()
        assert where is None, ('preview.png is not what pagegen/preview.py draws now: rerun it and look at the image', where)
    finally:
        shutil.rmtree(d)


def q_preview_is_judged_by_what_chrome_wrote():
    # Replicata: pagegen/preview.py's render, its Chrome replaced by a wrapper that (a) runs the real Chrome with the
    # arguments it was given and then exits 2; (b) runs it and then cuts the screenshot it wrote to half its bytes,
    # exiting 0; (c) runs nothing and exits 0.  Each into a file that holds "as it was".
    # Expectata (Fable 5.2, 2026-11-13): (a) render returns its image, preview.png's pixels: Chrome's exit status is not
    # read.  Under load its teardown watchdog fires after the shot and the page's dump are written, whole (that day: 7 of
    # 8 renders run at once exited 2, "Teardown watchdog expired", each shot preview.png's bytes; and
    # q_preview_png_is_current failed so in the suite's own run, where it passes alone), with the display-sleep flag too.
    # What Chrome wrote is what render checks: the page's dump with CHECK's mark, nothing on it, and a whole PNG.  So (b)
    # and (c) fail (AssertionError), and leave the file as it was.
    # Resultata before: (a) failed on the status ('Chrome failed', 2, ...).
    from PIL import Image, ImageChops
    import preview
    d = tempfile.mkdtemp(prefix='index-quals-')
    real = preview.CHROME
    try:
        wrapper = os.path.join(d, 'chrome')
        open(wrapper, 'w').write(f"""#!{sys.executable}
import os, sys, subprocess
mode = os.environ['PREVIEW_QUAL_MODE']
shot = next(a.split('=', 1)[1] for a in sys.argv[1:] if a.startswith('--screenshot='))
if mode != 'nothing': subprocess.run([{real!r}, *sys.argv[1:]])
if mode == 'cut': open(shot, 'r+b').truncate(os.path.getsize(shot) // 2)
sys.exit(2 if mode == 'exit2' else 0)
""")
        os.chmod(wrapper, 0o755)
        preview.CHROME = wrapper
        out = os.path.join(d, 'out.png')
        said = {}
        for mode in ('exit2', 'cut', 'nothing'):
            open(out, 'w').write('as it was')
            os.environ['PREVIEW_QUAL_MODE'] = mode
            try: preview.render(out); how = 'drawn'
            except AssertionError: how = 'refused'
            kept = open(out, 'rb').read() == b'as it was'
            same = how == 'drawn' and ImageChops.difference(Image.open(out).convert('RGB'), Image.open(PREVIEW).convert('RGB')).getbbox() is None
            said[mode] = (how, kept, same)
        assert said == dict(exit2=('drawn', False, True), cut=('refused', True, False), nothing=('refused', True, False)), said
    finally:
        preview.CHROME = real
        os.environ.pop('PREVIEW_QUAL_MODE', None)
        shutil.rmtree(d)


def q_links_into_an_entry_land_in_the_appendix_while_a_box_shows_it():
    # 2026-11-18 (Opus 5.5; dreeves, of a link from a derivation: "something's wrong when i click on the link here. it
    # goes to the column version of the box? ... is this qualsifiable?", then "yes, please fix that!").
    # Replicata: index.html loaded on its own (headless Chrome, 1280 px); the appendix's fold opened and closed, so that
    # KaTeX has drawn its entries' math (later that night: dreeves, "links not working for me still"); the box of column
    # 432 opened by its fragment, #n432, so that it shows 432's entry; then, with it open, a click on the first link to
    # the code 432:11 outside the appendix and the boxes (the page's \href{#432:11}{p_{432}}), and then a click on the
    # appendix's first construction that names p_432 (2^20's until 2026-11-21, Fable 5.2: found by its N:M then, which the chart's own
    # construction of 2^20 shares since the sequence at 2^13 made that p_8192 # tau_7, with no p_432 in it) and, in its derivation, on its
    # part p_432, a link to 432's entry (#entry-432); then
    # the box of column 80, whose entry's witness is the construction p_2 # p_40, and a click on that construction in
    # the box.
    # Expectata: the box shows 432's entry the whole time, and each link lands in the appendix: its target, the code
    # 432:11 and then 432's entry, is in the section of class appendix, not in a box, the appendix's fold open and the
    # target in the viewport.  A box shows a copy of an entry, so that every link to the entry or into it lands in the
    # appendix.  The construction in 80's box, a copy of the drawn entry's, expands: its derivation shows; and nothing
    # is thrown.
    # (In view: its top less than a pixel above the viewport's or below it, since 2026-11-19, when the scroll to 432's entry
    # stopped on a whole pixel 0.3125 px past the entry's top, which the page's new content above it had put at a fraction:
    # r.top >= 0 until then; Opus 5.5.)
    # Resultata before: since 2026-11-03 a box moved the entry itself out of the list: both targets were in the box,
    # and each click scrolled the page to the box, the appendix left shut.  Then (the copy's first version) a box that
    # copied an entry whose math KaTeX had drawn threw, its construction read as drawn math, not TeX, and its buttons
    # after it went unmade.
    probe = ('<script>addEventListener("load", () => setTimeout(async () => { const errs = []; addEventListener("error", e => errs.push(String(e.message)));'
             ' const wait = t => new Promise(r => setTimeout(r, t)); const fold = document.querySelector("section.appendix details");'
             ' fold.open = true; await wait(800); fold.open = false; await wait(100); location.hash = "#n432"; await wait(600);'
             ' const region = document.getElementById("mstar-panel"), shows = () => !region.hidden && [...region.querySelectorAll("[data-panel-entries] p.entry")].some(p => p.dataset.lengths === "432");'
             ' const at = id => { const t = document.getElementById(id), r = t && t.getBoundingClientRect();'
             '   return t && {appendix: t.closest("section.appendix") !== null, box: t.closest(".column-panel") !== null, inView: r.top > -1 && r.top < innerHeight,'
             '     fold: document.querySelector("section.appendix details").open, shows: shows()}; };'
             ' const out = {before: shows()}; const link = [...document.querySelectorAll(\'a[href="#432:11"]\')].find(a => !a.closest("section.appendix, .column-panel"));'
             ' link.click(); await wait(500); out.code = at("432:11");'
             ' const f = [...document.querySelectorAll("section.appendix [data-construction]")].find(e => e.textContent.includes("432")); f.click(); await wait(300);'
             ' const part = [...document.getElementById(f.getAttribute("aria-controls")).querySelectorAll("a")].find(a => a.getAttribute("href") === "#entry-432");'
             ' part.click(); await wait(500); out.entry = at("entry-432");'
             ' location.hash = "#n80"; await wait(600); const built = region.querySelector("[data-panel-entries] [data-construction]"); built.click(); await wait(300);'
             ' const shown = document.getElementById(built.getAttribute("aria-controls") || ""); out.derived = [built.getAttribute("aria-expanded"), !!shown && shown.checkVisibility()]; out.errs = errs;'
             ' document.documentElement.dataset.landed = JSON.stringify(out); }, 1500));</script>')
    d = tempfile.mkdtemp(prefix='landing-quals-')
    try:
        open(os.path.join(d, 'index.html'), 'w', encoding='utf-8').write(page().replace('</body>', probe + '</body>'))
        copy_page_dir(d)
        shutil.copy(DATA, data_file(d, 'mstar.js'))
        shutil.copy(POW2, data_file(d, 'pow2.js'))
        dom = chrome(d, ['--window-size=1280,900', '--virtual-time-budget=20000', '--dump-dom', 'file://' + os.path.join(d, 'index.html')])
    finally:
        shutil.rmtree(d)
    m = re.search(r'<html[^>]* data-landed="([^"]*)"', dom)
    assert m, dom[:300]
    got = json.loads(html.unescape(m[1]))
    want = {'appendix': True, 'box': False, 'inView': True, 'fold': True, 'shows': True}
    assert got['errs'] == [] and got['before'] and got['code'] == want and got['entry'] == want and got['derived'] == ['true', True], got


def q_box_heading_links_keep_the_page_still_and_each_box_links_its_entry():
    # 2026-11-18 (Opus 5.5; dreeves: "having a link from a cell popup box to the corresponding ones for the column and for
    # the row makes sense. (sub-bug: the page scrolls when i click those, making the box flush with the top of the
    # screen. i expect it to not cause scrolling). what i *also* want is a link to take me to the corresponding entry in
    # the appendix.").
    # Replicata: index.html loaded on its own (headless Chrome, 1280 x 900); the m*(n) chart's box of the cell (80, 13)
    # opened by its fragment, the page scrolled so that the box's top is 150 px down the viewport; a click on its
    # heading's n = 80 (to its column's box), then the cell's box again, its top again 150 px down, and a click on its
    # heading's m = 13 (to its row's box); then, in turn, the boxes #n80m13, #n80, #m13, #k10 and #k30, each read: its
    # link to the appendix (data-panel-entry), and for each one with an href, a click on it.
    # Expectata: each heading click switches the box (to the column's, to the row's) and leaves the page where it was;
    # a cell's or a column's box links its length's entry in the appendix, #entry-N (80's from #n80m13 and #n80, 1024's
    # from #k10, 2^30's from #k30), and the link lands there, the appendix's fold open and the entry in the viewport;
    # a row's box has that link grayed out (no href, aria-disabled), a row having no entry; nothing thrown.
    # Resultata before: each heading click scrolled the box's top to the viewport's top; no box linked its entry.
    probe = ('<script>addEventListener("load", () => setTimeout(async () => { const errs = []; addEventListener("error", e => errs.push(String(e.message)));'
             ' const wait = t => new Promise(r => setTimeout(r, t)); const panel = id => document.getElementById(id);'
             ' const at150 = r => { scrollBy(0, r.getBoundingClientRect().top - 150); }; const out = {};'
             ' const heading = async (href, key) => { location.hash = "#n80m13"; await wait(600); const r = panel("mstar-panel"); at150(r); await wait(100);'
             '   const y = scrollY; r.querySelector(`[data-panel-title] a[href="${href}"]`).click(); await wait(600);'
             '   out[key] = {kind: r.dataset.kind, moved: Math.abs(scrollY - y) > 1}; };'
             ' await heading("#n80", "column"); await heading("#m13", "row");'
             ' out.links = []; for (const [frag, id] of [["n80m13", "mstar-panel"], ["n80", "mstar-panel"], ["m13", "mstar-panel"], ["k10", "pow2-panel"], ["k30", "pow2-panel"]]) {'
             '   location.hash = "#" + frag; await wait(600); const a = panel(id).querySelector("[data-panel-entry]"); const href = a && a.getAttribute("href");'
             '   const row = [frag, href, a && a.getAttribute("aria-disabled")];'
             '   if (href) { a.click(); await wait(500); const t = document.getElementById(href.slice(1)), b = t && t.getBoundingClientRect();'
             '     row.push(!!t && t.closest("section.appendix") !== null && document.querySelector("section.appendix details").open && b.top > -2 && b.top < innerHeight); }'
             '   out.links.push(row); }'
             ' out.errs = errs; document.documentElement.dataset.boxes = JSON.stringify(out); }, 1500));</script>')
    d = tempfile.mkdtemp(prefix='boxlinks-quals-')
    try:
        open(os.path.join(d, 'index.html'), 'w', encoding='utf-8').write(page().replace('</body>', probe + '</body>'))
        copy_page_dir(d)
        shutil.copy(DATA, data_file(d, 'mstar.js'))
        shutil.copy(POW2, data_file(d, 'pow2.js'))
        dom = chrome(d, ['--window-size=1280,900', '--virtual-time-budget=30000', '--dump-dom', 'file://' + os.path.join(d, 'index.html')])
    finally:
        shutil.rmtree(d)
    m = re.search(r'<html[^>]* data-boxes="([^"]*)"', dom)
    assert m, dom[:300]
    got = json.loads(html.unescape(m[1]))
    assert got['errs'] == [] and got['column'] == {'kind': 'column', 'moved': False} and got['row'] == {'kind': 'row', 'moved': False}, got
    # (an entry's top within 2 px of the viewport's: the scroll to it rounds, -0.44 px at 80's)
    assert got['links'] == [['n80m13', '#entry-80', 'false', True], ['n80', '#entry-80', 'false', True], ['m13', None, 'true'],
                            ['k10', '#entry-1024', 'false', True], ['k30', f'#entry-{2 ** 30}', 'false', True]], got['links']


def main():
    names = sys.argv[1:] or [n for n in globals() if n.startswith('q_')]
    failed = 0
    for n in names:
        t0, c0 = time.time(), time.process_time()
        try:
            globals()[n]()
            # TODO: runner line; says the named qual passed, with its seconds and this process's CPU seconds
            print(f'Claude: "PASSED" {n} ({time.time() - t0:.1f} s, {time.process_time() - c0:.1f} CPU s)', flush=True)
        except Exception:
            failed += 1
            # TODO: runner line; says the named qual failed, with its seconds and this process's CPU seconds, followed by the traceback
            print(f'Claude: "FAILED" {n} ({time.time() - t0:.1f} s, {time.process_time() - c0:.1f} CPU s)\n' + traceback.format_exc(), flush=True)
    # TODO: runner summary; says how many quals passed out of how many
    print(f'Claude: "{len(names) - failed} of {len(names)} passed"')
    sys.exit(1 if failed else 0)


if __name__ == '__main__':
    main()
