#!/usr/bin/env python3
"""Opus 5.5's quals for searchwatch/bandit.py, the Bayesian bandit over the black cells (2026-12-01; dreeves: "can we get
principled with a scoring system, like anything that would be changed gold-trimmed cells is worth a lot, black cells past
2048 are worth a lot less, etc, and then just sort the black cells by expected score ... some way to have a dynamic list
and always be grinding on whatever's currently at the top of that list", then "oh, right, bayesian bandit").
Run from the repo:
    python3 -B quals/quals_bandit.py [name ...]
Each qual is a function q_*: a passing qual returns, a failing one raises; each comment gives its replicata and
expectata; a failure's message or traceback gives the resultata.  Each was seen red before bandit.py was written (no
such module); the ones that run the grinder run it in a temporary directory, on made-up arms and a stand-in for the
tilted search."""
import sys
sys.dont_write_bytecode = True
import os, re, json, math, time, shutil, signal, fnmatch, subprocess, tempfile, traceback
from unittest.mock import patch
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))   # the repository's root, above quals/
sys.path.insert(0, os.path.join(HERE, 'searchwatch'))
import bandit
PY = sys.executable


def arm(n=100, m=5, W=280, top=30.0, d=208, setup=0.1, exists=1.0, before=0.0, pow2=()):
    return dict(n=n, m=m, W=W, top=top, d=d, setup=setup, exists=exists, before=before, pow2=list(pow2))


def close(a, b, tol=1e-9): return abs(a - b) <= tol * max(1.0, abs(a), abs(b))


# ---------- worth ----------

def chart(lo, hi): return dict(lo=[0] + lo, hi=[0] + hi)


def q_a_find_is_worth_the_cells_it_colors():
    # Replicata: a chart of 12 columns, column 8 known to reach 2 and open to 5, every other column settled at 0; its opening view ends
    # at column 8; no gold ring is in play (a ring's points 0).
    # Expectata: a find of order 5 at 8 colors three cells of the opening view, 3 points; with the view ending at 7, three cells past it,
    # 0.3 points; a find that colors none is worth 0.
    lo, hi = [0] * 12, [0] * 12
    lo[7], hi[7] = 2, 5
    before = chart(lo, hi)
    points = dict(bandit.POINTS, ring=0.0)
    after = bandit.closure(before['lo'], 8, 5)
    assert close(bandit.points_of(before['lo'], after, before['hi'], 8, lambda i: 0, points), 3.0)
    assert close(bandit.points_of(before['lo'], after, before['hi'], 7, lambda i: 0, points), 0.3)
    assert bandit.points_of(before['lo'], before['lo'], before['hi'], 8, lambda i: 0, points) == 0


def q_a_find_is_worth_the_rings_it_moves():
    # Replicata: rows 1 to 3 of a chart of 8 columns: column 2 reaches order 1 and may reach no more; column 6 reaches 1 and may reach 2;
    # column 8 reaches 2 and may reach 2.
    # Expectata: order 2's gold ring, the least column known to reach it, is at 8 and its least column not ruled out is 6; a find of
    # order 2 at 6 moves that one ring and settles it, 10 points more than the cell's own; a find that moves no ring has none.
    lo, hi = [0, 1, 0, 0, 0, 1, 0, 2], [0, 1, 0, 0, 0, 2, 0, 2]
    before = chart(lo, hi)
    assert bandit.rings(before['lo'], before['hi'], lambda i: 0) == {1: (2, 2), 2: (8, 6)}
    after = [0] + lo[:]; after[6] = 2
    assert close(bandit.points_of(before['lo'], after, before['hi'], 8, lambda i: 0, bandit.POINTS), bandit.POINTS['ring'] + bandit.POINTS['near'])


def q_a_find_reaches_other_columns_by_products_and_joins():
    # Replicata: 24 columns, columns 2 (order 1) and 8 (order 3) known; a find of order 4 at 6.
    # Expectata: 12 = 2 x 6 reaches 5, 24 = 2 x 12 reaches 6 (two steps), 14 = 6 + 8 reaches 3 (the lesser of 4 and 3), and 12 is not
    # lowered by the join 6 + 6 (order 4).
    lo = [0] * 25
    lo[2], lo[8] = 1, 3
    after = bandit.closure(lo, 6, 4)
    assert (after[6], after[12], after[24], after[14]) == (4, 5, 6, 3), after
    assert after[2] == 1 and after[8] == 3 and after[7] == 0


def q_the_rings_are_the_pages():
    # Replicata: page/shared.js's own function of the gold rings, raised, run in node on the data of both charts, and bandit.rings on them.
    # Expectata: the same ring cells, row by row, on both.
    src = open(os.path.join(HERE, 'page', 'shared.js'), encoding='utf-8').read()
    raised = src[src.index('function raised(cols, shift)'):]
    raised = raised[:raised.index('\n}\n') + 3]
    code = raised + ("const D = JSON.parse(require('fs').readFileSync(0, 'utf8'));"
                     "const out = {}; for (const [name, shift] of [['mstar', () => 0], ['pow2', j => j + 1]]) {"
                     "  out[name] = raised(D[name], shift).flatMap(([known, possible], i) => [...known.map(r => [r, 'known', i + 1]), ...possible.map(r => [r, 'possible', i + 1])]); }"
                     "console.log(JSON.stringify(out));")
    charts = bandit.charts()
    given = {k: [[l, h] for l, h in zip(c['lo'][1:], c['hi'][1:])] for k, c in charts.items()}
    said = json.loads(subprocess.run(['node', '-e', code], input=json.dumps(given), capture_output=True, text=True, check=True).stdout)
    for name, shift in (('mstar', lambda i: 0), ('pow2', lambda i: i)):
        page = {}
        for r, what, i in said[name]: page.setdefault(r, {})[what] = i
        mine = bandit.rings(charts[name]['lo'], charts[name]['hi'], shift)
        assert {r: (v.get('known'), v.get('possible')) for r, v in page.items()} == mine, name
        assert len(mine) > 10, name


def q_the_opening_views_are_the_pages():
    # Replicata: the caps pressed as the page loads, in index.html (data-cap, aria-pressed), of both charts.
    # Expectata: bandit.NEAR, the last column of each opening view.
    html = open(os.path.join(HERE, 'index.html'), encoding='utf-8').read()
    pressed = {name: [int(re.search(r'data-cap="(\d+)"', b)[1]) for b in re.findall(r'<button[^>]*>', html[html.index(f'id="{name}-caps"'):].split('</span>')[0]) if 'aria-pressed="true"' in b]
               for name in ('mstar', 'pow2')}
    assert {k: [v] for k, v in bandit.NEAR.items()} == pressed, pressed


def q_worth_on_the_page_s_data():
    # Replicata: the page's data, and bandit.worth of every black cell of Figure 1 with no power of 2 named.
    # Expectata: every one is worth at least a far cell's points; a cell gold-trimmed black is worth more than a ring's; every cell
    # past the opening view that moves no ring is worth less than a cell of the opening view.
    charts = bandit.charts()
    lo, hi = charts['mstar']['lo'], charts['mstar']['hi']
    rows = bandit.rings(lo, hi, lambda i: 0)
    black = [(n, m) for n in range(1, len(lo)) for m in range(lo[n] + 1, hi[n] + 1)]
    trimmed = {(possible, r) for r, (known, possible) in rows.items() if known != possible}
    worth = {c: bandit.worth(arm(n=c[0], m=c[1]), charts, frozenset()) for c in black}
    assert trimmed and all(worth[c] > bandit.POINTS['ring'] for c in trimmed), {c: worth[c] for c in trimmed}
    assert all(w >= bandit.POINTS['far'] * 0.999 for w in worth.values())
    assert all(w < bandit.POINTS['near'] for c, w in worth.items() if c[0] > bandit.NEAR['mstar'] and w < bandit.POINTS['ring'])


def q_a_power_of_2_s_rings_count():
    # Replicata: the page's data and an arm whose find would give order K + e at 2^K, one power below the first of its excess e.
    # Expectata: its worth is at least a ring's more than the same arm's with no such power.
    charts = bandit.charts()
    lo = charts['pow2']['lo']
    e, K = max((lo[k] - k, -k) for k in range(1, 100))
    first = next(k for k in range(1, len(lo)) if lo[k] - k >= e)
    a, b = arm(n=2288, m=13), arm(n=2288, m=13, pow2=[[first - 1, first - 1 + e]])
    assert bandit.worth(b, charts, frozenset()) >= bandit.worth(a, charts, frozenset()) + bandit.POINTS['ring']


def q_a_found_cell_is_worth_nothing_more():
    # Replicata: the page's data, a black cell, and the same cell once a find at it is known (not yet on the page).
    # Expectata: its worth falls to 0.
    charts = bandit.charts()
    lo, hi = charts['mstar']['lo'], charts['mstar']['hi']
    n = next(n for n in range(2049, len(lo)) if lo[n] < hi[n])
    a = arm(n=n, m=lo[n] + 1)
    assert bandit.worth(a, charts, frozenset()) > 0
    assert bandit.worth(a, charts, frozenset({(n, lo[n] + 1)})) == 0


def q_a_verified_find_gets_no_second_batch_while_its_dyadic_gain_awaits_publication():
    # Replicata: a cell would move a Figure 2 ring, and a verified witness reaches its target
    # before publication. At 40, beyond Figure 1's 32 columns, the witness exceeds the target.
    # Expectata: stop a redundant sibling and put all eight next seeds on the open alternative.
    # Resultata before: credit for the dyadic gain persisted, and a running 40 indexed past the chart.
    page, a, b = focus_example()
    page['pow2']['hi'][2] = 3
    for n, order_found in ((40, 2), (20, 1)):
        lift = dict(a, n=n, pow2=[[2, 3]])
        assert bandit.worth(lift, page, frozenset()) > bandit.worth(dict(a, n=n), page, frozenset())
        live = [recorded_pull(lift, 11), recorded_pull(lift, 12)]
        assert focus_step(page, [lift, b], live, live, {}) == ([], [])
        found = frozenset({(n, order_found)})
        live[0]['found'] = [dict(n=n, order=order_found)]
        assert bandit.worth(lift, page, found) == 0
        assert focus_step(page, [lift, b], live, live, {}, found) == ([], [(12, signal.SIGTERM)])
        launches, _ = focus_step(page, [lift, b], live, [], {}, found)
        assert len(launches) == 8 and all(setting == b for setting, _, _ in launches), launches


# ---------- the chance of a find ----------

def q_hours_without_a_find_lower_the_rate():
    # Replicata: an arm, with 0, 1, 10, 100 and 1000 core-hours of search and no find.
    # Expectata: its chance of a find in the next hour falls strictly, the chance that a witness exists falls where it started below 1,
    # and stays 1 where it started at 1.
    a = arm(exists=0.9)
    hours = (0.0, 1.0, 10.0, 100.0, 1000.0)
    next_hour = [1 - bandit.survival(a, t + 1) / bandit.survival(a, t) for t in hours]
    assert all(x > y > 0 for x, y in zip(next_hour, next_hour[1:])), next_hour
    exists = [bandit.exists(a, t) for t in hours]
    assert exists[0] == 0.9 and all(x > y for x, y in zip(exists, exists[1:])), exists
    assert all(close(bandit.exists(arm(), t), 1.0) for t in hours)


def q_the_prior_moves_with_the_reading():
    # Replicata: two arms alike but for their reading, 40 and 20 bits; two alike but for the lattice's dimension, 208 and 268.
    # Expectata: the larger reading and the smaller dimension have the larger chance within an hour.
    p = lambda a: 1 - bandit.survival(a, 1.0)
    assert p(arm(top=40)) > p(arm(top=20)) > p(arm(top=0)) and p(arm(d=208)) > p(arm(d=268))


def q_the_prior_holds_on_the_logged_runs():
    # Replicata: quals_bandit_runs.json, the 121 settings (cell and window) of the tilted search logged before 2026-12-01 whose order was not
    # ruled out since: core-hours of search, runs that found, reading, dimension; and the prior's survival.
    # Expectata: of the settings with a find, the hours per find lie in the prior's middle 80 percent about 80 times in 100 (70 to 92: the
    # prior was fitted on them, so this holds the code to the fit, not the fit to the world); and settings searched in vain for longer
    # than the prior's 95th percentile are under a tenth of those in vain.
    data = json.load(open(os.path.join(HERE, 'quals', 'quals_bandit_runs.json')))
    assert len(data) == 121
    inside, total, long_, vain = 0, 0, 0, 0
    for x in data:
        a = arm(n=x['n'], m=x['m'], W=x['W'], top=x['top'] + bandit.NOISE, d=x['d'])
        s = bandit.survival(a, x['hours'] / max(1, x['finds']))
        if x['finds']:
            total += 1; inside += 0.1 <= s <= 0.9
        else:
            vain += 1; long_ += s < 0.05
    assert 0.70 <= inside / total <= 0.92, (inside, total)
    assert long_ < 0.1 * vain, (long_, vain)


def q_a_certain_rate_is_the_exponential_law():
    # Replicata: an arm whose prior is one rate, ten finds an hour (bandit.rates replaced by it).
    # Expectata: the chance of no find in t hours is exp(-10 t); the best slice's score is the worth over the setup and the mean time, to the
    # grid's coarseness: worth 1, setup 0.1 hours, score within 10 percent of 1 / (0.1 + 0.1).
    import numpy as np
    keep = bandit.rates
    bandit.rates = lambda a: (np.array([10.0]), np.array([1.0]))
    try:
        a = arm(setup=0.1)
        assert close(bandit.survival(a, 0.3), math.exp(-3.0), 1e-9)
        score, hours = bandit.score(a, 1.0, 0.0, 0.0)
        assert 0.9 * 5.0 <= score <= 5.0 * 1.0001 and hours > 0.2, (score, hours)
    finally:
        bandit.rates = keep


# ---------- the score and the list ----------

def fixed_rate(a):
    """A qual arm's top is its known rate conditional on the cell having a solution."""
    import numpy as np
    return np.array([a['top']]), np.ones(1)


def q_team_score_counts_every_setup_and_returns_one_seeds_time():
    # Replicata: one possible rate of 4 finds per core-hour, or no solution. Some core-hours
    # have already elapsed and some are in flight. For each proposed duration, integrate the
    # team's core-hours until its first find or the deadline, then charge every worker's setup.
    # Expectata: score maximizes expected points per core-hour and returns the duration per seed.
    # Resultata before: the score priced only one pull.
    a = arm(top=4, exists=0.6, setup=0.12, before=0.05)
    points, searched, flying = 3.0, 0.15, 0.1
    rate, prior = a['top'], a['exists']
    def survival(t): return 1 - prior + prior * math.exp(-rate * t)
    done = a['before'] + searched
    pending = done + flying
    exists = prior * math.exp(-rate * pending) / survival(pending)
    with patch.object(bandit, 'rates', fixed_rate):
        for workers in (1, 8):
            offers = []
            for duration in bandit.SLICES:
                exposure = workers * duration
                hit = -math.expm1(-rate * exposure)
                chance = survival(pending) / survival(done) * exists * hit
                cost = workers * a['setup'] + (1-exists) * exposure + exists * hit / rate
                offers.append((points * chance / cost, duration))
            expected, duration = max(offers)
            score, per_seed = bandit.score(a, points, searched, flying, workers=workers)
            assert close(score, expected) and close(per_seed, duration), (workers, score, per_seed, expected, duration)


def focus_example():
    """Two equally valuable open cells; the faster search has a higher setup cost."""
    lo = [0]*32
    hi = lo.copy()
    hi[19] = hi[23] = 1
    page = dict(mstar=chart(lo, hi), pow2=chart([1, 2], [1, 2]))
    a = arm(n=20, m=1, W=8, top=1, setup=0.04, exists=0.6)
    b = arm(n=24, m=1, W=10, top=4, setup=0.25, exists=0.6)
    return page, a, b


def q_the_highest_scoring_arm_can_change_with_the_number_of_workers():
    # Replicata: rank the same two cells for one seed and for eight simultaneous seeds.
    # Expectata: one seed favors the faster rate, eight favor the smaller setup. The list
    # quotes each team's score and per-seed time. Resultata before: only one seed was priced.
    page, a, b = focus_example()
    got = frozenset()
    with patch.object(bandit, 'rates', fixed_rate):
        for workers, winner in ((1, b), (8, a)):
            rows = bandit.ranking([a, b], page, got, {}, {}, workers=workers)
            assert rows[0]['arm'] == winner, (workers, rows)
            for row in rows:
                score, duration = bandit.score(row['arm'], row['worth'], 0, 0, workers=workers)
                assert close(row['score'], score) and close(row['slice'], duration), row


def q_the_score_is_points_an_hour():
    # Replicata: one arm at worths 1 and 2; a quick arm of worth 0.1 (found in minutes) and a slow one of worth 1 (about a thousand hours).
    # Expectata: the score doubles with the worth, and the quick cell comes first though the slow one has the larger worth: what is compared is
    # points an hour, not points.
    a = arm(top=30)
    assert close(2 * bandit.score(a, 1.0, 0.0, 0.0)[0], bandit.score(a, 2.0, 0.0, 0.0)[0])
    assert bandit.score(arm(top=75, setup=0.05), 0.1, 0.0, 0.0)[0] > bandit.score(arm(top=-5, setup=0.05), 1.0, 0.0, 0.0)[0]
    assert bandit.score(a, 0.0, 0.0, 0.0)[0] == 0


def q_pulls_in_flight_lower_the_next_pull_s_score():
    # Replicata: an arm with 0, 1, 10 and 100 core-hours of search already in flight.
    # Expectata: the next pull's score falls with each, and is positive.
    s = [bandit.score(arm(), 1.0, 0.0, f)[0] for f in (0.0, 1.0, 10.0, 100.0)]
    assert all(x > y > 0 for x, y in zip(s, s[1:])), s


def q_the_list_is_sorted_by_score_and_holds_every_arm_s_best():
    # Replicata: three cells, one with two arms (windows), on the page's data.
    # Expectata: one line a cell, its best arm's, sorted by score, the found one at 0.
    charts = bandit.charts()
    lo, hi = charts['mstar']['lo'], charts['mstar']['hi']
    cells = [(n, lo[n] + 1) for n in range(2049, len(lo)) if lo[n] < hi[n]][:3]
    arms = [arm(n=cells[0][0], m=cells[0][1], top=20), arm(n=cells[0][0], m=cells[0][1], W=320, top=60, d=247), arm(n=cells[1][0], m=cells[1][1], top=60), arm(n=cells[2][0], m=cells[2][1], top=60)]
    rows = bandit.ranking(arms, charts, frozenset({cells[2]}), {}, {})
    assert [r['cell'] for r in rows[-1:]] == [cells[2]] and rows[-1]['score'] == 0
    assert len(rows) == 3 and all(a['score'] >= b['score'] for a, b in zip(rows, rows[1:]))


# ---------- the estimator ----------

def q_the_estimate_holds_to_the_record_s_form():
    # Replicata: bandit.estimate for an arm, an hour old, with 1 and with 5 pulls running.
    # Expectata: with a time it holds to track.checked; unit seconds and basis bandit; the time to go with five pulls is a fifth of that with
    # one; exists is at most the prior.
    import track
    a = arm(exists=0.9)
    one, five = (bandit.estimate(a, 3600.0, 1.0, k, False) for k in (1, 5))
    for e in (one, five):
        track.checked([dict(event='start', name='x', search='bandit', target='100:5', estimator='e', command='c', cwd='/', found=None, adopted=False, pid=1, tracker=1, time=0.0), dict(e, time=1.0)])
    assert one['basis'] == 'bandit' and one['unit'] == 'seconds' and one['exists'] < one['prior'] == 0.9 and one['finds'] is None
    assert all(close(one['to_go'][k], 5 * five['to_go'][k], 1e-6) for k in ('lo', 'median', 'hi'))
    assert one['to_go']['lo'] < one['to_go']['median'] < one['to_go']['hi']


def q_a_found_cell_s_estimate_says_that_it_exists():
    # Replicata: bandit.estimate for an arm with and without a find at its cell.
    # Expectata: exists is 1 with the find, below the prior without.
    # Resultata before (2026-12-01): the boxes of seven found cells said 0.90 to 0.93.
    a = arm(exists=0.9)
    assert bandit.estimate(a, 3600.0, 1.0, 1, True)['exists'] == 1.0
    assert bandit.estimate(a, 3600.0, 1.0, 1, False)['exists'] < 0.9


# ---------- the grinder, on a stand-in search ----------

STAND_IN = r'''
import json, os, sys, time
n, m, W, seconds, seed = int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]), float(sys.argv[7]), int(sys.argv[sys.argv.index('--seed') + 1])
print('12:00:00 Tilted n=%d m=%d W=%d th=1.1: f=1 rho=1 d=1 L=1; lattice 0.1s, levels 0.1s' % (n, m, W), flush=True)
time.sleep(0.3)
if (n, m) == (16, 4):
    # Thue-Morse of length 16, order 4: 1001 0110 and its mirror image; the code is the left half
    open('found_%d_%d.jsonl' % (n, m), 'a').write(json.dumps(dict(n=n, m=m, order=4, code='96', t=0.3)) + '\n')
    print('done: runs 1, cosets 30, nodes 1e3, sum E 2^1.0, witnesses 1, beam 0s, enumeration 1s, 1s', flush=True)
else:
    time.sleep(%s)
    print('done: runs 1, cosets 30, nodes 1e3, sum E 2^1.0, witnesses 0, beam 0s, enumeration 36s, 36s', flush=True)
'''


def sandbox(arms, wait='0.5', stand_in=STAND_IN):
    d = tempfile.mkdtemp(prefix='bandit-quals-')
    for sub in ('searchwatch', 'runs', 'pagedata', os.path.join('searches', 'tilted'), 'page'): os.makedirs(os.path.join(d, sub))
    for f in ('track.py', 'bandit.py'): shutil.copy(os.path.join(HERE, 'searchwatch', f), os.path.join(d, 'searchwatch'))
    shutil.copy(os.path.join(HERE, 'searches', 'tilted', 'verify_witness.py'), os.path.join(d, 'searches', 'tilted'))
    open(os.path.join(d, 'searches', 'tilted', 'tilted.py'), 'w').write(stand_in.replace('%s)\n    print', wait + ')\n    print'))
    cols = [[0, 0, ['x'], ['y']] for _ in range(32)]
    cols[15] = [3, 4, ['x'], ['y']]; cols[23] = [2, 3, ['x'], ['y']]
    open(os.path.join(d, 'pagedata', 'mstar.js'), 'w').write('const MSTAR = ' + json.dumps(dict(nmax=32, cols=cols, past=[])) + ';\n')
    open(os.path.join(d, 'pagedata', 'pow2.js'), 'w').write('const POW2 = ' + json.dumps(dict(kmax=4, cols=[[k, k, ['x'], ['y']] for k in range(1, 5)])) + ';\n')
    open(os.path.join(d, 'searchwatch', 'arms.jsonl'), 'w').write(''.join(json.dumps(a) + '\n' for a in arms))
    return d


def grind(d, seconds, slots=2):
    """The grinder run for seconds in the sandbox d, then stopped; its output."""
    p = subprocess.Popen([PY, '-B', os.path.join('searchwatch', 'bandit.py'), 'grind', str(slots)], cwd=d, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, start_new_session=True)
    time.sleep(seconds)
    p.send_signal(signal.SIGTERM)
    out = p.communicate(timeout=30)[0]
    return p.returncode, out


def records(d): return {f[:-6]: [json.loads(s) for s in open(os.path.join(d, 'runs', f))] for f in sorted(os.listdir(os.path.join(d, 'runs'))) if f.endswith('.jsonl')}


def recorded_pull(a, seed):
    return dict(a, name=f"qual-{a['n']}-{seed}", tracker=seed, seed=seed, status=None, found=[])


def focus_step(page, arms, history, running, hours, got=frozenset()):
    """One eight-slot scheduler decision against supplied records, with launches and signals observed."""
    with (patch.object(bandit, 'look', return_value=(history, page, got, running, hours, {})),
          patch.object(bandit, 'arms', return_value=arms), patch.object(bandit, 'rates', fixed_rate),
          patch.object(bandit, 'launch') as launch, patch.object(bandit.os, 'kill') as kill,
          patch.object(bandit, 'write')):
        bandit.step(8)
    return [c.args for c in launch.call_args_list], [c.args for c in kill.call_args_list]


def q_no_pull_is_replaced_until_the_last_running_seed_ends():
    # Replicata: seven of eight seeds at one target have ended. Expectata: the last seed runs
    # to its deadline and no second batch starts. Resultata before: seven more pulls started.
    page, a, b = focus_example()
    batch = [recorded_pull(a, seed) for seed in range(1001, 1009)]
    launches, signals = focus_step(page, [a, b], batch, batch[-1:], {})
    assert not launches and not signals, (launches, signals)


def q_a_restart_drains_a_mixed_batch_and_still_stops_a_finds_siblings():
    # Replicata: restart with three live pulls left from the old scheduler, on two cells.
    # Expectata: it adopts them until they finish. A verified find stops only the redundant
    # sibling. Resultata before: idle slots immediately started other searches.
    page, a, b = focus_example()
    first, second, other = recorded_pull(a, 11), recorded_pull(a, 12), recorded_pull(b, 13)
    live = [first, second, other]
    assert focus_step(page, [a, b], live, live, {}) == ([], [])
    first['found'] = [dict(n=20, m=1)]
    launches, signals = focus_step(page, [a, b], live, live, {}, frozenset({(20, 1)}))
    assert not launches and signals == [(second['tracker'], signal.SIGTERM)], (launches, signals)


def q_each_finished_batch_gets_a_fresh_choice_and_a_full_set_of_seeds():
    # Replicata: select eight seeds on two equally valuable cells; repeat after an unsuccessful
    # batch has accumulated enough evidence to change their ranking.
    # Expectata: each batch shares one length, order, window and positive time; seeds are distinct
    # and the next batch uses the new highest-scoring cell. Resultata before: one batch was split.
    page, a, b = focus_example()
    prior = recorded_pull(b, 1001)
    history = [prior]
    hours = {}
    for winner in (a, b):
        launches, signals = focus_step(page, [a, b], history, [], hours)
        assert len(launches) == 8 and not signals, (launches, signals)
        assert all(setting == winner for setting, _, _ in launches), launches
        durations = {duration for _, duration, _ in launches}
        seeds = {seed for _, _, seed in launches}
        assert len(durations) == 1 and min(durations) > 0 and len(seeds) == 8, launches
        with patch.object(bandit, 'rates', fixed_rate):
            _, duration = bandit.score(winner, bandit.worth(winner, page, frozenset()),
                                       hours.get(bandit.key(winner), 0), 0, workers=8)
        assert close(min(durations), duration), (durations, duration)
        assert seeds.isdisjoint(p['seed'] for p in history if bandit.key(p) == bandit.key(winner)), seeds
        history.extend(recorded_pull(winner, seed) for seed in seeds)
        hours[bandit.key(winner)] = sum(duration for _, duration, _ in launches)


def q_the_grinders_report_shows_its_running_batch_and_team_score():
    # Replicata: start a batch and read the Markdown written on the next observation, when the
    # trackers report the launches. Expectata: each cell has its actual seed count, and the idle
    # alternative's score and duration price all eight slots. Resultata before: a one-seed score was printed.
    page, a, b = focus_example()
    got = frozenset()
    launches, _ = focus_step(page, [a, b], [], [], {})
    live = [dict(recorded_pull(setting, seed), slice=duration) for setting, duration, seed in launches]
    flying = {bandit.key(setting): sum(p['slice'] for p in live if bandit.key(p) == bandit.key(setting))
              for setting in (a, b)}
    with (tempfile.TemporaryDirectory() as tmp, patch.object(bandit, 'LIST', os.path.join(tmp, 'list.md')),
          patch.object(bandit, 'look', return_value=(live, page, got, live, {}, flying)),
          patch.object(bandit, 'arms', return_value=[a, b]), patch.object(bandit, 'rates', fixed_rate),
          patch.object(bandit, 'launch')):
        bandit.step(8)
        with open(bandit.LIST) as stream:
            table = [[cell.strip() for cell in line.strip().strip('|').split('|')]
                     for line in stream if line.startswith('|')]
        header, _, *rows = table
        printed = {row[header.index('cell')]: row for row in rows}
        for setting in (a, b):
            row = printed[f"{setting['n']}:{setting['m']}"]
            assert int(row[header.index('running')]) == sum(p['n'] == setting['n'] for p in live)
        alternative = printed[f"{b['n']}:{b['m']}"]
        expected, duration = bandit.score(b, bandit.worth(b, page, got), 0, 0, workers=8)
        time_column, = [i for i, label in enumerate(header) if re.search(r'\b8\b', label)]
        assert math.isclose(float(alternative[header.index('score')]), expected, rel_tol=0.005), alternative
        assert math.isclose(float(alternative[time_column]), duration, rel_tol=0.005), alternative


def q_list_reads_the_active_grinders_published_report():
    # Replicata: publish a report, then hold the grinder's exclusive lock on finds.jsonl.
    # Expectata: a reader gets the exact published report without observing searches or writing.
    # Resultata before: list recalculated with its own worker count and overwrote the report.
    import fcntl
    page, a, b = focus_example()
    got = frozenset()
    with (tempfile.TemporaryDirectory() as tmp, patch.object(bandit, 'DIR', tmp),
          patch.object(bandit, 'LIST', os.path.join(tmp, 'bandit.md'))):
        published = bandit.write(bandit.ranking([a, b], page, got, {}, {}), [a, b], got)
        with (open(os.path.join(tmp, 'finds.jsonl'), 'a') as lock,
              patch.object(bandit, 'look', side_effect=AssertionError('list inspected live records')),
              patch.object(bandit, 'write', side_effect=AssertionError('list rewrote the report'))):
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
            assert bandit.listed() == published
            with open(bandit.LIST) as stream:
                assert stream.read() == published


def q_an_offline_list_finishes_before_a_new_grinder_starts():
    # Replicata: list holds the report lock while it reads the records. Start a grinder
    # during that read. Expectata: list publishes and the grinder reaches its first step.
    # Resultata before: grind raised BlockingIOError as if another grinder were running.
    import fcntl
    from concurrent.futures import ThreadPoolExecutor
    from contextlib import suppress
    from threading import Event
    page, a, b = focus_example()
    reading, finish_read = Event(), Event()
    def read_records():
        reading.set()
        assert finish_read.wait(5), 'the grinder never tried to acquire the report lock'
        return [], page, frozenset(), [], {}, {}

    flock = fcntl.flock
    def acquire(stream, flags):
        # Release the reader only when the grinder attempts to wait, or after a nonblocking
        # attempt has truly failed. The kernel takes and releases the actual locks.
        if not flags & fcntl.LOCK_NB: finish_read.set()
        try:
            return flock(stream, flags)
        except BlockingIOError:
            finish_read.set()
            raise

    with (tempfile.TemporaryDirectory() as tmp, patch.object(bandit, 'DIR', tmp),
          patch.object(bandit, 'LIST', os.path.join(tmp, 'bandit.md')),
          patch.object(bandit, 'look', side_effect=read_records), patch.object(bandit, 'arms', return_value=[a,b]),
          ThreadPoolExecutor(max_workers=1) as pool):
        reader = pool.submit(bandit.listed)
        assert reading.wait(5), 'list never reached the records'
        try:
            with (patch.object(fcntl, 'flock', side_effect=acquire),
                  patch.object(bandit, 'step', side_effect=StopIteration) as step):
                with suppress(StopIteration):
                    bandit.grind(8)
                step.assert_called_once_with(8)
                assert os.path.isfile(bandit.LIST), 'grinder started before list published its report'
        finally:
            finish_read.set()
        with open(bandit.LIST) as report:
            assert report.read() == reader.result(timeout=5)


def q_the_grinder_runs_the_top_and_stops_at_a_find():
    # Replicata: a sandbox with two black cells, 16:4 (whose stand-in search finds at once) and 24:3 (whose stand-in never does), two slots.
    # Expectata: the find is verified and listed (finds.jsonl), 16:4 gets no pull after it, and the pulls that follow are 24:3's, each under
    # track.py with the label bandit and an estimate of basis bandit; bandit.md names both cells.
    d = sandbox([arm(n=16, m=4, top=70, setup=0.001), arm(n=24, m=3, top=70, setup=0.001)])
    try:
        code, out = grind(d, 14)
        rec = records(d)
        names = {k: v[0] for k, v in rec.items()}
        assert all(v['search'] == 'bandit' for v in names.values()) and names, out
        finds = [json.loads(s) for s in open(os.path.join(d, 'runs', 'bandit', 'finds.jsonl'))]
        assert [(f['n'], f['m'], f['order']) for f in finds] == [(16, 4, 4)], finds
        when = min(v[-1]['time'] for k, v in rec.items() if v[0]['target'] == '16:4' and v[-1]['event'] == 'end')
        assert not [k for k, v in rec.items() if v[0]['target'] == '16:4' and v[0]['time'] > when + 5], rec.keys()
        assert len([k for k, v in rec.items() if v[0]['target'] == '24:3']) >= 2, (rec.keys(), out)
        assert all(x['basis'] == 'bandit' for v in rec.values() for x in v if x['event'] == 'estimate')
        listed = open(os.path.join(d, 'scratch', 'bandit.md')).read()
        assert '24:3' in listed and '16:4' in listed, listed
    finally:
        shutil.rmtree(d, ignore_errors=True)


def q_the_pull_that_finds_ends_by_itself():
    # Replicata: the sandbox, its stand-in search at 16:4 going on for some seconds after it wrote its find, as the tilted search does when a batch
    # of cosets ends and as a tracker does for its last estimate; a second cell, so that the grinder has something left.
    # Expectata: that pull's record ends with status 0, not a stop's, and the grinder is still at work at the end.
    # Resultata before (2026-12-01, the grinder's first quarter of an hour): the grinder sent SIGTERM to the trackers of the pulls that had found, and
    # died when one had ended between its look and its signal (ProcessLookupError).
    late = STAND_IN.replace("    print('done: runs 1, cosets 30, nodes 1e3, sum E 2^1.0, witnesses 1", "    time.sleep(8)\n    print('done: runs 1, cosets 30, nodes 1e3, sum E 2^1.0, witnesses 1")
    d = sandbox([arm(n=16, m=4, top=70, setup=0.001), arm(n=24, m=3, top=70, setup=0.001)], stand_in=late)
    try:
        code, out = grind(d, 24)
        assert code == -signal.SIGTERM, out
        rec = {k: v for k, v in records(d).items() if v[0]['target'] == '16:4'}
        ends = {k: v[-1].get('status') for k, v in rec.items() if v[-1]['event'] == 'end'}
        assert 0 in ends.values(), (ends, out)
    finally:
        shutil.rmtree(d, ignore_errors=True)


def q_the_other_pulls_of_a_found_cell_are_stopped():
    # Replicata: the sandbox with the one cell 16:4 and two slots; the stand-in finds for seed 1001 alone, and goes on for a minute for others.
    # Expectata: the other pull is stopped (its record ends with SIGTERM's status) within a few looks, and the grinder, with no cell left, ends with
    # an error.
    one = STAND_IN.replace('if (n, m) == (16, 4):', 'if seed == 1001:\n    time.sleep(3)').replace('time.sleep(%s)', 'time.sleep(60)')
    d = sandbox([arm(n=16, m=4, top=70, setup=0.001)], stand_in=one)
    try:
        p = subprocess.run([PY, '-B', os.path.join('searchwatch', 'bandit.py'), 'grind', '2'], cwd=d, capture_output=True, text=True, timeout=90)
        assert p.returncode != 0 and 'Nihil restat' in p.stderr, (p.returncode, p.stderr[-400:])
        time.sleep(10)
        ends = sorted(v[-1].get('status') for v in records(d).values())
        assert ends == [-signal.SIGTERM, 0], ends
    finally:
        shutil.rmtree(d, ignore_errors=True)


def q_a_pull_s_first_witness_is_its_find():
    # Replicata: the sandbox, its stand-in writing one witness three times over, as a batch of rich cosets gives many.
    # Expectata: finds.jsonl has one line for the pull.
    # Resultata before (2026-12-01): 30 lines a pull.
    many = STAND_IN.replace("    open('found_%d_%d.jsonl' % (n, m), 'a').write(", "    for code in ('96', '69', '96'): open('found_%d_%d.jsonl' % (n, m), 'a').write(").replace("code='96', t", "code=code, t")
    d = sandbox([arm(n=16, m=4, top=70, setup=0.001), arm(n=24, m=3, top=70, setup=0.001)], stand_in=many)
    try:
        grind(d, 14)
        finds = [json.loads(s) for s in open(os.path.join(d, 'runs', 'bandit', 'finds.jsonl'))]
        assert [f['pull'] for f in finds] == sorted({f['pull'] for f in finds}) and len(finds) >= 1, finds
    finally:
        shutil.rmtree(d, ignore_errors=True)


def q_a_false_witness_stops_the_grinder():
    # Replicata: the sandbox, its stand-in search reporting a code of order less than it claims.
    # Expectata: the grinder ends with an error, nothing is listed as found.
    bad = STAND_IN.replace("code='96'", "code='97'")
    d = sandbox([arm(n=16, m=4, top=70, setup=0.001)], stand_in=bad)
    try:
        p = subprocess.run([PY, '-B', os.path.join('searchwatch', 'bandit.py'), 'grind', '1'], cwd=d, capture_output=True, text=True, timeout=60)
        assert p.returncode != 0, p.stdout
        assert not os.path.exists(os.path.join(d, 'runs', 'bandit', 'finds.jsonl')) or not open(os.path.join(d, 'runs', 'bandit', 'finds.jsonl')).read()
    finally:
        shutil.rmtree(d, ignore_errors=True)


def ignored(path, patterns):
    """Whether VS Code's Live Server leaves path, relative to the workspace, unwatched: its own filter of names, or a pattern of its settings."""
    name = os.path.basename(path)
    return name.startswith('.') or any(
        {True: fnmatch.fnmatch(name, p[3:]), False: path.startswith(p[:-2]) if p.endswith('/**') else path == p}[p.startswith('**/')] for p in patterns)


def q_the_page_is_not_reloaded_for_what_the_grinder_writes():
    # Replicata: .vscode/settings.json's liveServer.settings.ignoreFiles, and every file that a sandbox's grinder and its pulls write in 14 seconds.
    # Expectata: each is one that Live Server ignores, so that the page open on localhost:5501 does not reload for it.
    # Resultata before (2026-12-01; dreeves: "the localhost:5501 page seems to be constantly refreshing itself? is something broken?"): runs/bandit/list.md,
    # rewritten every 5 seconds, each pull's log (no .log at its end) and pull.json were watched.
    patterns = json.load(open(os.path.join(HERE, '.vscode', 'settings.json')))['liveServer.settings.ignoreFiles']
    assert ignored('a/b.log', patterns) and ignored('scratch/x/y.md', patterns) and not ignored('index.html', patterns) and not ignored('page/shared.js', patterns)
    d = sandbox([arm(n=16, m=4, top=70, setup=0.001), arm(n=24, m=3, top=70, setup=0.001)])
    files = lambda: {os.path.relpath(os.path.join(a, f), d) for a, _, fs in os.walk(d) for f in fs}
    try:
        before = files()
        grind(d, 14)
        written = files() - before
        assert len(written) > 5 and [f for f in written if f.endswith('bandit.md')], written
        assert not [f for f in written if not ignored(f, patterns)], [f for f in written if not ignored(f, patterns)]
    finally:
        shutil.rmtree(d, ignore_errors=True)


def q_one_grinder_at_a_time():
    # Replicata: a grinder running in the sandbox, and a second one started there.
    # Expectata: the second ends at once with an error; the first goes on.
    d = sandbox([arm(n=24, m=3, top=70, setup=0.001)])
    try:
        p = subprocess.Popen([PY, '-B', os.path.join('searchwatch', 'bandit.py'), 'grind', '1'], cwd=d, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, start_new_session=True)
        time.sleep(4)
        q = subprocess.run([PY, '-B', os.path.join('searchwatch', 'bandit.py'), 'grind', '1'], cwd=d, capture_output=True, text=True, timeout=30)
        alive = p.poll() is None
        p.send_signal(signal.SIGTERM); p.communicate(timeout=30)
        assert q.returncode != 0 and alive, (q.returncode, q.stderr[-300:], alive)
    finally:
        shutil.rmtree(d, ignore_errors=True)


def q_a_restarted_grinder_goes_on_from_the_records():
    # Replicata: the sandbox's grinder run, stopped and run again.
    # Expectata: every pull's name is its own (the seeds go on), and the hours searched before the stop are counted (the arm's searched hours in
    # bandit.md grow from run to run).
    d = sandbox([arm(n=24, m=3, top=70, setup=0.001)])
    try:
        grind(d, 8, 1); time.sleep(2); first = set(records(d))
        grind(d, 8, 1); second = set(records(d))
        assert first and first < second, (first, second)
    finally:
        shutil.rmtree(d, ignore_errors=True)


def q_the_arms_file_names_black_cells_and_their_settings():
    # Replicata: searchwatch/arms.jsonl.
    # Expectata: each line an arm (its fields, numbers in their ranges), no arm twice; every black cell of Figure 1 from length 600 on that is not
    # settled has an arm or is named in bandit.ARMLESS.
    # Spec change (Fable 5.2, 2026-12-04; dreeves, asked whether the list's floor of 50 arms may become a floor of none: "if you're sure that's
    # what makes sense"): the list is not empty.  Until then it had to hold more than 50 arms, a count of 2026-12-01 (91 arms that day, 73 after
    # its finds) that each batch of finds lowers: made anew on 2026-12-04, the list was the 50 arms of the cells still black.  What the floor
    # stood for, a list that keeps every arm but those of cells settled since, q_the_arms_file_keeps_the_arms_of_open_cells holds arm by arm.
    arms = bandit.arms()
    assert len({(a['n'], a['m'], a['W']) for a in arms}) == len(arms) > 0
    for a in arms:
        assert set(a) == set(arm()) and 0 < a['exists'] <= 1 and a['setup'] > 0 and a['before'] >= 0 and a['W'] <= a['n'] // 2, a
    charts = bandit.charts()
    lo, hi = charts['mstar']['lo'], charts['mstar']['hi']
    black = {(n, m) for n in range(1, len(lo)) for m in range(lo[n] + 1, hi[n] + 1)}
    assert black - {(a['n'], a['m']) for a in arms} <= set(bandit.ARMLESS), black - {(a['n'], a['m']) for a in arms} - set(bandit.ARMLESS)


def q_the_arms_file_keeps_the_arms_of_open_cells():
    # Replicata: searchwatch/arms.jsonl as it is and as it was at the bandit's first commit (quals_index.BEFORE_BATCH, 38cb052, of 2026-12-01),
    # that one read by bandit.arms from a temporary root, today's reader on that day's list; and Figure 1's black cells today but those named
    # in bandit.ARMLESS.
    # Expectata: the first list holds more than 50 arms, none twice (91: the floor that q_the_arms_file_names_black_cells_and_their_settings
    # asked of the list of the day until 2026-12-04); at least one of its arms is of such a cell; and each arm of it (length, order, window)
    # of such a cell is in today's list: a list made anew drops the arms of the cells settled since, or given up with a reason in ARMLESS,
    # and no others.  Control: today's list less one such arm is told apart, by that arm.
    # Resultata before: no qual held the list to its past: the floor of 50 arms stood for it, and the list of 73 arms could have lost 22
    # windows of open cells and passed.
    import quals_index as qi
    with tempfile.TemporaryDirectory() as root:
        os.makedirs(os.path.join(root, 'searchwatch'))
        with open(os.path.join(root, 'searchwatch', 'arms.jsonl'), 'w', encoding='utf-8') as f:
            f.write(qi.at_commit(qi.BEFORE_BATCH, 'searchwatch/arms.jsonl'))
        first = bandit.arms(root)
    assert len({bandit.key(a) for a in first}) == len(first) > 50, len(first)
    charts = bandit.charts()
    lo, hi = charts['mstar']['lo'], charts['mstar']['hi']
    black = {(n, m) for n in range(1, len(lo)) for m in range(lo[n] + 1, hi[n] + 1)} - set(bandit.ARMLESS)
    due = {bandit.key(a) for a in first if (a['n'], a['m']) in black}
    lost = lambda arms: sorted(due - {bandit.key(a) for a in arms})
    arms = bandit.arms()
    assert due and lost(arms) == [], lost(arms)
    one = min(due)
    assert lost([a for a in arms if bandit.key(a) != one]) == [one], one


def main():
    names = sys.argv[1:] or sorted(k for k in globals() if k.startswith('q_'))
    failed = []
    for k in names:
        try:
            globals()[k](); print(f'PASSED {k}', flush=True)
        except Exception:
            traceback.print_exc(); print(f'FAILED {k}', flush=True); failed.append(k)
    print(f'{len(names) - len(failed)} of {len(names)} quals passed')
    raise SystemExit(bool(failed))


if __name__ == '__main__': main()
