#!/usr/bin/env python3
"""
dj_face — the puck's local compositor: ambient motion + DJ touch rotation.

Runs ON THE PUCK (python3 + PIL + evdev, all present). The RTX renders the
face as three registered layers every ~20s (see deploy/push_puck_face.sh):

    /tmp/aura_face/base.png    everything static: bezel, wedges, text, shards
    /tmp/aura_face/rings.png   the radar rings alone, on black
    /tmp/aura_face/bolt.png    the lightning + glow alone, on black

and this process makes them live at frame rate, locally:

    - rings rotate continuously (slow drift — the face is never still)
    - the bolt breathes/flickers (two incommensurate sines + a rare spike)
    - a finger spins the whole dial like a turntable, with iPhone-style
      inertia: 1:1 tracking while touching, momentum on release, exponential
      friction until it dies

Rotation physics are ported from the previous generation's GUI
(~/LedgerAI/aura/gui/touch.py on the RTX box), simplified where the owner
said to improve it ("make it better, I didn't do a perfect job"):
    - velocity comes from a short ring buffer of (t, angle) samples instead
      of a one-sample EMA — steadier flicks;
    - drag is exact 1:1 (no velocity-scaled gain): direct manipulation is
      the whole iPhone trick; (2026-08-02: 1:1 now holds from ROT_FULL_R
      outward — inside that, gain rolls off with touch radius and dies at
      ROT_DEAD_R, because angle-per-pixel explodes near the hub)
    - no snap detents by default — free spin.

Layers are composited with screen-blend, so they carry NO alpha channel —
black is transparent. This sidesteps headless-screenshot alpha entirely.

Touch device: the Waveshare panel (ABS_MT, 0..4096). If the spin direction
feels backwards on this panel's mounting, set DJ_INVERT=1 in the env.
"""

from __future__ import annotations

import fcntl
import json
import math
import os
import random
import re
import select
import struct
import subprocess
import sys
import threading
import time
from pathlib import Path

import evdev
from PIL import Image, ImageChops, ImageDraw, ImageFilter, ImageFont, ImageOps

import settings_store   # sibling file; the script's own dir is on sys.path

#: The AuraConnect page of the settings book (phase 2, 2026-08-02). Its
#: own sibling module because the page is large and dj_face is larger.
#: Imported DEFENSIVELY on purpose: a deploy that copies dj_face.py and
#: forgets connect_page.py must lose one page, not the whole face — an
#: ImportError here would take the compositor down at boot and the puck
#: would come up black. The page itself then says what is missing
#: (PRINCIPLES §1: a visible failure beats a silent one).
try:
    import connect_page
except Exception as _e:        # noqa: BLE001 — any failure, same answer
    connect_page = None
    print(f"connect: page module unavailable {_e!r}", flush=True)

FB = Path("/dev/fb0")
SIZE = 1080
LAYERS = Path("/tmp/aura_face")
LEGACY_FRAME = Path("/tmp/aura_face_frame.png")   # single-frame fallback
TOUCH_NAME_HINT = "Waveshare"
#: Default ON: this Waveshare panel's coordinate sense vs the fb is mirrored,
#: so the raw mapping spins opposite the finger (owner-verified 2026-08-01,
#: fixed by inversion, "yep! fixed"). Set DJ_INVERT=0 for a panel that
#: doesn't need it.
INVERT = os.environ.get("DJ_INVERT", "1") not in ("", "0")

#: ── 2026-08-08, FACE THEMES: PATEK BECOMES A THEME OF THIS ENGINE ─────────
#: Owner, at the glass wearing the frozen e13215b bundle: "the patek color
#: scheme is gorgeous, but the power reserve overlaps with AURAVISION in the
#: center and we also need to give depth to everything... that we can really
#: sell." The overlap is the frozen bundle's two-day-old LAYOUT, not the
#: colourway — so the fix is doctrine rather than a patch: a sellable face
#: is a COLOURWAY OVER THIS ENGINE, a row in a table under a flag, never
#: frozen code. The bundle store keeps frozen artifacts because the 3s
#: switch needs them, but they are CAPTURED FROM this engine wearing a
#: theme — so every theme inherits the current layout constants, the pocket
#: recessions, the embossed wordmark pair and the $LEDGER instrument for
#: free, which is precisely what kills the reserve/wordmark overlap: the
#: theme moves NO geometry, and the geometry's clearances are the measured
#: ones in the notes below.
#:
#: WHAT A THEME OWNS is exactly the constants whose own dated notes already
#: promise to move "in the same commit as the colourway": the three duotone
#: anchors (colourway history at DESERT_BLACK), PAT_COL (five honourings of
#: its tracks-DESERT_MID clause), RES_METAL, and the VISION steel family
#: (VISION_LO/HI, STEEL_UNDER) — a Patek carries NO AP BLUE (identity
#: doctrine, docs/PREMIUM.md), so its steel family is warm. Each constant
#: keeps its name and its site in this file; the site assigns from this
#: table, so every argument stays beside the number it argues about.
#:
#: 2026-08-08, second pass: A THEME ALSO OWNS ITS BEZEL. Owner, looking at
#: patek-premium: "what I see on my screen right now still has the AP steel
#: ring around it." Correct, and structural rather than an oversight — the
#: baked ring is composited AFTER desertify() (it must be; the duotone would
#: flatten eight differently-lit facets onto one ramp) and so escapes the
#: colourway by construction. No colourway constant can reach it. So the
#: row names a FILE: `bezel` is the bake this theme wears, and a row that
#: names none wears the steel one, which keeps royal-oak byte-identical.
#: The warm file is scripts/bake_bezel.py --gold; the two bakes differ in
#: reflectance and room tint only, so the geometry cannot drift apart.
#:
#: The patek row is e13215b's dial VERBATIM — the grand-feu-and-rose-gold
#: triples of the 2026-08-06 evening note, byte-equal to the frozen
#: bundle's — so the colourway medians match the dial the owner called
#: gorgeous exactly, on today's layout. Where e13215b and this engine
#: disagreed, the ENGINE won; the divergences are logged in docs/PREMIUM.md
#: (2026-08-08, patek-as-theme).
#:
#: ── 2026-08-08, third pass: A THEME ALSO OWNS ITS TILE PALETTE ────────────
#: Owner, at the glass on patek: "the color scheme of the patek is boxed in
#: the octagon and it's filled with still the blue AP background." MEASURED,
#: median R-B by 15-degree bearing at r=470: warm (+22..+40) on most
#: bearings, COOL (-8..-23) in clean bands. The cool bands are not a shape
#: on the dial ground — they are the WEDGE TILES and their washes, which are
#: composited AFTER desertify() and therefore kept their cool identity fills
#: while every pixel the duotone touched went rose. (-8 is arithmetically
#: exactly PANEL_FILL screened at alpha 36, which is what identified them.)
#:
#: THE PRINCIPLE, and it generalises past this bug: ANYTHING DRAWN AFTER THE
#: COLOURWAY MUST CHOOSE ITS OWN COLOURS PER THEME, BECAUSE THE DUOTONE
#: CANNOT REACH IT. desertify() opens with convert("L"); everything below it
#: in main() is on the far side of that and is a colour decision this table
#: has to make, not one the ramp makes for free.
#:
#: So `tiles` carries the after-colourway family: the five wedge sectors,
#: the live panels' wash and the conjured lift over it, the WORLD tenant's
#: ink, and the tiles' two row inks. TWO EXEMPTIONS, both deliberate and
#: both the owner's: STERLING KEEPS ITS GOLD in either theme (it is the
#: brand, not the colourway), and the generated-widget PLATINUM caste keeps
#: its own metal (CONJ_PT/CONJ_HI — white gold is the mark of the class).
#: LOCK's red stays too: it is an outcome colour, exempt from any house
#: family by the palette note in PUCK-SHOW.md, and it was warm already.
#:
#: THE WARM FAMILY IS SPREAD BY VALUE AND SATURATION, NOT BY HUE, which is
#: the whole trick — five rose/copper tiles sitting in the ground's own
#: family still have to be told apart, and hue is the one axis the family
#: has spent. So the ladder is Rec.601 luminance with saturation breaking
#: the ties: opaline 221/0.23, gold 177/0.57, copper 160/0.64, brushed
#: 143/0.27, brick 142/0.63 — the two that share a value are the muted one
#: and the saturated one. Note the patek wedges DO diverge from home.html's
#: MENU here, unlike the note at WEDGES; that is the point of this section.
#: The baked tiles reach the glass through the duotone and are rose whatever
#: home.html painted, so a live overlay matching home.html would be the one
#: cool mark left on its own warm tile.
#: ── 2026-08-09, fourth pass: A THEME ALSO OWNS ITS TWO METALS ─────────────
#: Owner, commissioning the ferrari row: "the gold accents of the other
#: themes becoming red: hands, hour ticks, the STERLING tile. Keep one warm
#: metal for contrast — brushed aluminium/silver rather than gold — so red
#: reads as paint on metal, which is what a car is."
#:
#: THAT SPLITS ONE CONSTANT INTO TWO ROLES IT HAS ALWAYS HELD AT ONCE, and
#: nobody had to notice because on both existing rows they are the SAME
#: champagne gold:
#:   accent  — the INSTRUMENT colour. The sprinkled strikes (the three hands'
#:             counterpoises, the reserve's F/E, the $LEDGER caption, the
#:             moon hand's tail and tip) and the listening ring. TOURB_GOLD
#:             and its lit/dark flanks at their own site.
#:   brand   — the applied METAL the wordmark is cut from: AURA_INK and the
#:             GOLD_FACE_* relief family.
#: On patek and royal-oak both keys carry (212,175,92) and its two flanks, so
#: those rows are byte-identical through this change — the split is a name,
#: not a move. On ferrari the accent goes Rosso Corsa and the brand goes
#: brushed aluminium, which is the owner's sentence exactly.
#:
#: ── 2026-08-09: THE GROUND IS A ROW'S CHOICE TOO (`ground`) ───────────────
#: Owner: "the tapisserie becomes a CARBON-FIBRE WEAVE: fine 2x2 twill, the
#: diagonal sheen alternating cell to cell so it flashes as the eye moves.
#: Same baked-ground machinery as the tapisserie, different pattern."
#: `ground="carbon"` turns on _carbon_weave_sync (see its own note for why
#: the weave is stamped onto the bake here rather than drawn in home.html);
#: a row without the key keeps the tapisserie the page bakes.
_THEMES = {
    "patek": dict(                    # e13215b's dial on today's engine
        black=(2, 7, 14), mid=(210, 127, 88), white=(250, 238, 222),
        pat=(210, 127, 88),           # tracks mid — PAT_COL's own clause
        res_metal=(232, 168, 128),    # the rose gold RES_METAL's note keeps
        vision_lo=(208, 192, 170),    # warm steel ink, 7.5:1 on this ground
        vision_hi=(232, 218, 198),    # peak short of the opaline white
        steel_under=(48, 38, 28),     # warm ambient in the crack, L≈40
        bezel="bezel_gold.png",       # rose gold ring — see bezel_steel()
        #: ── THE RM WHISPER (2026-08-09) ─────────────────────────────────
        #: PREMIUM.md, 2026-08-08: "Patek identity spec FILED: absence at
        #: the centre + RM-style sub-visible gear train in the ground (<8%
        #: lift)". Filed, never built — the owner noticed: "what happened to
        #: the background gears for the patek ... subtle in the background."
        #: Turns on _gear_train_sync; see its note for why the ground is the
        #: only place this can live.
        #:
        #: ── 2026-08-12: OFF, AND THE THRESHOLD WAS MEASURED IN THE WRONG
        #: UNITS FROM THE FIRST DAY ────────────────────────────────────────
        #: Owner, this morning, having reported it about ten times: "damn i
        #: am still seeing the inner circle come up on my patek sometimes ...
        #: i thought for the 10th time we solved this."
        #:
        #: He is right, and every previous fix was aimed at the wrong number.
        #: Measured on his own framebuffer this morning: circular edges of
        #: 12-15.7 luminance levels in a chain across the lower dial, at radii
        #: matching GEAR_TEETH. Not in the wedge panes — last night's mask
        #: works — on OPEN GROUND, which is where the spec said it was fine.
        #:
        #: THE SPEC IS "<8% LIFT" AND IT IS SATISFIED. GEAR_LIFT is 20 of 255
        #: = 7.8%, and after the duotone (measured gain 0.77-0.80 across the
        #: ground band) it lands at 15.3 levels = 6.0% of range. Under spec on
        #: both sides of desertify. And still plainly visible, because 6% OF
        #: FULL RANGE on a ground that sits at luminance 60 is 25% LOCAL
        #: contrast, and the eye judges locally. This is CLAUDE.md's audio
        #: rule in pixels: express a threshold against the floor it competes
        #: with, never as a fraction of the full scale. A bed at -34 dBFS was
        #: inaudible for the same arithmetic.
        #:
        #: So there is no ceiling to tune (PRINCIPLES §3). Sub-visible against
        #: THIS ground means about 2 levels, which is below the panel's own
        #: quantisation — the train would not exist. Ten attempts were
        #: unwinnable before they started.
        #:
        #: The train is a chain of FULL CIRCLES, and a circle is what he has
        #: objected to every single time (the 08-11 note records four
        #: different objects, all circles, all reported as "the inner
        #: circle"). If it comes back it comes back as arcs — tooth flanks
        #: catching the key light, no closed rim anywhere — which is a shape
        #: change, not another number. Until then the ground is quiet.
        #:
        #: ── 2026-08-12, TWENTY MINUTES LATER: BACK ON, I HAD THE WRONG
        #: OBJECT ─────────────────────────────────────────────────────────
        #: Owner: "bring back the gear train! that was totally wrong."
        #: The paragraph above stands with its date and its arithmetic is
        #: still correct — but it was aimed at the wrong circle. The ring he
        #: has been reporting all along is the BEZEL STATE RING at r=450-460,
        #: 26,800 px of bright copper straight through BRIEFING, STERLING,
        #: LOCK, VOLUME and SETTINGS. I measured gear wheels because I went
        #: looking for gear wheels, found some, and stopped — the 08-11 note
        #: warns in as many words that this complaint has been four different
        #: objects and that you must MEASURE WHICH ONE, and I read that note
        #: and did it anyway. The gears are 12-15 levels; the ring is a
        #: 90-level copper band. It was never a close call and I never
        #: LOOKED at the frame, only at a detector I had aimed myself.
        ghost="gears",
        #: ── 2026-08-13, THE IDEALFACE PASS (owner, with a Theorema skeleton
        #: reference on screen): "get rid of those lightning bolts ... very
        #: very subtly do the hour/minute hands emanating from the tourbillon
        #: ... get rid of those random speckles ... make it a clean grid ...
        #: get rid of the shooting stars / comets ... background gear turning
        #: a slightly bit brighter." Simplify first, then add.
        #: The tapisserie IS the clean grid — the speckles were the starfield
        #: screened over it, so the sky goes and the grid that was always
        #: underneath is what remains.
        hands=True,               # blued steel, like the reference's
        hands_subtle=True,        # slimmer + translucent — see draw_chopard_hands
        hands_sprite=True,        # raymarched blades when hands/ exists
        no_bolt=True,             # the breathing bolt layer, retired here
        no_sky=True,              # starfield off: tapisserie grid, unspeckled
        no_comets=True,           # this face, not MINIMAL, so per-theme
        btn_flat=True,            # engraved line-art buttons, no copper cap
        case_pushers=True,        # SLEEP/POWER leave the dial for the bezel
                                  # band — see the block at PUSHER_DIR
        ledger_coin=True,         # the balance is a struck medallion — see
                                  # draw_ledger_coin
        gear_lift=27,             # GEAR_LIFT 20 -> 27 on this face: "a
                                  # slightly bit brighter", ~35% more lift,
                                  # still well under local-contrast trouble
        #: The two metals (fourth-pass note above). One gold, twice named.
        accent=(212, 175, 92), accent_lit=(247, 227, 170),
        accent_dark=(124, 96, 44),
        brand_ink=(212, 175, 92), brand_lit=(247, 227, 170),
        brand_dark=(124, 96, 44), brand_under=(86, 66, 30),
        #: The after-colourway family — see the third-pass note above. Order
        #: is WEDGE_KEYS' order, which is home.html's MENU order.
        tiles=dict(
            wedges=((246, 214, 190),  # BRIEFING — opaline rose, L221 sat .23
                    (212, 175, 92),   # STERLING — gold, unchanged in both
                    (255, 94, 94),    # LOCK     — the brick, warm already
                    (166, 136, 121),  # SETTINGS — brushed copper, L143 s.27
                    (228, 140, 82)),  # VOLUME   — bright copper, L160 s.64
            panel_fill=(86, 52, 38),        # the dial's own ground, dark:
                                            # screens at a36 to (12,7,5),
                                            # R-B +7 where the navy gave -9
            panel_lift=(128, 84, 62, 24),   # the conjured lift, same family
            world=(238, 214, 186),          # warm ivory, the tenant's ink
            row_ink=((238, 224, 208),       # label — off DESERT_WHITE
                     (250, 240, 228)),      # body  — the opaline itself
        ),
        # ── THE PATEK GETS THE RTX CARRIAGE TOO (2026-08-11) ────────────
        # centre_tourbillon/ has existed since 2026-08-09 and NO THEME
        # NAMED IT, so this face has drawn its centre procedurally the
        # whole time and got none of the renderer work — not the
        # 50-degree key that gave the metal a specular at all, not the
        # shadow catcher, not the real ambient occlusion. A rendered
        # asset nothing references is indistinguishable from one that
        # was never built.
        centre_pack="tourbillon",
    ),
    # ══ CHOPARD — HIS MOTHER'S WATCH (2026-08-11) ═══════════════════════
    # Spec and reference in docs/PREMIUM.md. The case is a tonneau and a
    # round panel cannot be one; the DOUBLE HALO is the identity and it
    # transfers exactly, so this theme is mostly one asset —
    # bezel_chopard.png, 169 pink stones inside 176 white ones with rose-gold
    # rails between.
    #
    # ── WHY THE DIAL IS NOT OPALINE YET, MEASURED ──────────────────────
    # Her watch has a white dial and the obvious route is to invert the
    # duotone: hand colorize() a cream `black` and an ink `white`. It works,
    # and it is not enough, and the reason is worth the paragraph because it
    # will look like an easy win to the next person too.
    #
    # The bake's luminance is p5=0, p50=33, p95=59 — the whole dial lives in
    # the bottom quarter, because it is a DARK ground with bright marks.
    # Inverted without a stretch, all of it lands in ten levels near cream:
    # a genuine opaline dial with wedge captions too faint to read. Stretch
    # 0..60 up to full range to fix the contrast and the tapisserie's own
    # texture — which lives in that same band — comes up as heavy dark
    # hatching over the entire face. Tried all four; the tests are in the
    # session's scratch.
    #
    # An opaline ground therefore has to come from a SMOOTH LIGHT BAKE in
    # home.html, not from the colourway. That is real work and it is Stage 2.
    # Until then this is the same watch at night: deep rose ground, cream
    # marks, rose gold, and the halo doing the identifying.
    "chopard": dict(
        black=(26, 18, 20),           # rose-black, never neutral
        mid=(196, 128, 132),          # the rose the whole face turns on
        white=(250, 240, 236),        # warm cream, not white
        pat=(196, 128, 132),
        res_metal=(236, 198, 190),    # pale rose gold
        vision_lo=(228, 200, 198),
        vision_hi=(248, 232, 228),
        steel_under=(44, 30, 32),
        bezel="bezel_chopard.png",
        #: Rose gold, one metal, twice named — the same discipline the patek
        #: row keeps. Warmer and pinker than the patek's yellow-leaning gold,
        #: because her case is rose and the difference is the whole point of
        #: having two.
        accent=(219, 172, 140), accent_lit=(250, 224, 206),
        accent_dark=(132, 96, 74),
        brand_ink=(219, 172, 140), brand_lit=(250, 224, 206),
        brand_dark=(132, 96, 74), brand_under=(92, 64, 50),
        tiles=dict(
            #: The five wedges take the strap, the stones and the crown:
            #: chassis pink, rose gold, the ruby cabochon, a soft mauve, and
            #: the pink-stone course. LOCK stays the reddest — it is the
            #: brick, and that meaning outranks the colourway.
            wedges=((214, 168, 186),   # BRIEFING — the strap's own pink
                    (219, 172, 140),   # STERLING — rose gold
                    (232, 84, 96),     # LOCK     — the ruby cabochon
                    (186, 150, 156),   # SETTINGS — mauve steel
                    (226, 152, 172)),  # VOLUME   — the pink course
            panel_fill=(72, 44, 48),
            panel_lift=(118, 76, 80, 24),
            world=(246, 228, 222),
            row_ink=((240, 222, 218), (252, 242, 238)),
        ),
        #: ── AND THE CENTRE IS HERS TOO (2026-08-12) ────────────────────
        #: The spec left this open — absence at the centre, or something in
        #: it. The answer came from her own watch: the dial carries a knurled
        #: tonneau CARTOUCHE, which is the case shape repeated small and the
        #: one part of a tonneau a round panel can show.
        #:
        #: What moves inside it is Chopard's own idea rather than ours:
        #: HAPPY DIAMONDS, loose stones running free between two crystals.
        #: Four of them drift on their own ellipses at their own rates, so
        #: the group never repeats a formation — a Happy Diamond wanders, and
        #: stones travelling in formation would be a carousel.
        centre_pack="chopard",
        #: ── HER PUSHERS ARE ROSE GOLD, NOT BLUE STEEL (2026-08-12) ──────
        #: See BTN_TINT. The ratios are this row's own res_metal
        #: (236,198,190) against its mean of 208 — the pale rose gold the
        #: case is already described in, rather than a fourth invented
        #: colour. Warm, red-leaning, the opposite cast to the default.
        btn_tint=(1.135, 0.952, 0.913),
        #: See draw_chopard_hands. Blued steel, and only this row asks.
        hands=True,
        #: See draw_proverb. Her dial only — a Taiwanese saying in the
        #: upper left is hers, not a feature of the engine.
        proverbs=True,
        #: ── HER RAMP, 2026-08-12: WHERE THE COLOUR FINALLY COMES FROM ───
        #: See the note in desertify(). A three-stop ramp can only produce
        #: one hue family, which is why this dial was rose on rose on rose
        #: no matter what went into the bake. These stops turn the bake's
        #: LUMINANCE shelves into MOTHER-OF-PEARL: the nacre bands are cut
        #: as light and dark in home_chopard.html and arrive here as hue.
        #:
        #: THE BOTTOM HALF IS THE OLD RAMP, TO THE LEVEL. 0.00 and 0.50 are
        #: this row's own `black` and `mid`, so every mark on the dial — the
        #: Roman numerals, the railroad track, the wedge panes, the engraved
        #: cap labels — comes out exactly as it did yesterday. All the new
        #: behaviour is above 0.62, which is ground and nothing else. That
        #: matters: hue that wanders into the ink is a legibility bug
        #: wearing a design brief.
        #:
        #: And the sweep is what nacre actually does — pink into cream, a
        #: warm gold shelf, then the faintest cool break before the
        #: highlight. Green is deliberately absent; green is abalone.
        #: THE STOPS SIT WHERE THE BAKE ACTUALLY IS, and the first cut of
        #: them did not. They were spread evenly from 0.62 to 1.00 while the
        #: measured dial ground occupies 0.84-0.98 — so 60% of the sweep was
        #: mapped to luminances that appear nowhere on the dial and the whole
        #: nacre lived in the top two stops. A ramp is only as useful as its
        #: overlap with the histogram it is applied to (PRINCIPLES §6, in the
        #: other direction: measure the thing you are calibrating AGAINST).
        #: ── 2026-08-12 13:47: SOLID OYSTER WHITE ────────────────────
        #: Her words: "Can you make the background in solid oyster white?"
        #:
        #: This retires the mother-of-pearl sweep on her dial, and the note
        #: above it stands with its date — the machinery is unchanged and one
        #: line brings the nacre back if she misses it. What she is asking
        #: for is the other half of the same watch: a Happy Sport comes with
        #: a MOP dial or a lacquered one, and the lacquered version is quiet
        #: on purpose, because everything that is meant to be looked at is
        #: moving in the middle of it.
        #:
        #: SOLID IS NOT FLAT. The stops still climb, they just stop changing
        #: HUE — an oyster white that is one value everywhere reads as paper,
        #: and the shelves baked into home_chopard.html would vanish with it.
        #: They now come through as a faint warm-to-cool shading across the
        #: same ground, which is what a lacquer does under a curved crystal.
        #: Below 0.62 nothing moves at all, so every mark keeps its ink.
        ramp=((0.00, (26, 18, 20)),      # her black, unchanged
              (0.50, (196, 128, 132)),   # her mid, unchanged
              (0.78, (226, 219, 205)),   # oyster, in shadow
              (0.86, (236, 230, 217)),   # oyster
              (0.91, (242, 237, 226)),   # oyster, lit
              (0.96, (246, 242, 234)),   # the faintest cool turn
              (1.00, (252, 250, 245))),  # highlight
        #: See MINIMAL. Her dial is defined by what it does not carry.
        minimal=True,
    ),
    "royal-oak": dict(                # the values that stood here at r180
        black=(0, 0, 0), mid=(100, 154, 230), white=(232, 240, 255),
        pat=(100, 154, 230),
        res_metal=(176, 184, 196),
        vision_lo=(60, 200, 255), vision_hi=(150, 210, 255),
        steel_under=(24, 46, 66),
        # no `bezel`: the steel bake IS this theme's ring, and leaving the
        # key out is what keeps that path unchanged rather than re-stated.
        #: The two metals (fourth-pass note above), the same gold twice — the
        #: literals that stood at TOURB_GOLD and AURA_INK at r236.
        accent=(212, 175, 92), accent_lit=(247, 227, 170),
        accent_dark=(124, 96, 44),
        brand_ink=(212, 175, 92), brand_lit=(247, 227, 170),
        brand_dark=(124, 96, 44), brand_under=(86, 66, 30),
        #: The values that stood at their own sites at r229 — moved here
        #: unchanged, so this theme stays byte-identical on the glass.
        tiles=dict(
            wedges=((56, 200, 255), (212, 175, 92), (255, 94, 94),
                    (122, 160, 216), (53, 208, 192)),
            panel_fill=(42, 63, 102),
            panel_lift=(66, 92, 142, 24),
            world=(216, 212, 196),
            row_ink=((221, 227, 238), (238, 244, 252)),
        ),
    ),
    #: ── 2026-08-09: THE FERRARI, THE FOURTH SELLABLE FACE ────────────────
    #: Owner: "this is a red color with black base... come up with an
    #: exciting idea, this is the sports car version." A racing chronograph
    #: reads NOTHING like a dress watch, which is the differentiation
    #: doctrine's whole point, so this row is not a hue rotation of the
    #: other two — it changes the GROUND (carbon weave), the CENTRE (a rev
    #: counter where the AP has its tourbillon and the patek has calm) and
    #: the two metals.
    #:
    #: WHY THE RAMP IS GRAPHITE AND NOT ROSSO CORSA, and this is the one
    #: number an earlier cut of this row got backwards. `mid` is the
    #: duotone's MIDPOINT: every source pixel at L=128 lands on it, and on
    #: this dial that band is the METAL — subdial rims, the reserve flange,
    #: the chapter furniture — while the dial ground sits far below it at
    #: L 8..68. A Rosso Corsa mid therefore paints the RINGS pink and leaves
    #: the ground a dark maroon: the exact opposite of "red on a black
    #: base", and it contradicts the same brief's "the subdial rings go
    #: silver". So the ramp is carbon-to-aluminium with a whisper of warmth
    #: in it, and RED ARRIVES ONLY WHERE IT IS AN INSTRUMENT — from the
    #: after-colourway family below, from `accent`, from the rev arc and
    #: from the bezel's own bake. Measured through this ramp: the weave
    #: field (source L 35) lands at (45,43,43), its lit chamfers (L 68) at
    #: (83,80,80), baked metal ink (L 193) at (198,193,193) — carbon
    #: ground, silver furniture.
    #:
    #: WHY `mid` IS 152 AND NOT THE 101 THIS ROW FIRST CARRIED, and it is a
    #: legibility number, not a taste one. A duotone is LINEAR from the
    #: black anchor, so the ratio between a caption baked at source L~130
    #: and the ground it sits on is fixed by the ramp's own arithmetic —
    #: and the mid IS that caption's colour. royal-oak's mid carries a
    #: relative luminance of 0.313 and patek's 0.295 because both are
    #: saturated colours; a graphite at 101 carries 0.127, so every piece of
    #: mid-tone micro-type on the dial arrived a third as bright as it does
    #: on the other two rows. MEASURED on the render at 101: five captions
    #: under the owner's 4.5:1 floor (the rate row at 2.63:1) that pass on
    #: both other themes. At 152 the worst is 4.57:1 and the dial is still
    #: the darkest of the three: ground medians (39,37,37) ferrari against
    #: (28,43,65) royal-oak and (60,41,34) patek.
    "ferrari": dict(                  # the sports-car version, 2026-08-09
        black=(5, 4, 4),              # carbon, not quite void
        mid=(152, 147, 147),          # graphite: the ramp's metal band
        white=(242, 238, 238),        # hot aluminium highlight
        #: PAT_COL's clause says this triple tracks DESERT_MID "so the
        #: sector is not a leftover colour". Honoured in its INTENT rather
        #: than its arithmetic here, and said out loud because five notes at
        #: PAT_COL promise the letter: this wedge is composited AFTER the
        #: duotone, so it must carry the metal the ramp PRODUCES on the
        #: panel (the aluminium above), not the ramp's own dark midpoint,
        #: which would be a grey sector nobody can read on a black dial.
        pat=(176, 172, 172),
        res_metal=(206, 210, 216),    # brushed aluminium, not gold
        #: ── 2026-08-09, THE RED CORRECTION: THIS PAIR IS TWO OF THE FOUR ──
        #: Owner, at the glass: "NOT ENOUGH RED ... push Rosso into the places
        #: the eye lands: ... the $LEDGER figure, and the AURA VISION
        #: wordmark's VISION half." Those two are ONE edit because they are
        #: one metal: _led_paste stamps the counter through VISION's own
        #: relief (STEEL_FACE_*/STEEL_RIM, all derived from this pair), so
        #: moving these two triples moves both marks and nothing else.
        #: (214,60,58)/(255,176,168) stood here from the first ferrari cut;
        #: the low end was already Rosso-adjacent but the PEAK was a pale
        #: salmon, so the wordmark breathed red-to-pink and the counter's lit
        #: rim was pink outright — which is what "not enough red" is looking
        #: at on this row. The low end goes to the accent's own Rosso Corsa
        #: and the peak stays hot instead of going pale.
        #: MEASURED against the ferrari ground median (39,37,37): the RIM —
        #: which is what an applied letter is read by, the button pass's own
        #: finding at _btn_machine_sync — is 5.59:1, over the 4.5 floor. The
        #: FACE at 2.88:1 is under it and is a colour statement, exactly as
        #: the pre-existing (214,60,58) face was at 3.33:1; no red at this
        #: saturation clears 4.5 on a near-black dial, and the note at
        #: PRINCIPLES §3 applies — the separation is not there to be tuned to.
        #: 2026-08-09, later: BOTH TRACK THE LIPSTICK ACCENT. The clause
        #: above promises the low end is "the accent's own number", and the
        #: accent moved — so these move in the same commit or the wordmark
        #: goes on breathing the retired orange-red while the tiles beside
        #: it wear the new one. The peak stays hot rather than pale for the
        #: reason the paragraph above gives; it is simply hot on the blue
        #: side of red now.
        vision_lo=(230, 28, 64),      # lipstick, the accent's own number
        vision_hi=(255, 105, 130),    # hot, NOT the old pale salmon
        steel_under=(28, 10, 10),     # warm-black ambient in the crack
        #: THE NAME OF THE FILE THE BAKE ACTUALLY WRITES, and it was wrong.
        #: scripts/bake_bezel_ferrari.py has always written
        #: packs/bezel_ferrari.png; this row asked for bezel_carbon.png, which
        #: does not exist in either home, so bezel_steel() fell through its
        #: candidate list to the LAST name — whatever bezel_steel.png happens
        #: to be on that device — and the ferrari wore another theme's ring.
        #: That is the gold the owner is looking at, and it is why the F0 in
        #: the bake "did not own the result": the bake was never on the glass.
        #: (bezel_steel() prints which file it loaded, once, for exactly this
        #: — PRINCIPLES §1 — and that line is how a future session checks it.)
        bezel="bezel_ferrari.png",    # gunmetal anodised, red ticks
        #: The instrument language (2026-08-09). Owner: "the complications
        #: still look like the AP's ... differentiate them as INSTRUMENTS."
        #: A truthy value turns on the three marks a car gauge has and a
        #: dress watch does not — red index marks, numerals on the track, a
        #: bevelled gauge bezel instead of a jewelled flange, and straight
        #: needle pointers with red tips and white counterweights. Read at
        #: INSTR; a row without the key keeps the AP's furniture exactly.
        instruments="tacho",
        ground="carbon",              # the weave; see _carbon_weave_sync
        #: THE RTX-RENDERED CENTREPIECE for this row (2026-08-09). Names a
        #: packs/centre_<this>/ frame table; absent or missing on the device
        #: and the drawn centre below is kept. See centre_pack_load.
        centre_pack="ferrari",
        centre="rev",                 # a rev counter, NOT a tourbillon —
                                      # the differentiation doctrine, and
                                      # the whole argument is at REV_ON
        moon="daynight",              # a moon on a race car is wrong; the
                                      # window shows the sun — MOON_DAYNIGHT
        #: The two metals. Rosso Corsa is the owner's own number (210,30,35)
        #: and it is the INSTRUMENT colour; the wordmark and the furniture
        #: keep brushed aluminium, so red is the only saturated thing on the
        #: dial and reads as paint on metal.
        #: ── 2026-08-09, LATER: ROSSO CORSA BECOMES LIPSTICK RED ──────────
        #: Owner, at the glass with the puck in his hand: "we need to make it
        #: lipstick red as much as possible to complement the actual
        #: beautiful casing color."
        #:
        #: The casing is Rosso Corsa, which leans ORANGE. Putting the same
        #: orange-red on the glass made the screen read as a duller copy of
        #: the shell — the two reds sat a few counts apart and the panel lost
        #: every time, because a backlit surface next to painted metal has to
        #: be MORE saturated to hold its own. A lipstick red leans BLUE, so
        #: it sits beside the shell instead of competing with it, which is
        #: what "complement" is asking for.
        #:
        #: MEASURED against the ferrari ground median (39,37,37), all three
        #: candidates weighed rather than picked by eye:
        #:     Rosso Corsa  (210,30,35)  2.87:1   blue-lean (b-g) +5
        #:     lipstick     (230,28,64)  3.34:1   blue-lean      +36
        #: The chosen red is both the more saturated and the more legible —
        #: it wins on the instrument as well as on the argument. Still under
        #: 4.5 and still deliberately so: the note at vision_lo above states
        #: why no red at this saturation clears that bar on a near-black
        #: dial, and that reasoning is unchanged.
        accent=(230, 28, 64), accent_lit=(255, 105, 130),
        accent_dark=(128, 10, 34),
        #: ── 2026-08-09: THE THIRD COLOUR, AND IT IS RARE ON PURPOSE ──────
        #: Owner, pointing at the 488 Spider's dashboard: "bring some yellow
        #: into it ... on a real Ferrari yellow is not a second red: it is
        #: the SHIELD and the TACHOMETER FACE ... Nothing else turns yellow —
        #: three colours only work when the third is rare."
        #: Giallo Modena, the owner's own number. Read at REV_FACE_R (the rev
        #: gauge's dial face), at the shift-light strip's middle LEDs and at
        #: the shield badge on the wheel, and NOWHERE ELSE — a row without
        #: this key is byte-identical, and a future pass that wants yellow
        #: somewhere new has to argue with the coverage figure at WHEEL_R.
        yellow=(250, 200, 20),
        brand_ink=(196, 200, 206), brand_lit=(240, 244, 250),
        brand_dark=(110, 116, 124), brand_under=(34, 36, 40),
        #: The after-colourway family. The ladder is the patek row's trick —
        #: Rec.601 value with saturation breaking the ties — because hue is
        #: spent here too: BRIEFING 227/.03, STERLING 79/.86, LOCK 137/.63,
        #: SETTINGS 141/.07, VOLUME 161/.82. The two that share a value are
        #: the saturated one and the muted one. STERLING LOSES ITS GOLD on
        #: this row and only this row — the owner named the tile — which
        #: supersedes the patek note's "STERLING keeps its gold in either
        #: theme" for ferrari alone; that note stands with its date. LOCK's
        #: red is still the outcome colour, unchanged in all three themes,
        #: and it clears STERLING's by 58 points of value.
        tiles=dict(
            wedges=((226, 228, 232),  # BRIEFING — aluminium white
                    (230, 28, 64),    # STERLING — lipstick, tracks `accent`
                    (255, 94, 94),    # LOCK     — the brick, exempt
                    (138, 142, 148),  # SETTINGS — gunmetal
                    (232, 146, 42)),  # VOLUME   — the rev arc's amber
            panel_fill=(44, 40, 41),        # smoked panels: screens at a36
                                            # to (6,6,6), a hair off carbon
            panel_lift=(96, 74, 78, 24),    # the conjured lift, same family
            world=(226, 228, 232),          # aluminium, the tenant's ink
            row_ink=((214, 216, 222),       # label
                     (238, 240, 246)),      # body
        ),
    ),
    #: ── 2026-08-16: AURORA — THE FIRST NON-WATCH FACE ────────────────────
    #: Owner, commissioning it in two breaths: "amorphous AI blob that is
    #: mysterious yet functional" and then "much simpler, brighter, sci fi,
    #: easier to read... push functionality to voice as much as possible to
    #: clear the screen... has to look from the future." So: a void-black
    #: ground with ONE luminous body — a breathing ice-blue core inside a
    #: thin crisp ring — and every state is told in light: bloom + a bright
    #: ring arc at the speaker's bearing while she listens, a violet spin
    #: while she thinks, a pulse with her own voice while she speaks. No
    #: ticks, no hands, no wedges at rest: the modes still open by tap and
    #: voice, the screen just no longer wears them.
    "aurora": dict(
        black=(4, 6, 9), mid=(70, 110, 150), white=(200, 224, 240),
        pat=(90, 180, 232),
        res_metal=(120, 150, 176),
        vision_lo=(90, 180, 232), vision_hi=(159, 226, 245),
        steel_under=(16, 28, 40),
        accent=(90, 180, 232), accent_lit=(159, 226, 245),
        accent_dark=(38, 76, 108),
        #: the wordmark metals: this face has no gold anywhere — the brand
        #: letters are the same light as the core, one hue on the glass.
        brand_ink=(120, 190, 235), brand_lit=(206, 238, 250),
        brand_dark=(44, 88, 124), brand_under=(18, 34, 50),
        minimal=True, no_comets=True, no_bolt=True, no_sky=True,
        blob=True,
        tiles=dict(
            wedges=((125, 211, 240), (90, 180, 232), (255, 94, 94),
                    (122, 160, 216), (138, 108, 245)),
            panel_fill=(20, 38, 56),
            panel_lift=(56, 96, 132, 24),
            world=(159, 226, 245),
            row_ink=((205, 224, 236), (230, 242, 250)),
        ),
    ),
    #: ── 2026-08-22: GALLERY — THE WHITE SHELL'S FACE (TIDE, mark9) ────────
    #: Owner, approving the mark9 enclosure: "almost art like, it belongs in
    #: a museum... we need a commensurate GUI face / color scheme to exactly
    #: complement its white enclosure." So the glass CONTINUES THE SHELL'S
    #: MATERIAL: gallery-plaster porcelain (never clinical #FFF), graphite
    #: placard ink, warm-grey hairlines, and exactly ONE metal — pale gold
    #: leaf — used at the aperture lip, the bezel fillet, and the accents.
    #: The centre is the one dark object on the wall: a basalt stone inside
    #: a gold lip. It shipped as a STILL on 2026-08-22 (the chopard
    #: frames-to-1 lesson), and that is no longer true: the pack was rebuilt
    #: to 360 frames over a 180 s loop and 360 PNGs are on disk. The comment
    #: is corrected rather than left standing because it describes what the
    #: code does, and a stale "still, on purpose" would send the next reader
    #: hunting for a frames-to-1 clamp that is not there.
    #:
    #: THE FIRST THEME THAT SHIPS ITS OWN FINISHED BASE. The chopard proved
    #: a light ground cannot come from the colourway (FAILURES 2026-08-12),
    #: and its light bake still needed five polarity fixes because the
    #: per-boot stamps assume "the marks are the bright pixels". This row's
    #: `base` names a PNG baked offline by scripts/bake_gallery_home.py —
    #: relief, buttons and typography already composed — so every bake
    #: stamp stands down (see BAKE_FINAL below) and the bright-pixel
    #: assumption never gets a light ground to invert on.
    #:
    #: THE RAMP IS THE COLOUR AUTHORITY, THE BAKER IS THE SHELF AUTHORITY
    #: (§15): the bake draws luminance shelves (ink 62, hairline 152,
    #: plaster 205-232) and these stops turn them porcelain. Move a shelf
    #: in bake_gallery_home.py and the matching stop moves here, same
    #: commit.
    "gallery": dict(
        black=(10, 9, 8),             # warm near-black, never neutral
        mid=(158, 152, 141),          # the hairline warm grey
        white=(250, 248, 241),        # gallery plaster, lit
        pat=(138, 133, 124),
        res_metal=(200, 190, 170),
        vision_lo=(150, 144, 134), vision_hi=(208, 202, 190),
        steel_under=(58, 54, 48),
        base="gallery_base.png",      # the finished bake, beside dj_face
                                      # or under packs/ — see Layers.refresh
        bezel="bezel_gallery.png",    # porcelain band, one gold fillet
        centre_pack="gallery",        # the stone — 360 frames, 180 s loop
        #: pale gold leaf — the ONE metal, named twice like every row
        accent=(192, 164, 104), accent_lit=(228, 206, 152),
        accent_dark=(122, 100, 58),
        brand_ink=(192, 164, 104), brand_lit=(228, 206, 152),
        brand_dark=(122, 100, 58), brand_under=(86, 72, 42),
        #: the listening light in INK, not in light — a cyan bloom on
        #: porcelain is the comet-on-opaline bug in reverse (bright-on-dark
        #: treatments invert on a light ground). Slate ink darkens the
        #: band; the hot core is the metal, so "she hears you" reads as
        #: gold on plaster. Read where LISTEN_COOL/LISTEN_CORE are set.
        #: measured on the first proof: (96,98,102) at full alpha lands on
        #: a band that darkens to ~(188,183,174) at six o'clock — 2.6:1,
        #: a whisper. The ink goes to near-black graphite; the core is the
        #: lit gold. CLAUDE.md's rule in pixels: contrast against the
        #: measured local floor, not against the face's average.
        listen_cool=(52, 52, 56),
        listen_core=(228, 202, 142),
        #: and the answer is stated in the CENTRE, not on the rim — see
        #: LISTEN_CENTRE for why the bezel bloom cannot work on this face.
        listen_centre=True,
        #: ── THE DOOR MATCHES THE ROOM (2026-08-26) ────────────────────
        #: The lock screen was a deep-space starfield from another face
        #: while the dial behind it is plaster. Owner: "they should be
        #: consistent." See LOCK_FACE.
        lock_face=True,
        #: graphite on plaster, the same ink this face writes everything
        #: else in — the hints' default is a pale blue for a black ground.
        lock_hint_ink=(84, 82, 78),
        lock_face_dim=0.88,       # plaster stays plaster
        lock_face_flat=0.66,      # it recedes by losing contrast

        listen_ink=True,              # ink grammar too, not just ink colour
                                      # — see LISTEN_INK
        minimal=True,                 # a museum wall is what is NOT on it
        no_sky=True, no_comets=True, no_bolt=True,
        no_moon=True,                 # watch furniture; this is not a watch
        no_rings=True,                # a stale /tmp rings.png from a prior
                                      # face would screen bright arcs over
                                      # the plaster — never composite them
        #: 2026-08-22 this row carried `no_intro=True`, because wedge_intro
        #: lifted five BLACK covers with a screened glow and that is
        #: dark-dial choreography. Skipping the entrance was the right
        #: emergency stop and the wrong resting place: the owner, 2026-08-24,
        #: "no fade in for the wedges ... bring it up to speed with its new
        #: skin". The entrance now has polarity (INTRO_INK) — the cover is
        #: the plaster, the throb is a graphite shadow — so this face gets
        #: the same arrival as every other one instead of no arrival at all.
        intro_ink=True,
        #: 2026-08-25: tap_wedges OFF. It was on for one deploy and the
        #: owner's first words at the glass were "now the wedges are empty
        #: when i bring it up" — which is exactly what it does: start
        #: hidden, reveal on a tap, re-hide after BAKED_UI_IDLE_S. The ask
        #: it was built for was "no fade in for the wedges", an ENTRANCE,
        #: and intro_ink above already delivers that. Hiding the controls
        #: at rest is a different feature nobody asked for, and on a face
        #: whose whole job is to be readable across a room it reads as a
        #: broken dial. The machinery stays (aurora uses the grammar); the
        #: flag does not.
        # tap_wedges=True,
        #: THE VOLUME CARD IN THE MUSEUM'S OWN INK (2026-08-25). Defaults
        #: are aurora's cyan-on-black; see the note at VOL_WASH. Washed to
        #: plaster rather than dimmed, the lit arc in the deep gold of
        #: brand_dark (192,164,104 is the LIGHT gold and vanishes on this
        #: ground — the same mistake as the bloom, one row up), and the
        #: readout in graphite. DONE inverts to a pale disc with a gold
        #: edge: on plaster a near-black button reads as a hole.
        vol_wash=(236, 232, 223),
        vol_on=(122, 100, 58),
        vol_off=(184, 177, 163),
        vol_label=(108, 100, 88),
        vol_big=(46, 44, 41),
        vol_hint=(140, 132, 120),
        vol_done_fill=(250, 248, 243),
        vol_done_edge=(150, 124, 68),
        vol_done_ink=(52, 48, 44),
        tiles=dict(
            #: the after-colourway family, value-laddered like every row:
            #: bone, gold, oxide red (LOCK keeps its meaning at museum
            #: saturation), warm steel, muted brass.
            wedges=((208, 201, 188),  # BRIEFING — bone
                    (192, 164, 104),  # STERLING — the gold, the brand
                    (188, 74, 64),    # LOCK     — iron-oxide red, outcome
                    (150, 144, 134),  # SETTINGS — warm grey steel
                    (176, 156, 118)), # VOLUME   — muted brass
            #: the open-mode panels keep the fleet's dark-room grammar
            #: (the takeover dims the frame first), so the wash stays a
            #: LIGHT ink on that dimmed ground — gallery lights down, the
            #: placard lights up
            panel_fill=(214, 206, 192),
            panel_lift=(238, 232, 220, 24),
            world=(242, 238, 228),
            row_ink=((235, 230, 220), (246, 242, 233)),
        ),
        ramp=((0.00, (10, 9, 8)),        # ink shelf, deepest
              (0.24, (54, 51, 46)),      # graphite — placard type
              (0.47, (120, 114, 105)),   # soft ink — tertiary labels
              (0.60, (158, 152, 141)),   # warm-grey hairlines
              (0.80, (221, 216, 205)),   # plaster, rim shadow
              (0.87, (231, 226, 216)),   # plaster
              (0.92, (240, 236, 226)),   # plaster, lit
              (1.00, (250, 248, 241))),  # highlight
    ),
    #: ── 2026-08-26: CARBON — THE PAHT-CF SHELL'S FACE (mark15) ───────────
    #: The third enclosure gets the third material argument. The pearl shell
    #: got gallery, which CONTINUES plaster onto the glass; this one is
    #: nylon with chopped carbon fibre in it — matte, near-black but never
    #: void, a fine fibre speckle, and a warm-grey sheen only where light
    #: rakes across it. It is an ENGINEERING material: nobody specifies
    #: PAHT-CF to be looked at, they specify it because it is stiff and it
    #: does not care about 85C. So the face is an INSTRUMENT — machined,
    #: numbered, unlit until it has something to report — and not the
    #: gallery inverted, which is the obvious move and the wrong one: a
    #: museum's identity is absence, a tool's identity is that you can read
    #: it.
    #:
    #: WHY THIS ROW NEEDS NO BAKE, unlike the gallery's. The chopard proved
    #: a LIGHT ground cannot come from the colourway (FAILURES 2026-08-12),
    #: which is why gallery ships finished pixels. A dark ground can and
    #: always has — the duotone was built for one — so carbon rides
    #: home.html's bake and states everything in the ramp. Nothing new has
    #: to be rendered for this face to exist.
    #:
    #: WHY IT IS NOT THE FERRARI'S WEAVE, and this is a material fact
    #: rather than a taste: `ground="carbon"` stamps a 2x2 TWILL, which is
    #: woven prepreg — a supercar's cosmetic panel. PAHT-CF is CHOPPED
    #: fibre: there is no weave in it anywhere, only a random speckle and
    #: the print's own layer lines. Wearing the twill here would be a lie
    #: about the part AND would make the two dark faces read as each
    #: other, which the differentiation doctrine at the ferrari row exists
    #: to prevent. The tapisserie stays, and through this ramp it stops
    #: being guilloche and reads as surface grinding — a machined ground,
    #: which is the right lie to tell. THE SPECKLE IS THE ONE THING STILL
    #: OWED (see the note at the bottom of this row).
    #:
    #: THE FIRST DARK ROW WITH A RAMP, and the material is the reason. The
    #: three-stop colorize has ONE hue family in it by construction (the
    #: proof is in desertify()), and this material's whole tell is that it
    #: is TWO: cool graphite in shadow where you see resin, warm grey in
    #: the light where you see fibre. Three stops can express one or the
    #: other. Seven can express the turn, and the turn is the material.
    #: R-B runs -1 at the deepest stop to +6 at the sheen.
    #:
    #: THE STOPS SIT WHERE THE BAKE ACTUALLY IS — the chopard's own lesson,
    #: which cost it 60% of a sweep. Measured on the standing bake
    #: (/tmp/aura_face/base.png): dial luminance p5=0, p50=36, p95=61, and
    #: the ferrari note records baked metal ink at 193. So the ground lives
    #: below 0.27 and the marks above 0.40, and the stops are dense where
    #: the pixels are.
    "carbon": dict(
        #: THE ROTOR — see its own note. The centre was falling through to
        #: draw_tourbillon, which is the watch faces' complication and
        #: reads as almost nothing through this duotone; the owner saw the
        #: result and said there is no centrepiece, which was exactly
        #: right.
        centre="disc",
        #: RESIN BLACK. Never (0,0,0), and the reason is the object, not
        #: taste: a screen that out-blacks the shell makes the shell look
        #: grey beside it. The part measures as a lifted warm charcoal, so
        #: the glass starts there too — the same continuation gallery makes
        #: with plaster. Faintly COOL here (b > r by 1); the warmth belongs
        #: further up, where the light is.
        black=(12, 12, 13),
        #: MACHINED GREY, and it is a legibility number rather than a
        #: taste one — the ferrari row's whole `mid` paragraph applies
        #: verbatim. Every source pixel at L=128 lands on this triple, and
        #: that band is the dial's METAL furniture and all of its mid-tone
        #: micro-type. MEASURED off the built LUT rather than reasoned
        #: about: a caption baked at L=130 arrives (152,149,143) against a
        #: ground body of (34,33,31) = 5.39:1, where the ferrari's
        #: equivalent worst case is 4.57. The first cut of this ramp put
        #: the stop at 0.55 and the same caption came out 4.37:1 — under
        #: the floor, invisibly, because the number the row DECLARES was
        #: fine and the number the LUT PRODUCES was not. See the stop's own
        #: note in `ramp` below.
        mid=(150, 147, 141),
        #: ETCH BONE. The top of the ramp is not paper white because a
        #: laser on nylon is not paper white — it lifts the surface to a
        #: warm bone and stops. Chasing 255 here would be the one mark on
        #: the face that no process could have made.
        white=(232, 230, 223),
        #: PAT_COL tracks `mid` in INTENT (five notes at PAT_COL promise
        #: the letter) — but this sector is composited AFTER the duotone,
        #: so it carries the metal the ramp PRODUCES rather than the ramp's
        #: own midpoint. Same exemption the ferrari row takes, same reason.
        pat=(176, 173, 166),
        res_metal=(192, 195, 198),    # bead-blasted titanium, not gold
        #: The VISION half and the $LEDGER counter stay TITANIUM. The
        #: ferrari puts its accent here because red is that car's identity;
        #: on a tool the numbers are etched metal and only the STATE is
        #: allowed to light up. See the amber's own note below — the third
        #: colour only works while it is rare.
        vision_lo=(150, 154, 158), vision_hi=(214, 218, 222),
        steel_under=(30, 29, 27),     # warm ambient in the crack
        #: no `bezel`: bezel_steel.png IS this theme's ring and leaving the
        #: key out is what keeps that path unchanged (the royal-oak note).
        #: A machined band around a black composite part is also what the
        #: object already looks like, and the gold and porcelain bakes
        #: would both be jewellery on a tool. ONE THING IS WRONG WITH IT
        #: AND IT IS COSMETIC, NOT STRUCTURAL: that bake's minute track is
        #: CHAMPAGNE, so twelve warm indices sit on a face whose brief says
        #: one metal and one lamp. Seen on the proof
        #: (data/glass/carbon/face_furniture.png) it reads as brass on
        #: steel and it is liveable; the fix is a bake, not a key —
        #: scripts/bake_bezel.py with a bead-blasted titanium band and the
        #: index at twelve only — and nobody has been asked for it yet.
        #:
        #: ── THE TWO METALS (the fourth-pass note at _THEMES) ─────────────
        #: SIGNAL AMBER is the INSTRUMENT colour and it is the only
        #: saturated thing on this face. Amber rather than another red or
        #: another cyan for three reasons: ferrari owns red and aurora owns
        #: cyan, an amber lamp is what a machine actually uses to say
        #: "running", and it is the warm side of the same sheen the fibre
        #: catches — so the one saturated colour belongs to the material
        #: instead of being applied to it. MEASURED against this row's
        #: ground body (34,33,31): 6.8:1, which is the widest margin any
        #: accent on any row has had — a near-black dial has never been
        #: able to carry a saturated RED at 4.5 (the ferrari's vision_lo
        #: note proves it cannot) and amber simply can.
        #:
        #: AMBER IS ONLY EVER READ, NEVER ADMIRED. Every place it lands is
        #: a place the face is reporting or being read from: the listening
        #: rings, the two registers' index marks and their 0/50/100, the
        #: needle tips, the volume arc, the STERLING tile. It fills
        #: nothing and it outlines nothing. The ferrari's yellow note
        #: ("three colours only work when the third is rare") is that rule
        #: being kept here with two — and the discipline is what stops a
        #: face this dark from turning into a christmas tree the moment
        #: something needs emphasis.
        accent=(238, 148, 40), accent_lit=(255, 206, 140),
        accent_dark=(128, 78, 20),
        #: TITANIUM is the applied metal the wordmark is cut from. Cool
        #: against a warm-grey ground on purpose: the letters then separate
        #: from the sheen by HUE as well as by value, which is the only axis
        #: left once a face has spent its saturation on one lamp.
        brand_ink=(182, 185, 188), brand_lit=(228, 231, 234),
        brand_dark=(96, 99, 102), brand_under=(34, 36, 38),
        #: The gauge language, and it is borrowed rather than invented: a
        #: truthy value gives numbered tracks, bevelled gauge rims and
        #: needle pointers with tipped counterweights (read at INSTR). It
        #: is not the ferrari's livery — INSTR_RED is `accent`, so the
        #: index marks come out amber here — it is the engine's existing
        #: way of saying "this dial is an instrument", which is the brief.
        instruments="gauge",
        btn_flat=True,                # engraved line-art caps, no copper
                                      # jewellery on a tool
        no_sky=True, no_comets=True,  # a workshop has no starfield and
        no_bolt=True,                 # nothing on it shoots past
        no_moon=True,                 # a moonphase on a tool is a costume
        #: DELIBERATELY NOT `minimal`. gallery and chopard suppress the
        #: wordmark, the subdials and the ledger because their identity is
        #: what is absent. An instrument's identity is the opposite one:
        #: the numbers stay, because the thing this material was chosen for
        #: is work, and a tool that shows nothing is a tool that is off.
        #:
        #: ── THE STATE IS STATED AT THE CENTRE, AND THE SHELL SAYS SO ────
        #: LISTEN_CENTRE's own note settles the WHERE on composition rather
        #: than on luminance — the rim is the last place a person looks —
        #: and that argument is ground-independent, so it carries onto a
        #: dark face unchanged. It also lands somewhere this enclosure has
        #: already been: mark15's shell is cut with OCEAN SWELL, and a ring
        #: leaving the centre when she hears you is that engraving
        #: continued onto the glass. Sonar, on a device whose whole job is
        #: to hear the room.
        #:
        #: The hearing ring is amber (the lamp). The thinking ring is
        #: TITANIUM and faster — same mechanism, so the acceleration reads
        #: as "it is working now" without a second indicator. That second
        #: colour needed a key: the burst hard-coded (38,36,34) graphite for
        #: thinking, which is correct on plaster and INVISIBLE here — 1.1:1
        #: against this ground. Fourth instance this week of one treatment
        #: written for one ground (see the note at LISTEN_THINK).
        listen_cool=(238, 148, 40),
        listen_core=(255, 206, 140),
        listen_think=(198, 201, 205),
        #: (hearing, thinking) alpha — see LISTEN_C_A, and this key exists
        #: because of what the first render of this row measured. At
        #: gallery's 150/190 the rings came out 2.18:1 and 3.77:1 against
        #: this ground: present in the frame, invisible from a sofa, which
        #: is the same silent success the rim bloom spent three rounds on.
        #: The travel envelope's own peak is 0.76, so nothing under ~230
        #: can reach 3:1 here at all. MEASURED after (the brightest ring at
        #: its peak, against the pixels it covered): hearing 3.74:1,
        #: thinking 5.03:1 — scripts/render_listening.py carbon, and the
        #: measurement is in the session note, not in this comment's
        #: arithmetic.
        listen_c_alpha=(255, 240),
        #: ── AND THE RIM COMES BACK, ON THIS FACE (2026-08-26) ──────────
        #: Owner: "what is the circumference going to look like during
        #: thinking, speaking, etc." The honest answer was NOTHING, and
        #: that was an inherited decision rather than one made for this
        #: row. listen_centre moves the whole statement to the middle
        #: because on PLASTER a rim bloom is invisible — measured at
        #: 1.23:1 on 08-25, which is why it moved. That reasoning is about
        #: a light ground and does not survive the trip to a black one:
        #: amber on near-black is the highest-contrast thing on this face,
        #: and the bezel is its largest element.
        #:
        #: So carbon states it where the original design intended, and the
        #: centre goes back to being an OBJECT rather than a second
        #: indicator — two indicators for one state was never the design,
        #: which is the argument that moved it in the first place, applied
        #: the other way round.
        listen_centre=False,
        #: no `listen_ink` either: that key is the LIGHT-ground grammar,
        #: where ink pools instead of glowing. This ground is dark, so the
        #: bright path the bloom was written for is the correct one.
        #: ── THE VOLUME CARD, IN THE TOOL'S OWN INK (2026-08-26) ─────────
        #: The defaults are aurora's teal-on-void (the note at VOL_WASH).
        #: This face is dark, so it SCRIMS rather than washes — an
        #: instrument panel dims when one control takes over, it does not
        #: paint itself out — and only the ink is restated.
        #:
        #: 0.30 AND NOT THE 0.42 DEFAULT, AND IT WAS LOOKED AT. aurora
        #: scrims a void, where 0.42 of nothing is still nothing; this
        #: ground is graphite with bone type on it, and at 0.42 every
        #: wedge outline, the $LEDGER block and both pushers were still
        #: plainly legible through the card — the same complaint the
        #: gallery's wash was built to answer, one ground over. At 0.30 the
        #: dial recedes to a ghost and the card owns the glass. Both were
        #: rendered and looked at (scripts/render_volume_card.py carbon);
        #: what is on disk is the 0.30 one.
        #:
        #: EVERY VALUE BELOW IS MEASURED AGAINST THE SCRIMMED GROUND
        #: (10,10,9), NOT AGAINST THE RESTING DIAL, because the scrimmed
        #: ground is what the card actually sits on: lit arc 8.4:1, unlit
        #: track 3.7:1, VOLUME caption 8.5:1, the readout 16.5:1, the small
        #: hint 4.9:1.
        #:
        #: DONE is a MACHINED CAP, not a hole and not a lamp. gallery
        #: learned that a near-black disc on plaster reads as a hole; the
        #: dark-ground equivalent is a disc at the ground's own value, which
        #: reads as nothing at all. So the fill is lifted clear of the scrim
        #: (1.5:1 — enough for a rim, not enough to shout) and the two
        #: things a finger actually aims at carry the contrast: the amber
        #: edge at 8.4:1 and the bone label at 11.3:1 on the cap. §8 is why
        #: it gets the margin — every other control on this screen costs a
        #: tap to undo, and this is the only one whose failure leaves him
        #: stuck inside a modal.
        vol_scrim=0.30,
        vol_on=(238, 148, 40),
        vol_off=(110, 107, 102),
        vol_label=(168, 170, 172),
        vol_big=(236, 234, 228),
        vol_hint=(128, 126, 120),
        vol_done_fill=(48, 46, 43),
        vol_done_edge=(238, 148, 40),
        vol_done_ink=(236, 234, 228),
        #: ── THE PANES ARE A SURFACE, NOT AN OUTLINE (2026-08-26) ────────
        #: Owner, at the glass on this face: "the wedges are just old
        #: school 2-d, where is the depth and embossing, extrusion, etc."
        #:
        #: He is right and the cause was ONE GATE. This file already owns a
        #: proper relief renderer — _aur_wedge_sprite computes a chamfered
        #: HEIGHT FIELD per pane, takes normals from its gradient, lights
        #: them Blinn-Phong against the house key at upper-left and casts a
        #: real shadow — and the whole path sat behind `if AURORA_BLOB`.
        #: carbon does not set `blob`, so it fell through to the flat
        #: WGLASS tile: a 3 px bevel drawn as two strokes, which is the
        #: "relief pair" the 2026-08-09 note at WGLASS_BEVEL added and is
        #: still a DRAWING of an edge rather than a lit surface. Every
        #: complaint that ring has ever had is in that distinction — see
        #: the note at _AUR_WEDGE_CACHE, which is the same owner asking the
        #: same question about the other ring five days earlier.
        #:
        #: WHAT THIS KEY DOES NOT TURN ON: the blob core, aurora's seven-
        #: pane geometry, aurora's colourway, its summon/idle choreography
        #: or its arrival dissolve. `wedges()` already answers per face, so
        #: carbon gets its own five sectors at its own band, filled from
        #: `tiles["wedges"]` below and named from `wedge_names` beside
        #: them. Read at RELIEF_PANES.
        #:
        #: AND THE PANE IS STILL GLASS OVER BAKED INK. This face's labels
        #: (BRIEFING/STOPPED, STERLING/CONCIERGE …) live in home.html's
        #: bake, underneath. The WGLASS note's rule holds — "a solid tile
        #: would be a red sticker with a highlight on it … the label ink
        #: underneath still reads" — so the relief is split: the CHAMFER
        #: WALLS are opaque machined metal and the plateau is a low-alpha
        #: smoke the type reads straight through. The depth is in the
        #: chamfer, the key and the cast shadow, never in a bright fill.
        relief_panes=True,
        #: and the lit edge is the LAMP, not the sheen — amber on a
        #: near-black pane, which is the accent this face already owns.
        relief_light=(238, 148, 40),
        #: ── AND THEN THE TYPE WAS RAISED TOO (2026-08-26, later) ────────
        #: Owner, having seen the panes: "raise the type" and "the icon /
        #: text still is not centered correctly in the wedges, they are
        #: near overlapping the perceived edge."
        #:
        #: THE PARAGRAPH ABOVE IS SUPERSEDED ON ONE POINT and stands with
        #: its date on every other. "The plateau is a low-alpha smoke the
        #: type reads straight through" was the right answer while the
        #: sprite could not see the bake. It can now — _relief_ink reads
        #: the same file the compositor draws, _relief_type lifts this
        #: pane's own legend out of it — so the plateau goes OPAQUE and
        #: the legend is struck into the height field instead, lit by the
        #: same key as the chamfer and casting its own shadow. The two
        #: halves are one decision: a raised label and the flat one it was
        #: sampled from cannot both be on the sector.
        #:
        #: WHAT THE SMOKE WAS ALSO DOING is not lost, it is paid for
        #: explicitly — the pane composites over its own baked fill at the
        #: same 38%, so the ring's colour is unchanged from this morning's
        #: build. Read at RELIEF_TYPE_* for every number and for the two
        #: measurements that overturned a plausible cause on the way.
        #:
        #: MEASURED, ink to the perceived edge, before -> after, worst of
        #: the four margins per pane: BRIEFING 8.7 -> 11.9, STERLING
        #: 2.7 -> 10.4, LOCK 8.2 -> 19.0, SETTINGS 0.2 -> 17.7,
        #: VOLUME 0.2 -> 20.4 px, with inner and outer now equal to within
        #: half a pixel on all five.
        tiles=dict(
            #: The after-colourway family (the third-pass note at _THEMES),
            #: laddered by Rec.601 value with saturation breaking the ties
            #: because hue is spent here too: BRIEFING 212/.04,
            #: STERLING 163/.83, VOLUME 151/.53, SETTINGS 142/.03,
            #: LOCK 121/.69. The two that nearly share a value are the
            #: saturated one and the muted one, which is the trick the
            #: patek row found and every row since has kept.
            wedges=((214, 212, 205),  # BRIEFING — etch bone
                    (238, 148, 40),   # STERLING — the amber, tracks accent
                    (214, 84, 66),    # LOCK     — oxide red, the outcome
                                      # colour, exempt from the house
                                      # family in every theme
                    (140, 142, 145),  # SETTINGS — machined grey
                    (186, 146, 88)),  # VOLUME   — dark brass
            #: ── AND THE SAME FIVE, NAMED (2026-08-26) ───────────────
            #: The relief renderer takes a NAME per pane (it is the
            #: sprite's cache key and the glyph the aurora ring strikes
            #: into its height field). It used to read `AUR_MENU[i]` —
            #: aurora's SEVEN-pane list, indexed by this ring's index —
            #: which is the SLEEP/POWER bug of 2026-08-17 with the
            #: operands swapped: two lists of different lengths, one
            #: subscripting the other, and the mismatch shows up as a
            #: pane wearing another pane's identity rather than as an
            #: error. So the names sit HERE, beside the colours they
            #: belong to, in WEDGES order, and pane_names() checks the
            #: two lists are the same length before anything indexes
            #: either (§15).
            wedge_names=("BRIEFING", "STERLING", "LOCK",
                         "SETTINGS", "VOLUME"),
            panel_fill=(40, 39, 36),        # screens at a36 to (5,5,5),
                                            # a hair off the resin
            panel_lift=(92, 88, 80, 24),
            world=(226, 224, 216),          # etch bone, the tenant's ink
            row_ink=((206, 206, 202),       # label
                     (234, 233, 228)),      # body
        ),
        #: THE RAMP IS THE COLOUR AUTHORITY; the bake is still the shelf
        #: authority (§15). Positions are luminances measured on the
        #: standing bake, not spread evenly — see the header note.
        ramp=((0.00, (12, 12, 13)),      # resin black, cool, in shadow
              (0.14, (34, 33, 31)),      # the ground's own body (L36)
              (0.27, (62, 60, 56)),      # lit chamfers (L68) — the sheen,
                                         # and the warmest point on the face
              (0.42, (104, 101, 96)),    # hairlines
              #: 0.50 AND NOT 0.55, AND THE FIVE HUNDREDTHS ARE A
              #: LEGIBILITY NUMBER. This stop IS `mid`, so it belongs at
              #: the duotone's own midpoint or the two disagree about the
              #: same band (§15) — and the first cut of this ramp put it at
              #: 0.55, which pulled a caption baked at L=130 down to
              #: (136,133,127) = 4.37:1, under the owner's 4.5 floor by
              #: exactly the margin the ferrari row spent a paragraph
              #: clearing. At 0.50 the same caption arrives (152,149,143)
              #: = 5.39:1. MEASURED off _RAMP_LUT, not derived.
              (0.50, (150, 147, 141)),   # machined grey — mid-tone type
              (0.78, (196, 194, 188)),   # bright furniture
              (1.00, (232, 230, 223))),  # etch bone, the laser's ceiling
        #: ── STILL OWED: THE SPECKLE (2026-08-26) ────────────────────────
        #: Chopped fibre is a fine random glint, and nothing in this row
        #: draws one — the tapisserie is standing in for it. The honest fix
        #: is a BAKE, not a per-frame pass (PUCK-STANDALONE: the RTX
        #: touches a puck at build time only): one 1080x1080 speckle field,
        #: fibres 2-4 px, oriented randomly, lifted 6-10 levels over the
        #: ground, stamped onto the bake beside _carbon_weave_sync. It has
        #: NOT been rendered — the owner has not been asked — and the note
        #: at the patek's gear train is the number to respect when it is:
        #: a lift is a fraction of the LOCAL ground (34), not of 255.
    ),
    #: ── 2026-08-27: LACQUER — THE RED ASA SHELL'S FACE ───────────────────
    #: The fourth enclosure, and the first one that is a COLOUR before it is
    #: a material. Owner, on the red print: he "loves the red", and the brief
    #: for the glass was two words — "awe inspiring" and "match the colors".
    #: Polymaker ASA in a saturated, faintly warm red: semi-gloss as printed,
    #: UV- and impact-proof, an outdoor engineering polymer that nobody
    #: chooses quietly. gallery CONTINUES plaster onto the glass and carbon
    #: continues chopped fibre; this row continues RED, which is a much
    #: bigger claim on the screen than either, because on the other two the
    #: shell's material is a texture and here it is the whole field.
    #:
    #: ── WHY THIS IS NOT THE FERRARI, AND THE DIFFERENCE IS ONE SENTENCE ──
    #: The differentiation doctrine lives at the ferrari row and it exists
    #: precisely so two red-adjacent faces cannot read as each other. There
    #: is a real risk here and it is worth stating as a test rather than as
    #: an intention. MEASURED on the two faces' own rendered proofs, dial
    #: ground median over r 200..470:
    #:
    #:     ferrari   (47,45,45)    R-B  +2    neutral, and its red is a
    #:                                        rare INSTRUMENT colour
    #:     carbon    (35,34,32)    R-B  +3
    #:     lacquer   (100,14,18)   R-B +82    the red IS the ground
    #:
    #: (The ferrari row's own note records (39,37,37) for the same thing
    #: over a different annulus; the sign of R-B is the half that matters
    #: and the two agree.) So:
    #:
    #:     ferrari   red light on a black object
    #:     lacquer   white light on a red object
    #:
    #: Every other choice in this row falls out of that inversion, and each
    #: one is a second axis of separation: the ground is a lacquer field and
    #: not a woven twill; there is no `instruments` key, because ferrari
    #: owns the gauge language and carbon borrowed it — this face is an
    #: OBJECT, not a dashboard; the centrepiece is a bar and not a rev
    #: counter; and the one saturated colour on the ferrari is its accent
    #: while on this face the accent is the only thing that ISN'T.
    #:
    #: ── AND THE ACCENT CANNOT BE RED, WHICH IS MEASURED, NOT CHOSEN ──────
    #: The obvious face for a red shell is red-on-red, and the arithmetic
    #: kills it before taste gets a vote. This row's ground body computes to
    #: relative luminance 0.033; the shell's own red (198,32,34) computes to
    #: 0.132. That is 2.19:1, off the built LUT — a mark you can find only
    #: because you know where it is, on a face whose whole job is to be
    #: read across a room.
    #: PRINCIPLES §3 in its other direction: there is no alpha, no
    #: saturation and no tuning pass that separates a colour from a ground
    #: made of the same colour. So the red is spent on the FIELD, and every
    #: applied mark is cold nickel; the one lamp is incandescent white.
    #: That is also why this face reads as a red OBJECT rather than as a red
    #: SCREEN — a red screen is red type too, and red type is what a warning
    #: dialog looks like.
    #:
    #: ── WHAT GLOSS WOULD CHANGE (nothing, and that is the point) ─────────
    #: ASA vapour-smooths with acetone to a true gloss and the owner has
    #: declined the step so far, so this is designed for as-printed
    #: semi-gloss: the lit facets of the ground reach the shell's exact red
    #: and stop, rather than blowing to a white specular. If he ever runs
    #: the acetone, the shell gains hard highlights the glass ALREADY has —
    #: the chalk top of the ramp and the bar's arris — so the two get closer
    #: together, not further apart. Nothing in this row would need moving.
    #:
    #: THE STOPS SIT WHERE THE BAKE ACTUALLY IS (the chopard's lesson, which
    #: cost it 60% of a sweep, and carbon's after it). MEASURED on the
    #: standing bake, inside the dial circle: p5=8, p25=25, p50=37, p75=44,
    #: p90=55, p95=64, and only 2.8% of the dial is above L=100. So 58% of
    #: the pixels live between L=30 and L=50 and the ramp is dense there;
    #: the whole red half of it is spent below L=70 and the metal half
    #: above L=107, where the marks are.
    "lacquer": dict(
        #: THE WAX SEAL — see centre_seal.py.
        #:
        #: 2026-08-27, SUPERSEDING THE BAR IN THE PARAGRAPH BELOW. The bar
        #: shipped this morning and the owner's verdict on the rendered
        #: product shot was *"we need a better centerpiece for the red
        #: face, it's just a rectangle."* He is right, and the note that
        #: stands directly under this one — "the centrepiece is a bar and
        #: not a rev counter" — is now WRONG about the object while still
        #: being right about the argument: the differentiation from the
        #: ferrari is that this face is an OBJECT and not a dashboard, and
        #: a struck seal is more of an object than a blank is, not less.
        #: centre_ingot.py is left in place with its notes; the bar's
        #: reasoning about linear-versus-radial is what licensed a round
        #: centrepiece to come back at all, so deleting it would delete
        #: the argument this one is built on.
        #:
        #: The product is Aura SARD — sard is the signet stone, the shell
        #: is the colour of sealing wax, and the device authorises and
        #: locks. A seal is the object that means "authorised by me".
        #:
        #: ── 2026-08-30, THE MATRIX RATHER THAN THE IMPRESSION ─────────
        #: Owner: "sard's centerpiece is still something i really don't
        #: like, redesign that completely." The seal's own bake log had
        #: the diagnosis in it and nobody read it against the ground:
        #: body L 3..78, matte, and round — same hue as an L~40 ground,
        #: overlapping luminance with it, no hard edge anywhere, on the
        #: only face where every other object is crisp white line work.
        #: centre_stone.py draws the STONE instead: step-cut, table up,
        #: the approved letterform cut INTO it in intaglio, in a bezel
        #: that is metal because it sits above this ramp's nickel knee.
        #: `centre="seal"` still selects the wax; it is one word away.
        centre="stone",
        #: OXBLOOD. Never (0,0,0) and never neutral, for carbon's reason
        #: stated about the other colour: a screen that out-blacks the
        #: shell makes the shell look grey beside it, and a NEUTRAL black
        #: under a red field makes the field look like a filter over a
        #: monochrome dial. The deepest shadow on a red lacquer object is
        #: still red.
        black=(22, 6, 8),
        #: NICKEL, and it is a legibility number rather than a taste one —
        #: the ferrari's whole `mid` paragraph and carbon's after it apply
        #: verbatim. Every source pixel at L=128 lands on this triple and
        #: that band is all of the dial's mid-tone micro-type. MEASURED off
        #: the built LUT rather than reasoned about: a caption baked at
        #: L=130 arrives (187,191,197) against a ground body of (104,14,18)
        #: = 6.85:1, the widest margin of any row in this table, which is
        #: what a cool metal on a dark saturated field buys you for free.
        mid=(186, 190, 196),
        #: CHALK. The ramp's ceiling is a cool white and not paper white —
        #: the marks on this object are plated hardware catching a cold
        #: room light, and a warm ceiling here would drag the furniture
        #: back toward the field's own hue, which is the one axis this face
        #: has left (carbon's titanium note, same argument, other ground).
        white=(232, 236, 242),
        #: PAT_COL tracks `mid` in INTENT — five notes at PAT_COL promise
        #: the letter — but this sector is composited AFTER the duotone, so
        #: it carries the metal the ramp PRODUCES rather than the ramp's own
        #: midpoint. Same exemption ferrari and carbon take, same reason.
        pat=(204, 208, 214),
        res_metal=(198, 202, 208),    # nickel-plated, not gold
        #: The VISION half and the $LEDGER counter stay NICKEL, and this is
        #: the row where that decision is load-bearing rather than tidy.
        #: ferrari puts its accent here because red is that car's identity;
        #: doing the same on this face would paint the two largest pieces
        #: of applied type in the field's own colour at 2.19:1 (see the
        #: header). The wordmark is hardware on lacquer.
        vision_lo=(168, 172, 178), vision_hi=(226, 230, 236),
        steel_under=(38, 10, 12),     # the crack: warm-dark, red ambient
        #: no `bezel`: bezel_steel.png IS this theme's ring, and leaving the
        #: key out is what keeps that path unchanged (the royal-oak note).
        #: A plated steel band around a red lacquer object is also exactly
        #: what the object is — the gold and porcelain bakes would both be
        #: jewellery, and bezel_ferrari.png is the ferrari's own identity
        #: and would undo half the differentiation above on the single most
        #: visible ring of the face. THE SAME COSMETIC FAULT CARBON LOGS IS
        #: HERE TOO and is worse on this ground: that bake's minute track is
        #: CHAMPAGNE, and twelve warm indices on a warm field read as a
        #: sixth hue rather than as brass on steel. Liveable; the fix is a
        #: bake, not a key (scripts/bake_bezel.py, a cold nickel band with
        #: the index at twelve only), and nobody has been asked for it.
        #:
        #: ── THE TWO METALS (the fourth-pass note at _THEMES) ─────────────
        #: INCANDESCENT WHITE is the INSTRUMENT colour and it is the only
        #: thing on this face that is neither the field nor the hardware.
        #: Not amber (carbon owns it, and amber on a red field is warm on
        #: warm), not cyan (aurora owns it), and not red (measured above:
        #: 2.19:1 against this row's own ground). What is left is the one
        #: thing a red-hot object does next, and it is not a compromise: a
        #: warm-cored white is the highest-contrast mark available here and
        #: it separates from the nickel furniture by HUE, which is the axis
        #: a face keeps when it has spent its saturation on the ground.
        #: MEASURED against the ground body (104,14,18): 10.20:1, where
        #: the shell's own red on the same ground manages 2.19:1.
        #:
        #: THE LAMP IS ONLY EVER READ, NEVER ADMIRED — carbon's discipline,
        #: kept. It lands on the listening rings, the reserve's F/E, the
        #: $LEDGER caption, the volume arc and the DONE cap's edge, and
        #: nowhere else. It fills nothing and it outlines nothing.
        accent=(255, 226, 196), accent_lit=(255, 246, 232),
        accent_dark=(150, 74, 38),
        #: NICKEL is the applied metal the wordmark is cut from — the same
        #: family as `mid`, so the letters belong to the same hardware as
        #: the type rather than being a fourth material.
        brand_ink=(186, 190, 196), brand_lit=(232, 236, 242),
        brand_dark=(96, 100, 106), brand_under=(30, 32, 35),
        #: no `instruments`: see the header. ferrari owns "tacho" and
        #: carbon borrowed "gauge"; a third face with numbered tracks and
        #: needle pointers would be the differentiation doctrine failing in
        #: the one place it is written down.
        btn_flat=True,                # engraved line-art caps: a copper
                                      # cap would be a fourth metal
        no_sky=True, no_comets=True,  # a starfield over a red field is
        no_bolt=True,                 # noise, and nothing here shoots past
        no_moon=True,                 # a moonphase on this object is a
                                      # costume, carbon's word for it
        #: DELIBERATELY NOT `minimal`, and the reason is mechanical rather
        #: than aesthetic. That key suppresses the LIVE wordmark, subdials
        #: and ledger — and gallery and chopard can afford it because both
        #: ship their own finished bake with those marks absent from the
        #: pixels. This row rides home.html's bake, which has the reserve
        #: gauge and the $LEDGER block baked INTO it, so asking for less
        #: here would delete the live copy and leave the baked ghost: a
        #: dial that is emptier in the code and identical on the glass,
        #: which is the silent-success shape (§1). If this face is ever to
        #: be stripped, it needs its own bake, not this flag.
        #:
        #: ── THE STATE IS STATED AT THE CENTRE, ON THE OBJECT ────────────
        #: carbon put the statement back on the RIM because on a near-black
        #: face amber on the bezel is the highest-contrast thing available
        #: (measured 11.2:1 on that row's own proof, and it is right). That
        #: argument does not survive the trip here, for a reason that has
        #: nothing to do with luminance: the rim bloom is drawn in
        #: LISTEN_COOL, and every colour this face could put there is
        #: either the field's red — which loses to the steel band — or the
        #: white lamp, which on a plated band reads as a reflection rather
        #: than as a signal. The gallery's argument is the one that carries:
        #: the answer belongs at the radius the eye is already on, and on
        #: this face the eye is on a bar in the middle.
        #:
        #: So: rings leaving the bar, and the bar itself taking heat. That
        #: is TWO marks and ONE event — the rings are what a hot object
        #: does to the air around it — which is the distinction the 08-25
        #: note is drawing when it refuses two indicators for one state.
        listen_centre=True,
        #: hearing is the LAMP; thinking is the NICKEL, faster. Same
        #: mechanism carrying both, so the acceleration reads as "it is
        #: working now" without a second indicator (carbon's trick, and it
        #: needed a key there for the same reason it needs one here: the
        #: burst's default thinking ink is (38,36,34) graphite, chosen
        #: against plaster, and it is 1.1:1 on any dark ground).
        listen_cool=(255, 226, 196),
        listen_core=(255, 246, 232),
        listen_think=(200, 210, 222),
        #: (hearing, thinking) alpha. How opaque a ring must be to be SEEN
        #: is a property of the ground, not of the ring: this ground is
        #: twice as bright as carbon's in relative luminance
        #: (0.033 against 0.016), so the defaults gallery shipped for
        #: plaster are nowhere near. MEASURED on this row's own proof —
        #: scripts/render_listening.py lacquer, then scripts/measure_face.py
        #: lacquer, which diffs the state frame against the ground it was
        #: composited onto rather than against the row's palette (§4).
        listen_c_alpha=(255, 244),
        #: ── THE VOLUME CARD, IN THE OBJECT'S OWN INK (2026-08-27) ───────
        #: The defaults are aurora's teal-on-void (the note at VOL_WASH).
        #: This face is dark, so it SCRIMS rather than washes, carbon's
        #: reasoning exactly — but the number is NOT carbon's, because a
        #: scrim multiplies, and what survives multiplication on this face
        #: is not the red — 0.22 of (104,14,18) is (23,3,4), gone — it is
        #: the dial's WHITE TYPE, which is the one thing on the resting
        #: face that is nowhere near the ground. 0.22 of a 235-level
        #: caption is still 52, and at that value BRIEFING, STERLING and
        #: the wedge outlines all read straight through the card: the same
        #: complaint carbon's 0.30 answers, arriving through a different
        #: term. At 0.15 the type is a ghost and the card owns the glass.
        #: Both were rendered and looked at
        #: (scripts/render_volume_card.py lacquer); on disk is the 0.15.
        #:
        #: EVERY VALUE BELOW IS MEASURED AGAINST THE SCRIMMED GROUND
        #: (15,2,2), NOT AGAINST THE RESTING DIAL, because the scrimmed
        #: ground is what the card actually sits on: lit arc 16.4:1, unlit
        #: track 3.35:1, VOLUME caption 9.8:1, the readout 17.9:1, the
        #: small hint 5.5:1.
        #:
        #: DONE is a MACHINED CAP, not a hole and not a lamp — gallery
        #: learned that a near-black disc on plaster reads as a hole and
        #: carbon that a disc at the ground's own value reads as nothing.
        #: The fill is the lacquer lifted clear of the scrim (1.28:1 —
        #: enough for a disc, not enough to shout) and the two things a
        #: finger aims at carry the contrast: the lamp on its edge at
        #: 16.4:1 and the chalk label on that fill at 13.9:1. §8 is why it
        #: gets the margin —
        #: every other control here costs a tap to undo, and this is the
        #: only one whose failure leaves him stuck inside a modal.
        vol_scrim=0.15,
        vol_on=(255, 226, 196),
        vol_off=(118, 92, 90),
        vol_label=(176, 180, 186),
        vol_big=(238, 240, 244),
        vol_hint=(140, 130, 130),
        vol_done_fill=(66, 17, 19),
        vol_done_edge=(255, 226, 196),
        vol_done_ink=(238, 240, 244),
        #: ── THE PANES ARE A SURFACE, NOT AN OUTLINE ────────────────────
        #: carbon's own note argues this in full and the argument is about
        #: the RENDERER, not about that face: without this key the ring
        #: falls through to the flat WGLASS tile, which is a drawing of an
        #: edge rather than a lit surface, and every "where is the depth"
        #: complaint the ring has ever had is in that distinction.
        relief_panes=True,
        #: and NO `relief_light`. carbon names the key because the owner
        #: asked for orange arrises on CF black; here the default is the
        #: decision — the arris takes the top of this row's ramp, which is
        #: the cold chalk, so the panes are lit by the same white light as
        #: everything else on a red object. An orange arris on this ground
        #: would be warm on warm and would spend the one hue the face has
        #: left. A key that agrees with its default is drift waiting to
        #: happen (§15), so it is not written.
        tiles=dict(
            #: The after-colourway family (the third-pass note at _THEMES),
            #: laddered by Rec.601 value with saturation breaking the ties
            #: because hue is spent here too — and it is spent harder here
            #: than on any other row, because the GROUND took it:
            #: BRIEFING 226/.04, STERLING 165/.54, VOLUME 160/.06,
            #: SETTINGS 120/.06, LOCK 82/.84. The two that nearly share a
            #: value are the saturated one and the muted one, which is the
            #: trick the patek row found and every row since has kept.
            #:
            #: STERLING KEEPS ITS GOLD, which restores the patek row's
            #: original clause ("it is the brand, not the colourway") that
            #: ferrari and carbon each suspended for themselves. It is also
            #: the only saturated warm mark on the face that is not the
            #: field, and gilt on lacquer is the one place those two
            #: materials have always been put together.
            #:
            #: LOCK'S RED IS THE ONE EXEMPTION THAT DOES NOT SURVIVE THIS
            #: ROW INTACT, and it has to be said out loud because the
            #: palette note in PUCK-SHOW.md calls it exempt in EVERY theme.
            #: The exemption works by hue: LOCK is the red one. On a face
            #: whose field is red, "the red one" identifies nothing. So the
            #: meaning is kept and the mechanism is changed: LOCK is the
            #: only pane that is NOT plated. Four pieces of hardware and
            #: one bare piece of the shell, told by VALUE instead of by
            #: hue, and its exact triple is the shell's own red so the tile
            #: is the material showing through the metalwork.
            #:
            #: ── AND THE MEASUREMENT SAYS THAT LADDER BARELY REACHES THE
            #: GLASS ON ANY RELIEF ROW (2026-08-27) ─────────────────────
            #: This is a finding about the RENDERER, not about this row,
            #: and it is written here because this is where the claim is
            #: made. On a `relief_panes` face the plateau is 38% of the
            #: pane's colour ALREADY DIMMED by its own diffuse term, over
            #: 62% of the bake's ground (see RELIEF_BODY_A and the note
            #: beside it about christmas trees). MEASURED, plateau medians
            #: in Rec.601 value against a declared spread of 144:
            #:
            #:     lacquer   38.3 .. 47.9   (9.6 points)
            #:     carbon    34.8 .. 41.1   (6.3 points, declared spread 91)
            #:
            #: — i.e. the shipped carbon row has the same collapse and was
            #: approved with it, because a relief pane is read by its
            #: RAISED LEGEND and its chamfer, not by its fill. Raising the
            #: mix was tried and measured rather than argued: at 150 the
            #: spread goes to 15 points and at 225 to 22, and BOTH make the
            #: ring DARKER (BRIEFING's plateau 51 -> 50 -> 48), because
            #: more of a diffuse-dimmed tile is less light than more of the
            #: lit ground. There is no setting that separates these panes
            #: by colour, so PRINCIPLES §3 applies and the tuning stops:
            #: the ladder below is honest about intent and the LEGEND is
            #: what tells the panes apart. If LOCK ever has to be legible
            #: as LOCK from across the room, that is a shape or a lamp,
            #: not a fill.
            wedges=((222, 226, 232),  # BRIEFING — chalk nickel
                    (200, 162, 92),   # STERLING — struck gold, the brand
                    (198, 32, 34),    # LOCK     — the shell's own red, the
                                      # outcome colour, told by value here
                    (118, 121, 126),  # SETTINGS — gunmetal
                    (156, 160, 166)), # VOLUME   — nickel
            #: The relief renderer takes a NAME per pane and pane_names()
            #: checks the two lists are the same length before anything
            #: indexes either — carbon's note has the bug that cost.
            wedge_names=("BRIEFING", "STERLING", "LOCK",
                         "SETTINGS", "VOLUME"),
            panel_fill=(58, 14, 16),        # the dial's own ground, dark:
                                            # screens at a36 to (8,2,2)
            panel_lift=(120, 44, 42, 24),
            world=(236, 238, 242),          # chalk, the tenant's ink
            row_ink=((208, 210, 214),       # label
                     (236, 238, 242)),      # body
        ),
        #: THE RAMP IS THE COLOUR AUTHORITY; the bake is still the shelf
        #: authority (§15). Positions are luminances measured on the
        #: standing bake, not spread evenly — see the header note. The
        #: whole hue turn happens between 0.275 and 0.42, which is 0.4% of
        #: the dial's pixels: below it the face is lacquer, above it the
        #: face is hardware, and almost nothing lives in between.
        ramp=((0.000, (22, 6, 8)),       # oxblood — the shadow floor
              (0.040, (46, 9, 12)),      # deep lacquer (L10)
              (0.100, (76, 11, 14)),     # the tapisserie's troughs (L25)
              #: 0.145 IS THE FACE. The bake's median is L=37 and 58% of
              #: the dial sits between L=30 and L=50, so this stop and the
              #: next one are what a person across the room actually sees.
              #: Its relative luminance is 0.033 and every contrast figure
              #: in this row is measured against it.
              (0.145, (104, 14, 18)),    # THE GROUND BODY (L37)
              (0.220, (148, 21, 25)),    # the lit cells (L56)
              #: 0.275 IS THE SHELL, to the triple. This is the top of the
              #: ground band (L70, the brightest 3% of the guilloche) and
              #: it is set to the ASA's own red on purpose: the only place
              #: the glass reaches the colour of the part is where light
              #: rakes across it, which is exactly what a semi-gloss
              #: surface does in the room the puck is sitting in.
              (0.275, (198, 32, 34)),    # SIGNAL — the shell's own red
              (0.420, (168, 170, 174)),  # hairlines, already hardware
              #: 0.50 IS `mid` and belongs at the duotone's own midpoint or
              #: the two disagree about the same band (§15). carbon's row
              #: records what five hundredths cost when they drift.
              (0.500, (186, 190, 196)),  # nickel — mid-tone type
              (0.780, (214, 218, 224)),  # bright furniture
              (1.000, (232, 236, 242))), # chalk, the cold ceiling
        #: ── STILL OWED (2026-08-27) ─────────────────────────────────────
        #: 1. THE LOCK SCREEN. gallery added `lock_face` on 08-26 because
        #:    its door was a deep-space starfield while the room behind it
        #:    was plaster; this face has the same mismatch and worse, since
        #:    a starfield over red is the `no_sky` decision above being
        #:    made twice and only landing once. Not set here because it
        #:    was not rendered, and a key that has not been looked at is
        #:    exactly what this week's four incidents were made of.
        #: 2. THE FINISH. The ground's texture is home.html's tapisserie
        #:    read through this ramp, which gives a fine stamped grid. A
        #:    printed part's real finish is LAYER LINES, and they are
        #:    concentric on a puck top — which is the one thing the
        #:    centrepiece note forbids (centre_disc.py's header: concentric
        #:    rings read as a web). If a finish is ever baked for this row
        #:    it should be the print's fine surface grain, NOT its layer
        #:    lines, and it is a bake and not a per-frame pass
        #:    (PUCK-STANDALONE).
    ),
}
#: The flag over the engine. DJ_THEME is a no-commit try-on at the glass;
#: the default is what a capture from HEAD bundles, so the default IS the
#: sellable patek. An unknown name wears that default and SAYS SO (§1)
#: rather than taking the face down over a spelling.
#: 2026-08-08, by voice: "back to the Audemars Piguet theme for my home
#: screen" — the default is royal-oak again; the note above stands as the
#: reason the fallback tracks the default.
#: 2026-08-08: the theme also comes from a FILE the profile switcher
#: writes, so a bundle can carry its own colourway and the three-second
#: voice switch changes theme as well as layers. Env var still wins — it
#: is the no-commit try-on at the glass. Order: DJ_THEME, then
#: ~/aura_face/THEME, then the default.
_THEME_FILE = Path.home() / "aura_face" / "THEME"


def _theme_name() -> str:
    env = os.environ.get("DJ_THEME", "").strip()
    if env:
        return env
    try:
        return _THEME_FILE.read_text().strip() or "royal-oak"
    except OSError:
        return "royal-oak"


FACE_THEME = _theme_name()
if FACE_THEME not in _THEMES:
    print(f"theme: unknown {FACE_THEME!r} — wearing 'royal-oak'", flush=True)
    FACE_THEME = "royal-oak"
_THEME = _THEMES[FACE_THEME]
#: The after-colourway family, pulled out because every site that reads it
#: is a thousand lines away from this one. See the third-pass note above.
_TILES = _THEME["tiles"]
#: ── MINIMAL: A DIAL WHOSE IDENTITY IS WHAT IS NOT ON IT (2026-08-12) ─────
#: The chopard face has its own bake — opaline, Roman numerals, an empty
#: centre — and putting it on a puck showed the half of the problem a bake
#: cannot solve: dj_face went on drawing ITS OWN instruments over the top.
#: The AURAVISION wordmark landed across XI, XII and I; the RESERVE and ROOM
#: subdials, which are drawn as light rings for a near-black ground, came out
#: as two empty circles on white; the $LEDGER bar sat in the chapter.
#:
#: This is the briefing-scrim lesson in another costume: a dial is only as
#: good as the LAST thing painted on it. Her watch is a ladies' tonneau whose
#: whole character is absence, and a theme system that can only change
#: colours will always hand it somebody else's furniture.
#:
#: So the row can ask for less. It suppresses DECORATION only — the wordmark,
#: the two counterpoise subdials, the ledger figure. Everything the device
#: needs to be usable stays: the wedges, the buttons, the time, the bezel
#: state, the briefing card.
MINIMAL = bool(_THEME.get("minimal"))
#: ── BAKE_FINAL: A THEME MAY SHIP ITS BASE AS FINISHED PIXELS (2026-08-22) ─
#: The gallery row's base is baked offline by scripts/bake_gallery_home.py
#: with relief, buttons and typography already composed. Every per-boot
#: stamp (_wedge_type_sync, _btn_machine_sync, the ground passes) was
#: written against home.html bakes and assumes "the marks are the bright
#: pixels" — the exact family that cut two near-black discs into the
#: chopard's opaline (FAILURES 2026-08-12 §3). A finished bake gives them
#: nothing to do and a light ground to do it wrongly on, so on such a
#: theme the stamps stand down as ONE decision, here, not five gates in
#: five functions (§15).
BAKE_FINAL = bool(_THEME.get("base"))
_BAKE_FINAL_SAID: list = []           # the stand-down line prints once
#: ── 2026-08-09: THE INSTRUMENT FLAG ───────────────────────────────────────
#: Owner, at the glass on the ferrari: "THE COMPLICATIONS STILL LOOK LIKE THE
#: AP's. Same rings, same snail, same hands, different colour. Differentiate
#: them as INSTRUMENTS: give the subdials tachymeter-style numerals instead
#: of the AP's plain tracks, square off or bevel their rims (a car gauge has
#: a bezel, not a jewelled flange), and swap the leaf hands for straight
#: needle pointers with red tips and white counterweights. Same three
#: positions, entirely different instrument language."
#:
#: ONE FLAG, FOUR SITES, and it is a flag rather than four theme keys because
#: the four marks are one language: a needle without a numbered track is a
#: bare gauge, and numerals under a jewelled flange are an AP with numbers
#: on it. Read at _snail_pocket/_pocket_relief (the bevelled bezel),
#: _draw_hand (the needle), _instr_scale (the red index marks and the
#: numerals) and draw_gold_strikes (the tip and counterweight strikes).
#: A row without the key is byte-identical through all four.
#:
#: BEVEL, NOT SQUARE, of the two the owner offered. A rounded square with a
#: half-side of REG_RIM=90 reaches 127 px at its corners against a ROOM tile
#: whose pivot has 116 to spare and a moon layer with 94 — the square is
#: geometrically outside two of the three registers, and shrinking the
#: registers to fit is a bigger move than the brief asks for. The bevel is
#: drawn INWARD from the same rim and therefore fits every register that
#: fits today.
INSTR = _THEME.get("instruments")

#: ── AURORA: THE CORE (2026-08-16) ────────────────────────────────────────
#: One luminous body on a void ground. Baked sprites (the perf rule: no
#: full-size allocation, nothing static rendered live), one reusable RGB
#: scratch box, one screen-blend of that box per frame. States ease, never
#: step (the CENTRE_RATE lesson): engagement lifts brightness and the halo,
#: thinking spins a violet outer ring, her own answer pulses the core, and
#: while she listens the ring carries one bright arc at the talker's
#: bearing — the legible, sci-fi version of the bezel bloom.
AURORA_BLOB = bool(_THEME.get("blob"))
#: ── RELIEF PANES WITHOUT THE REST OF AURORA (2026-08-26) ─────────────────
#: One gate is the reason a face looks 2-D. `_aur_wedge_sprite` is this
#: file's only real surface renderer for the wedge ring — height field,
#: normals, Blinn-Phong against AUR_KEY_L, a cast shadow — and it was
#: reachable only from draw_aurora_menu, which was reachable only from
#: `if AURORA_BLOB`. So every face that is not aurora drew its panes as
#: strokes, and the owner asked the same question about carbon on 08-26
#: that he asked about aurora on 08-16: "where is the depth".
#:
#: THIS FLAG IS THE RENDERER, NOT THE AESTHETIC. It is deliberately NOT
#: `blob`: turning that on would bring the luminous core, aurora's seven
#: panes at aurora's radii, aurora's hue ramp and its summon/idle
#: choreography, none of which the carbon brief asks for and three of
#: which contradict it. Everything the relief path needs that could differ
#: per face already answers per face — `wedges()`, `wedge_band()`,
#: `pane_names()` — so this key only decides HOW the pane is drawn, never
#: what or where it is.
#:
#: A row without the key is byte-identical: every branch this flag opens
#: is written as `if RELIEF_PANES`, and the four preview harnesses were
#: diffed before and after (gallery and aurora, 49 PNGs, md5-identical).
RELIEF_PANES = bool(_THEME.get("relief_panes"))
#: ── AND WHAT A RAISED PANE NEEDS THAT A RECESSED ONE DOES NOT ────────────
#: aurora's pane is SET INTO the bezel — the 2026-08-19 note in
#: _aur_wedge_sprite retired its cast shadow for a symmetric groove on
#: purpose, and AUR_RECESS darkens its border inward. carbon's brief is
#: the opposite word: "embossing, extrusion". So the relief branch flips
#: those two and states its own numbers here rather than moving aurora's.
#:
#: THE SPLIT ALPHA IS THE WHOLE TRICK, and it is what stops this being the
#: "bright fill" mistake the WGLASS note spent a paragraph on. The pane's
#: PLATEAU stays a low-alpha smoke, so home.html's baked label reads
#: through it exactly as it does under the flat tile today; the CHAMFER
#: WALLS go fully opaque, because a wall is machined metal and you cannot
#: see through the side of a step. Depth then comes from the chamfer, the
#: key and the contact shadow — never from making the pane light up.
RELIEF_BODY_A = 96.0        # the plateau: the smoke, WGLASS_FILL_A's kin
RELIEF_WALL_A = 255.0       # the chamfer: opaque metal
RELIEF_CAST_DX = 7.0        # down-right, away from AUR_KEY_L's upper-left
RELIEF_CAST_DY = 8.0
RELIEF_CAST_A = 168.0
RELIEF_CAST_BLUR = 5.5
#: ── AND A MACHINED STEP IS NARROW AND ITS TOP IS FLAT ────────────────────
#: aurora's pane is 15 px of smoothstepped chamfer with a 0.62 gradient
#: laid across its face. RENDERED on this ground and looked at, that is a
#: glass dome: the eye reads a wide soft ramp plus a graded top as ONE
#: curved surface, and the wedges came out as five lozenges of smoked
#: perspex. A milled chamfer is the other thing — a short, steep wall and a
#: FLAT land — and it is the land being flat that makes the wall read as a
#: wall. Both numbers are the same statement said twice, which is why they
#: move together and are written next to each other.
RELIEF_BEVEL = 9.0          # px of wall, was aurora's 15
RELIEF_KEY_GRAD = 0.20      # of face gradient, was AUR_KEY_GRAD 0.62
#: THE HIGHLIGHT IS THE ROOM'S LAMP, NOT AURORA'S. The specular and the
#: arris are hard-coded (200,232,255) and (190,226,255) — a cold blue-white
#: that belongs to a face built on a void. This row's whole material
#: argument is "cool graphite in shadow, WARM grey in the light" (see its
#: ramp), so a blue highlight is the one mark on it no lamp in that room
#: could have made. Taken from the theme's own top-of-ramp, so a row that
#: states a warmer or cooler ceiling gets a warmer or cooler sheen for
#: free and nothing here has to be re-tuned.
#: ── THE ARRIS TAKES THE LAMP (2026-08-26) ───────────────────────────
#: Owner: "use orange highlights on the borders for the wedges, it's a
#: good contrast to the CF black." He is right about the contrast and it
#: is the cheapest accent on the face: the arris is already the one place
#: the pane catches light, so colouring it costs no new element. A row may
#: name the colour; without the key it stays the top-of-ramp sheen every
#: other face has had.
RELIEF_LIGHT = (tuple(_THEME.get("relief_light"))
                if _THEME.get("relief_light")
                else (_THEME.get("white") or (232, 230, 223)))
#: ── AND THE PANE MUST COVER THE OUTLINE IT REPLACES ─────────────────────
#: home.html bakes a pale 2 px stroke around every sector, and that stroke
#: IS the flat wedge: it is the "2-d" the owner is pointing at. The relief
#: pane is drawn over it, but its own alpha ramps over 1.4 px at the
#: border, so the baked hairline came through at roughly half strength on
#: all four sides at once — a uniform outline that ignores the lamp, sat on
#: top of a surface that does not, and the composite read as a drawn shape
#: again even though the sprite on its own (rendered against a plain field,
#: which is how this was caught) reads as machined.
#:
#: THIS IS A DILATION OF THE PAINT, NOT A MOVE OF THE RING. Every radius
#: and angle still comes from `wedges()`/`wedge_band()` — the two-file band
#: contract at WEDGE_R0 is untouched and the hit-test is not consulted
#: about how wide a chamfer's anti-aliasing is. 2.5 px against a touch
#: target with 30 px of slop; scripts/test_modal_taps.py is the check that
#: this stayed cosmetic.
RELIEF_OUTSET = 2.5
#: ── AND THE TYPE IS PART OF THE SURFACE (2026-08-26, second pass) ────────
#: Owner: "raise the type." The first relief pass left the label and the
#: icon as FLAT INK read through a smoked plateau — its own closing note
#: says so — because carbon's art lives in home.html's bake and the sprite
#: had no way to see it. The whole of the fix is that it can: the bake is a
#: file on disk (_base_bake_path), the sprite is built once per bake, and
#: what a pane needs is the ink under its own footprint.
#:
#: SO THE PANE TAKES THE TYPE OVER, and that is a real change of ownership
#: rather than an effect laid on top. Three things follow from it and they
#: are one decision, not three:
#:   1. the ink is added to the HEIGHT FIELD before the normals — the
#:      2026-08-16 note twelve hundred lines down ("THE ICON IS GEOMETRY,
#:      NOT PAINT") is the argument, and it applies verbatim to a label;
#:   2. the plateau goes OPAQUE, because a raised label and the flat one it
#:      was sampled from cannot both be on the glass — that is the "two
#:      BRIEFING marks on one sector" the first pass refused, arriving from
#:      the other direction;
#:   3. and once the sprite owns the type it can SEAT it, which is the only
#:      way this face's label was ever going to be centred: home.html bakes
#:      it and this workstation has no browser to re-bake with.
#: The plateau's smoke (RELIEF_BODY_A) is NOT deleted — it is what a pane
#: wears when no bake can be read, which is the one state in which the
#: baked type must keep showing through (§1).
#:
#: THE SEPARATION IS A HIGH-PASS, and the numbers are measured on the
#: standing bake rather than chosen. Over a 9 px neighbourhood the type
#: runs 60..179 above its own ground, the sector strokes similar, and the
#: waffle field peaks near 30. CORE 46 is comfortably above the waffle and
#: below the thinnest stroke of the sub-label; SOFT 16 lets a core pixel
#: claim its own anti-aliasing so the letters keep their edges; GROW is how
#: far that claim reaches. Rendered to data/glass/carbon/type_mask.png and
#: LOOKED AT — five clean groups, no waffle, no border furniture.
RELIEF_TYPE_BLUR = 9.0
RELIEF_TYPE_CORE = 46.0
RELIEF_TYPE_SOFT = 16.0
RELIEF_TYPE_GROW = 3
#: ── AND THE FLANKS ARE READ FURTHER IN THAN THE ARCS ─────────────────────
#: The sample window is the PLATEAU — everything at less than a chamfer's
#: depth is the bake's own border furniture (the 2 px sector stroke, the
#: occluded hairline at inset 2.2, STERLING's gold ring at inset 5) and is
#: under an opaque wall anyway. The two flanks get more than that, and it
#: is not symmetry-for-its-own-sake: home.html paints a chevron in the 86..90
#: degree GAP between SETTINGS and VOLUME, half of it inside VOLUME's
#: sector, and read as this pane's type it would anchor the group at the
#: flank and forbid every useful move.
#:
#: 12 IS MEASURED AND IT SITS IN THE MIDDLE OF A GAP. Swept 8..20 px on the
#: standing bake: at 8 the chevron is in and pins VOLUME's group at 8.5 px
#: from its own cw edge; at 10 it is gone (the pane loses ONE pixel and the
#: binding clearance jumps to 76); nothing else in the ring changes at all
#: until 20, where BRIEFING's label starts losing 18 px of its ccw end. So
#: the window either side of 12 is wide, which is the difference between a
#: threshold and a guess (§3).
RELIEF_TYPE_FLANK_PAD = 12.0
#: how much clearance the icon+label group is ENTITLED to, from its own ink
#: to the perceived edge — the top of the chamfer, not the geometric border,
#: because the top of the chamfer is the edge the eye draws. MEASURED on the
#: standing bake before the seat existed: SETTINGS 0.2 px, VOLUME 0.2,
#: STERLING 2.7, LOCK 8.2, BRIEFING 8.7. Three of the five were touching
#: it. The owner: "the icon / text still is not centered correctly in the
#: wedges, they are near overlapping the perceived edge."
#:
#: 10 IS THE HOUSE MINIMUM AND IT IS BORROWED, NOT INVENTED — home.html's
#: own seating note sets its wedge content "at >=12 units (>=13 px on the
#: 1080 panel), House minimum 10". Same rule, measured against the edge
#: the relief actually draws instead of against the baked stroke.
RELIEF_TYPE_CLEAR = 10.0
#: and the ladder it is allowed to shrink down if translation alone cannot
#: buy that clearance. STERLING is why this exists rather than being an
#: unused generality: "STERLING" is a long word at 3 o'clock, where a
#: horizontal row's ENDS reach further out in radius than its middle, so
#: the group is wider in the radial direction than the band can hold and no
#: translation on earth centres it. Shrinking is the last resort and the
#: rungs are shallow, because a re-sampled baked glyph loses a little edge
#: every step. On the standing bake exactly one pane uses it: STERLING, at
#: 0.92, which buys it 2.7 px -> 10.4. The other four seat at 1.00.
RELIEF_TYPE_SCALES = (1.0, 0.98, 0.96, 0.94, 0.92, 0.90, 0.88, 0.85)
#: how far the group may travel, px. Wide enough for the worst seat on the
#: ring (BRIEFING moves 36) and bounded so a mis-read mask can never fling
#: a label into the next sector.
RELIEF_TYPE_TRAVEL = 34
#: how much of the worst margin a seat may give up to be BALANCED instead
#: — see the objective's own note in _relief_type. 1.5 px is under the
#: chamfer's anti-aliasing and buys a group that is centred rather than
#: merely legal.
RELIEF_TYPE_TOL = 1.5
#: the strike, POSITIVE — this is the one place in this function where the
#: relief goes UP. AUR_GLYPH_CUT is aurora's engraved glyph and its whole
#: 08-20 note is about the sign; a label struck into a plateau with the
#: same sign would be an intaglio inscription, which is not what "raise the
#: type" asks for and not what a machined control panel does with its
#: legends.
RELIEF_TYPE_RAISE = 1.85
#: the raised type's own shadow, cast DOWN-RIGHT onto the plateau (the key
#: is upper-left) and kept OUTSIDE the letters, where a real shadow is.
#: aurora's AUR_GLYPH_AO is the opposite object — contact occlusion INSIDE
#: a cut — and the two must not be one constant (§15 in reverse: they only
#: look like the same number).
RELIEF_TYPE_AO = 0.42
#: and the gain that pays back what the lighting takes. The type's albedo
#: is the bake's own luminance through _colourway — i.e. exactly the colour
#: it has on the glass today — but a flat plateau under the house key sits
#: at 0.30 + 0.90 * 0.57 = 0.81 of its albedo, so a faithful sample would
#: arrive 19% darker than the flat ink it replaces. CHECKED ON THE RENDER
#: rather than trusted: mean of the brightest 260 px over each label's own
#: box, flat ink -> raised, BRIEFING 222 -> 219, VOLUME 218 -> 229,
#: STERLING 221 -> 196 (that one is also 8% smaller). The type is no
#: dimmer than the ink it replaces, which is the property that had to
#: hold — legibility across a room is luminance and nothing else.
RELIEF_TYPE_GAIN = 1.24
#: and the unconditional floor under the letters, as a fraction of the
#: row's own top-of-ramp. aurora's equivalent is a fixed cool triple; the
#: reason it has to exist at all is in the note beside it.
RELIEF_TYPE_LIFT = 0.20
#: ── THE UI IS SUMMONED, NOT WORN (2026-08-16) ────────────────────────────
#: Owner: "make sure we can make it usable with all the functionality
#: except ported for this new simplistic style." The five wedges and their
#: tenants are how this device is DRIVEN by hand, so they cannot simply be
#: deleted — an invisible control is the silent-success shape in glass
#: (§1). They are TRANSIENT instead: a touch raises the whole ring, it
#: holds while you work, and it fades back into the void a few seconds
#: after your hand leaves. Voice needs none of it, which is the point.
#: ── THE REVEAL (2026-08-16) ──────────────────────────────────────────────
#: Owner: "i want the wedges to appear anytime the screen is first unlock
#: and then fade in one by one clockwise, elegantly... if they touch the
#: screen they fade in elegantly and another click they fade out or when
#: the interface is not used they fade out gracefully."
#:
#: So the ring is a MODE with three ways in and three ways out, and every
#: one of them is a ramp:
#:   in   — the unlock (it introduces the device), a touch, a drag
#:   out  — a second touch (a toggle: the same gesture undoes itself),
#:          the idle timer, or the show taking the glass
#: The stagger runs in WEDGE ORDER, which is already clockwise from the
#: upper right — index order and screen order are the same thing here, so
#: "one by one clockwise" needs no sorting, only a delay per index.
#: ── THE PACE (2026-08-16, twice) ─────────────────────────────────────────
#: Owner: "the fade in for the wedges are way too fast... the fade in has
#: to be dramatic so people can see the transition, it has to look
#: beautiful", and then: "so slow it down."
#:
#: The first cut ran 0.11 s apart over 0.46 s each — the whole ring was up
#: in under a second, which the eye reads as a POP, not an arrival. These
#: numbers are chosen so a person can WATCH it happen: each pane takes
#: most of a second to materialise, and the five of them walk round the
#: dial over about two and a half. Leaving is slower still, because the
#: only thing worse than a control that appears too fast is one that
#: vanishes while you are still deciding.
AUR_UI_HOLD_S = 12.0
#: ── THE STAGGER GAVE BACK ITS SHARE (2026-08-19) ───────────────────────
#: Owner, at the glass: "the puck has a regression where the wedges are no
#: longer transitioning in correctly they used to fade in, now they are
#: just there and the highlights for the wedges do still come up but the
#: fade in process is gone."
#:
#: HE IS DESCRIBING AN ARITHMETIC ACCIDENT, NOT A BROKEN PAINTER. Measured
#: off the real schedule, first pane, at the moment he reported it:
#:
#:     before 2026-08-18   pane 0 fades over 0.84 s   21 frames at 25 fps
#:     as he saw it        pane 0 fades over 0.44 s   11 frames
#:     now                 pane 0 fades over 0.88 s   22 frames
#:
#: What happened: on 08-18 he asked to "trim the arrival time to
#: approximately 3 seconds", and AUR_UI_ARRIVE_S was added to scale the
#: WHOLE schedule to hit it — delay and duration together, which is the
#: right way to keep the shape. But the shape spent 3.12 of its 5.74
#: seconds on STAGGER, so scaling it uniformly took 46% off the dead time
#: and 46% off the fade, and the fade is the only part anybody watches.
#: The first pane, which is the one the eye is already on when the ring
#: opens, was left with eleven frames — and eleven frames of a per-pixel
#: condensation is a pane appearing.
#:
#: THE GENERAL FORM, because this will happen again: NORMALISING A TOTAL
#: OVER A SHAPE THAT IS MOSTLY DEAD TIME SPENDS THE ANIMATION. If a
#: gesture has a visible part and a waiting part and you shorten the whole
#: thing proportionally, the visible part takes the same percentage cut
#: while being a much smaller number to start with.
#:
#: So the 3.0 s total is UNCHANGED — it is his — and the shape inside it
#: is rebalanced: less stagger, and a per-pane duration whose FLOOR is
#: most of it rather than a fifth of it. Every pane now gets 0.88-1.56 s
#: of its own fade inside the same three seconds. What that costs is
#: written down rather than discovered later: the panes overlap more, so
#: the ring reads slightly less as seven things arriving in turn and more
#: as one thing sweeping round. Seven panes, three seconds and a fade you
#: can watch are three constraints and only two of them fit; the fade is
#: the one he asked for twice ("it has to look beautiful", and this), so
#: the sequence is what gives.
AUR_UI_STAGGER = 0.34        # between one wedge lighting and the next
AUR_UI_IN_S = 1.35           # each wedge's own fade in
AUR_UI_OUT_S = 1.35          # and out — SAME speed, the owner's ask
#: The per-pane duration profile: `AUR_UI_OUT_S * (FLOOR + GROWTH * k)`.
#: Named, and stated ONCE, because `_ui_step` needs them twice — inside
#: the normalisation and inside the answer — and two copies of a shape
#: that must agree is exactly the drift §15 is about. 0.62/0.22 -> 0.92/
#: 0.12: the first pane keeps most of the fade the last one gets, and the
#: last one still lingers, which is the deceleration he asked for.
AUR_UI_DUR_FLOOR = 0.92
AUR_UI_DUR_GROWTH = 0.12
#: ── THE FLOOR ON A FADE, IN FRAMES, STATED ONCE (2026-08-19) ───────────
#: Below this many frames a per-pixel condensation stops reading as a pane
#: arriving and starts reading as a pane switching on. Eleven was what he
#: complained about; twenty-one was what he had liked the day before.
#:
#: It is a MODULE constant and not a number in the test, because three
#: places have an opinion about it — the schedule log at show time, the
#: painter's own arrival report, and scripts/test_wedge_arrival.py — and
#: §15 is exactly about what happens when a shared policy is written down
#: three times. The test imports this; it does not carry its own copy.
AUR_ARRIVE_MIN_FRAMES = 15


#: ── ONE SCHEDULE, WALKED FORWARDS OR BACKWARDS (2026-08-17) ─────────────
#: Owner: "make the wedges fade in the same pace that the fade out of the
#: wedges happens. right now fade in is faster, keep the same pace
#: symmetrical and make the fade in for the wedges the same profile as the
#: fade out timeline."
#:
#: He is right, and the two schedules had drifted into opposites. Entry
#: used a TIGHTENING stagger and a duration that shrank 13% per pane
#: (1.35s down to 0.65s — "gathers pace as it comes round"). Exit used a
#: constant stagger and a duration that GREW 22% per pane (0.84s up to
#: 2.03s — "slowest for the last ones to go"). Each was asked for
#: separately, each was implemented faithfully, and together they made a
#: ring that snapped open and drained shut.
#:
#: So there is now one function, and the direction is the only difference:
#: pane k in its own sequence gets the same delay and the same duration
#: whether that sequence is arriving or leaving. Entry order is clockwise
#: (k = i), exit order is counter-clockwise (k = n-1-i), so the first pane
#: to arrive is the last to leave and the whole gesture reverses exactly.
#: AUR_UI_IN_S is deliberately no longer read — one place states the pace
#: (PRINCIPLES §15) and it is AUR_UI_OUT_S.
#: -- A BRIEFING DOES NOT WAIT FOR THE BALLET (2026-08-17) ---------------
#: Owner: "the wedges and aura vision should fade out when the briefing is
#: given." They already did -- the compositor calls aurora_ui_hide the
#: frame a show comes up -- but they took 5.73 s to finish, measured, and
#: her first sentence starts immediately. From the seat that is not "it
#: cleared", it is "it was still there while she talked".
#:
#: The dissolve itself is right and he asked for it twice: decelerating,
#: counter-clockwise, the last pane holding the stage. That is the answer
#: to a PERSON dismissing the ring, where the gesture is the point. A show
#: taking the glass is not a gesture, it is a scene change, and a scene
#: change is quick. So the same schedule is simply run fast: every delay
#: and every duration scaled by one number, which keeps the shape of the
#: exit -- same order, same deceleration, same curve -- and finishes it
#: inside a second.
#: ── STATED AS A DURATION, NOT A RATIO (2026-08-18) ─────────────────────
#: This was `AUR_UI_SHOW_EXIT_K = 0.17`, a multiplier chosen because 0.17 x
#: 5.73 s landed just under a second. Trimming the arrival to 3 s moved the
#: thing it multiplies, so the same 0.17 quietly became 0.51 s and the
#: comment next to it became false — the exact failure the ratio was
#: introduced to avoid, one level up. A number derived from another number
#: needs to be derived in the code, not in someone's head at the time.
AUR_UI_SHOW_EXIT_S = 0.95     # a scene change, not a gesture


def _ui_show_exit_k() -> float:
    """The scale that makes a briefing's dismissal take EXIT_S."""
    return (AUR_UI_SHOW_EXIT_S / AUR_UI_ARRIVE_S) if AUR_UI_ARRIVE_S else 1.0


#: ── THE WHOLE GESTURE TAKES THREE SECONDS (2026-08-18) ─────────────────
#: Owner: "trim the arrival time to approximately 3 seconds for the ring."
#:
#: It was 5.74 s, which is the number the exit note above already measured
#: and which nobody had connected to the arrival — the same schedule runs
#: both, so the ring took as long to appear as it did to leave.
#:
#: Stated as the TOTAL rather than as two constants to hand-tune. The pair
#: below are the SHAPE of the gesture — how much of it is stagger against
#: how much is each pane's own fade, and the 0.22 that makes later panes
#: linger — and that shape is his, adjusted over several evenings. Scaling
#: them to hit a target keeps every bit of it and changes only the tempo.
#:
#: It also survives the pane count changing. The ring has been five panes
#: and is seven; with two hand-set constants, adding one would have
#: silently added 0.52 s to a duration nobody would think to re-measure.
AUR_UI_ARRIVE_S = 3.0        # first pane starting to last pane landed

#: ── HOW MUCH A PANE'S SIZE MAY STRETCH ITS OWN FADE ───────────────────
#: The ring's widths vary by more than two to one, so an unclamped ratio
#: would make the narrowest pane a flicker and the widest a crawl. These
#: bound it to a range that reads as "the big one takes a moment longer"
#: rather than as two different animations. See _ui_step.
AUR_UI_SIZE_W_MIN = 0.80
AUR_UI_SIZE_W_MAX = 1.30


def _ui_step(k: int, hurry: bool = True) -> tuple:
    """(delay, duration) for the k'th pane in its own sequence.

    Scaled by `hide_k` when the current transition is a show taking the
    glass. One place computes the schedule for the panes AND the wordmark
    AND both tests, so the fast exit cannot apply to one and not the other
    (S15) -- which is exactly how the wordmark would otherwise be left
    hanging on the glass for five seconds after the ring had gone.

    `hurry=False` asks for the gesture AS DESIGNED, with the briefing's
    scene-change scale left off. Exactly one caller wants that —
    `_aur_ui_dt_cap`, which sizes the per-frame clamp from the ARRIVAL's
    own first pane and must not shrink that clamp to a fifth whenever a
    briefing happens to be dismissing the ring. Everything that draws
    wants the scaled answer, so it is the default.
    """
    k_s = (_AUR_UI.get("hide_k") or 1.0) if hurry else 1.0
    #: normalise the shape to AUR_UI_ARRIVE_S for the CURRENT pane count.
    #: The last pane is the one that ends the gesture, so it sets the scale.
    #: ── AND THIS IS THE LINE THAT ATE THE FADE (2026-08-19) ──────────
    #: Read the note on AUR_UI_STAGGER before touching any of these four
    #: numbers. This scaling is correct and is not the bug; the bug was
    #: that it was applied to a shape which was 54% stagger, so the fade
    #: paid the same 46% the dead time did while being half the size.
    #: If a future brief shortens AUR_UI_ARRIVE_S again, the thing to
    #: check is `_ui_step(0)[1]` — the FIRST pane's own duration, which is
    #: the smallest one and therefore the first to become invisible.
    #: ── THAT SENTENCE IS FALSE NOW, AND IT COST FOUR FIXES ────────────
    #: (2026-08-20) It was true when it was written and the size-weighting
    #: DIRECTLY BELOW inverted it the same day: widest fades longest, and
    #: pane 0 is the widest, so pane 0 now has the LONGEST duration, not
    #: the smallest. `_aur_ui_dt_cap` read this note, trusted it, and sized
    #: the per-frame clamp from the loosest pane instead of the tightest —
    #: which left panes 3-6 under the frame floor at every rate between 7.3
    #: and 11.2 fps, which is the band the device actually delivers while
    #: the ring is arriving. See the measurement in _aur_ui_dt_cap.
    #: The correct read is `min(_ui_step(j)[1] for j in range(len(wedges())))`
    #: and it is left as an expression rather than a pane index on purpose:
    #: the next weighting change will invert this again.
    #: ── A BIG PANE TAKES LONGER TO ARRIVE THAN A SMALL ONE ───────────
    #: Owner: "wedge transition in still is off, it looks like it doesn't
    #: take into account the differing sizes of the wedges as they rotate
    #: clockwise."
    #:
    #: He is describing exactly what the arithmetic did. The ring is
    #: GRADUATED — wedges() hands back seven panes of different angular
    #: span, and wedge_band(i) gives each its own thickness — but the
    #: duration here grew only with the INDEX k. So the widest pane and
    #: the narrowest faded over the same time, which sweeping clockwise
    #: reads as the small ones snapping and the big ones dragging.
    #:
    #: Weighted by the pane's own span against the mean, clamped, because
    #: an unclamped ratio would make the narrowest pane a flicker on a ring
    #: whose widths already vary by more than two to one — and the 15-frame
    #: floor exists precisely to stop a pane APPEARING rather than
    #: arriving.
    #:
    #: THE GESTURE STILL ENDS WHEN IT ENDS: the normalisation below divides
    #: by the LAST pane's weighted duration, so AUR_UI_ARRIVE_S remains
    #: what it says it is and every test that asserts the total is
    #: unaffected. What changes is how the time is shared out.
    _wg = wedges()
    _n = max(1, len(_wg))
    _spans = [max(1e-6, (a1 - a0)) for a0, a1, _c in _wg]
    _mean = sum(_spans) / float(_n)
    #: ── k IS NOT ALWAYS AN INTEGER ────────────────────────────────────
    #: `_mark_alpha` asks for the schedule at a FRACTIONAL pane — it
    #: interpolates the wordmark's fade between two panes — and every
    #: expression here before today was arithmetic, which does not care.
    #: The moment the span became a list LOOKUP it did: TypeError, caught
    #: by the painter's never-raises guard, and the whole ribbon silently
    #: went blank. Rounded and clamped, so a fractional pane takes the
    #: nearer pane's width and no caller has to change.
    _ki = max(0, min(_n - 1, int(round(k))))
    _w = min(AUR_UI_SIZE_W_MAX,
             max(AUR_UI_SIZE_W_MIN, _spans[_ki] / _mean))
    _wlast = min(AUR_UI_SIZE_W_MAX,
                 max(AUR_UI_SIZE_W_MIN, _spans[_n - 1] / _mean))
    #: ── AND SIZE REPLACES INDEX, IT DOES NOT MERELY MODULATE IT ──────
    #: The first cut multiplied the existing `DUR_FLOOR + GROWTH * k` by
    #: the size weight, and measured:
    #:
    #:     pane 0  span 38.2  w 1.27  dur 1.22   <- the WIDEST, fading FASTEST
    #:     pane 6  span 25.1  w 0.84  dur 1.43
    #:
    #: because the index term grows faster than the weight shrinks. On this
    #: ring the panes get NARROWER as the index rises, so "later panes
    #: linger" and "bigger panes take longer" point in opposite directions
    #: and the older intention won. That is the same complaint he made,
    #: with an extra multiply in front of it.
    #:
    #: So every pane now takes the SAME base duration — the one the last
    #: pane used to get, which is what the gesture was tuned around — and
    #: its own span is the only thing that moves it. Widest fades longest,
    #: narrowest quickest, in the order they sweep.
    _base = AUR_UI_OUT_S * (AUR_UI_DUR_FLOOR
                            + AUR_UI_DUR_GROWTH * (_n - 1))
    _raw = (_n - 1) * AUR_UI_STAGGER + _base * _wlast
    k_s *= (AUR_UI_ARRIVE_S / _raw) if _raw > 1e-6 else 1.0
    return (k * AUR_UI_STAGGER * k_s, _base * _w * k_s)


def _ui_from(i: int, default: float) -> float:
    """Where pane i was when the current transition began.

    `default` is what to assume when there is no record — 1.0 for an exit
    (fully arrived) and 0.0 for an entry (not yet here), which are the
    values those directions used before `from_a` existed. Deliberately
    tolerant of a short list: WEDGES could change length between a
    transition starting and this being read, and a face that raises here
    takes the compositor with it.
    """
    fa = _AUR_UI.get("from_a") or ()
    return float(fa[i]) if i < len(fa) else default
#: A DISMISS THE DIAL CANNOT OVERRULE (2026-08-17). See aurora_ui_tick.
AUR_UI_REARM_S = 8.0
#: `from_a` is where each pane WAS when the current transition began — see
#: the note on aurora_ui_hide. Empty means "assume fully arrived", which is
#: the only safe default for an exit that starts without one.
#: `hide_k` scales the exit schedule: 1.0 for a person dismissing the ring,
#: _ui_show_exit_k() for a briefing taking the glass. Reset on every
#: arrival so a fast exit can never leak into the next entrance.
_AUR_UI: dict = {"show_t0": 0.0, "hide_t0": 0.0, "vis": False,
                 "last": 0.0, "user_hide_at": 0.0, "from_a": [],
                 "hide_k": 1.0}


#: ── A TRANSITION STARTS FROM WHERE THE PANES ARE (2026-08-17) ───────────
#: Owner: "inexplicably, when there are no wedges showing on my screen,
#: when i tap the screen it shows all the wedges suddenly and then it fades
#: them out. the real behavior is they fade in if they are not displayed."
#:
#: The log named it: `tap: aurora ring dismissed` with no `summoned` beside
#: it — the same signature as the 08-17 toggle bug, and NOT the same cause,
#: which is why the test for that one still passes.
#:
#: What actually happens: he taps, the ring is summoned and begins a 4.11 s
#: staggered entry. He taps again a second later — reasonably, nothing much
#: has appeared yet — and that second tap lands off-pane, so it dismisses.
#: The exit's alpha was `1.0 - max(0, t)/dur`, and for every pane whose
#: stagger delay has not elapsed t is NEGATIVE, so `max(0, t)` is zero and
#: the pane reports **alpha 1.0**. Five panes that were at 0.2, 0.1, 0.0,
#: 0.0, 0.0 all snap to full and then fade out in order. From the chair:
#: they appear suddenly and drain away, which is exactly what he described.
#:
#: This was always latent — the old exit had the same shape — but the old
#: entry finished in ~2.6 s and the symmetric one takes 4.11 s, so the
#: window in which a second tap produces the pop roughly doubled. Making a
#: rare bug easy to hit is shipping it.
#:
#: The fix is that a transition begins where the panes ARE. `from_a` is
#: sampled at the instant of the turn, and both directions move from it at
#: the schedule's RATE (subtract/add, never scale — scaling would stretch a
#: dim pane's exit into a long ghost). The gesture is now reversible
#: mid-flight in both directions, and no pane's alpha ever jumps.
#: ── THE VOICE PULLS THE SAME LEVER AS THE FINGER (2026-08-17) ───────────
#: puck_conduct touches one of these when it hears "show menu" / "hide the
#: menu". Polled once per frame — two stat calls, and only on this face.
#: The flag is CONSUMED on read, so a stale one from a killed conductor
#: raises the ring once and never again.
MENU_SHOW = Path("/tmp/aura_face/menu_show")
MENU_HIDE = Path("/tmp/aura_face/menu_hide")
#: ── AND A TOGGLE, DECIDED HERE (2026-08-18) ───────────────────────────
#: The conductor sends this when a short line names the ring but no
#: DIRECTION survived transcription — "hi menu", "or a hard menu", "it
#: works on the menu", "so many", all of which are one command in a room.
#:
#: It resolves HERE because this file owns whether the ring is up. Having
#: the conductor track that would be a second copy of a state that is
#: already authoritative on this side, and the two would drift the first
#: time a tap raised the ring without a word being said (S15).
MENU_TOGGLE = Path("/tmp/aura_face/menu_toggle")


def aurora_menu_voice(now: float) -> None:
    """Act on a spoken menu command. Never raises; says what it did."""
    try:
        if MENU_SHOW.exists():
            MENU_SHOW.unlink(missing_ok=True)
            aurora_ui_show(now)
            print("voice: MENU shown — same arrival as a tap", flush=True)
        if MENU_TOGGLE.exists():
            MENU_TOGGLE.unlink(missing_ok=True)
            #: up means anything other than fully gone: a ring still
            #: arriving, or one part-way through its exit, both read as
            #: "on screen" to the person looking at it, and a toggle has
            #: to agree with the eye rather than with the state machine
            _up = _AUR_UI["vis"] and not _AUR_UI["hide_t0"]
            if _up:
                aurora_ui_hide(now, by_user=True)
                print("voice: MENU toggled — was up, dismissed", flush=True)
            else:
                aurora_ui_show(now)
                print("voice: MENU toggled — was down, summoned", flush=True)
        if MENU_HIDE.exists():
            MENU_HIDE.unlink(missing_ok=True)
            #: by_user, so the dial cannot re-summon it for AUR_UI_REARM_S —
            #: asking for it to go away by voice is as deliberate as
            #: waving it away by hand
            aurora_ui_hide(now, by_user=True)
            print("voice: MENU dismissed", flush=True)
    except Exception as exc:                            # noqa: BLE001
        print(f"voice: menu flag failed {exc!r}", flush=True)


def aurora_ui_show(now: float = None) -> None:
    n = time.time() if now is None else now
    #: only when it is actually ARRIVING — a re-summon of a ring that is
    #: already fully up (the dial nudged, a second tap on a pane) must not
    #: re-announce itself, or the sound becomes noise
    if not _AUR_UI["vis"] or _AUR_UI["hide_t0"]:
        _ui_sound("up")
    _AUR_UI["from_a"] = [_aurora_ui_alpha(n, i)
                         for i in range(len(wedges()))]
    #: hide_k back to 1.0 on every arrival. It scales `_ui_step`, which
    #: serves the ENTRANCE as well as the exit, so a fast show-takeover
    #: left in place would make the next summon snap in at six times speed
    #: — a state that only ever appears after a briefing, which is the
    #: hardest kind of bug to reproduce on purpose.
    _AUR_UI.update(show_t0=n, hide_t0=0.0, vis=True, last=n, hide_k=1.0,
                   #: ── THE CLOCK STARTS HERE, NOT WHEREVER IT WAS ─────
                   #: `aurora_menu_voice` runs BEFORE `aurora_ui_tick` on
                   #: purpose (a spoken summon advances on this very frame),
                   #: so without this line the very first `_aur_ui_stall`
                   #: after the summon charges this arrival for a gap that
                   #: happened before it existed — a lock screen, a sleep,
                   #: or the whole of process start-up. See _aur_ui_inflight.
                   tick_t=n,
                   #: per-arrival, so the held-back line below is said once
                   #: for THIS summon and not once per process — a startup
                   #: storm and a compositor that stalls at 11am are two
                   #: different reports and both are worth having
                   stalled=0.0, stall_said=False,
                   #: ── AND AN ARRIVAL NEEDS AN ID THAT DOES NOT MOVE ──
                   #: `show_t0` was the obvious identity for "which arrival
                   #: is this" and it is the wrong one, because
                   #: `_aur_ui_stall` MUTATES it — so the painter's counter
                   #: keyed on it re-opened itself every stalled frame and
                   #: reported [0,0,0,0,0,0,0] for an arrival that was
                   #: painting perfectly well. Caught by the starved-frame
                   #: case in scripts/test_wedge_arrival.py, which is the
                   #: only reason it is not on the puck right now: the two
                   #: halves of the same fix broke each other and each was
                   #: individually correct (§15, one more time).
                   show_n=(_AUR_UI.get("show_n") or 0) + 1)
    #: ── SAY WHAT THE ARRIVAL IS ACTUALLY GOING TO BE (2026-08-19) ──────
    #: PRINCIPLES §1. "The fade in process is gone" was true for a day and
    #: nothing in any log said so, because the schedule was a derived
    #: quantity that existed only as pixels: four constants, a pane count
    #: and a normalisation, none of which is the number that matters. The
    #: number that matters is THE FIRST PANE'S OWN DURATION IN FRAMES,
    #: because it is the smallest and therefore the first to stop being an
    #: animation, and it is printed here once per process so that the next
    #: time somebody trims the gesture the cost shows up in the log beside
    #: the change rather than on the glass a day later.
    if not _AUR.get("sched_said"):
        _AUR["sched_said"] = True
        _n = max(1, len(wedges()))
        _d0, _u0 = _ui_step(0)
        _dn, _un = _ui_step(_n - 1)
        _fps = AUR_IDLE_FPS if "AUR_IDLE_FPS" in globals() else 25.0
        print(f"aurora: ring arrival {_dn + _un:.2f}s over {_n} panes — "
              f"first pane fades in {_u0:.2f}s ({_u0 * _fps:.0f} frames at "
              f"{_fps:.0f} fps), last {_un:.2f}s, stagger "
              f"{AUR_UI_STAGGER * (_dn / max(1e-6, (_n - 1) * AUR_UI_STAGGER)):.2f}s"
              #: the frame count above is what a 26 fps face would give and
              #: this face has never once measured 26 — the floor below is
              #: what it gets at ANY rate, and the two being different
              #: numbers is the whole point of the clamp (§1: say which)
              + f", floor {AUR_ARRIVE_MIN_FRAMES} frames at any rate "
                f"({_aur_ui_dt_cap() * 1000:.0f} ms per-frame cap)"
              + (f"  *** UNDER {AUR_ARRIVE_MIN_FRAMES} FRAMES: this reads as "
                 f"the pane APPEARING, not arriving — see the note on "
                 f"AUR_UI_STAGGER ***"
                 if _u0 * _fps < AUR_ARRIVE_MIN_FRAMES else ""), flush=True)


def aurora_ui_hide(now: float = None, by_user: bool = False,
                   quiet: bool = False) -> None:
    n = time.time() if now is None else now
    if _AUR_UI["vis"] and not _AUR_UI["hide_t0"]:
        #: `quiet` is for the compositor's own housekeeping — a briefing
        #: taking the glass hides the ring, and that is the SHOW's entrance,
        #: not the ring's exit. Chirping under her first sentence would be
        #: the device talking over itself.
        if not quiet:
            _ui_sound("down")
        _AUR_UI["from_a"] = [_aurora_ui_alpha(n, i)
                             for i in range(len(wedges()))]
        #: read the scale BEFORE the clock starts, and read it from the
        #: same `quiet` flag that already distinguishes the two callers --
        #: a briefing's takeover is exactly the case that passes quiet
        _AUR_UI["hide_k"] = _ui_show_exit_k() if quiet else 1.0
        _AUR_UI["hide_t0"] = n
        #: same reason as the `tick_t` line in aurora_ui_show: the briefing
        #: branch of the compositor calls this BEFORE the tick, and a
        #: dissolve must not be charged for the frames that preceded it
        _AUR_UI["tick_t"] = n
        _AUR_UI["stalled"], _AUR_UI["stall_said"] = 0.0, False
    #: Recorded even if a hide was already running: what matters is the
    #: last time a PERSON said "go away", not which call set the clock.
    if by_user:
        _AUR_UI["user_hide_at"] = n


def aurora_ui_hurry_exit(now: float = None) -> None:
    """Finish a dissolve that is already running, fast, from where it is.

    ONE owner for this, because there are two callers and they used to
    disagree: `aurora_ui_touched` and the aurora branch of `handle_tap`
    each carry their own copy of "is the ring visible", and the fix for
    the re-summon bug went into the first of them — which the touchscreen
    never calls. The second is the live path. A behaviour stated in two
    places is a behaviour implemented in one of them (S15).
    """
    n = time.time() if now is None else now
    if not _AUR_UI["hide_t0"]:
        return
    _AUR_UI["from_a"] = [_aurora_ui_alpha(n, i)
                         for i in range(len(wedges()))]
    _AUR_UI["hide_k"] = _ui_show_exit_k()
    _AUR_UI["hide_t0"] = n
    _AUR_UI["tick_t"] = n            # see aurora_ui_show
    _AUR_UI["user_hide_at"] = n


def aurora_ui_touched(now: float = None) -> None:
    """A hand on the glass TOGGLES the ring — the same gesture that calls
    it back dismisses it, which is the behaviour a person guesses first."""
    n = time.time() if now is None else now
    #: ── A TAP DURING THE EXIT IS NOT A SUMMON (2026-08-17) ──────────────
    #: Owner: "weird behavior my touches no longer make the widgets fade."
    #: The log had nine `aurora ring summoned` in a row and not one
    #: `dismissed` — the mirror image of the bug this file already carries
    #: a long note about, and with the same root: the toggle asking a
    #: question whose answer changes underneath it.
    #:
    #: The exit takes 5.73 s by design (decelerating, counter-clockwise,
    #: the last pane holding the stage — he asked for that twice). For all
    #: of those 5.73 s `hide_t0` is set, so this branch read "not fully
    #: visible" and summoned. Tap to dismiss, tap again a second later
    #: because nothing seems to have happened, and the ring comes back. It
    #: never gets to leave, and from the chair the touches simply stop
    #: working.
    #:
    #: A person tapping again during a dissolve is not asking for the ring;
    #: they are asking, harder, for it to go. So the second tap CUTS THE
    #: EXIT SHORT rather than reversing it — visible progress, in the
    #: direction they meant, and the third tap (with the ring actually
    #: gone) summons as it always did.
    #: RESTARTED from where the panes actually are, not merely rescaled.
    #: `_ui_step` scales the delay as well as the duration, so dropping
    #: hide_k under a running clock moves every pane's start time backwards
    #: and the alphas jump — a snap, not a hurry. Re-seeding `from_a` with
    #: the current alphas and restarting the clock is the same trick the
    #: reversible show/hide already uses, and it is smooth.
    if _AUR_UI["hide_t0"]:
        aurora_ui_hurry_exit(n)
        return
    if _AUR_UI["vis"]:
        aurora_ui_hide(n, by_user=True)
    else:
        aurora_ui_show(n)


#: ── THE ANIMATION MUST NOT RUN WHILE NOBODY IS BEING SHOWN IT ─────────
#: (2026-08-19) The `[0, 0, 0, 0, 0, 0, 1]` line. The painter's own
#: arrival counter, one restart after it was added, on puck-10634:
#:
#:     aurora: ring ARRIVED — panes condensed over [0,0,0,0,0,0,1] frames
#:       *** BRIEFING, SLEEP, VOLUME, SETTINGS, STERLING, LOCK PAINTED NO
#:       CONDENSATION AT ALL: the fade did not run, it was SKIPPED ***
#:
#: Six of seven panes went from nothing to fully landed BETWEEN TWO
#: CONSECUTIVE PAINTED FRAMES. Not a short fade — no fade. And it is not
#: reproducible in `scripts/test_wedge_arrival.py`, because that harness
#: steps a perfect 30 fps and this is a bug about frames that never came.
#:
#: THE CAUSE, and it is not in the ring at all. `show_t0` is a wall clock
#: and `_aurora_ui_alpha` reads a wall clock, so the arrival runs on
#: elapsed TIME while the animation is only visible in delivered FRAMES.
#: The two are the same thing at 25 fps and completely different during
#: the first seconds after a start, when the compositor is loading an
#: 828-frame entity pack, baking the mist, the steel rim, five raised
#: captions and two machined caps — and delivering perhaps two frames a
#: second. Three seconds of arrival, four frames to show it in, and the
#: pane's whole fade falls between two of them. A summon in that window
#: is the ordinary case, not a corner: a spoken "menu" the moment the
#: face comes back, or a `menu_show` flag left over from before a restart,
#: which is exactly how this one was caught.
#:
#: THE FIX IS THE STANDARD ONE FOR A FRAME-RATE-INDEPENDENT ANIMATION
#: THAT MUST NOT SKIP: clamp the per-frame delta. A frame that took 900 ms
#: advances the animation by AUR_UI_DT_CAP and the remainder is pushed
#: into `show_t0`, which is arithmetically identical to running the
#: schedule on a clock that stalls — and touches ONE variable instead of
#: re-plumbing every reader of it (§15: `show_t0` is compared against
#: `time.time()` in three other places and they all keep working).
#:
#: 0.20 s is five normal frames on this face (it composes in 40-55 ms).
#: Anything under that is a healthy frame and shifts nothing at all, so
#: in normal running this function is two subtractions and a compare.
#: Above it, the ring waits for the glass rather than performing to it.
#:
#: §1: IT SAYS SO. A skipped fade was invisible for a day; a fade that had
#: to be held back is now a line in the log naming how long and why.
#: ── 0.20 s WAS FIVE TIMES TOO LOOSE TO EVER FIRE (2026-08-19, later) ──
#: The note above is right about the mechanism and its clamp is what took
#: the puck's arrival from `[0,0,0,0,0,0,1]` to `[11,14,16,19,22,25,27]`.
#: It is NOT what was still wrong, and the reason is worth writing down
#: because the number looked so reasonable: **0.20 s is five normal frames,
#: so it only engages on a frame that is five times too slow.** The face
#: does not fail that way. Its own pace lines say 18.0-25.6 fps with a
#: 37-55 ms compose, and during a start-up the painter measured ~12 fps —
#: 40 ms to 83 ms per frame, EVERY ONE OF WHICH IS UNDER THE CAP. So on
#: the exact runs this was written for, `_aur_ui_stall` returned at the
#: `_lost <= 0` line every single frame and the arrival ran on the wall
#: clock after all. A three-second gesture at 12 fps is 36 frames spread
#: over seven overlapping panes, and the first pane — the shortest, 0.88 s
#: — got 11 of them. Eleven is the number he complained about.
#:
#: A cap is only a floor on frames if it is EXPRESSED as one. So it is:
#: the most a frame may advance the ring is the first pane's own fade
#: divided by AUR_ARRIVE_MIN_FRAMES, which makes the guarantee arithmetic
#: rather than hopeful — pane 0 paints at least 15 condensation frames at
#: ANY frame rate, because at worst it advances by exactly one fifteenth
#: of itself per frame. 0.88/15 = 59 ms today. A healthy face (38-50 ms
#: frames) is under it and the gesture still takes his 3.00 s to the
#: millisecond; a starving one stretches in WALL time instead of dropping
#: the animation, which is the trade the ring wants and the opposite of
#: what it was doing.
#:
#: §15: the floor is stated once, in AUR_ARRIVE_MIN_FRAMES, and the
#: schedule log, the painter's report, the test and now the clamp all read
#: THAT. Nothing here re-states 15 or 0.88 — both are derived, so trimming
#: AUR_UI_ARRIVE_S again moves the clamp with it instead of leaving it
#: behind, which is the failure this constant has now had twice.
#:
#: AUR_UI_DT_CAP survives as an OVERRIDE, not as the policy: 0.0 means
#: "derive it", and a positive value pins it. scripts/test_wedge_arrival.py
#: pins 1e9 to render the unclamped build side by side with this one.
AUR_UI_DT_CAP = 0.0

#: ── THE PAINTER'S TWO THRESHOLDS, NAMED (2026-08-19) ──────────────────
#: draw_aurora_menu skips a pane below AUR_PANE_INK_K and takes the settled
#: paste at or above AUR_PANE_SETTLED_E, so the band it can COUNT a
#: condensation frame in is narrower than the fade itself — 93% of it. The
#: first version of the derived cap below divided the whole fade by 15 and
#: measured 14, which is that 7% and nothing else. They are named here
#: because the clamp now has to size itself against exactly this band and
#: two files' worth of literals that must agree is what §15 is about.
AUR_PANE_INK_K = 0.01
AUR_PANE_SETTLED_E = 0.995
_AUR_PANE_K: dict = {}


def _aur_pane_settled_k() -> float:
    """The alpha at which the painter stops condensing and starts pasting.

    `e = k*k*(3-2k)` is the arrival's ease, and it is monotonic on [0,1],
    so the inverse is a bisection and not a formula worth writing out.
    Solved once and kept — this is called every frame.
    """
    _k = _AUR_PANE_K.get(AUR_PANE_SETTLED_E)
    if _k is None:
        lo, hi = 0.0, 1.0
        for _ in range(48):
            mid = 0.5 * (lo + hi)
            if mid * mid * (3.0 - 2.0 * mid) < AUR_PANE_SETTLED_E:
                lo = mid
            else:
                hi = mid
        _k = _AUR_PANE_K[AUR_PANE_SETTLED_E] = 0.5 * (lo + hi)
    return _k


def _aur_ui_dt_cap() -> float:
    """The most one frame may advance the ring, in seconds of schedule."""
    if AUR_UI_DT_CAP > 0.0:
        return AUR_UI_DT_CAP
    #: hurry=False: sized from the ARRIVAL, so a briefing's fast dismissal
    #: cannot shrink the clamp to a fifth and stretch a 0.95 s scene change
    #: into something the owner sees underneath her first sentence.
    #: ── SIZED FROM THE SHORTEST FADE, NOT PANE 0's (2026-08-20) ───────
    #: Owner, FIFTH report of the same sentence: "the wedge fade in is
    #: still wrong."
    #:
    #: This clamp exists to guarantee AUR_ARRIVE_MIN_FRAMES painted frames
    #: per pane, and it was computed from pane 0 alone. The note above says
    #: why that was thought safe — "the FIRST pane's own duration, which is
    #: the smallest one". **That stopped being true when the fade was
    #: weighted by pane size on 08-19.** Widest fades longest, pane 0 is
    #: the widest, so pane 0 now has the LONGEST duration and sizing the
    #: clamp from it produces the LOOSEST possible cap. Measured, seven
    #: panes, band 0.949, floor 15:
    #:
    #:     pane 0  dur 2.17 s   needs a 137.2 ms cap    7.3 fps floor
    #:     pane 3  dur 1.62 s   needs a 102.7 ms cap    9.7 fps floor
    #:     pane 5  dur 1.41 s   needs a  89.3 ms cap   11.2 fps floor
    #:     shipped cap (pane 0)             137.2 ms    7.3 fps
    #:
    #: So between 7.3 and 11.2 fps the clamp NEVER FIRES and panes 3-6 are
    #: under the floor by construction. The device delivers 8.3-10.3 fps
    #: *during* the gesture (the arrival is what costs the frames; the 30 s
    #: average is 16). That is dead centre of the broken band, and it is
    #: why his own log has been printing the same thin-list every time —
    #: always SETTINGS, LOCK, SLEEP, POWER, always the tail of the ring:
    #:
    #:     [19, 17, 16, 14, 13, 12, 12]   *** four under 15 frames ***
    #:
    #: AND THIS IS WHY FOUR FIXES RENDERED CLEAN HERE. The workstation
    #: draws the legacy 5-pane ring, whose panes are all the same width —
    #: so every duration is 1.74 s, every pane needs the same 9.1 fps, and
    #: pane 0 IS the tightest. The bug is arithmetically invisible on this
    #: machine and only exists on a graduated ring. §6, exactly.
    _band = max(1e-6, _aur_pane_settled_k() - AUR_PANE_INK_K)
    _tight = min(_ui_step(_j, hurry=False)[1]
                 for _j in range(max(1, len(wedges()))))
    return max(1e-3, _tight * _band
               / float(max(1, AUR_ARRIVE_MIN_FRAMES)))


def _aur_ui_inflight(now: float) -> bool:
    """Is a transition actually running right now?

    ── AND A GAP MUST NOT UN-ARRIVE A SETTLED RING (2026-08-19) ─────────
    This gate is not a shortcut, it is a correctness fix, and it is the
    second half of the same bug. `aurora_ui_tick` lives inside the
    compositor's `if AURORA_BLOB` block, which every full-screen mode
    jumps over with a `continue` — sleep, the brick, the login ceremony,
    the lock screen, a scene, a countdown. `tick_t` therefore does not
    advance for as long as any of those own the glass, and the first tick
    afterwards sees a delta of minutes.

    The unguarded clamp charged that delta to `show_t0` unconditionally.
    Two ways that shows up on the glass, both worse than the bug it was
    fixing: a ring that was fully up before the puck slept comes back with
    every alpha driven NEGATIVE — visibly gone, `vis` still True, and it
    creeps back over the next several minutes; and a summon raised on the
    first unlocked frame (the stale `menu_show` case, which is exactly how
    this was all caught) has its `show_t0` pushed minutes into the future
    before it draws a single pane, so the chime plays and nothing arrives.

    So: hold back only a transition that is mid-flight. A settled ring and
    a hidden one have no schedule to protect, and `aurora_ui_show` /
    `aurora_ui_hide` re-seed `tick_t` at the moment they start their clock
    so no gap that predates a transition can be charged to it either.
    """
    if _AUR_UI.get("hide_t0"):
        return True
    if not _AUR_UI.get("vis"):
        return False
    #: the arrival is over when the LAST pane has landed — same expression
    #: the exit's own end-of-gesture test uses, one pane index apart
    _d, _u = _ui_step(max(0, len(wedges()) - 1))
    return (now - (_AUR_UI.get("show_t0") or 0.0)) <= (_d + _u)


def _aur_ui_stall(now: float) -> None:
    """Hold the ring's schedule back over frames the glass never got."""
    _prev = _AUR_UI.get("tick_t") or 0.0
    _AUR_UI["tick_t"] = now
    #: first tick of a process, or a clock that went backwards: no delta
    #: worth trusting, and inventing one is how a jump becomes a shift
    if _prev <= 0.0 or now < _prev:
        return
    if not _aur_ui_inflight(now):
        return
    _cap = _aur_ui_dt_cap()
    _lost = (now - _prev) - _cap
    if _lost <= 0.0:
        return
    for _k in ("show_t0", "hide_t0"):
        if _AUR_UI.get(_k):
            _AUR_UI[_k] += _lost
    _AUR_UI["stalled"] = _AUR_UI.get("stalled", 0.0) + _lost
    #: once per stalled arrival, not once per slow frame — a start-up
    #: storm is dozens of them and a line per frame is a line nobody reads
    if not _AUR_UI.get("stall_said"):
        _AUR_UI["stall_said"] = True
        print(f"aurora: ring animation HELD BACK — a frame took "
              f"{now - _prev:.3f}s against a {_cap:.3f}s cap (the first "
              f"pane's {_ui_step(0, hurry=False)[1]:.2f}s fade over its "
              f"{AUR_ARRIVE_MIN_FRAMES}-frame floor), so the schedule was "
              f"pushed {_lost:.3f}s later rather than advancing with "
              f"nobody watching. The gesture now takes longer in WALL "
              f"time and the same number of FRAMES, which is the trade",
              flush=True)


def aurora_ui_tick(now: float, moving: bool) -> None:
    """Advance the ring's state ONCE per frame. All of it lives here.

    ── WHY THIS FUNCTION EXISTS (2026-08-17) ────────────────────────────
    Owner: "i did one touch which brought the wedges up and then another
    to make them disappear. when i touched again they just popped up and
    disappeared, the animation sequence is wrong. it happened twice."

    The log said it exactly: four `aurora ring dismissed` in a row and
    NOT ONE `summoned` between them. The toggle was not toggling, because
    the ring kept coming back without being asked.

    The cause was that `_aurora_ui_alpha` — a function whose job is to
    return a number — also MUTATED the state, five times a frame, once
    per wedge, with `i == 0` special-cased to end the exit. Two of those
    side effects fought each other: the exit's last frame set vis=False,
    and the `moving` branch at the top of the very next call read
    "not visible, and the dial is turning, so summon it". The dismissal
    completed and was instantly undone. From the chair that is a pop and
    a vanish; from the tap handler the ring was always visible, so every
    subsequent tap took the dismiss branch and nothing ever summoned.

    Two rules come out of it, and both are the fix:
      * STATE CHANGES ONCE PER FRAME, IN ONE PLACE. An accessor called
        per-wedge is not that place. `_aurora_ui_alpha` is now pure.
      * A DISMISS OUTRANKS THE DIAL. Turning the dial may summon the
        ring, but not for AUR_UI_REARM_S after a person has waved it
        away — otherwise the gesture that dismisses it is also the
        gesture that brings it back, and the control feels haunted.

    ── AND THE CLOCK STALLS WHEN THE FRAMES DO (2026-08-19) ─────────────
    See `_aur_ui_stall`. The arrival is a wall-clock animation and the
    compositor does not always deliver frames; when it does not, the
    animation happens with nobody watching.
    """
    _aur_ui_stall(now)
    if moving and (now - _AUR_UI["user_hide_at"]) > AUR_UI_REARM_S:
        _AUR_UI["last"] = now
        if not _AUR_UI["vis"]:
            aurora_ui_show(now)
    if not _AUR_UI["vis"]:
        return
    if _AUR_UI["hide_t0"]:
        #: the exit is over when the LAST pane to leave has finished. i=0
        #: leaves last (j = n-1), and its schedule is the one below.
        j = len(wedges()) - 1
        _d, _u = _ui_step(j)
        if (now - _AUR_UI["hide_t0"] - _d) > _u:
            _AUR_UI.update(vis=False, hide_t0=0.0)
        return
    #: ── THE RING DOES NOT LEAVE ON ITS OWN (2026-08-17) ─────────────
    #: Owner: "don't make them disappear anymore automatically. they have
    #: to click on the blank space to make them dissolve."
    #:
    #: There was a 12 s idle timeout here. It is gone, and the constant is
    #: left standing so the next person can see what was removed rather
    #: than wonder whether it was ever there. Controls that withdraw while
    #: you are deciding are controls you learn not to trust — and with the
    #: panes now covering two thirds of the dial there is a large, obvious
    #: place to put a finger when you want them gone.
    #:
    #: The ring still leaves for a BRIEFING (the compositor hides it when a
    #: show takes the glass) — that is a different thing taking over, not
    #: the ring deciding it has been up too long.


def _aurora_ui_alpha(now: float, i: int) -> float:
    """Wedge `i`'s own alpha, 0..1. PURE — every state change this used to
    make now happens once per frame in aurora_ui_tick(), which is the
    whole reason the toggle stopped toggling. Read it, do not touch it."""
    if not _AUR_UI["vis"]:
        return 0.0
    if _AUR_UI["hide_t0"]:
        #: ── LEAVING IS THE ARRIVAL, RUN BACKWARDS (2026-08-16) ───────────
        #: Owner: "i don't want them to disappear all at once i want them
        #: to fade out counter clockwise, slowly like the same speed the
        #: fade in clockwise." So the exit is the same stagger and the
        #: same duration, walked in REVERSE index order — and since the
        #: index order is clockwise, reversed is counter-clockwise. The
        #: last pane to arrive is the first to leave, which is what makes
        #: the ring look like it is closing rather than being switched off.
        #: ── THE BALLET, LEAVING (2026-08-16) ─────────────────────────────
        #: Owner: "when they exit faster for the first ones to leave and
        #: slowest for the last ones to go." So the exit DECELERATES: the
        #: first pane out goes briskly, each one after it takes longer,
        #: and the final pane holds the stage. j is the order of exit.
        n = len(wedges())
        j = n - 1 - i                       # 0 = first to leave
        d, dur = _ui_step(j)
        t = now - _AUR_UI["hide_t0"] - d
        return max(0.0, min(1.0, _ui_from(i, 1.0) - max(0.0, t) / dur))
    #: ── THE BALLET, ARRIVING ─────────────────────────────────────────────
    #: Same schedule, walked forwards: pane i arrives in position i with
    #: exactly the delay and duration pane i would take to LEAVE from that
    #: position. See _ui_step for why the old accelerating entry went.
    d, dur = _ui_step(i)
    t = now - _AUR_UI["show_t0"] - d
    return max(0.0, min(1.0, _ui_from(i, 0.0) + max(0.0, t) / dur))
AUR_CX, AUR_CY = 540, 540
#: ── 640 -> 552: THE CORNERS WERE ALWAYS BLACK (2026-08-20) ─────────────
#: Owner: "we are definitely wasting some painting ... we must be doing
#: something stupid." This was the stupid one.
#:
#: This box is blacked, composited into and screened onto the frame WHOLE,
#: three times every frame — core:ground + core:mist + core:out, 12.1 ms of
#: the eye's 19.4 on the device. Measured lit extent of its contents, over
#: four states including the ignition bloom (scripts/test_core_box.py):
#:
#:     at rest              reach 210 px from centre
#:     engaged (hearing)    reach 230
#:     speaking             reach 243
#:     ignition mid-bloom   reach 243
#:
#: 486 px of content in a 640 px canvas. A quarter of every one of those
#: operations was guaranteed-black corner.
#:
#: IT CANNOT GO TO 496, WHICH IS WHAT THE CONTENT ALONE WOULD ALLOW.
#: _aur_rim() bakes into an AUR_BOX-square image and draws at an ABSOLUTE
#: radius (AUR_RIM_R1 = 270), so anything under 540 clips the steel band —
#: two consumers of one constant with different requirements, which is why
#: the safe floor is the rim's and not the mist's. 552 clears the rim by
#: 12 px and the measured content by 66.
#:
#: Splitting them (a small box for the per-frame work, the rim keeping its
#: own canvas) is worth another 12% and is NOT done here: the rim is baked
#: once and costs nothing per frame, so it buys nothing on the number that
#: matters and adds a second size to keep in step.
AUR_BOX = 552
_AUR: dict = {"ground": None, "sprites": None, "box": None, "black": None,
              "cache": {}, "mistph": {"t": 0.0, "at": 0.0},
              "bang": {"t0": 0.0, "was": False, "k": 0.0},
              "flare": {"t0": 0.0, "seen": None},
              "dimph": {"v": 1.0, "at": 0.0},
              "st": {"e": 0.0, "t": 0.0, "p": 0.0, "at": 0.0, "lean": 0.0}}


def _aur_sprite(size: int, rgb: tuple, gain: float = 1.0,
                falloff: float = 2.2) -> "Image.Image":
    """A radial light, as PREMULTIPLIED RGB — screen-blended, never alpha
    composited, so it is an ADD of light rather than a paste of paint. That
    is why the core reads as luminous instead of as a blue disc."""
    import numpy as _np
    r = size // 2
    y, x = _np.mgrid[-r:r, -r:r].astype("float32")
    d = _np.sqrt(x * x + y * y) / float(r)
    a = _np.clip(1.0 - d, 0.0, 1.0) ** falloff * gain
    px = _np.zeros((size, size, 3), "uint8")
    for i in range(3):
        px[..., i] = _np.clip(a * rgb[i], 0, 255).astype("uint8")
    return Image.fromarray(px, "RGB")


def _aur_scaled(name: str, px: int) -> "Image.Image":
    """Resized sprites are CACHED per quantised size — a resize per frame
    cost 100ms of a 125ms budget on the puck; a paste costs ~2ms."""
    px = max(8, (px // 8) * 8)
    key = (name, px)
    c = _AUR["cache"]
    im = c.get(key)
    if im is None:
        src = _AUR["sprites"][name]
        im = (src if px == src.size[0]
              else src.resize((px, px), Image.BILINEAR))
        if len(c) > 240:                  # bounded: a runaway cache is a leak
            c.clear()
        c[key] = im
    return im


def _aur_init() -> None:
    if _AUR["sprites"] is not None:
        return
    blue, cyan, white = (60, 170, 255), (150, 225, 255), (225, 248, 255)
    vio = (150, 110, 255)
    #: SIZED SO THE GLOW DIES BEFORE THE RING. The first cut used a 560px
    #: halo against a 536px ring and the falloff's own edge read as a
    #: second, murky disc sitting inside the hard one — two circles where
    #: the design has one. The body now ends around r=190, leaving clean
    #: void between the light and the ring: an arc reactor, not a smudge.
    _AUR["sprites"] = {
        "halo": _aur_sprite(380, blue, 0.62, 2.3),
        "glow": _aur_sprite(240, blue, 1.00, 1.9),
        "core": _aur_sprite(130, cyan, 1.00, 1.6),
        "hot": _aur_sprite(64, white, 1.00, 1.3),
        "vio": _aur_sprite(300, vio, 0.60, 2.2),
    }
    _AUR["cache"] = {}
    _AUR["box"] = Image.new("RGB", (AUR_BOX, AUR_BOX), (0, 0, 0))
    _AUR["black"] = Image.new("RGB", (AUR_BOX, AUR_BOX), (0, 0, 0))
    _AUR["ground"] = Image.new("RGB", (SIZE, SIZE), (0, 0, 0))
    _AUR["blackfull"] = Image.new("RGB", (SIZE, SIZE), (0, 0, 0))


#: ── THE LIVING GROUND (2026-08-16) ───────────────────────────────────────
#: Owner: "make the screen background subtly dynamic so it always feels
#: alive but not in your face." A void that never changes reads as a dead
#: panel; a void that MOVES reads as depth. So: one baked field — a very
#: low-frequency nebula plus sparse stars — cut LARGER than the screen and
#: PANNED on a slow Lissajous. Panning is a crop and a screen-blend; the
#: alternative (rotating 1080² per frame) costs 18 ms and buys nothing the
#: eye can tell apart at this amplitude.
#:
#: THE AMPLITUDE IS THE WHOLE DESIGN. Peak lift is ~13 of 255 — measured,
#: not eyeballed, because "subtle" against a black ground is exactly the
#: room-floor arithmetic CLAUDE.md warns about: a level that looks
#: reasonable in isolation is either invisible or a grey wash on the glass.
AUR_FIELD = 1240
#: 13 read as SMUDGES on the panel — cloud without stars is smoke. 8, with
#: half again as many stars, reads as depth: the field is mostly void and
#: the few points of light are what the eye tracks as it drifts.
AUR_NEB_PEAK = 8
#: ── COLOURED NEBULAE, AND WHY THEY COST NOTHING (2026-08-17) ────────────
#: Owner, not urgent: "the background 'sky' of stars is very lame and not
#: dynamic, perhaps some very very light red or green nebulae in the
#: background that is dynamic (pre render it)."
#:
#: Pre-rendered is right, and the cheapest possible version of it already
#: exists here. The sky is TWO star fields panning at different rates for
#: parallax, and both are baked once and cached. So the nebulae are baked
#: INTO those fields: green into the near one, red into the far one. They
#: then drift past each other at different speeds for free, which is more
#: dynamic than a frame pack would have been and costs exactly zero per
#: frame — no second pack in memory, no blend, nothing added to a compose
#: budget already at 30 ms of 38.
#:
#: VERY light, as asked. 5 and 4 against the blue's 8, and each is a
#: DIFFERENT low-frequency field rather than a tint of the same one — two
#: clouds of the same shape in different colours read as a printing error.
#: The green sits on the near field because green reads as closer at equal
#: luminance; the red goes far, where the eye forgives it being dimmer.
#: 5 -> 17 and 4 -> 15. At 5 they were arithmetically present and visually
#: absent — about 2% of full, under a starfield, on a panel in a lit room.
#: "Very very light" has a floor: below the point where a person can see it,
#: lighter is not more subtle, it is nothing. 17 is still only 7%.
AUR_NEB_GREEN = 17
AUR_NEB_RED = 15


def _aur_cloud(rng, cells: int, gate: float, gain: float):
    """One low-frequency cloud, 0..1. Small noise upscaled — smooth for free.

    `cells` sets the scale: fewer, larger cells make a cloud that reads as a
    nebula rather than as fog. `gate` is where it starts existing at all,
    which is what keeps most of the sky EMPTY — a nebula everywhere is a
    colour cast, and a colour cast on a black sky looks like a fault.
    """
    import numpy as _np
    small = rng.random((cells, cells)).astype("float32")
    c = _np.array(Image.fromarray((small * 255).astype("uint8"))
                  .resize((AUR_FIELD, AUR_FIELD), Image.BICUBIC),
                  dtype="float32") / 255.0
    return _np.clip((c - gate) * gain, 0.0, 1.0) ** 1.6
AUR_PAN_R = (AUR_FIELD - SIZE) // 2


def _aur_field() -> "Image.Image":
    if _AUR.get("field") is not None:
        return _AUR["field"]
    import numpy as _np
    rng = _np.random.default_rng(7)
    #: low-frequency cloud: small noise upscaled is a smooth field for free
    small = rng.random((14, 14)).astype("float32")
    cloud = _np.array(Image.fromarray((small * 255).astype("uint8"))
                      .resize((AUR_FIELD, AUR_FIELD), Image.BICUBIC),
                      dtype="float32") / 255.0
    cloud = _np.clip((cloud - 0.42) * 1.8, 0.0, 1.0) ** 1.6
    px = _np.zeros((AUR_FIELD, AUR_FIELD, 3), "float32")
    px[..., 0] = cloud * AUR_NEB_PEAK * 0.42     # cool: blue-dominant
    px[..., 1] = cloud * AUR_NEB_PEAK * 0.72
    px[..., 2] = cloud * AUR_NEB_PEAK * 1.00
    #: the green, on its own field at its own scale — larger cells and a
    #: higher gate, so it is one or two soft regions rather than a wash
    _grn = _aur_cloud(_np.random.default_rng(41), 9, 0.56, 2.4)
    px[..., 0] += _grn * AUR_NEB_GREEN * 0.22
    px[..., 1] += _grn * AUR_NEB_GREEN * 1.00
    px[..., 2] += _grn * AUR_NEB_GREEN * 0.46
    base = Image.fromarray(_np.clip(px, 0, 255).astype("uint8"), "RGB")
    _aur_starfield(base, rng, n=300)
    _AUR["field"] = base
    return _AUR["field"]


#: ── THE STARS ARE OBJECTS (2026-08-16) ───────────────────────────────────
#: Owner: "slightly larger / brighter (alternate them) stars with magic 3d
#: effects, some raised some embossed... to give depth to the starscape."
#:
#: Two populations, and the difference is the whole trick:
#:
#:   RAISED  — a filled core with a specular offset UP-LEFT (the house key
#:             light) inside a graded halo. Light coming off a bead.
#:   RECESSED— an annulus whose LOWER-RIGHT arc is bright and whose upper
#:             -left is nearly dark. A pit lit from the same key: the far
#:             wall catches the light, which is the bore trick at 6 px.
#:
#: Everything is additive against a black ground, so a "shadow" cannot be
#: drawn — the recess has to be built out of WHERE THE LIGHT IS, not out
#: of darkness. That constraint is what makes these read as sculpted
#: rather than as dots with rings.
#:
#: Baked once, so the cost is startup-only and the detail is free forever.
#: 0.8 — owner, at the glass with the sculpted field up: "decrease the
#: average star brightness by 20% ish". Applied to the LIGHT (every alpha
#: term) rather than to the finished tile, so the nebula keeps its own
#: level and only the stars step back. The sculpting is unchanged: a
#: dimmer bead is still a bead, because the read comes from the specular
#: offset and the falloff, not from the peak.
AUR_STAR_GAIN = 0.8


def _aur_starfield(im: "Image.Image", rng, n: int,
                   scale: float = 1.0, gain: float = AUR_STAR_GAIN) -> None:
    d = ImageDraw.Draw(im, "RGBA")
    W = im.size[0]
    xs = rng.integers(14, W - 14, n)
    ys = rng.integers(14, W - 14, n)
    mags = rng.random(n) ** 2.6
    kinds = rng.random(n)
    for i in range(n):
        x, y, m = int(xs[i]), int(ys[i]), float(mags[i])
        #: alternate the temperature a little — a starfield of one colour
        #: is a texture; a starfield of two is a sky
        cool = (i % 3) != 0
        tint = (128, 196, 255) if cool else (255, 226, 196)
        core_c = (222, 242, 255) if cool else (255, 246, 232)
        if kinds[i] < 0.09 and m > 0.42:
            #: ── RECESSED ────────────────────────────────────────────────
            #: Small and dim on purpose. The first cut ran 3-8 px at 150
            #: alpha and read as CRESCENT MOONS scattered through the sky —
            #: a pit is a texture, not a subject. Held under 5 px and under
            #: a third of a raised star's light, it does its one job: the
            #: field has a surface that things can sit in as well as on.
            r = int((2.0 + 2.6 * m) * scale)
            if r < 2:
                continue
            bb = (x - r, y - r, x + r, y + r)
            d.arc(bb, 350, 460, fill=tint + (int(74 * m * gain),), width=1)
            d.point((x, y), fill=tint + (int(30 * m * gain),))
            continue
        #: ── RAISED ──────────────────────────────────────────────────────
        rh = max(2, int((2.5 + 9.0 * m) * scale))
        for k in range(rh, 0, -1):
            a = int(74 * m * gain * (1.0 - k / (rh + 1.0)) ** 2.1)
            if a <= 1:
                continue
            d.ellipse((x - k, y - k, x + k, y + k), fill=tint + (a,))
        rc = max(1, int((0.7 + 2.0 * m) * scale))
        d.ellipse((x - rc, y - rc, x + rc, y + rc),
                  fill=core_c + (int((190 + 65 * m) * gain),))
        #: the specular: a smaller, whiter dot pushed up-left off centre.
        #: This one pixel of offset is what turns a disc into a bead.
        if rc >= 2:
            d.ellipse((x - rc + 1, y - rc + 1, x - rc + 2, y - rc + 2),
                      fill=(255, 255, 255, int((150 + 90 * m) * gain)))
        #: diffraction on the brightest few only — rarity is what keeps a
        #: sky from looking like a lens flare advert
        if m > 0.72:
            sp = int((7.0 + 16.0 * m) * scale)
            for j in range(1, sp):
                a = int(120 * m * gain * (1.0 - j / float(sp)) ** 1.8)
                if a <= 2:
                    break
                for dx, dy in ((j, 0), (-j, 0), (0, j), (0, -j)):
                    d.point((x + dx, y + dy), fill=tint + (a,))


#: ── THE MIST (2026-08-16) ────────────────────────────────────────────────
#: Owner: "'Aura' and 'Aurora' conjure this moving kind of mist. pre render
#: it if you have to." So the centre stops being a static glow with a
#: breath on it and becomes VOLUME: three noise strata, each turning at its
#: own rate, summed under a radial envelope. Live rotation of three layers
#: is ~12 ms a frame; BAKED it is a paste.
#:
#: SEAMLESS BY CONSTRUCTION. Each stratum turns a whole number of
#: revolutions across the loop (1, -1, 2), so frame N is frame 0 exactly —
#: no cross-fade, no visible seam, no drift. That is why the speeds are
#: integers and not "nice" numbers.
#:
#: The bake costs ~1.5 s once at startup and 33 MB resident. Both are
#: cheap against the alternative: this is the one element the owner asked
#: to be high quality, and quality here means real volume, not a blur.
#: ── WHY THE FIRST MIST STEPPED (2026-08-16, owner: "still poor FPS") ─────
#: The panel was running 16 fps; the MIST was not. 48 baked frames across a
#: 26 s loop is 1.8 frames of content per second — every displayed frame
#: held the same billow for half a second. The display rate was never the
#: problem, and raising it would have burned watts fixing nothing.
#:
#: Two changes, and the second is the one that matters: more frames (72),
#: and CROSS-FADED playback — consecutive baked frames blended by the
#: fractional phase, so the mist is continuous at ANY display rate and the
#: loop length becomes a free parameter rather than a quality ceiling.
#: Blending two 470px tiles costs ~2 ms; baking 10x the frames to get the
#: same smoothness would have cost 300 MB.
AUR_MIST_N = 72
AUR_MIST_PX = 470
AUR_MIST_SRC = 720
#: seconds for one turn of the slowest stratum at rest — long on purpose:
#: mist you can watch move is smoke, mist you notice HAS moved is weather.
AUR_MIST_LOOP_S = 30.0


def _aur_noise(px: int, cells: int, seed: int) -> "Image.Image":
    import numpy as _np
    rng = _np.random.default_rng(seed)
    a = (rng.random((cells, cells)) * 255).astype("uint8")
    return Image.fromarray(a, "L").resize((px, px), Image.BICUBIC)


#: ── THE RTX CURTAIN (2026-08-16, night) ──────────────────────────────────
#: If a rendered pack is on the device, it REPLACES the procedural mist.
#: scripts/render_aurora_pack.py marches a real volumetric aurora on the
#: workstation — wandering curtain feet, field-aligned rays of varying
#: reach, oxygen green at the foot through her nitrogen blue to a violet
#: crown — and writes a seamless loop the puck simply plays.
#:
#: FALLBACK IS THE POINT. No pack, or a pack that will not load, and the
#: baked mist runs exactly as before with a line in the log saying which
#: one is on the glass. A device that quietly shows the lesser thing is
#: the silent-success shape this project keeps paying for (§1).
AUR_PACK_DIR = Path.home() / "aura_face" / "packs" / "centre_aurora"


def _aur_pack() -> "tuple | None":
    if "pack" in _AUR:
        return _AUR["pack"]
    _AUR["pack"] = None
    try:
        man = json.loads((AUR_PACK_DIR / "manifest.json").read_text())
        fs = sorted(AUR_PACK_DIR.glob("frame_*.png"))
        want = int(man.get("frames") or 0)
        if not fs:
            raise FileNotFoundError("no frames in the pack")
        #: the same cross-check centre_pack_load makes, for the same
        #: reason: a directory holding two builds plays both of them
        if want and len(fs) != want:
            raise ValueError(f"{len(fs)} frames on disk, manifest says "
                             f"{want} — stale files in the pack")
        ims = []
        for p in fs:
            im = Image.open(p).convert("RGB")
            im.load()
            ims.append(im)
        loop = float(man.get("seconds_per_loop") or 34.0)
        #: ── THE PACK BRINGS ITS OWN RING GEOMETRY (2026-08-17) ───────────
        #: The entity pack renders concentric SHELLS at known radii, and
        #: the face has to light "around the concentric rings when it hears
        #: people and is thinking" — the owner's words. Those two sets of
        #: rings must be the same rings, so the radii are read from the
        #: manifest the renderer wrote rather than typed here to match
        #: (PRINCIPLES §15). No `rings` key — an older pack, or the baked
        #: mist — and the reactive rings simply do not draw.
        _AUR["packman"] = man
        _AUR["rings"] = list(man.get("rings") or ())
        _AUR["packname"] = str(man.get("name") or "aurora")
        _AUR["pack"] = (ims, loop)
        print(f"aurora: {_AUR['packname'].upper()} PACK loaded — "
              f"{len(ims)} frames at {ims[0].size[0]}px, {loop:.0f}s loop, "
              f"{len(_AUR['rings'])} reactive rings, built "
              f"{man.get('built')} on {man.get('device', '?')[:28]}",
              flush=True)
    except (FileNotFoundError, NotADirectoryError):
        print("aurora: no RTX curtain on this device — the baked mist "
              "runs (render_aurora_pack.py + push_aurora_pack.sh)",
              flush=True)
    except Exception as exc:                        # noqa: BLE001
        print(f"aurora: RTX curtain REFUSED ({exc!r}) — baked mist runs",
              flush=True)
    return _AUR["pack"]


def _aur_mist() -> list:
    if _AUR.get("mist") is not None:
        return _AUR["mist"]
    pk = _aur_pack()
    if pk is not None:
        _AUR["mist"] = pk[0]
        _AUR["mist_loop"] = pk[1]
        return _AUR["mist"]
    import numpy as _np
    t0 = time.time()
    S, P = AUR_MIST_SRC, AUR_MIST_PX
    #: FOUR strata now (was three): broad, medium, fine, and a very fine
    #: counter-turning one that gives the billows their filament structure.
    #: This is the "higher quality" the owner asked for — detail comes from
    #: another octave, not from a bigger blur.
    layers = [(_aur_noise(S, 4, 11), 1, 0.46),
              (_aur_noise(S, 8, 23), -1, 0.28),
              (_aur_noise(S, 15, 37), 2, 0.17),
              (_aur_noise(S, 26, 53), -3, 0.09)]
    #: the envelope: a soft orb, so the mist HAS an edge without a rim
    r = P // 2
    y, x = _np.mgrid[-r:r, -r:r].astype("float32")
    dist = _np.sqrt(x * x + y * y) / float(r)
    env = _np.clip(1.0 - dist, 0.0, 1.0) ** 1.9
    core = _np.clip(1.0 - dist * 2.1, 0.0, 1.0) ** 2.2
    out = []
    off = (S - P) // 2
    for i in range(AUR_MIST_N):
        acc = _np.zeros((P, P), "float32")
        for im, rev, w in layers:
            ang = 360.0 * rev * i / AUR_MIST_N
            rot = im.rotate(ang, resample=Image.BILINEAR)
            acc += _np.asarray(rot.crop((off, off, off + P, off + P)),
                               dtype="float32") * (w / 255.0)
        #: contrast the field so it reads as billows rather than fog, then
        #: put it under the envelope and lift the core toward white
        acc = _np.clip((acc - 0.34) * 2.5, 0.0, 1.0) ** 1.35
        v = acc * env
        rgb = _np.zeros((P, P, 3), "float32")
        rgb[..., 0] = v * 74.0 + core * 205.0
        rgb[..., 1] = v * 168.0 + core * 238.0
        rgb[..., 2] = v * 246.0 + core * 255.0
        out.append(Image.fromarray(
            _np.clip(rgb, 0, 255).astype("uint8"), "RGB"))
    _AUR["mist"] = out
    print(f"aurora: mist baked — {AUR_MIST_N} frames at {P}px in "
          f"{time.time() - t0:.1f}s (seamless, 3 strata)", flush=True)
    return out


def _aur_field2() -> "Image.Image":
    """The FAR field: distant stars only, no cloud. Dimmer and panned
    slower than the near one, so the two cross and the void gets depth."""
    if _AUR.get("field2") is not None:
        return _AUR["field2"]
    import numpy as _np
    rng = _np.random.default_rng(19)
    #: the far field carries the RED nebula — dimmer, slower, and it will
    #: be multiplied by 0.62 below on top of that, which is exactly how a
    #: distant cloud should behave
    _red = _aur_cloud(_np.random.default_rng(53), 7, 0.60, 2.2)
    _px = _np.zeros((AUR_FIELD, AUR_FIELD, 3), "float32")
    _px[..., 0] = _red * AUR_NEB_RED * 1.00
    _px[..., 1] = _red * AUR_NEB_RED * 0.30
    _px[..., 2] = _red * AUR_NEB_RED * 0.34
    im = Image.fromarray(_np.clip(_px, 0, 255).astype("uint8"), "RGB")
    #: the far population: same sculpting, half the size — distance takes
    #: scale and contrast away, not detail, which is why they still read as
    #: beads rather than as noise
    _aur_starfield(im, rng, n=340, scale=0.5)
    _AUR["field2"] = im.point(lambda p: int(p * 0.62))
    return _AUR["field2"]


def _aurora_ground(now: float = 0.0) -> "Image.Image":
    """The void, with the field drifting through it. Returns a fresh RGB
    frame the caller owns — never layers.base, which must stay pristine."""
    _aur_init()
    g = _AUR["ground"]
    try:
        #: ── PARALLAX (2026-08-16, "more alive yet subtle") ───────────────
        #: One panning field is a texture sliding behind glass. TWO, drifting
        #: at different rates, is DEPTH — the near field crosses the far one
        #: and the eye reads volume without ever being shown a horizon. The
        #: far layer is dimmer and slower, as distance actually works.
        f, f2 = _aur_field(), _aur_field2()
        dx = int(AUR_PAN_R * (1.0 + math.sin(now / 71.0)) / 2.0)
        dy = int(AUR_PAN_R * (1.0 + math.sin(now / 97.0 + 1.1)) / 2.0)
        dx2 = int(AUR_PAN_R * (1.0 + math.sin(now / 173.0 + 2.2)) / 2.0)
        dy2 = int(AUR_PAN_R * (1.0 + math.sin(now / 211.0)) / 2.0)
        #: the field breathes as a whole, very slowly — 0.82..1.0
        k = 0.91 + 0.09 * math.sin(now / 23.0)
        #: ── CACHED, BECAUSE NOTHING HERE MOVES FAST ──────────────────────
        #: Two 1080² screen-blends cost 15 ms a frame, and the pan drifts
        #: about 2 px/s: at 14 fps the SAME ground was being rebuilt six
        #: times before it changed by a pixel. Keyed on the integer offsets
        #: and a quantised brightness (32 steps, finer than the panel can
        #: show), so the cache never hides a change the eye could see.
        kq = int(k * 32.0)
        key = (dx, dy, dx2, dy2, kq)
        if _AUR.get("gkey") != key:
            _AUR["gkey"] = key
            win = f.crop((dx, dy, dx + SIZE, dy + SIZE))
            g.paste(win if k > 0.995 else
                    win.point(lambda p, b=kq / 32.0: int(p * b)), (0, 0))
            w2 = f2.crop((dx2, dy2, dx2 + SIZE, dy2 + SIZE))
            g.paste(ImageChops.screen(g, w2), (0, 0))
    except Exception as exc:                       # noqa: BLE001
        _AUR.setdefault("said", set())
        if "field" not in _AUR["said"]:
            _AUR["said"].add("field")
            print(f"aurora: field failed {exc!r} — plain void", flush=True)
        g.paste(_AUR["blackfull"], (0, 0))
    return g


#: ── THE SUMMONED MENU (2026-08-16) ───────────────────────────────────────
#: The five wedges are how this device is driven by hand, and the baked
#: labels live in layers.base — which this face does not use. So aurora
#: draws its OWN menu in its own language: a thin luminous sector arc per
#: wedge with the name struck along the ring, raised only while a hand is
#: on the glass. Hit-testing is untouched — handle_tap still owns the same
#: sectors, so what appears is exactly what is already tappable.
#: ── ONE TABLE OWNS THE RING (2026-08-19) ────────────────────────────────
#: The menu order, the tap keys and the palette were three parallel
#: sequences in three parts of the file that had to agree by hand, and the
#: reorder below is exactly the edit that would have shipped a ring whose
#: POWER pane opens VOLUME. §15: one place states it, everything else reads
#: it. AUR_MENU and AUR_WEDGE_KEYS are now derived, so they cannot drift.
#:
#: ── AND THE ORDER IS HIS (2026-08-19) ───────────────────────────────────
#: Owner: "sleep should be next to the power wedge, they should be grouped
#: together at the bottom in the order of power, sleep, lock/mute/settings
#: after that, volume after that, and concierge after that."
#:
#: Read from the END of the ring backwards, because that is where "the
#: bottom" is: the arc starts at 12 o'clock and runs clockwise to about 8,
#: so slot 6 is the bottom-left and slot 0 is due north. POWER 6, SLEEP 5,
#: LOCK 4, SETTINGS 3, VOLUME 2, CONCIERGE 1 — and BRIEFING, the seventh he
#: did not name, takes slot 0.
#:
#: CONCIERGE IS STERLING and it is not a guess: WEDGES at the baked ring
#: below has carried the comment "STERLING (gold, the concierge)" since
#: 2026-08-07, in his own words at the time.
#:
#: "lock/mute" is ONE control, not two. The LOCK pane is the brick — the
#: log line for it reads "tap: lock — holding 0.42s for the bolt" and then
#: "tap: BRICKED — going red and deaf" — so mute IS what lock does here.
#:
#: AND POWER MUST NOT BE THE BIGGEST. The size gradient runs largest at
#: slot 0 to smallest at slot 6, so putting the only control that ends
#: things at the bottom of his list also makes it the smallest pane on the
#: ring. That is the right way round and it happened for free; if the order
#: is ever reversed, this is the line that has to be reconsidered.
#:
#: The colour columns are L*C*h — see _aur_ramp for why the family is held
#: in CIELAB rather than in HSV, and why hue is free to mean something.
AUR_PANES = (
    #  tap key      glyph       h*     C*    L*   icon sat
    ("meetings",  "BRIEFING", 212.0, 56.0, 66.0, 0.50),
    ("sterling",  "STERLING",  84.0, 56.0, 66.0, 0.58),
    ("volume",    "VOLUME",   152.0, 56.0, 66.0, 0.52),
    ("settings",  "SETTINGS", 255.0, 16.0, 66.0, 0.10),
    ("lock",      "LOCK",      30.0, 72.0, 58.0, 0.76),
    ("sleep",     "SLEEP",    300.0, 56.0, 66.0, 0.52),
    ("power",     "POWER",     56.0, 56.0, 66.0, 0.60),
)
#: L* 66 rather than 62 (2026-08-19, second render). Gold and amber are
#: hues that only exist ABOVE a certain lightness — at L* 62 STERLING came
#: out khaki and POWER came out brown, which is not "the one amber", it is
#: mud. Four points fixes both and costs the cool end nothing.
#:
#: AND C* IS "AS MUCH AS THE HUE CAN CARRY, UP TO 56", which is not the
#: same as constant and the difference has to be stated or someone will
#: read the table as a promise. sRGB cannot hold a saturated yellow and a
#: saturated blue at the SAME lightness — its yellow primary is L* 97 and
#: its blue primary is L* 32 — so a family that spans gold and steel-blue
#: at one lightness has to let chroma vary. BRIEFING is served C* 37 at
#: this lightness and everything else gets the full 56; run
#: `scripts/wedge_color_separation.py --gamut` for the ceiling by hue
#: before moving any of these. The variation is monotone with hue rather
#: than arbitrary — cool hues quieter, warm hues louder — which is also
#: how real pigment behaves, and it is L* that carries the family.
#: WHY THESE SEVEN HUES, one line each, because "make sense" was the ask:
#:   BRIEFING  212  daylight blue — the day, read out
#:   STERLING   84  GOLD. The brand, in either colourway, exempt from the
#:                  house family by the palette note in PUCK-SHOW.md
#:   VOLUME    152  the green of every level meter ever built
#:   SETTINGS  255  MACHINED STEEL, and the one deliberate break in C*. The
#:                  gear is the only control that is about the DEVICE
#:                  rather than about the room, so it wears the device's
#:                  own metal. It is also what stops seven hues reading as
#:                  a charm bracelet: every dial worth copying has exactly
#:                  one neutral in it, and a set with no rest point is the
#:                  "gaudy Cartier" complaint waiting to be made again.
#:   LOCK       30  RED, and the second break: L* 58 and C* 72, darker and
#:                  more saturated than the family. "LOCK's red stays: it
#:                  is an OUTCOME colour, exempt from any house family"
#:                  (the tiles note, 2026-08-09) — and he asked for it by
#:                  name again today. Exempt means exempt in both
#:                  directions, so it is allowed to be the loud one.
#:   SLEEP     300  the indigo of the night sky the lock screen wears
#:   POWER      56  the amber, "because it is the only control that ends
#:                  things". Held 28 degrees off STERLING's gold and on the
#:                  far side of the ring from it, so the two warm metals
#:                  are never compared.
AUR_MENU = tuple(_p[1] for _p in AUR_PANES)


#: ── THE WEDGES ARE BAKED, LIKE THE RIM (2026-08-16) ──────────────────────
#: Owner: "it still has absolutely no 3d depth, we already accomplished
#: this with the recessed and raised aspects of the wedges before i don't
#: see why they look so crude now just use the same language."
#:
#: He is right, and the answer is the one the rim already proved: stroked
#: arcs cannot make a surface. Depth on this device comes from computing
#: a HEIGHT FIELD and lighting it — that is what _pocket_relief does for
#: the subdials, what the steel rim does for its bevel, and what the panes
#: were not doing while I drew them with concentric arcs.
#:
#: So each pane is baked once, per pixel, into an RGBA sprite:
#:   height    a raised plateau, chamfered on ALL FOUR sides — the two
#:             arcs and the two radial edges — so the corners are real
#:   normals   from the gradient of that height field
#:   light     Blinn-Phong against the house key at upper-left: the top
#:             -left chamfer blazes, the bottom-right falls to ambient
#:   contact   a real cast shadow offset down-right, alpha-only
#:   type      embossed INTO the bake, so the label is lit by the same
#:             key as the glass it sits on and cannot drift from it
#:
#: Baked at first use (~0.4 s for five), then a paste per frame. Fading is
#: a scale of the sprite's own alpha, which is why a dramatic reveal costs
#: nothing per wedge.
_AUR_WEDGE_CACHE: dict = {}


def _aur_icon(d: "ImageDraw.ImageDraw", kind: str, cx: float, cy: float,
              r: float) -> None:
    """One large glyph per wedge, drawn as a HEIGHT MASK (white = raised).

    Vector, in the house tradition (_cat_icon's note: "somebody walking
    past a puck reads a SHAPE at four metres and a word at one"). These
    are drawn thick, because a stroke thinner than the chamfer it sits on
    disappears into the lighting rather than catching it.
    """
    w = max(5, int(r * 0.17))
    if kind == "BRIEFING":
        #: the world, spoken about: a globe with a meridian and a parallel
        d.ellipse((cx - r, cy - r, cx + r, cy + r), outline=255, width=w)
        d.ellipse((cx - r * 0.42, cy - r, cx + r * 0.42, cy + r),
                  outline=255, width=max(3, w - 2))
        d.line((cx - r, cy, cx + r, cy), fill=255, width=max(3, w - 2))
    elif kind == "STERLING":
        #: the concierge's bell — dome, base, and the button on top
        d.arc((cx - r, cy - r * 0.86, cx + r, cy + r * 1.0), 180, 360,
              fill=255, width=w)
        d.line((cx - r, cy + r * 0.5, cx + r, cy + r * 0.5),
               fill=255, width=w)
        d.line((cx - r * 1.15, cy + r * 0.5, cx + r * 1.15, cy + r * 0.5),
               fill=255, width=max(4, w - 1))
        d.ellipse((cx - w * 0.9, cy - r * 1.12, cx + w * 0.9,
                   cy - r * 0.72), fill=255)
    elif kind == "LOCK":
        #: a padlock, shackle CLOSED into the body — the old bbox left the
        #: shackle ends floating 0.33r above the case, which is the glyph
        #: for unlocked, drawn on the screens that mean locked
        d.arc((cx - r * 0.62, cy - r * 0.95, cx + r * 0.62, cy + r * 0.75),
              180, 360, fill=255, width=w)
        d.rounded_rectangle((cx - r * 0.86, cy - r * 0.12,
                             cx + r * 0.86, cy + r * 0.96),
                            radius=int(r * 0.22), outline=255, width=w)
        d.ellipse((cx - w * 0.8, cy + r * 0.28, cx + w * 0.8,
                   cy + r * 0.28 + w * 1.6), fill=255)
    elif kind == "SLEEP":
        #: a crescent, cut from a disc rather than stroked — the moon is
        #: the one glyph here that is a SHAPE and not a diagram, and a
        #: stroked crescent at this size reads as a banana
        d.ellipse((cx - r * 0.92, cy - r * 0.92, cx + r * 0.92,
                   cy + r * 0.92), fill=255)
        d.ellipse((cx - r * 0.36, cy - r * 1.06, cx + r * 1.34,
                   cy + r * 0.78), fill=0)
    elif kind == "POWER":
        #: the IEC mark: a ring broken at the top, with the bar through the
        #: gap. Drawn at the standard proportions because this is the one
        #: symbol on the device that everyone already knows
        d.arc((cx - r * 0.82, cy - r * 0.82, cx + r * 0.82, cy + r * 0.82),
              -62.0, 242.0, fill=255, width=w)
        d.line((cx, cy - r * 1.02, cx, cy - r * 0.16), fill=255, width=w)
    elif kind == "SETTINGS":
        #: ── A GEAR, NOT A PORCUPINE (2026-08-17) ─────────────────────────
        #: Owner: "the settings icon used to look like a gear, now it looks
        #: like a porcupine." Exactly right, and it is what happens when a
        #: drawing made of STROKES is scaled up: the eight teeth were thin
        #: radial lines whose length grew with r while their width grew far
        #: more slowly, so at 33 px they read as teeth and at 44 they read
        #: as spines.
        #:
        #: A tooth is not a line. It is a short, BLUNT block sitting on the
        #: rim, wider than it is long — so this draws each one as a filled
        #: quad between two radii, and the teeth now scale in both
        #: dimensions at once. Six of them, not eight: at this size eight
        #: leaves less gap than tooth, which is the other half of why it
        #: bristled.
        d.ellipse((cx - r * 0.40, cy - r * 0.40, cx + r * 0.40,
                   cy + r * 0.40), outline=255, width=w)
        d.ellipse((cx - r * 0.74, cy - r * 0.74, cx + r * 0.74,
                   cy + r * 0.74), outline=255, width=max(5, int(w * 1.2)))
        for i in range(6):
            a = math.radians(i * 60.0)
            _hw = math.radians(15.0)          # half the tooth's own angle
            _q = []
            for _s_, _rr in ((-1, 0.66), (1, 0.66), (1, 1.02), (-1, 1.02)):
                _aa = a + _s_ * _hw * (1.0 if _rr > 0.9 else 1.25)
                _q.append((cx + math.cos(_aa) * r * _rr,
                           cy + math.sin(_aa) * r * _rr))
            d.polygon(_q, fill=255)
        if False:
            a = 0.0
            d.line((cx + math.cos(a) * r * 0.78, cy + math.sin(a) * r * 0.78,
                    cx + math.cos(a) * r * 1.14, cy + math.sin(a) * r * 1.14),
                   fill=255, width=w)
    elif kind == "VOLUME":
        #: a speaker with two waves — the one glyph everyone already knows
        d.polygon([(cx - r * 0.92, cy - r * 0.30),
                   (cx - r * 0.42, cy - r * 0.30),
                   (cx + r * 0.06, cy - r * 0.86),
                   (cx + r * 0.06, cy + r * 0.86),
                   (cx - r * 0.42, cy + r * 0.30),
                   (cx - r * 0.92, cy + r * 0.30)], fill=255)
        d.arc((cx - r * 0.20, cy - r * 0.62, cx + r * 0.72, cy + r * 0.62),
              300, 60, fill=255, width=w)
        d.arc((cx - r * 0.06, cy - r * 0.98, cx + r * 1.14, cy + r * 0.98),
              300, 60, fill=255, width=w)
    else:
        d.ellipse((cx - r * 0.6, cy - r * 0.6, cx + r * 0.6, cy + r * 0.6),
                  outline=255, width=w)


#: -- ONE MATERIAL PER PANE (2026-08-17) ---------------------------------
#: Owner, twice: "make each wedge background way way more detailed, render
#: the crap out of it with the RTX to give it individual texture and
#: brightness", and "i want every wedge to have a super high end render
#: that is unique in design in color of its background that is suitable for
#: what it does, lock should look red, etc. but they all have to be
#: distinctive."
#:
#: The panes have been seven copies of one object in seven hues since they
#: were written -- same height field, same chamfer, `col` swapped. Hue is
#: the weakest distinction the eye has at this size: at arm's length across
#: a dark room, a dark red pane and a dark blue one are two dark panes.
#: What separates materials is how they handle LIGHT -- brushed metal
#: streaks along one axis, engine turning throws concentric arcs, anodised
#: aluminium is matte and even.
#:
#: So each pane gets a baked HEIGHT map and ALBEDO map, sampled in pane
#: space (u across the arc, v out from the inner edge). The height goes
#: into the same `h` the Blinn-Phong below already lights, which is the
#: whole trick: the texture is genuinely lit by the house key rather than
#: printed on, so it turns with the dial and catches the same highlight as
#: the chamfer. The lighting model is not touched at all -- it is simply
#: given a surface that has something on it.
#:
#: Free at runtime: the maps are PNGs, loaded once, and the sprite they
#: feed is itself cached per pane. See scripts/render_wedge_materials.py
#: for what each material is and why that material for that pane.
AUR_MAT_DIR = AUR_PACK_ROOT / "wedge_mats" if "AUR_PACK_ROOT" in dir() \
    else Path(__file__).resolve().parent / "packs" / "wedge_mats"
#: how hard the material bites. The icon strike is 2.30 in the same units,
#: so 0.42 is a surface the light finds without ever competing with the
#: glyph -- which has to stay the most legible thing on the pane.
#: 0.42 -> 0.13 -> 0.075. Owner: "make the texture even finer and more
#: subdued." A machined surface announces itself by CATCHING the light at
#: one angle, not by being visibly bumpy from every angle; past a point,
#: more relief reads as damage. This is now roughly a seventeenth of the
#: icon strike, which is the ratio that keeps the glyph the most legible
#: thing on the pane -- the property that matters most at arm's length.
AUR_MAT_AMP = 0.075
#: ── ONE WEAVE FOR THE WHOLE RING (2026-08-19) ──────────────────────────
#: Owner: "keep the colors for each but make the textures all the same to
#: some high qualify carbon fiber style we pre render."
#:
#: Which is a straight reversal of the 2026-08-17 note above, and the note
#: above stands with its date because its reasoning was not wrong — hue
#: alone IS the weakest distinction the eye has, and seven materials did
#: separate the panes. What changed underneath it is that the palette
#: became one ordered hue sweep and the ring became a graduated object.
#: Seven different materials on one graduated ring is seven things again;
#: one material in seven liveries is the ring he has been asking for since
#: "it should almost feel like a graduated step by step colour gradient".
#:
#: `scripts/render_wedge_materials.py` and its seven map pairs are LEFT ON
#: DISK, and this is the rollback: delete CARBON_h.png / CARBON_a.png and
#: every pane goes back to its own material with no code change, because
#: the name lookup below falls through to it.
#:
#: The colour is untouched by any of this. `base` is built from `col` and
#: the material only ever multiplies it (`0.72 + 0.42 * alb`), so a shared
#: weave tints seven ways for free — the weave is the material, the hue is
#: the livery.
AUR_MAT_SHARED = "CARBON"
#: and the shared weave bites harder than the per-pane dust did.
#: 0.075 was set against FINE GRAIN, where the whole problem is that a
#: steep local gradient under a 90-exponent specular lobe sparkles
#: ("make the texture even finer and more subdued"). A tow is 9-14 px
#: wide, so its gradients are an order of magnitude gentler than that
#: grain's and the same amplitude that glittered there cannot glitter
#: here. 0.10 is still a twenty-third of the icon strike (2.30), which
#: keeps the glyph the most legible thing on the pane.
#: ── AND THEN IT WENT BEHIND THE COLOUR (2026-08-19, second bake) ───────
#: Owner: "make the carbon fiber finer as the background."
#:
#: The weave went from 20x12 tows to 28x16 in the same bake, and THAT
#: ALONE WOULD HAVE MADE IT LOUDER, which is the trap in "finer": a normal
#: is a gradient, so it scales as amplitude / feature width, and tows 0.71x
#: as wide at the same height are 1.4x steeper under a 90-exponent
#: specular lobe. 0.064 is the amplitude that leaves the gradients exactly
#: where they were — i.e. as loud as before, which is the opposite of the
#: ask.
#:
#: 0.055 was the first cut and it was still wrong, and looking at a 1:1
#: strip is how it got shipped: at 3x on a real baked sprite every pane was
#: covered in small hard WHITE DASHES, reading as lint rather than as
#: fibre. So it was counted instead of judged — blown pixels on the pane
#: BODY, glyph and arris and chamfer excluded, all seven panes:
#:
#:     amp    blown px    of which the weave's own
#:     0.090      7337                        2352
#:     0.055      6875                        1890
#:     0.040      6161                        1176
#:     0.030      5435                         450
#:     0.024      5026                          41
#:     0.018      4985                           0   (the floor: the pane's
#:                                                    own baked gloss sweep)
#:
#: It is not a threshold, it is a KNEE, and the knee is what makes this a
#: measurement rather than a taste: between 0.055 and 0.024 the weave stops
#: contributing highlights and becomes purely texture, and below 0.024
#: there is nothing left to remove. §3 — the reason this took one pass and
#: not eight is that the two states are separated, not overlapping.
#:
#: THE TWILL DOES NOT GO WITH IT, and that is the whole design: at 0.024
#: the pattern is still plainly legible because it is carried by the ALBEDO
#: tiers, not by the relief. Tone survives being averaged down to a few
#: pixels; relief turns into glitter. That is the soleil dial's lesson
#: (2026-08-17, 72 rays across 55 px) applied to a material instead of to a
#: dial, and it is why "make it finer" and "make it recede" turn out to be
#: the same instruction here.
#:
#: 0.024 is a ninety-sixth of the icon strike (2.30), so the glyph is by a
#: very long way the most legible thing on a pane.
AUR_CARBON_AMP = 0.024
_AUR_MAT_CACHE: dict = {}


def _wedge_material(name: str):
    """(height, albedo, amplitude) for a pane, or None. Never raises.

    None is a working face with plain panes, which is what every puck had
    an hour ago -- a missing pack must degrade to the old look and say so
    once, not take the compositor with it.

    The shared weave is preferred when it is on disk and the per-pane
    material is the fallback, so the two answers cannot disagree about
    which one is live -- and WHICH ONE IT PICKED IS PRINTED, once, because
    a pane that quietly used its fallback looks exactly like a pane that
    was meant to (PRINCIPLES §15's corollary, and §1).
    """
    #: ── THE WEAVE IS AURORA'S, AND ON PAHT-CF IT IS A LIE (2026-08-26) ─
    #: packs/wedge_mats ships a 2x2 TWILL — woven prepreg, a supercar's
    #: cosmetic panel. The carbon row's own note says why that cannot go on
    #: this face: the part is CHOPPED fibre, there is no weave in it
    #: anywhere, and wearing the twill would also make the two dark faces
    #: read as each other. So a relief-panes theme gets None, which this
    #: function already documents as "a working face with plain panes", and
    #: the pane's material comes from the guilloché the ramp turns into
    #: surface grinding. SAID ONCE, because a pane that quietly declined a
    #: material looks exactly like a pane that was never offered one (§1).
    if RELIEF_PANES:
        _AUR.setdefault("said", set())
        if "matrelief" not in _AUR["said"]:
            _AUR["said"].add("matrelief")
            print(f"relief: panes wear NO material map — {AUR_MAT_DIR} is "
                  f"aurora's woven twill and this face is chopped fibre; "
                  f"the grain is the guilloche", flush=True)
        return None
    if name in _AUR_MAT_CACHE:
        return _AUR_MAT_CACHE[name]
    import numpy as _np
    got = None
    #: the shared weave is a SINGLE object shared by all seven keys, not
    #: seven copies of one PNG -- it is loaded under its own name and the
    #: pane's name is aliased onto it.
    use = name
    amp = AUR_MAT_AMP
    if AUR_MAT_SHARED and (AUR_MAT_DIR / f"{AUR_MAT_SHARED}_h.png").exists():
        use, amp = AUR_MAT_SHARED, AUR_CARBON_AMP
        if use in _AUR_MAT_CACHE and _AUR_MAT_CACHE[use] is not None:
            _AUR_MAT_CACHE[name] = _AUR_MAT_CACHE[use]
            return _AUR_MAT_CACHE[name]
    try:
        hp = AUR_MAT_DIR / f"{use}_h.png"
        ap = AUR_MAT_DIR / f"{use}_a.png"
        if hp.exists() and ap.exists():
            _hi = Image.open(hp).convert("L")
            _ai = Image.open(ap).convert("RGB")
            #: ── THE WEAVE STOPS BEING RESOLVABLE (2026-08-19, night) ──
            #: "the wedges still look a bit too cartoonish, color and
            #: texture wise." A tow is 7.9 px on the smallest pane — the
            #: 08-19 morning bake measured that and correctly called it
            #: the last rung of the fineness ladder. The mistake was
            #: assuming the ladder was the axis: at ANY size where you
            #: can resolve individual tows, a twill reads as BASKETWORK,
            #: and basketwork is a cartoon of carbon. Real carbon at
            #: 250x130 px is not a pattern you resolve at all; it is an
            #: anisotropic sheen, and you see it by how the light MOVES.
            #:
            #: So the map is blurred rather than made finer. The tows
            #: dissolve; the twill's low-frequency tonal blocks survive,
            #: because a blur is exactly the operation that keeps the low
            #: frequencies and drops the high ones. That is the same
            #: finding as the amplitude knee ("tone survives being
            #: averaged down, relief turns into glitter") applied to the
            #: albedo instead of to the height — one rung past the end of
            #: the ladder, in the other direction.
            #:
            #: Applied ONCE, at import, to the shared map — not per pane
            #: and not per frame.
            _s = float(globals().get("AUR_CARBON_SOFT", 0.0)) \
                if use == AUR_MAT_SHARED else 0.0
            if _s > 0.05:
                _hi = _hi.filter(ImageFilter.GaussianBlur(_s))
                _ai = _ai.filter(ImageFilter.GaussianBlur(_s))
            hm = _np.asarray(_hi, dtype="float32") / 255.0
            am = _np.asarray(_ai, dtype="float32") / 255.0
            got = (hm, am, amp)
    except Exception as exc:                            # noqa: BLE001
        _AUR.setdefault("said", set())
        if "mat" not in _AUR["said"]:
            _AUR["said"].add("mat")
            print(f"aurora: wedge material {use} failed {exc!r} — plain "
                  f"panes", flush=True)
    if got is None:
        _AUR.setdefault("said", set())
        if "matmiss" not in _AUR["said"]:
            _AUR["said"].add("matmiss")
            print(f"aurora: no wedge materials in {AUR_MAT_DIR} — panes are "
                  f"flat colour, which is the old look, not a broken one",
                  flush=True)
    else:
        _AUR.setdefault("said", set())
        if "matsrc" not in _AUR["said"]:
            _AUR["said"].add("matsrc")
            print(f"aurora: wedge material is {use!r} at amp {amp} "
                  f"({'ONE SHARED WEAVE for all panes' if use != name else 'per-pane materials'})"
                  f" from {AUR_MAT_DIR}", flush=True)
    _AUR_MAT_CACHE[use] = got
    _AUR_MAT_CACHE[name] = got
    return got


#: ── QUIET LUXURY, NOT A CARTIER (2026-08-17) ────────────────────────────
#: Owner: "wedges still look a bit too blingy color wise, it's like looking
#: at a gaudy cartier watch, refine it somehow."
#:
#: Exactly the right reference, and it names the mistake. Seven fully
#: saturated hues around a rim is a charm bracelet: the eye reads the
#: COLOURS first, as decoration, and has to get past them to reach the
#: icons. What actually looks expensive on a dial is near-monochrome —
#: everything within a stop or two of the same neutral, with hue present
#: only as a tint you notice on the second look. Every real reference this
#: face has borrowed from (the AP, the Patek, the steel rim above) works
#: that way, and the panes were the one place that did not.
#:
#: So each pane keeps its identity and loses its volume: mixed 62% toward
#: its own luminance, which desaturates without darkening and without
#: flattening the seven into one. LOCK is still recognisably the red one;
#: it is simply no longer shouting.
#:
#: Applied here rather than to AUR_WEDGE_COLS because the ICON keeps the
#: full-strength hue (see the inlay note below): a muted pane under a
#: saturated glyph is the contrast that reads as jewellery-grade, and the
#: same value used for both is what made it costume.
#: 0.62 -> 0.73. Owner, after the first pass: "the wedges are still too
#: blingy, tone them down 30%". Taken as 30% of the REMAINING saturation
#: rather than 30% off the number -- 0.62 to 0.806 would have been the
#: literal reading and would have left almost no hue at all, which is a
#: different mistake and one he would have had to correct again. What is
#: left is 27% of the original chroma: enough that LOCK still reads red on
#: a second look, not enough to notice as colour on the first.
#: 0.73 -> 0.40 -> 0.10. Owner: "wedges still not differentiated enough.
#: raise it a lot." Nearly all of the chroma is back. The earlier crushing
#: answered a real complaint (seven unrelated saturated hues read as a charm
#: bracelet) and stopped being the right answer the moment the palette
#: became one ordered sweep: a ramp cannot look disarrayed, so the reason to
#: mute it went away and I kept muting anyway.
#: 0.10 -> 0.0 (2026-08-19). The last of the "gaudy Cartier" crushing, and
#: it has been arguing with every complaint since. The panes are already
#: multiplied to a third of their brightness before they are drawn; muting
#: them toward their own luminance on top of that is the same subtraction
#: twice. Kept as a constant rather than deleted so the next person can see
#: what it was and put it back with a number rather than re-deriving it.
AUR_WEDGE_DESAT = 0.0

#: The luminance an inlay must reach to read against smoked glass, paid for
#: by mixing toward white rather than by clipping channels — see the note at
#: the clip in _aur_wedge_sprite for why that distinction cost the icons all
#: of their colour for two days.
AUR_ICON_LUM_FLOOR = 150.0


#: ── SMOKED GLASS IN A POCKET, NOT PAINTED PLASTIC (2026-08-19, night) ────
#: Owner, at the glass: "the wedges still look a bit too cartoonish, color
#: and texture wise. come up with some creative ideas of how we can
#: reimagine this."
#:
#: THE DIAGNOSIS IS A MISMATCH, NOT A COLOUR. The centre iris is photoreal
#: — depth, layered light, real material — and the wedges were flat vector
#: art sitting on top of it. Two different rendering languages in one
#: frame is what "cartoonish" names; nothing about the palette was wrong.
#: Four causes were readable off a /dev/fb0 capture, and he approved a
#: direction for each: "ok do smoked glass, one light source makes sense,
#: colour in the light not the body, and recess them".
#:
#:   1 THE WEAVE READ AS WICKER. Individual tows are resolvable at 7.9 px
#:     (the 08-19 morning bake measured exactly that and called it the end
#:     of the ladder), so the eye sees BASKETWORK. Real carbon at this
#:     size is not a texture you resolve; it is an anisotropic sheen —
#:     you see it by how light MOVES over it. AUR_CARBON_SOFT blurs the
#:     map in MAP pixels so the tows dissolve into that sheen while the
#:     twill's low-frequency tonal blocks survive, which is the same
#:     "tone survives averaging, relief turns to glitter" finding the
#:     morning bake landed on, taken one rung further.
#:   2 FLAT UNIFORM FILLS. One colour per pane with only a RADIAL lift, so
#:     every pane had the same gradient in its own frame and therefore no
#:     form. AUR_KEY_GRAD replaces that with a WORLD-SPACE gradient.
#:   3 A GLOWING STROKE ROUND THE WHOLE PERIMETER. The single most
#:     "sticker" element on the screen: four arris strokes at one alpha,
#:     every pane, every edge. Real objects do not glow equally on every
#:     edge. AUR_ARRIS_FLOOR + the per-element key weighting below.
#:   4 NO LIGHT DIRECTION. Every edge lit the same, so nothing had a near
#:     side or an up.
#:
#: THE ONE LIGHT IS THE HOUSE KEY AT UPPER-LEFT — the same `L` the sprite
#: has always used for its Blinn-Phong, and the same one the steel rim and
#: every pocket on this face are lit by. It was already there; nothing but
#: the chamfer normals was reading it. It is NOT restated here: the
#: gradients below derive their direction from `L` inside the sprite, so a
#: future session that moves the key moves the panes with it (§15).
#:
#: AND THE PANE IS NOW RECESSED, which settles a sign that had been
#: ambiguous for months. A raised plateau blazes on the edge NEAREST the
#: light and casts down-right; a pocket does the opposite — its far wall
#: catches the key and its near lip casts INTO the glass. Everything below
#: commits to the pocket, because he asked for it and because a pane that
#: sits IN the bezel cannot look like a sticker ON it.
#:
#: EVERY ONE OF THESE IS BAKED INTO THE SPRITE. The compose budget was
#: already blown (47-60 ms against 38) before this work, so a gradient, a
#: specular or an inner shadow computed per frame was never available.
#: They are all inside _aur_wedge_sprite, which is cached per pane, and
#: scripts/test_aurora_menu_cache.py proves the warm draw is pixel
#: identical to the cold one.
#:
#: The body's alpha. 255 was an opaque chip; the starfield and the iris's
#: outer haze are now faintly visible THROUGH each pane, which is the
#: cheapest and strongest of the four cues — it is the same material
#: language as the centre, and the centre is the part that already reads.
#: The INLAY stays fully opaque (see the alpha line in the sprite): the
#: glyph is polished steel, not glass, and a translucent icon would give
#: back the legibility the inlay exists to provide.
#: THE HOUSE KEY, STATED ONCE (§15). It was a literal inside
#: _aur_wedge_sprite and nothing else could read it, so the live arris in
#: draw_aurora_menu had no way to agree with the baked one about where the
#: lamp is. Upper-left, and slightly in front — unchanged in value, moved
#: so there is exactly one of it.
AUR_KEY_L = (-0.58, -0.58, 0.57)
AUR_GLASS_A = 224.0
#: how much of the pane's own colour is in the BODY. 0.40/0.40/0.42 was
#: the old figure and it is what made the bodies read as painted plastic:
#: at that strength the fill is the loudest statement of the pane's hue,
#: and a fill is a SURFACE. Colour now arrives as LIGHT — the arris, the
#: bloom, the inlay — and the body is near-black glass that light passes
#: through. The 1.06 on blue keeps the glass smoked rather than neutral.
AUR_GLASS_TINT = 0.185
#: the near-black the smoked glass sits over, so a fully desaturated pane
#: is still a dark OBJECT and not a hole in the frame.
AUR_GLASS_BLACK = (8.0, 9.0, 12.0)
#: the across-face gradient from the one key, as a fraction. The face runs
#: from (1 - g/2) on the edge facing the light to (1 + g/2) on the far
#: edge — dark on the near lip because that lip casts into the pocket,
#: bright on the far wall because that is the wall the key actually hits.
#:
#: THIS IS THE ONE THAT SELLS IT, and the reason is the ring: each pane
#: sits at a different bearing, so "the edge facing the light" is a
#: DIFFERENT EDGE on every one of the seven. Seven panes with the same
#: gradient in their own frame is a pattern; seven panes with one gradient
#: in the WORLD's frame is a lit object.
AUR_KEY_GRAD = 0.62
#: the RADIAL lift the world-space gradient replaced — bright at the inner
#: edge, dark at the outer, the same in every pane's own frame. Kept as a
#: constant at zero rather than deleted so the next person can put it back
#: with a number instead of re-deriving it, which is the same reason
#: AUR_WEDGE_DESAT is still here. Its mean over the band is 0.975, so it
#: never changed a pane's brightness — only its shape, which is precisely
#: why it could not read as a light.
AUR_RADIAL_LIFT = 0.0
#: and the same key across the whole RING: a pane up at twelve o'clock is
#: nearer the source than one at four. +/- this fraction, by the bearing of
#: the pane's centre. It also buys lightness separation between neighbours
#: for free, which is what wedge_color_separation reports.
AUR_RING_KEY = 0.20
#: the inner shadow. Strength of the darkening just inside the pane's
#: border, weighted by how much each edge faces the key — plus a floor on
#: the INNER arc, because the bezel's inner lip is there whatever the
#: light is doing. This is the cue that says "in the bezel" rather than
#: "on it", and it is what replaced the offset cast shadow.
AUR_RECESS = 0.72
AUR_RECESS_PX = 13.0
#: the groove: a soft symmetric dark fringe OUTSIDE the pane, where the
#: pocket wall is. Replaces the old down-right offset cast shadow at alpha
#: 150, which was the geometry of a raised tile and read as floating.
AUR_CAST_A = 62.0
#: ── LESS PROUD BODY, DEEPER CUT GLYPH (2026-08-20) ───────────────────────
#: Owner: "i like the wedges more and more. very slight adjustment — make
#: the embossing slightly less stick out for the wedge and make the icons
#: look more engraved deeper."
#:
#: THAT IS ONE INSTRUCTION ABOUT DEPTH ORDERING, NOT TWO BRIGHTNESS TWEAKS.
#: The pane body comes DOWN toward the glass and the glyph goes FURTHER
#: INTO it; what he is asking to widen is the gap between the two. Written
#: as three named constants rather than as edits to the literals they
#: replace, because the next pass will be about this gap again and there
#: should be one place that states it.
#:
#: AND THE GLYPH WAS RUNNING AS AN EMBOSS, WHICH IS THE WHOLE BUG. The
#: strike was `h + ico_h * 2.30` — a POSITIVE bump — with its occlusion
#: rolled DOWN-RIGHT and clipped to the outside, i.e. the cast shadow of a
#: raised object. Under the upper-left key that gives a bright top-left
#: wall and a dark bottom-right one: the exact inverse of an engrave.
#: Turning 2.30 up, which is what "deeper" reads as if you never check the
#: sign, would have made the glyph stick out MORE and the pane read as more
#: raised — the opposite of both halves of the ask, and the third time on
#: this project a relief would have been tuned in the wrong direction. The
#: sign is flipped here and the occlusion goes with it: an incision's
#: shadow lives INSIDE the cut, against the wall the lamp cannot reach,
#: which under an upper-left key is the up-left wall.
#:
#: The legibility this cannot cost: the inlay is ALBEDO, not relief (see
#: the inlay note below) — a near-white face at a fixed HSV value plus an
#: unconditional lift — so flipping which of its two walls is bright does
#: not touch the luminance ratio that makes the glyph readable across a
#: room. Only the walls swap, and the walls are what say "cut".
#:
#: 1.0 -> 0.86 on the body. Multiplies the CHAMFER height field only,
#: before the material and the glyph are added, so it tilts the bevel's
#: walls a little less without touching the grain or the strike. `h` is
#: read nowhere but the gradient that makes the normals, so this is a
#: statement about relief and nothing else. 0.86 is "very slight" and is
#: meant to be: he likes the glass, this is the fourth relief pass on it,
#: and the failure mode of over-correcting here is flat.
AUR_BODY_RELIEF = 0.86
#: the strike, now SUBTRACTED. 2.30 -> 2.85: the flip alone changes the
#: character, and "deeper" asks for the cut to be stronger as well as the
#: right way round.
#: ── 2.85 -> 3.70, ASKED AGAIN THE SAME DAY (2026-08-20) ────────────────
#: Owner, after seeing the flip on the glass: "i think the icons on the
#: wedges could be engraved a bit deeper, to be honest."
#:
#: The direction is now settled — the pair was running as an emboss this
#: morning and turning this number up would have made the icons stick out
#: FURTHER. It is a cut now, so deeper genuinely is bigger, and this is
#: the first time on this control that "more" has been the safe word.
#: +30%, because "a bit" is the second-smallest step he has ever asked for
#: and the first one landed.
AUR_GLYPH_CUT = 3.70
#: the incision's own shadow, inside the groove, against its up-left wall.
#: 0.58 was the strength of the old OUTSIDE cast shadow, where it landed on
#: bare pane; this one lands on the inlay, so it is roughly halved — enough
#: to read as a wall in shadow, not enough to eat the face.
#: 0.32 -> 0.20, from the render (2026-08-20). At 0.32 the glyph came out
#: visibly DIMMER than the one it replaced — which is a real regression and
#: not a matter of taste: the old shadow lived OUTSIDE the glyph and so
#: never touched the face, and moving it inside spent up to a third of the
#: luminance the inlay exists to provide. 0.20 keeps the up-left wall
#: readable as a wall and gives the face back.
AUR_GLYPH_AO = 0.20
#: and the arris amplitude on the baked chamfer. Part of "less stick out":
#: a plateau that blazes on its lit edges is the loudest raised cue on the
#: pane. Kept as a multiplier at 1.0-minus-a-little rather than folded into
#: the colour, so it can be swept against AUR_BODY_RELIEF.
AUR_ARRIS_K = 0.88
#: AND AUR_CAST_A IS DELIBERATELY UNTOUCHED, which is worth stating because
#: it is the obvious fourth knob. It is no longer a cast shadow: since
#: 08-19 it is the GROOVE — a symmetric dark fringe where the pocket wall
#: meets the glass — and the note at it says in as many words that this is
#: what makes the pane read as "set into" rather than "hovering above".
#: Turning it down to make the body less proud would push it back toward
#: floating, which is the same mistake in the other direction.
#: how dark the arris gets on the edges that are NOT facing the key. 0.18
#: was the old floor and it is why the ring had a continuous glowing
#: outline: no edge could ever go dark. At 0.04 a pane shows a bright rim
#: on one or two edges and essentially nothing on the others, and WHICH
#: ones differ by bearing.
AUR_ARRIS_FLOOR = 0.04
#: the specular lobe on the glass. The tight term is what reads as a hard
#: polished surface; the broad term is a wash and too much of it is the
#: flat look. 90/1.25 + 14/0.30 was the old pair.
AUR_SPEC_TIGHT = 140.0
AUR_SPEC_TIGHT_K = 1.15
AUR_SPEC_BROAD_K = 0.16
#: WICKER -> SHEEN, in MAP pixels (the maps are 448x224 for a pane that
#: lands at roughly 250x130 on the glass, so one map pixel is ~0.56 glass
#: px and a sigma of 7 map px is ~4 glass px — about half a tow).
#: 0 restores the shipped weave exactly.
AUR_CARBON_SOFT = 7.0
#: how much of the weave's albedo survives. `0.72 + 0.42 * alb` was the
#: shipped pair; the sheen wants the same mean and less swing.
AUR_CARBON_ALB = 0.30
#: the mean the albedo swings about. 0 derives it as (1 - swing/2), which
#: keeps a pane's average brightness fixed as the weave is turned down —
#: the property that lets AUR_CARBON_SOFT and AUR_CARBON_ALB be swept
#: without also sweeping exposure. The 08-19 morning build's pair was
#: `0.72 + 0.42 * alb`, i.e. a mean of 0.93.
AUR_CARBON_ALB_MID = 0.0


#: how much of the arrival flash survives as a permanent rim. 0.30 keeps
#: the burst clearly a burst — it is still 3.3x brighter at its peak — while
#: leaving an edge that reads across a room. Below about 0.2 the panes go
#: back to being mundane; above about 0.45 the arrival stops being an event.
AUR_EDGE_FLOOR = 0.58
#: how much of the arrival bloom survives permanently. 0.34 is enough to
#: read as a coloured halo around each pane from across a room, and the
#: arrival still peaks at 3x that, so the moment keeps its event.
#: 0.34 -> 0.66. Owner, a third time: "the bloom for the first transition
#: in for the wedges is beautiful in color it just fades to mediocrity
#: afterwards, we have to preserve that distinctiveness." Two thirds is not
#: a nudge and it is not meant to be — the resting state is now nearly the
#: thing he likes, and the arrival is a lift above it rather than the only
#: moment it exists. If the arrival stops reading as an event, that is the
#: number to bring back down, not this one.
AUR_BLOOM_FLOOR = 0.66


def _aur_edge_tint(col: tuple) -> tuple:
    """The pane's hue at full brightness, for its arris.

    An EDGE can carry saturation a face cannot: it is two pixels wide, so
    the eye reads it as a coloured light rather than as a coloured surface,
    and the ring stays quiet while the individual panes stay distinct. This
    is the same reason the icons took the hue in HSV rather than the panes
    taking it back.
    """
    import colorsys as _cs
    _mx = max(1.0, float(max(col)))
    h, s, _ = _cs.rgb_to_hsv(col[0] / _mx, col[1] / _mx, col[2] / _mx)
    #: ── AND THIS IS THE BLUE CIRCLE (2026-08-19) ─────────────────────────
    #: Owner, live: "whoah when did you push out the update where there is a
    #: blue circle all throughout the perimeter? the ribbon is supposed to
    #: be subtle and only go between the left dead space between the
    #: wedges."
    #:
    #: The ribbon's geometry is NOT the cause and was measured before
    #: anything was changed: on the device the damage rect logs as
    #: "412x614 at (14,36) — 21.7% of the glass", the span is 169..253
    #: degrees, and both derive from `wedges()`. It is in the left dead
    #: space and it always was.
    #:
    #: THIS LINE IS THE CIRCLE. Every pane's arris and its permanent bloom
    #: are drawn in `_aur_edge_tint(col)`, and at saturation 0.38 with value
    #: pinned to 1.0 every hue on the old blue-violet ramp came out the same
    #: pale blue-white. Seven of them, at AUR_EDGE_FLOOR 0.58 and
    #: AUR_BLOOM_FLOOR 0.66, spanning 210 degrees, plus the ribbon's own
    #: blue channel across 84 of the remaining 150 — that is 294 degrees of
    #: continuous pale blue light at the rim, and the eye closes the last
    #: 66. He described what was there.
    #:
    #: So the edge takes the PANE's saturation, floored so a near-neutral
    #: still lights up and ceilinged so nothing becomes a laser. The
    #: docstring above is the licence for it: an edge is read as a coloured
    #: LIGHT rather than a coloured surface, which is why it can carry
    #: chroma the face cannot. Seven differently coloured lights do not
    #: close into a ring.
    r, g, b = _cs.hsv_to_rgb(h, min(0.86, max(0.22, s * 0.92)), 1.0)
    return (int(r * 255), int(g * 255), int(b * 255))


def _aur_mute(col: tuple) -> tuple:
    lum = 0.2126 * col[0] + 0.7152 * col[1] + 0.0722 * col[2]
    k = AUR_WEDGE_DESAT
    return tuple(c * (1.0 - k) + lum * k for c in col)


_RELIEF_INK: dict = {}


def _relief_ink() -> dict:
    """home.html's baked TYPE, separated from the pane field it sits on.

    Read once per bake, for the whole frame, and cached — the five panes
    then take their own footprints out of it. Returns {} when there is no
    bake to read, which is a state with a picture attached: the panes keep
    their smoke plateau and the flat baked type shows through it exactly
    as it did before this work. It says so, once, because a face that
    quietly stopped raising its labels looks like a face that never did
    (§1).

    THE MTIME IS THE CACHE KEY FOR THE WHOLE RING. The sub-labels are
    live text — STOPPED becomes LIVE, CONCIERGE stays — and the group's
    centre depends on how tall the group is, so a new bake has to re-seat
    the type as well as re-draw it. Clearing the sprite cache here is the
    one place that decides it; five sprites cost ~0.4 s and a bake change
    is already a whole-frame event.
    """
    if not RELIEF_PANES:
        return {}
    p = _base_bake_path()
    try:
        m = p.stat().st_mtime
    except OSError:
        if not _RELIEF_INK.get("said_missing"):
            _RELIEF_INK["said_missing"] = True
            print(f"relief: no bake at {p} — the panes keep their smoke "
                  f"plateau and home.html's flat type reads through it. "
                  f"The type is NOT raised and NOT re-seated this run",
                  flush=True)
        return {}
    if _RELIEF_INK.get("mtime") == m:
        return _RELIEF_INK
    import numpy as _np
    t0 = time.time()
    im = Image.open(p).convert("L")
    if im.size != (SIZE, SIZE):
        im = im.resize((SIZE, SIZE))
    lo = im.filter(ImageFilter.GaussianBlur(RELIEF_TYPE_BLUR))
    hp = _np.asarray(im, "float32") - _np.asarray(lo, "float32")
    #: TWO FIELDS, NOT ONE, AND THE GROWTH IS THE CALLER'S. `core` is the
    #: strokes; `soft` is how much of a pixel a stroke covers, which only
    #: means anything NEXT TO a core pixel. Growing one into the other has
    #: to happen inside a pane's own sample window — see the note in
    #: _relief_type, where doing it here cost an afternoon.
    core = (hp > RELIEF_TYPE_CORE)
    soft = _np.clip((hp - RELIEF_TYPE_SOFT)
                    / (RELIEF_TYPE_CORE - RELIEF_TYPE_SOFT), 0.0, 1.0)
    #: the geometry is NOT cached with it — a full-frame radius and bearing
    #: pair is 9 MB resident on a device that is already holding three
    #: 1080² layers, and each pane needs them over its own box only, which
    #: is 90k pixels and takes microseconds to build there.
    _RELIEF_INK.clear()
    _RELIEF_INK.update(mtime=m, path=p, lum=im, core=core, soft=soft)
    _AUR_WEDGE_CACHE.clear()
    print(f"relief: type ink read from {p} — {int(core.sum())} core px over "
          f"the whole bake in {time.time() - t0:.2f}s; the five pane sprites "
          f"rebake and re-seat", flush=True)
    return _RELIEF_INK


def _relief_hull(sel):
    """The pixels of `sel` that could ever be the closest one to an edge.

    Every one of the four edge distances is monotone in radius or in the
    angle off a flank, so its minimum over a blob is reached on the blob's
    SILHOUETTE. Taking the per-row and per-column extremes is a cheap
    superset of the convex hull — a few hundred points instead of a few
    thousand — and it makes the seat search below exact rather than
    sampled, which matters because the answer is a position on the glass
    and a sampled minimum would be off by however coarse the sampling was.
    """
    import numpy as _np
    ys, xs = _np.nonzero(sel)
    out = []
    for key, other, flip in ((ys, xs, False), (xs, ys, True)):
        order = _np.argsort(key, kind="stable")
        k, o = key[order], other[order]
        first = _np.ones(len(k), bool)
        first[1:] = k[1:] != k[:-1]
        last = _np.ones(len(k), bool)
        last[:-1] = k[:-1] != k[1:]
        take = first | last
        out.append((o[take], k[take]) if flip else (k[take], o[take]))
    return (_np.concatenate([o[0] for o in out]),
            _np.concatenate([o[1] for o in out]))


def _relief_type(i: int, a0: float, a1: float, bR0: float, bR1: float,
                 x0: int, y0: int, W: int, H: int):
    """This pane's baked icon+label group, lifted out and re-seated.

    Returns (ink, albedo, report) in the sprite's own box — `ink` a float
    field 0..1 to add to the height and to use as the inlay's mask,
    `albedo` an (H, W, 3) array of the colour that type has on the glass —
    or None when there is nothing to lift.

    ── THE GROUP, NOT THE ICON (2026-08-26) ─────────────────────────────
    Owner: "the icon / text still is not centered correctly in the wedges,
    they are near overlapping the perceived edge."

    home.html seats each wedge's content on the spoke at a hand-tuned
    radius and then hangs the label 44 px below the icon and the sub-label
    64 px below it, IN SCREEN Y. Two things follow. The block grows
    downward whatever bearing the pane is at, so "below the icon" is a
    different direction on every pane; and carbon is the only face that
    fills the sub row (STOPPED, CONCIERGE), so its group is taller than
    the one those offsets were measured against. The result measures as
    three of five panes with their ink TOUCHING the top of the chamfer.

    So the seat is solved rather than nudged: the group is a rigid block,
    and the block is put where its own worst clearance to the four edges
    is greatest — the Chebyshev centre of the pane, restricted to
    translations of the ink that is actually there. Among the positions
    that tie (a block smaller than its pane has a whole plateau of them)
    the SMALLEST move wins, so a pane that was already seated well stays
    where home.html put it and only the crowded ones travel.
    """
    d = _relief_ink()
    if not d:
        return None
    import numpy as _np
    #: everything below is in the SPRITE'S OWN BOX, not the frame. The box
    #: already contains the whole sector plus its pad, the seat can only
    #: move ink to a position with non-negative clearance and therefore
    #: never off the pane, and the difference is 90k pixels a pane instead
    #: of 1.17M — measured at 0.90 s for a cold ring against 0.41 s, same
    #: seats to the pixel. That matters because the ring rebakes whenever
    #: the bake does, and 0.41 s is what the ring cost before any of this.
    _sl = (slice(y0, y0 + H), slice(x0, x0 + W))
    _c = SIZE / 2.0
    _yy, _xx = _np.mgrid[y0:y0 + H, x0:x0 + W].astype("float32")
    _dx, _dy = _xx - _c, _yy - _c
    r = _np.sqrt(_dx * _dx + _dy * _dy)
    adeg = _np.degrees(_np.arctan2(_dy, _dx))
    span = a1 - a0
    ang = (adeg - a0) % 360.0
    off = ang > span + 5.0
    d_in = r - bR0 + RELIEF_OUTSET
    d_out = bR1 - r + RELIEF_OUTSET
    d_a0 = _np.where(off, -1e6, _np.radians(ang) * r + RELIEF_OUTSET)
    d_a1 = _np.where(off, -1e6, _np.radians(span - ang) * r + RELIEF_OUTSET)
    #: the four clearances to the PERCEIVED edge, which is the top of the
    #: chamfer (dist == bevel) and not the geometric border
    E = _np.stack([d_in, d_out, d_a0, d_a1]) - RELIEF_BEVEL
    win = ((E[0] >= 0.0) & (E[1] >= 0.0)
           & (E[2] >= RELIEF_TYPE_FLANK_PAD)
           & (E[3] >= RELIEF_TYPE_FLANK_PAD))
    #: ── THE GROWTH IS MASKED FIRST, AND THIS WAS THE AFTERNOON'S BUG ──
    #: (2026-08-26) The soft field is only type where a CORE pixel is
    #: within GROW of it, and the first build computed that growth once
    #: over the whole frame and multiplied by the window afterwards. Every
    #: stroke the window is there to EXCLUDE — the sector's own outline,
    #: STERLING's gold ring at inset 5 — then reached three pixels inward
    #: past the boundary and seeded a line of single-pixel specks just
    #: inside every plateau.
    #:
    #: They were nearly invisible and they were not the problem. The
    #: problem is that a speck is a POINT OF THE GROUP: it inflated
    #: STERLING's block from 105 px tall to 211 and pinned it against the
    #: outer edge, so the seat search reported that pane as impossible to
    #: centre and shrank it to 0.85 to fit a block that was mostly ring.
    #: The numbers all improved while doing it, which is why it survived a
    #: reading — a seat measured against the wrong ink is a silent success
    #: (§1), and it took rendering the mask itself to see.
    #:
    #: So the window is applied to the SEED as well as to the result.
    cw = Image.fromarray(((d["core"][_sl] & win) * 255).astype("uint8"), "L")
    reg = _np.asarray(cw.filter(
        ImageFilter.MaxFilter(2 * RELIEF_TYPE_GROW + 1)), "float32") / 255.0
    tk = d["soft"][_sl] * reg * win
    sel = tk > 0.30
    if not sel.any():
        print(f"relief: pane {i} has NO baked type under it — the plateau "
              f"stays smoke so whatever the bake does carry still reads",
              flush=True)
        return None
    sy, sx = _relief_hull(sel)
    before = E[:, sy, sx].min(1)
    #: the block's own centre, for the shrink ladder to work about
    cy_g = 0.5 * (float(sy.min()) + float(sy.max()))
    cx_g = 0.5 * (float(sx.min()) + float(sx.max()))
    T = RELIEF_TYPE_TRAVEL
    gx, gy = _np.meshgrid(_np.arange(-T, T + 1), _np.arange(-T, T + 1))
    gx, gy = gx.ravel(), gy.ravel()
    best = None
    for s in RELIEF_TYPE_SCALES:
        py = _np.rint(cy_g + (sy - cy_g) * s).astype("int32")
        px = _np.rint(cx_g + (sx - cx_g) * s).astype("int32")
        YY = _np.clip(py[:, None] + gy[None, :], 0, H - 1)
        XX = _np.clip(px[:, None] + gx[None, :], 0, W - 1)
        e4 = [E[k][YY, XX].min(0) for k in range(4)]
        m = _np.minimum(_np.minimum(e4[0], e4[1]),
                        _np.minimum(e4[2], e4[3]))
        vmax = float(m.max())
        #: ── AND THE WORST MARGIN IS NOT THE ONLY ONE (2026-08-26) ────
        #: A pure Chebyshev centre optimises the SMALLEST clearance and is
        #: indifferent to the rest, which on this ring is not a technical
        #: nicety: VOLUME's binding pair is radial, so the search was free
        #: to slide the group 25 px along the arc for a fifth of a pixel
        #: and seated it 51 px from one flank and 104 from the other. The
        #: numbers were optimal and the label was visibly off to one side,
        #: which is the complaint this whole function exists to answer.
        #:
        #: So the objective is the worst margin FIRST, and among the
        #: positions that essentially tie for it, the one whose opposite
        #: pairs are most equal — which is what "centred" means when you
        #: are looking at it — and then the smallest move, so a pane that
        #: home.html already seated well stays where it was put.
        ok = _np.nonzero(m >= vmax - RELIEF_TYPE_TOL)[0]
        bal = (_np.abs(e4[0][ok] - e4[1][ok])
               + _np.abs(e4[2][ok] - e4[3][ok]))
        j = int(ok[_np.lexsort((gx[ok] ** 2 + gy[ok] ** 2,
                                _np.round(bal, 1)))[0]])
        cand = (float(m[j]), int(gx[j]), int(gy[j]), s)
        if best is None or cand[0] > best[0]:
            best = cand
        if vmax >= RELIEF_TYPE_CLEAR:
            best = cand
            break
    vmax, tx, ty, s = best
    py = _np.rint(cy_g + (sy - cy_g) * s).astype("int32") + ty
    px = _np.rint(cx_g + (sx - cx_g) * s).astype("int32") + tx
    after = E[:, _np.clip(py, 0, H - 1), _np.clip(px, 0, W - 1)].min(1)
    #: P' = C + s(P - C) + T, inverted for PIL's output->input affine, in
    #: the box's own coordinates
    ax = (-cx_g - tx) / s + cx_g
    ay = (-cy_g - ty) / s + cy_g
    aff = (1.0 / s, 0.0, ax, 0.0, 1.0 / s, ay)
    mask = Image.fromarray(
        _np.clip(tk * 255.0, 0, 255).astype("uint8"), "L").transform(
            (W, H), Image.AFFINE, aff, Image.BICUBIC)
    lum = d["lum"].crop((x0, y0, x0 + W, y0 + H)).transform(
        (W, H), Image.AFFINE, aff, Image.BICUBIC)
    alb = _np.asarray(_colourway(lum), dtype="float32") * RELIEF_TYPE_GAIN
    #: ── THE GROUND THE SMOKE USED TO BE A SMOKE OVER (2026-08-26) ────
    #: The plateau goes opaque the moment the pane owns its type, and what
    #: it covers is not nothing: it is home.html's tile fill seen at 38%,
    #: which is the pane body the owner has been looking at all day.
    #: Dropping it hands every pane its own undiluted colour and the ring
    #: arrives as five saturated chips — the "christmas tree" this row's
    #: amber note forbids, produced as a side effect of a change about
    #: type. So the pane composites over that ground itself, and the
    #: ground is this pane's OWN baked fill: the median luminance under
    #: its plateau, through the row's colourway.
    #:
    #: A SCALAR AND NOT THE BAKE'S PIXELS, and the reason is a render I
    #: had to look at twice. Sampling the bake here brings its TYPE back
    #: with it, so the pane wore a legible grey ghost of its old label
    #: beside the new raised one. Removing the type from the sample first
    #: is a hole that has to be filled with something, and both obvious
    #: fillers are made of what is being removed — a low-pass of a word is
    #: still that word, and a normalised convolution around it still
    #: leaves the letters' outlines. The median takes no position from the
    #: type at all: it is 5% of the pixels under a plateau and the median
    #: of the other 95% is the fill. What is genuinely lost is the waffle
    #: inside the panes, which the guilloche has been standing in for
    #: since 08-16 and which was never visible through the smoke anyway.
    gl = _np.asarray(d["lum"], "float32")[_sl][win & (tk < 0.05)]
    gnd = _np.asarray(_colourway(Image.new(
        "L", (1, 1), int(round(float(_np.median(gl)) if gl.size else 0)))),
        dtype="float32")[0, 0]
    rep = (f"relief seat {i}: ink->perceived-edge px, "
           f"in {before[0]:.1f}->{after[0]:.1f}  out {before[1]:.1f}->"
           f"{after[1]:.1f}  cw {before[2]:.1f}->{after[2]:.1f}  ccw "
           f"{before[3]:.1f}->{after[3]:.1f}   worst {before.min():.1f}->"
           f"{after.min():.1f}  by ({tx:+d},{ty:+d}) x{s:.2f}")
    return (_np.asarray(mask, dtype="float32") / 255.0, alb, gnd, rep)


def _aur_wedge_sprite(i: int, a0: float, a1: float, col: tuple, name: str):
    key = (i, name)
    #: per-pane, since the graduated ring gives each its own thickness
    #: (2026-08-19). The cache key already carries `i`, so it cannot serve
    #: one pane's sprite to another.
    _bR0, _bR1 = wedge_band(i)
    #: BEFORE the cache lookup, and that is the whole reason it is here: a
    #: new bake carries new sub-label text, which changes both what the
    #: type says and where the group's centre is, and _relief_ink clears
    #: this cache when it sees one. A stat() per pane per bake.
    _relief_ink()
    if key in _AUR_WEDGE_CACHE:
        return _AUR_WEDGE_CACHE[key]
    import numpy as _np
    c = SIZE / 2.0
    #: pad 22 -> 30 on the relief path, and it is arithmetic rather than
    #: taste: the dilation (2.5) plus the cast shadow's offset (8) plus
    #: three sigmas of its blur (16.5) is 27, and a box that clips a shadow
    #: gives it a straight edge — the amputation the 08-20 halo note
    #: measured at alpha 121 and had to fix radially.
    pad = 30 if RELIEF_PANES else 22
    bevel = RELIEF_BEVEL if RELIEF_PANES else 15.0
    #: bounding box of the sector, plus room for the chamfer and shadow
    pts = []
    for _t in (a0, a1):
        for _r in (_bR0, _bR1):
            _ra = math.radians(_t)
            pts.append((c + _r * math.cos(_ra), c + _r * math.sin(_ra)))
    for _t in range(int(a0), int(a1) + 1):
        _ra = math.radians(_t)
        pts.append((c + _bR1 * math.cos(_ra),
                    c + _bR1 * math.sin(_ra)))
    x0 = max(0, int(min(p[0] for p in pts)) - pad)
    y0 = max(0, int(min(p[1] for p in pts)) - pad)
    x1 = min(SIZE, int(max(p[0] for p in pts)) + pad)
    y1 = min(SIZE, int(max(p[1] for p in pts)) + pad)
    W, H = x1 - x0, y1 - y0
    #: ── THE BAND, NOT THE BAKED CONSTANTS (2026-08-17) ───────────────
    #: These four lines read WEDGE_R0/WEDGE_R1 — the radii of the panes
    #: PAINTED INTO the watch-face bundles — while the aurora face draws
    #: its own at its own radii through wedge_band(). Only the bounding box
    #: had been switched over, so moving the band moved the sprite's canvas
    #: and not one pixel of what was drawn on it: the ring measured
    #: 369..498 before and after a 32 px move, which is how it was caught
    #: (measuring the ink rather than looking at the render, because the
    #: two renders were identical and looked plausible).
    rc0 = (_bR0 + _bR1) / 2.0
    yy, xx = _np.mgrid[y0:y1, x0:x1].astype("float32")
    dx, dy = xx - c, yy - c
    r = _np.sqrt(dx * dx + dy * dy)
    ang = (_np.degrees(_np.arctan2(dy, dx)) - a0) % 360.0
    span = a1 - a0

    #: the paint's own dilation — see RELIEF_OUTSET. Zero on every other
    #: face, and the four expressions below are then arithmetically the
    #: ones that shipped.
    _out = RELIEF_OUTSET if RELIEF_PANES else 0.0
    #: the angular clip is a WRAP guard, not the cut (d_a1 already goes
    #: negative past the span), so it has to be loosened by at least the
    #: dilation or the two radial edges grow and the two flanks do not.
    _span_lim = span + (5.0 if _out else 0.0)

    def _height(shift_x=0.0, shift_y=0.0):
        _dx, _dy = dx - shift_x, dy - shift_y
        _r = _np.sqrt(_dx * _dx + _dy * _dy)
        _ang = (_np.degrees(_np.arctan2(_dy, _dx)) - a0) % 360.0
        d_in, d_out = _r - _bR0 + _out, _bR1 - _r + _out
        d_a0 = _np.radians(_ang) * _r + _out
        d_a1 = _np.radians(span - _ang) * _r + _out
        dist = _np.minimum(_np.minimum(d_in, d_out),
                           _np.minimum(d_a0, d_a1))
        dist = _np.where(_ang <= _span_lim, dist, -1.0)
        return dist
    dist = _height()
    h = _np.clip(dist / bevel, 0.0, 1.0)
    h = h * h * (3.0 - 2.0 * h)                       # smoothstep chamfer
    #: the body's relief, scaled here and only here (2026-08-20, "make the
    #: embossing slightly less stick out for the wedge"). Before the
    #: material and before the strike, so the grain and the glyph keep
    #: their own bite while the chamfer's walls tilt less.
    h = h * AUR_BODY_RELIEF
    #: the chamfer on its own, kept before the material and the strike add
    #: to it — the relief path's alpha split reads it as "how far up the
    #: wall is this pixel", and that question has no answer once a weave
    #: and a glyph are also in the field. Costs one reference.
    _hch = h
    #: ── THE ICON IS GEOMETRY, NOT PAINT (2026-08-16) ─────────────────────
    #: Owner: "i would to avoid text completely... if each wedge is just
    #: one large icon that would be great. we will explain what each means
    #: in the enrollment process." Which also settles the font complaint by
    #: deleting the fonts.
    #:
    #: The icon is drawn into a mask, blurred, and ADDED TO THE HEIGHT
    #: FIELD before the normals are computed — so it is struck INTO the
    #: pane and lit by the same key as the chamfer, with its own arris and
    #: its own shadow side. Painting a glyph on top would have been half
    #: the work and none of the depth.
    _ic = Image.new("L", (W, H), 0)
    _icd = ImageDraw.Draw(_ic)
    _cxp = c + rc0 * math.cos(math.radians((a0 + a1) / 2.0)) - x0
    _cyp = c + rc0 * math.sin(math.radians((a0 + a1) / 2.0)) - y0
    #: 33 -> derived (2026-08-17): "increase the wedge sizes and
    #: corresponding icons" AND "the icons are bleeding beyond the edge of
    #: the wedge, that should never, ever happen". Both are satisfied by
    #: computing the largest glyph the band can actually hold rather than
    #: choosing a number and hoping — see icon_radius().
    #: ── A BAKED FACE ALREADY HAS ITS ART (2026-08-26) ────────────────
    #: On aurora the glyph IS the pane's meaning, because that face has no
    #: bake at all. A relief-panes theme has one: home.html paints the
    #: icon, the label and the tenant line (STOPPED, CONCIERGE) into
    #: base.png at these very radii, and striking a second globe into the
    #: height field would put two BRIEFING marks on one sector. So the
    #: icon mask stays empty, and every consumer of it downstream — the
    #: strike, the inlay, the occlusion, the texture break — multiplies by
    #: zero and costs nothing. Written as a skipped DRAW rather than as
    #: five guards, so there is exactly one place this decision is made.
    #: ── ...AND THE BAKE'S OWN ART IS WHAT GOES IN THE MASK ────────────
    #: (2026-08-26, second pass) The paragraph above stands and its
    #: conclusion is unchanged: nothing is DRAWN here on a relief face,
    #: because a drawn glyph would be the second BRIEFING mark. What is
    #: new is that the bake's mark is now SAMPLED into the same mask —
    #: same three blurs, same strike, same inlay, same occlusion, same
    #: texture break — so the type is geometry rather than paint without
    #: any of it being invented twice. `_tl` is None when there is no bake
    #: to read, and then this whole path is exactly the flat-ink build
    #: that shipped this morning.
    _tl = (_relief_type(i, a0, a1, _bR0, _bR1, x0, y0, W, H)
           if RELIEF_PANES else None)
    if _tl is not None:
        _ic = Image.fromarray(
            _np.clip(_tl[0] * 255.0, 0, 255).astype("uint8"), "L")
        print(_tl[3], flush=True)
    elif not RELIEF_PANES:
        _aur_icon(_icd, name, _cxp, _cyp, icon_radius(i))
    #: ── WHY RELIEF ALONE COULD NEVER WORK (2026-08-17) ───────────────────
    #: Owner: "the icons on the wedges are simply not readable, they need
    #: way more depth or contrast to their background wedges." He is right,
    #: and the reason is geometric rather than a matter of taste.
    #:
    #: AN EMBOSS ONLY MAKES CONTRAST WHERE THE SURFACE TILTS. The flat top
    #: of a raised stroke has exactly the same normal as the flat pane
    #: around it, so it takes exactly the same light and comes out exactly
    #: the same colour. All an emboss can draw is the WALLS — a thin bright
    #: line on one side, a thin dark one on the other. That is an outline
    #: of an outline, on a dark smoked pane, under a guilloché. Turning the
    #: strike depth up makes those two lines brighter and darker; it can
    #: never fill the glyph, because there is nothing there to fill.
    #:
    #: So the glyph stops being a bump in the same material and becomes a
    #: DIFFERENT MATERIAL: polished steel inlaid into smoked glass. Four
    #: things carry it, and only the first is depth:
    #:   1. a deeper, crisper strike            — stronger walls
    #:   2. a bright inlay face                 — LUMINANCE, the one that
    #:                                            actually makes it legible
    #:   3. its own occlusion cast on the pane  — it sits ON something
    #:   4. no guilloché on the inlay           — polished metal is smooth,
    #:                                            and the texture break is
    #:                                            itself a material cue
    #: Three copies of the glyph, each with a different job.
    inside = dist >= 0.0
    ico = _np.asarray(_ic.filter(ImageFilter.GaussianBlur(0.7)),
                      dtype="float32") / 255.0          # crisp: the FACE
    ico_h = _np.asarray(_ic.filter(ImageFilter.GaussianBlur(1.05)),
                        dtype="float32") / 255.0        # soft: the STRIKE
    ico_ao = _np.asarray(_ic.filter(ImageFilter.GaussianBlur(6.5)),
                         dtype="float32") / 255.0       # wide: the SHADOW
    #: the pane's own material, in pane space: u across the arc, v out
    #: from the inner edge. Added to the height BEFORE the normals are
    #: taken, so the key light carves it rather than tinting it.
    _mat = _wedge_material(name)
    _mat_alb = None
    if _mat is not None:
        _mh, _ma, _mamp = _mat
        _u = _np.clip(ang / max(1e-6, span), 0.0, 1.0)
        _v = _np.clip((r - _bR0) / max(1e-6, _bR1 - _bR0), 0.0, 1.0)
        #: -- BILINEAR, BECAUSE THE NORMALS ARE A GRADIENT (2026-08-17) ---
        #: Nearest sampling put the whole thing back to sandpaper even
        #: after the maps were rebaked at pane resolution, and the reason
        #: is specific to how this surface is lit: `h` is differentiated a
        #: few lines down to get normals. Nearest sampling at roughly 1:1
        #: makes texel-sized STEPS, the gradient of a step is a spike, and
        #: a field of spikes is a field of specular glints. The map was
        #: smooth; the sampler was not.
        #:
        #: Bilinear costs four lookups and a lerp, once, at bake time.
        _fy = _np.clip(_v * (_mh.shape[0] - 1), 0, _mh.shape[0] - 1.001)
        _fx = _np.clip(_u * (_mh.shape[1] - 1), 0, _mh.shape[1] - 1.001)
        _y0 = _fy.astype("int32")
        _x0 = _fx.astype("int32")
        _ty = (_fy - _y0)[..., None] if False else (_fy - _y0)
        _tx = _fx - _x0
        _y1 = _np.minimum(_y0 + 1, _mh.shape[0] - 1)
        _x1 = _np.minimum(_x0 + 1, _mh.shape[1] - 1)

        def _bilerp(_m):
            _a = _m[_y0, _x0]
            _b = _m[_y0, _x1]
            _c = _m[_y1, _x0]
            _d = _m[_y1, _x1]
            if _a.ndim > _tx.ndim:
                _sx, _sy = _tx[..., None], _ty[..., None]
            else:
                _sx, _sy = _tx, _ty
            return (_a * (1 - _sx) * (1 - _sy) + _b * _sx * (1 - _sy)
                    + _c * (1 - _sx) * _sy + _d * _sx * _sy)

        #: -- AND IT STOPS AT THE GLYPH (2026-08-17) --------------------
        #: Owner: "the icons now need to stand out, some are lost in that
        #: dust. they are too 'blingy' in a diamond way."
        #:
        #: Both halves of that are one mistake. The note two hundred lines
        #: down already says the inlay carries NO texture -- "polished metal
        #: is smooth, and the texture break is itself a material cue" -- and
        #: the material I added ran straight through it. So the glyph lost
        #: the one thing that separated it from its pane, and it gained a
        #: field of micro-normals under a specular exponent of 90, which is
        #: precisely how you render a diamond. The bling was not the icon's
        #: highlight; it was the pane's grain, sparkling through it.
        #:
        #: Masked by (1 - ico), so the pane is machined right up to the
        #: glyph's edge and the glyph itself is polished flat.
        #: the amplitude travels WITH the map (2026-08-19) rather than
        #: being a module constant read here — the shared weave and the
        #: per-pane dust want different bites, and a single global would be
        #: two components with an opinion about one number (§15).
        h = h + ((_bilerp(_mh) - 0.5) * _mamp * inside
                 * (1.0 - _np.clip(ico * 1.15, 0.0, 1.0)))
        _mat_alb = _bilerp(_ma)
    #: ── AND IT IS A CUT, NOT A BUMP (2026-08-20) ─────────────────────
    #: `h + ico_h * 2.30` for four days. That is an EMBOSS, and the note
    #: at AUR_GLYPH_CUT has the full reasoning: under the upper-left key a
    #: positive strike blazes on its top-left wall and darkens on its
    #: bottom-right, which is the signature of something PROUD of the
    #: pane. Owner asked for "more engraved deeper", so the sign flips
    #: and the walls swap with it.
    #: ── AND ON A RAISED PANE THE LEGEND IS RAISED TOO (2026-08-26) ───
    #: The sign is the OBJECT's, for the third time in this function (the
    #: face gradient and the arris both flip on the same argument). aurora
    #: engraves a glyph into a pocket; carbon's brief is "embossing,
    #: extrusion" and the owner's words for this step were "raise the
    #: type". A legend cut INTO a plateau under an upper-left key blazes
    #: on its bottom-right wall — the inverse of everything else on the
    #: pane — and that disagreement between two halves of one surface is
    #: what the 08-20 note names as reading "cartoonish".
    h = (h + ico_h * RELIEF_TYPE_RAISE * inside if _tl is not None
         else h - ico_h * AUR_GLYPH_CUT * inside)
    #: The key is up-left (L below), so the glyph's shadow falls down-right.
    #: Subtracting the crisp mask keeps the occlusion OUTSIDE the glyph,
    #: where a real shadow would be — darkening the inlay itself would
    #: undo the contrast the inlay exists to create.
    #: ── AND THE SHADOW MOVED INSIDE THE GROOVE (2026-08-20) ──────────
    #: The paragraph above is correct FOR A RAISED GLYPH and is left
    #: standing as the record of one. An incision has no cast shadow on
    #: the pane at all — the pane is the higher surface — what it has is
    #: contact occlusion down in the cut, deepest against the wall the
    #: lamp cannot reach, which under an upper-left key is the up-left
    #: one. So the roll reverses to -6,-6 and the mask MULTIPLIES rather
    #: than subtracts, which confines every pixel of it to the glyph.
    #: Leaving the old outward down-right shadow under a flipped strike
    #: would have been the two halves of the pane arguing about which way
    #: is up, and that argument is exactly what reads as "cartoonish".
    #: and a RAISED legend has the other shadow — the first paragraph
    #: above, which was written for a raised glyph and has been correct
    #: about one all along. Rolled down-right, away from the key, and
    #: kept OUTSIDE the letters where a cast shadow lives; darkening the
    #: type itself would spend the contrast the type exists to have.
    if _tl is not None:
        ao = _np.roll(_np.roll(ico_ao, 6, axis=0), 6, axis=1)
        ao = _np.clip(ao * (1.0 - ico), 0.0, 1.0) * inside
    else:
        ao = _np.roll(_np.roll(ico_ao, -6, axis=0), -6, axis=1)
        ao = _np.clip(ao * ico, 0.0, 1.0) * inside
    gy, gx = _np.gradient(h)
    nx, ny = -gx * 26.0, -gy * 26.0
    nz = _np.ones_like(nx)
    nl = _np.sqrt(nx * nx + ny * ny + nz * nz)
    nx, ny, nz = nx / nl, ny / nl, nz / nl
    L = _np.array(AUR_KEY_L, "float32")     # one lamp, stated once (§15)
    L /= _np.linalg.norm(L)
    Hv = L + _np.array([0.0, 0.0, 1.0], "float32")
    Hv /= _np.linalg.norm(Hv)
    diff = _np.clip(nx * L[0] + ny * L[1] + nz * L[2], 0.0, 1.0)
    ndh = _np.clip(nx * Hv[0] + ny * Hv[1] + nz * Hv[2], 0.0, 1.0)
    #: 90/1.25 + 14/0.30. The broad lobe is a WASH over the whole face —
    #: it lights every pixel a little regardless of where the pixel is,
    #: which is half of why the panes read flat under a key they were
    #: supposedly lit by. Tightened and the broad half nearly halved; what
    #: it was standing in for is now the world-space gradient below, which
    #: is a statement about direction rather than an even lift.
    spec = (ndh ** AUR_SPEC_TIGHT * AUR_SPEC_TIGHT_K
            + ndh ** 14.0 * AUR_SPEC_BROAD_K)
    #: polished metal takes a harder, tighter light than smoked glass does
    #: -- LUMINANCE, NOT GLITTER (2026-08-17) ---------------------------
    #: 1.60 made the inlay a mirror under a 90-exponent lobe, which is a
    #: gemstone rather than a metal: tiny, blinding, angle-dependent
    #: points instead of a readable shape. Owner: "too 'blingy' in a
    #: diamond way." Halved, and the legibility it was standing in for is
    #: put where it belongs -- into the inlay's own diffuse face below,
    #: which is what the eye actually resolves across a room.
    spec = spec * (1.0 + 0.80 * ico)
    #: smoked glass in the wedge's own colour. The RADIAL `lift` that used
    #: to live here is gone — it is the world-space key gradient below now
    #: (2026-08-19, night) — and it is deleted rather than left at zero
    #: because a dead variable in this function has already cost a day
    #: once (`tex`, computed and never applied, 2026-08-16 to 08-17).
    _mcol = _aur_mute(col)
    #: -- AND THE FACE IS LIT, NOT JUST TINTED (2026-08-17) --------------
    #: 0.20/0.22/0.26 makes SMOKED glass, which is right for a bed under a
    #: bright inlay and wrong as the only carrier of a pane's identity: at
    #: a fifth brightness every hue converges on black, which is most of
    #: why seven different colours were reading as seven dark tiles. Raised
    #: to 0.34/0.37/0.42 -- still clearly a dark pane, no longer a pane so
    #: dark that its colour cannot be seen.
    #: ── AND THE COOL CAST WAS EATING THE WARM HALF (2026-08-19) ────────
    #: 0.34/0.37/0.42 is a blue-biased dimmer: it takes 19% more off the red
    #: channel than off the blue. That was invisible while every pane was
    #: blue or violet, and it is the reason the first render of the new
    #: palette had STERLING coming out khaki and POWER coming out brown —
    #: the ring's own smoked-glass tint was rotating every warm hue toward
    #: olive on the way to the glass. A pane's colour has to survive being
    #: dimmed or it is not the pane's colour.
    #:
    #: 0.40/0.40/0.42 keeps a cool cast (the glass is still smoked, and the
    #: blue channel is still the last to go) without the tint being a hue
    #: rotation. It is also 15-18% brighter, which is the cheapest half of
    #: "they are just too bland looking right now".
    #: ── AND 0.40 WAS STILL A PAINTED SURFACE (2026-08-19, night) ──────
    #: Owner: "the wedges still look a bit too cartoonish, color and
    #: texture wise" -> "colour in the light not the body".
    #:
    #: Every number above this line is an argument about how much hue to
    #: put in the FILL, and the fill was the wrong place for it all along.
    #: A fill is a surface: paint it and the pane is a coloured chip, dim
    #: it and the pane is a dark chip, and the hue never stops being the
    #: flattest thing in the frame. What actually carries colour on a real
    #: object is the LIGHT it catches — the rim, the halo, the inlay — and
    #: those are edges and highlights, which is exactly where saturation
    #: is allowed to be loud (the _aur_edge_tint docstring has said so
    #: since 08-17 and the body kept competing with it).
    #:
    #: So the body drops to near-black smoked glass over AUR_GLASS_BLACK,
    #: and the ring's colour identity moves wholesale onto the arris, the
    #: bloom and the glyph. What that costs is stated rather than
    #: discovered: PANE-fill CIEDE2000 between neighbours falls, because
    #: there is much less pane left to differ. The number that has to hold
    #: is the ICON/EDGE separation, and wedge_color_separation.py reports
    #: all three now.
    base = _np.stack(
        [_np.full_like(h, _mcol[0] * AUR_GLASS_TINT + AUR_GLASS_BLACK[0]),
         _np.full_like(h, _mcol[1] * AUR_GLASS_TINT + AUR_GLASS_BLACK[1]),
         _np.full_like(h, _mcol[2] * AUR_GLASS_TINT * 1.06
                       + AUR_GLASS_BLACK[2])], axis=-1)
    #: ── ONE LIGHT SOURCE, IN THE WORLD'S FRAME (2026-08-19, night) ────
    #: `(1.20 - 0.45 * lift)` was a RADIAL gradient — bright at the inner
    #: edge, dark at the outer, identically on all seven. In each pane's
    #: own frame that is a gradient; across the ring it is a PATTERN, and
    #: a pattern is the one thing that cannot read as light.
    #:
    #: `_kf` is the pixel's position projected on the key direction, so it
    #: is large on the side of the pane that faces the light. Normalised
    #: over the pane's own footprint and INVERTED: the face is darkest on
    #: the lip nearest the key (that lip casts into the pocket) and
    #: brightest on the far wall (which is the wall the key strikes).
    #: Because the projection is in WORLD space and each pane sits at its
    #: own bearing, the dark edge is a different edge on every pane — that
    #: is the whole trick, and it is what a viewer reads as "these are
    #: seven things under one lamp" instead of "these are seven tiles".
    _kf = dx * float(L[0]) + dy * float(L[1])
    _ki = _kf[inside]
    if _ki.size:
        _klo, _khi = float(_ki.min()), float(_ki.max())
    else:                                    # pragma: no cover - degenerate
        _klo, _khi = 0.0, 1.0
    _kg = _np.clip((_kf - _klo) / max(1e-6, _khi - _klo), 0.0, 1.0)
    #: ── AND THE INVERSION IS THE POCKET'S, NOT THE PLATEAU'S ─────────
    #: (2026-08-26) The paragraph above is right FOR A RECESS and is left
    #: standing as the record of one: in a pocket the lip nearest the lamp
    #: casts INTO it, so the near side is dark and the far wall is lit. A
    #: pane that is PROUD of the dial is the other object entirely — its
    #: top face is simply tilted toward the light on the side facing it —
    #: and rendered with the pocket's sign the whole ring came out as five
    #: concave trays with the highlight running down the far edge. That is
    #: what a raised pane must never look like, and it is worth being
    #: explicit that this is a SIGN, not a strength: the same gradient at
    #: the same amount, read the other way round.
    if not RELIEF_PANES:
        _kg = 1.0 - _kg
    _kgk = RELIEF_KEY_GRAD if RELIEF_PANES else AUR_KEY_GRAD
    base *= ((1.0 - _kgk * 0.5) + _kgk * _kg)[..., None]
    if AUR_RADIAL_LIFT:                       # the incumbent, for the sheet
        base *= ((1.0 + AUR_RADIAL_LIFT * 0.444)
                 - AUR_RADIAL_LIFT * _np.clip(
                     (r - _bR0) / (_bR1 - _bR0), 0.0, 1.0))[..., None]
    #: and the same key across the whole RING, by the bearing of the
    #: pane's own centre: twelve o'clock is nearest the lamp, four o'clock
    #: is furthest. A distant key has no falloff in physics, but the eye
    #: reads an even ring as unlit, and this is the cue that makes the
    #: seven belong to one scene. It also separates NEIGHBOURS in
    #: lightness for nothing, which is the axis the 08-19 pendulum note
    #: says "disarray" and "bland" are both really about.
    _am = math.radians((a0 + a1) / 2.0)
    _kc = math.cos(_am) * float(L[0]) + math.sin(_am) * float(L[1])
    base *= (1.0 + AUR_RING_KEY * _kc)
    #: and the material's own colour variation over the top, gently — the
    #: pane's identity is still `col`, this is the grain within it
    if _mat_alb is not None:
        _cmid = AUR_CARBON_ALB_MID or (1.0 - AUR_CARBON_ALB * 0.5)
        base *= (_cmid + AUR_CARBON_ALB * _mat_alb)
    #: ── THE INLAY (2026-08-17) ───────────────────────────────────────────
    #: The pane is deliberately dark — col * ~0.22, dimmed further toward
    #: the foot — which is exactly what makes it a good bed for something
    #: bright. This is the step that makes the glyph READ: a cool near-white
    #: face against a smoked ground is a luminance difference of roughly an
    #: order of magnitude, and luminance is what the eye resolves at arm's
    #: length. A hint of the wedge's own hue keeps it Aura's metal and not
    #: a white sticker.
    #: ── AND EACH ONE IS ITS OWN METAL (2026-08-17) ───────────────────
    #: Owner: "try to make the colors and borders and highlighting more
    #: distinctive but still classy." They were seven near-identical
    #: near-white inlays — 188/212/236 with 6% of the pane's hue mixed in,
    #: which at these luminances is invisible. Seven controls that differ
    #: only in the shape of a glyph are seven controls you have to read.
    #:
    #: The inlay now carries 42% of its pane's hue against a fixed cool
    #: base, so LOCK is warm steel, SLEEP is cold steel, POWER is amber
    #: steel — distinguishable at a glance and across the room, in the way
    #: the wedge colours already were before the glyph flattened them all
    #: back to white. Still a polished METAL and not paint: the base holds
    #: the luminance that makes it read against smoked glass (the whole
    #: point of the inlay), and the hue only tints it.
    #: ── THE ICON CARRIES THE RAMP (2026-08-17) ───────────────────────────
    #: Owner: "the wedges still don't differentiate between each other
    #: enough, maybe subtly change the icon color for each in a graduated
    #: way, they all just kind of look terribly similar."
    #:
    #: True, and I caused it an hour ago. The panes were desaturated to
    #: settle the "gaudy Cartier" complaint, and the inlay was ALREADY a
    #: near-neutral with 42% of the hue added and then clipped to a floor
    #: of 196 — a clip that exists to guarantee legibility and that, on a
    #: dark hue, throws most of the colour away. So the one element bright
    #: enough to show colour was the one element forbidden from having any.
    #:
    #: Built in HSV instead of by mixing toward a constant. Taking the
    #: pane's HUE at a fixed high value and modest saturation gives an
    #: inlay that is guaranteed bright — the property the clip was there to
    #: protect — while carrying its pane's colour honestly. Because the
    #: panes are now one hue sweep, the icons inherit that sweep: seven
    #: tinted metals walking the same ramp, which is exactly the graduated
    #: differentiation he asked for and cannot go gaudy, because value and
    #: saturation are fixed and only the hue moves.
    #: ── AND 0.30 WAS SEVEN GREYS (2026-08-19) ────────────────────────────
    #: Owner: "try changing the color of the icons or something within each
    #: background so they make sense." MEASURED before touching it
    #: (`scripts/wedge_color_separation.py`): the seven inlays rendered as
    #: (125,155,171) (143,157,192) (152,142,184) (180,151,192) (164,133,162)
    #: (167,136,146) (159,147,136) — seven greyish lavenders, chroma in
    #: single figures. The BRIGHTEST element on each pane, the one thing the
    #: eye actually resolves at arm's length, was carrying none of the
    #: identity, which is most of "they all look the same".
    #:
    #: Saturation is now per pane (AUR_PANES' last column) rather than one
    #: constant, because the icons are where the meaning is allowed to live:
    #: LOCK's glyph is properly red, SETTINGS' is bare steel, STERLING's is
    #: gold. Value stays fixed at 0.97 for all seven — the icons are their
    #: own family and they keep the invariant the PANES just gave up, so a
    #: saturated glyph can never be a DIM glyph.
    import colorsys as _cs
    _face = ico[..., None]
    _mx = max(1.0, float(max(col)))
    _h, _, _ = _cs.rgb_to_hsv(col[0] / _mx, col[1] / _mx, col[2] / _mx)
    _isat = next((_p[5] for _p in AUR_PANES if _p[1] == name), 0.44)
    _ir, _ig, _ib = _cs.hsv_to_rgb(_h, _isat, 0.97)
    _inlay = _np.array([_ir * 255.0, _ig * 255.0, _ib * 255.0])
    #: never let a dark pane colour drag the glyph below the luminance it
    #: needs — the inlay exists to be an order of magnitude brighter than
    #: its bed, and a moody hue must not be able to undo that
    #: floor 168 -> 196 (2026-08-17). Owner: "the icons now need to stand
    #: out, some are lost in that dust." Half the legibility was coming
    #: from a specular lobe that has just been halved for being blingy, so
    #: it has to come from the honest place instead: the face's own value.
    #: the clip stays as a floor only — HSV already guarantees the value,
    #: so this can no longer flatten a hue, but it still catches a future
    #: palette change that pushes a colour dark.
    #: ── AND THAT CLAIM WAS FALSE, AND TODAY IS THE PALETTE CHANGE THAT
    #: PROVES IT (2026-08-19) ─────────────────────────────────────────────
    #: `clip(x, 150, 255)` is PER CHANNEL. On a saturated red inlay
    #: (237, 81, 81) it returns (237, 150, 150) — it does not raise the
    #: brightness of a dark colour, it raises the two channels that were
    #: carrying the hue, and the glyph comes out pink. Every icon
    #: saturation above about 0.35 was being eaten by this line, which is
    #: precisely why the constant above had to be 0.30 to look like
    #: anything, which is why the icons were seven greys.
    #:
    #: What the floor was FOR is legibility — the inlay must out-luminance
    #: its bed by an order of magnitude — and luminance is a property of
    #: the colour, not of a channel. So the floor is stated in luminance
    #: and paid for by the ONE move that raises luminance without touching
    #: hue: a mix toward white, by exactly as much as is missing and no
    #: more. A colour already above the floor is returned untouched, so the
    #: full-strength palette below passes straight through and only a
    #: future dark hue ever pays.
    _ilum = float(0.2126 * _inlay[0] + 0.7152 * _inlay[1]
                  + 0.0722 * _inlay[2])
    if _ilum < AUR_ICON_LUM_FLOOR:
        _t = (AUR_ICON_LUM_FLOOR - _ilum) / max(1e-6, 255.0 - _ilum)
        _inlay = _inlay * (1.0 - _t) + 255.0 * _t
    _inlay = _np.clip(_inlay, 0.0, 255.0)
    #: ── EXCEPT WHEN THE TYPE CAME FROM THE BAKE (2026-08-26) ─────────
    #: Everything above builds ONE colour for a whole glyph, which is
    #: right for a drawn icon and wrong for a sampled legend: the bake
    #: already grades its own type — the label is bright etch, the tenant
    #: line under it is deliberately dimmer, and STERLING's wordmark is
    #: applied metal with a shadow and a facet. That hierarchy is the
    #: bake's, it is the one the owner has approved, and inventing a flat
    #: colour here would flatten it. So the albedo is the sampled
    #: luminance through _colourway — which is, exactly, the colour that
    #: type has on the glass today — lifted by RELIEF_TYPE_GAIN to pay
    #: back what a lit plateau takes off it.
    if _tl is not None:
        _inlay = _np.clip(_tl[1], 0.0, 255.0)
    base = base * (1.0 - _face) + _inlay * _face
    lit = base * (0.30 + 0.90 * diff[..., None])
    _glyph_ao = RELIEF_TYPE_AO if _tl is not None else AUR_GLYPH_AO
    #: AND A FLOOR UNDER THE GLYPH SPECIFICALLY. `diff` is the local
    #: normal against the key, so a stroke whose walls face away from the
    #: light goes to 30% ambient and disappears -- which is exactly which
    #: icons were being "lost in the dust": the ones whose strokes run
    #: along the light. The inlay exists to be read, so it gets a small
    #: unconditional lift that does not depend on which way it happens to
    #: be facing. Applied to the glyph only, so the pane keeps its
    #: modelling.
    #: ...and it is a COOL lift, which is aurora's lamp and not this one.
    #: The floor is exactly as necessary here — a 2.4 px letter stroke
    #: raised 1.85 is mostly WALL, and the walls facing away from the key
    #: fall to 30% ambient, which measured as the raised label coming out
    #: dimmer in the mean than the flat ink it replaced (189 against 222
    #: over BRIEFING's top 260 px) even while it peaked brighter. What
    #: changes is the colour: (34,40,48) is a blue-white and belongs to a
    #: face built on a void, so a relief row takes the same lift out of
    #: its OWN top-of-ramp instead. Same job, no blue mark on a face whose
    #: material argument is "warm grey in the light".
    lit += _face * (_np.array(_THEME.get("white") or (232, 230, 223),
                              "float32") * RELIEF_TYPE_LIFT
                    if _tl is not None else _np.array([34.0, 40.0, 48.0]))
    _spc = (_np.array(RELIEF_LIGHT, "float32") if RELIEF_PANES
            else _np.array([200.0, 232.0, 255.0]))
    lit += _spc * spec[..., None] * 0.85
    #: ── TEXTURE (2026-08-16, owner: "there is no texture to them") ───────
    #: A plain lit plateau is a plastic chip. Every premium surface on this
    #: device has a MICRO-PATTERN under the light — the AP's tapisserie,
    #: the ferrari's carbon weave — and the pattern is what the eye reads
    #: as material. Here: a fine radial guilloché, one line about every
    #: 4 px, modulated by the same diffuse term so it FOLLOWS the lighting
    #: instead of sitting on top of it. Amplitude is deliberately tiny —
    #: it should be felt at arm's length and invisible in a screenshot.
    guil = _np.sin(r * (math.pi * 2.0 / 4.4)) * 0.5 + 0.5
    guil_a = _np.sin(_np.radians(ang) * 46.0) * 0.5 + 0.5
    #: ...AND IT WAS NEVER APPLIED (found 2026-08-17). `tex` was computed
    #: here and then simply not used — the guilloché the owner asked for
    #: after "there is no texture to them" has been dead code since the
    #: day it was written, which is part of why the panes still read flat.
    #: A visible mistake is cheap and this one was invisible: the variable
    #: was right there, the comment above it was right, and nothing on the
    #: glass ever changed. Applied now, and kept OFF the inlay, because
    #: polished metal is smooth and the texture break is a material cue.
    tex = 1.0 + (0.085 * (guil - 0.5) + 0.055 * (guil_a - 0.5)) * (1.0 - ico)
    lit *= tex[..., None]
    #: the glyph's own occlusion on the pane it is sitting proud of
    #: — now the occlusion in the groove it is cut into (2026-08-20)
    lit *= (1.0 - _glyph_ao * ao)[..., None]
    #: the bright arris where the plateau meets the chamfer, keyed by
    #: which way the edge faces — the detail that reads as CUT
    edge = _np.exp(-((dist - bevel) ** 2) / (2 * 3.4 ** 2))
    #: ── THE ARRIS STOPS GLOWING ON EVERY EDGE (2026-08-19, night) ─────
    #: `keyd` was the RADIAL direction against the key, so it could only
    #: ever distinguish the inner arc from the outer one — both flanks
    #: took whatever the radius happened to say — and its floor of 0.18
    #: guaranteed that no edge anywhere ever went dark. Seven panes each
    #: outlined on all four sides at a common minimum is the "sticker"
    #: element, and it is the same near-white circle the 08-19 evening
    #: note found in _aur_edge_tint, one layer down.
    #:
    #: The outward normal of an edge is -grad(dist): `dist` is the signed
    #: distance to the nearest border, so its gradient points INTO the
    #: pane everywhere near a border, on all four sides and round the
    #: corners, with no case analysis. Dotting that against the key gives
    #: a genuine per-edge answer — and the sign is the POCKET's: bright
    #: where the outward normal points AWAY from the lamp, because that is
    #: the far wall of the recess, the one the light actually reaches.
    _dgy, _dgx = _np.gradient(dist)
    _dn = _np.sqrt(_dgx * _dgx + _dgy * _dgy) + 1e-6
    _enx, _eny = -_dgx / _dn, -_dgy / _dn
    #: ── AND THE SIGN IS THE OBJECT'S, ONE MORE TIME (2026-08-26) ─────
    #: Same flip as the face gradient above, for the same reason and it
    #: must be the same decision: on a RECESS the lit wall is the one
    #: whose outward normal points away from the lamp; on a PLATEAU it is
    #: the one that points at it. Getting these two out of step is the
    #: pane lit on one edge and rimmed on the other, which reads as a
    #: rendering fault rather than as a shape.
    keyd = (_enx * float(L[0]) + _eny * float(L[1]))
    keyd = _np.clip(keyd if RELIEF_PANES else -keyd, 0.0, 1.0)
    lit += ((_np.array(RELIEF_LIGHT, "float32") if RELIEF_PANES
             else _np.array([190.0, 226.0, 255.0])) * AUR_ARRIS_K
            * (edge * (AUR_ARRIS_FLOOR
                       + (1.0 - AUR_ARRIS_FLOOR) * keyd ** 1.5))[..., None])
    #: ── AND THE PANE SITS IN THE BEZEL (2026-08-19, night) ────────────
    #: Owner: "recess them". An inner shadow hugging the border, weighted
    #: by how much each edge faces the key — the near lip casts into the
    #: glass, the far one does not — plus an unconditional floor on the
    #: INNER arc, because the bezel's inner lip is a physical thing that
    #: is there whatever the lamp is doing, and the inner radius is the
    #: edge he named.
    #:
    #: `1 - keyd` is exactly the complement of the arris weight above, so
    #: the bright rim and the shadow are two readings of ONE statement
    #: about where the light is (§15) and cannot drift into a pane that is
    #: lit and shadowed on the same edge.
    #: ── A RAISED PANE IS NOT SET INTO ANYTHING (2026-08-26) ──────────
    #: This whole block is the RECESS, and it is aurora's answer to
    #: "recess them" — an inner shadow hugging the border, plus a floor on
    #: the inner arc for the bezel's lip. A relief-panes face was asked for
    #: the opposite word ("embossing, extrusion"), and an inner shadow on
    #: something proud of the surface is the two halves of the pane
    #: arguing about which way is up — the argument the 08-20 note names
    #: as exactly what reads as "cartoonish". So it stands down here, and
    #: the contact shadow below does the job instead.
    if not RELIEF_PANES:
        _rin = _np.clip(1.0 - (r - _bR0) / AUR_RECESS_PX, 0.0, 1.0)
        _rec = _np.clip(_np.exp(-_np.maximum(dist, 0.0) / AUR_RECESS_PX)
                        * (1.0 - keyd) + 0.55 * _rin, 0.0, 1.0) * inside
        lit *= (1.0 - AUR_RECESS * _rec)[..., None]
    #: ── SMOKED GLASS: THE STARFIELD COMES THROUGH (2026-08-19, night) ─
    #: The body was opaque, which is the one thing a piece of glass never
    #: is. At AUR_GLASS_A the iris's outer haze and the starfield read
    #: faintly through each pane — the same material language as the
    #: centre, which is the half of the frame that already reads as real.
    #: The INLAY stays at 255: it is polished steel inlaid into the glass,
    #: not more glass, and a translucent glyph gives back exactly the
    #: legibility the inlay was invented to provide.
    _op = AUR_GLASS_A + (255.0 - AUR_GLASS_A) * _np.clip(ico, 0.0, 1.0)
    if RELIEF_PANES:
        #: ── THE WALLS ARE OPAQUE, THE PLATEAU IS NOT (2026-08-26) ────
        #: See the note at RELIEF_BODY_A. `h` before the material and the
        #: strike is exactly the chamfer's smoothstep, 0 at the border and
        #: AUR_BODY_RELIEF on the flat, so `1 - h/AUR_BODY_RELIEF` IS the
        #: wall — no second field to keep in step with the first (§15).
        #: The plateau then stays a smoke at the same order as the flat
        #: tile this replaces (WGLASS_FILL_A 70 + WGLASS_LIFT 26), so the
        #: baked label under it loses nothing, while the chamfer goes
        #: solid and carries the whole step.
        _wall = 1.0 - _np.clip(_hch / max(1e-6, AUR_BODY_RELIEF), 0.0, 1.0)
        #: ── AND ONCE THE PANE OWNS THE TYPE, THE SMOKE IS OVER ───────
        #: (2026-08-26, second pass) The split above exists so the FLAT
        #: baked label can be read through the plateau. The pane now
        #: carries that label itself, raised, and both of them on one
        #: sector is the "two BRIEFING marks" this file has refused twice
        #: — once by declining to draw a glyph, once here by covering the
        #: one it sampled. Opaque is therefore not a taste change; it is
        #: the second half of taking the type over, and it arrives in the
        #: same branch as the sampling so the two can never disagree.
        #:
        #: NOTHING ELSE IS LOST TO IT. Everything home.html bakes inside
        #: this sector except the type — the 2 px stroke, the occluded
        #: hairline at inset 2.2, STERLING's gold ring at inset 5, the
        #: contact shade at +5.5 — sits at less than a chamfer's depth
        #: and has been under the OPAQUE WALL since this morning.
        #: THE SMOKE IS NOT DELETED, IT IS RESOLVED. Going opaque without
        #: this would hand every pane its own undiluted body colour, and
        #: five tiles that were a dark graphite at 38% arrive as five
        #: saturated chips — the "christmas tree" this row's amber note
        #: spends a paragraph forbidding, produced as a side effect of a
        #: change about type. So the plateau composites over the bake's
        #: own ground HERE, at the same 38%, and what leaves this function
        #: is the picture that shipped this morning with the legend lifted
        #: out of it. The walls and the type are exempt: a wall is metal
        #: and the legend is the thing being raised.
        _body_a = RELIEF_WALL_A if _tl is not None else RELIEF_BODY_A
        _op = _body_a + (RELIEF_WALL_A - _body_a) * _wall
        if _tl is not None:
            _mix = (RELIEF_BODY_A / 255.0
                    + (1.0 - RELIEF_BODY_A / 255.0)
                    * _np.clip(_np.maximum(_wall, ico), 0.0, 1.0))[..., None]
            lit = lit * _mix + _tl[2] * (1.0 - _mix)
    a = _np.where(inside, _np.clip(dist / 1.4, 0.0, 1.0) * _op, 0.0)
    #: ── THE GROOVE, NOT A CAST SHADOW (2026-08-19, night) ─────────────
    #: What was here was `_height(-6, -7)` at alpha 150 — the pane's own
    #: silhouette offset down-right, i.e. the shadow a RAISED tile throws
    #: onto the surface behind it. That is the geometry of something
    #: floating ON the bezel, and it was arguing with every other cue in
    #: this function. A recessed pane has no cast shadow at all; what it
    #: has is a soft dark fringe all the way round, where the pocket wall
    #: meets the glass. Symmetric, so it says "set into" rather than
    #: "hovering above".
    _sil = Image.fromarray((inside * 255).astype("uint8"), "L")
    _grv = (_np.asarray(_sil.filter(ImageFilter.GaussianBlur(5.0)),
                        dtype="float32") / 255.0)
    shadow = _np.clip(_grv - inside, 0.0, 1.0) * AUR_CAST_A
    if RELIEF_PANES:
        #: ── AND THE RAISED PANE GETS ITS CONTACT SHADOW BACK ─────────
        #: (2026-08-26) The groove above is a symmetric fringe: it says
        #: "set into". The pane's own silhouette offset AWAY from the key
        #: says "sitting on", which is the whole of "extrusion" as the eye
        #: reads it, and it is what the WGLASS tile has been drawing with
        #: strokes since 08-09 (WGLASS_SH_DX/DY, same direction, same
        #: reason — down-right, away from POCKET_KEY).
        #:
        #: AND IT HAS TO BE BLACK. `lit` is computed over the whole box,
        #: so the pixels OUTSIDE the pane already hold a lit pane colour;
        #: pasting those as a shadow would put a pale halo on a near-black
        #: dial and read as a glow, not as contact. That is the ambient-bed
        #: mistake in visual form (§6) — a value that sounds like shadow,
        #: landing above the ground it is meant to darken. So the colour
        #: outside the silhouette is forced to black and only the alpha
        #: carries the shape.
        _cs_ = _np.clip(_height(-RELIEF_CAST_DX, -RELIEF_CAST_DY) / 1.4,
                        0.0, 1.0)
        _cs_ = _np.asarray(
            Image.fromarray((_cs_ * 255.0).astype("uint8"), "L").filter(
                ImageFilter.GaussianBlur(RELIEF_CAST_BLUR)),
            dtype="float32") / 255.0
        shadow = _cs_ * RELIEF_CAST_A * (~inside)
        lit = lit * inside[..., None]
    rgba = _np.zeros((H, W, 4), "uint8")
    rgba[..., :3] = _np.clip(lit, 0, 255).astype("uint8")
    rgba[..., 3] = _np.clip(a + shadow, 0, 255).astype("uint8")
    sprite = Image.fromarray(rgba, "RGBA")
    #: NO TEXT (2026-08-16). The labels were auto-fitted per pane and
    #: so came out at five different sizes — 'the fonts are all over
    #: the place', correctly. The glyph carries the meaning now, and
    #: what each one means is taught during enrolment, where there is
    #: a voice to explain it and nobody is squinting at a dial.
    #: ── THE DISSOLVE FIELD (2026-08-17) ──────────────────────────────────
    #: Owner: "a subtle mist / dissolve effect when the tiles fade in and
    #: similarly when they fade out." A uniform alpha ramp is a dimmer
    #: switch — the whole pane arrives at once, just faintly at first.
    #: Condensation is per-pixel and ORDERED: some of the glass exists
    #: before the rest of it does.
    #:
    #: So each pane carries a field saying WHEN each pixel arrives. It is
    #: low-frequency noise (soft blobs, not television static) biased by
    #: radius, so the pane condenses from its inner edge outward and
    #: evaporates the same way in reverse. Baked with the sprite, because
    #: it never changes; at draw time it costs one point() and a multiply.
    _dn = _np.zeros((H, W), "float32")
    _rng = _np.random.default_rng(1000 + i)
    #: TWO OCTAVES. One low-frequency field dissolves in smooth gradients
    #: — which reads as translucency, not mist. The finer octave breaks
    #: the boundary into wisps, which is what the eye calls vapour.
    def _oct(cells):
        a = _rng.random((cells, cells)).astype("float32")
        return _np.asarray(
            Image.fromarray((a * 255).astype("uint8"))
            .resize((W, H), Image.BICUBIC), dtype="float32") / 255.0
    _dn = _np.clip(0.68 * _oct(7) + 0.32 * _oct(22), 0.0, 1.0)
    #: bias: 0 at the inner edge, 1 at the outer, so it grows outward
    _bias = _np.clip((r - _bR0) / max(1.0, _bR1 - _bR0),
                     0.0, 1.0)
    #: ── 0.42 -> 0.15 OF BIAS, AND WHY THE RIM FORCED IT ────────────────
    #: Owner, 2026-08-20: "the highlights are both DELAYED and too large
    #: for the wedges."
    #:
    #: The rim is gated on this field (see the arris block in
    #: draw_aurora_menu — a lit edge may not exist where its glass does
    #: not). The rim draws on BOTH edges of the pane; the bias makes the
    #: OUTER edge the last part to condense. So the outer stroke waited for
    #: the pane to finish. Measured, as the lag between a pane's first lit
    #: pixel and its rim's (scripts/measure_pane_highlight.py):
    #:
    #:     STERLING 0.23 s    VOLUME 0.21 s    SETTINGS 0.31 s
    #:
    #: a fifth of those fades, and always the thin-banded panes, because a
    #: thin band spends more of its width at high bias.
    #:
    #: TWO THINGS I TRIED FIRST, BOTH RECORDED BECAUSE THEY LOOK RIGHT:
    #:  1. A SCALAR gate — dim the rim by how much of the pane exists.
    #:     That is the whitelist answer: it dims the complete outline
    #:     without removing it. test_arris_not_before_glass caught it at
    #:     63% of the rim over nothing.
    #:  2. Gating the rim on the UNBIASED noise, so it mists in evenly
    #:     while the glass still grows outward. That decouples exactly the
    #:     thing the guard asserts, and it failed too — 28% over nothing —
    #:     because the glass genuinely is not there yet at the outer edge.
    #:
    #: Neither can work while the body grows strongly outward: "the rim is
    #: where the glass is" and "the rim does not lag" are the same
    #: statement about one field, and 0.42 of bias is what put them in
    #: conflict. So the DIRECTION weakens. The pane still condenses with an
    #: outward tendency — it is 0.15, not 0 — but the mist is now mostly
    #: the two noise octaves, which is what reads as vapour anyway; the
    #: radial ramp was reading as a wipe.
    _dis = _np.clip(0.85 * _dn + 0.15 * _bias, 0.0, 1.0)
    dis = Image.fromarray((_dis * 255).astype("uint8"), "L")
    #: ── AND THE VAPOUR IT CONDENSES OUT OF ───────────────────────────────
    #: The pane's own silhouette, blurred wide and tinted its own colour.
    #: It peaks halfway through the transition and is gone at both ends,
    #: so the glass appears to come out of a breath of light rather than
    #: simply becoming opaque.
    #: ── AND THE HALO WAS WASHING TOWARD BLUE (2026-08-19) ────────────────
    #: `col + (40, 55, 70)` lifts the blue channel most, which is a
    #: deliberate cool cast and was fine when the halo lasted half a second.
    #: AUR_BLOOM_FLOOR is 0.66 now — this is a PERMANENT band of light
    #: around every pane — and the additive lift desaturates as it
    #: brightens, so seven halos converged on the same pale blue and joined
    #: up into the rim he is complaining about (see _aur_edge_tint).
    #:
    #: The halo is the pane's own coloured light, so it is now literally
    #: that: the same tint the arris takes. One statement of "what colour is
    #: this pane's light", read twice (§15), instead of two lifts that
    #: happened to agree while both were brief.
    vap = Image.new("RGBA", (W, H), (0, 0, 0, 0))
    #: ── THE HALO IS SIZED FROM THE PANE, NOT FROM A CONSTANT ─────────
    #: Owner, 2026-08-20: "the highlights are both delayed and TOO LARGE
    #: FOR THE WEDGES."
    #:
    #: "For the wedges" is a RATIO and that is the whole fix. 14 px of
    #: sigma reaches about 42 px, and the ring is GRADUATED — its panes are
    #: 140 px thick at BRIEFING and 99 px at POWER (wedge_band). So the
    #: same halo was 30% of one pane's thickness and 42% of another's, and
    #: on the thin ones it stopped being an edge and became a band running
    #: the length of the glass. Rendered at the peak of the fade, which is
    #: the moment he is describing and the moment nobody had looked at, the
    #: pane reads as a dark plate with a fat grey sweep along both long
    #: edges rather than a pane of glass with a lit rim.
    #:
    #: Tied to the pane's own band now, so every pane in a graduated ring
    #: gets the same PROPORTION of glow — which is what "for the wedges"
    #: asks for, and which cannot drift the next time the radii move.
    _va = sprite.getchannel("A").filter(
        ImageFilter.GaussianBlur(max(3.0, (_bR1 - _bR0) * AUR_BLOOM_SIG_K)))
    #: ── AND THE HALO LEANS AWAY FROM THE LAMP (2026-08-19, night) ─────
    #: An even halo on all four sides of all seven panes is the same
    #: "sticker" statement the arris was making, just softer and wider —
    #: and with AUR_BLOOM_FLOOR at 0.66 it is permanent, so it was the
    #: larger half of the glow. Weighted by the SAME `_kg` the face
    #: gradient uses, so the light pools on the side the key reaches and
    #: thins to a third on the side in shadow. It still surrounds the
    #: pane — the arrival has to read as a breath the glass condenses out
    #: of, and he has asked for that bloom three times — it simply stops
    #: being symmetric.
    _vg = _np.clip(0.34 + 0.66 * _kg, 0.0, 1.0)
    #: ── AND IT FADES INTO THE RIM RATHER THAN BEING CUT BY IT ────────
    #: Owner: "the wedges look good close to the perimeter but the
    #: highlighting of them when they transition in is totally off."
    #:
    #: The halo is a 14 px-sigma blur, so it reaches about 42 px, and it
    #: lives inside the sprite's box which carries pad=22 — and that box is
    #: CLAMPED at the panel edge. Measured, as the alpha the halo was still
    #: at when its box ended (0-8 means it faded out; 40+ is an amputation
    #: with a visible straight edge):
    #:
    #:     band 404..524   worst  28
    #:     band 412..532   worst  66      <- what shipped before today
    #:     band 420..540   worst 121      <- after pushing to the rim
    #:
    #: So this was already wrong and moving the ring out doubled it. He
    #: likes where the panes are, so the band stays and the LIGHT is what
    #: changes — which is also the rule the last wedge pass earned: colour
    #: and glow live in the light, not in the body.
    #:
    #: A square box cannot fade a round thing. The falloff is therefore
    #: RADIAL, keyed to the glass itself: full brightness until 26 px
    #: inside the rim, zero at the rim. Nothing is lost — everything past
    #: r=540 was off the panel anyway — but it now ARRIVES at zero instead
    #: of being sliced, and a pane at the rim glows inward the way a light
    #: behind glass actually would.
    _vr = _np.clip((SIZE / 2.0 - r) / AUR_BLOOM_RIM_FADE, 0.0, 1.0)
    #: ── A HALO IS AROUND A THING, NOT ON IT (2026-08-20) ─────────────
    #: Owner: "the fade in is still ridiculously off with oversized
    #: highlights over the wedges."
    #:
    #: `_va` is GaussianBlur(14) of the pane's OWN alpha — and the blur of
    #: a solid shape is still solid in the middle. So what was called a
    #: halo was a wash laid across the whole pane. Measured, halo alpha
    #: inside the pane against outside it:
    #:
    #:     pane 0   inside mean 129.4   outside mean 4.9   ratio 26x
    #:     pane 3   inside mean 118.7   outside mean 2.3   ratio 51x
    #:
    #: Twenty-six to fifty times more glow ON the pane than around it, at
    #: up to 62% alpha mid-arrival. That is the oversized highlight, and it
    #: is why the fade reads as a bright slab appearing rather than a pane
    #: condensing.
    #:
    #: The fix is the standard outer-glow construction: subtract the shape
    #: from its own blur, so the interior cancels and only the spread
    #: survives. AUR_BLOOM_ON_PANE leaves a little behind on purpose — he
    #: has asked for that breath three times and a hard zero would remove
    #: it entirely, which is the other complaint waiting to happen.
    _vsrc = _np.asarray(sprite.getchannel("A"), dtype="float32")
    _vout = _np.clip(_np.asarray(_va, dtype="float32")
                     - _vsrc * (1.0 - AUR_BLOOM_ON_PANE), 0.0, 255.0)
    _va = Image.fromarray(
        _np.clip(_vout * _vg * _vr, 0, 255).astype("uint8"), "L")
    vap.paste(Image.new("RGB", (W, H), _aur_edge_tint(col)), (0, 0), _va)
    _AUR_WEDGE_CACHE[key] = (sprite, (x0, y0), dis, vap)
    return _AUR_WEDGE_CACHE[key]


def _aur_wedge(d, c: int, a0: float, a1: float, col: tuple,
               k: float, name: str, font) -> None:
    """One wedge, in the AP's own glass grammar (see WGLASS_FILL_A): a
    drop shadow down-right away from the key, smoked fill that LIFTS
    toward the foot, a pale stroke with an inner hairline, a specular on
    the lit flank, and the label set HORIZONTALLY with three-pass relief.

    The first cut had none of this — flat bands and tangential type — and
    the owner's read was exactly right: no refinement, no depth, and a
    label you cannot read is furniture, not a control.
    """
    a0i, a1i = a0 + 1.4, a1 - 1.4
    #: 1 — THE SHADOW, down-right, away from POCKET_KEY. Drawn first and
    #: wide, so the wedge sits ON the face rather than in it.
    for _o, _a in ((7, 60), (5, 90), (3, 110)):
        d.arc((c - WEDGE_R1 + _o, c - WEDGE_R1 + _o,
               c + WEDGE_R1 + _o, c + WEDGE_R1 + _o), a0i, a1i,
              fill=(0, 0, 0, int(_a * k)),
              width=int(WEDGE_R1 - WEDGE_R0))
    #: 2 — THE SMOKE, in bands from the lit inner edge to the darker foot
    #: (WGLASS_FILL_A / WGLASS_LIFT: more of it at the foot, always).
    bands = 7
    step = (WEDGE_R1 - WEDGE_R0) / bands
    for b in range(bands):
        r_out = WEDGE_R1 - b * step
        r_mid = r_out - step / 2.0
        lift = b / float(bands - 1)                 # 0 at foot, 1 at head
        a = int((70 + 26 * (1.0 - lift)) * k * 0.55)
        d.arc((c - r_mid, c - r_mid, c + r_mid, c + r_mid), a0i, a1i,
              fill=(int(col[0] * 0.34), int(col[1] * 0.36),
                    int(col[2] * 0.42), a), width=int(step) + 2)
    #: 3 — THE STROKE PAIR: a pale outline on the outer edge and a bright
    #: hairline just inside it. Two lines, not one — that is the whole
    #: difference between a pane of glass and a filled shape.
    _ro = WEDGE_R1 - 3
    d.arc((c - _ro, c - _ro, c + _ro, c + _ro), a0i, a1i,
          fill=col + (int(150 * k),), width=3)
    _ri = WEDGE_R0 + 4
    d.arc((c - _ri, c - _ri, c + _ri, c + _ri), a0i, a1i,
          fill=col + (int(230 * k),), width=3)
    d.arc((c - _ri - 3, c - _ri - 3, c + _ri + 3, c + _ri + 3), a0i, a1i,
          fill=(235, 250, 255, int(96 * k)), width=1)
    #: 4 — THE SIDE EDGES, so the pane has four sides and not two
    for _a in (a0i, a1i):
        _ra = math.radians(_a)
        d.line((c + WEDGE_R0 * math.cos(_ra), c + WEDGE_R0 * math.sin(_ra),
                c + WEDGE_R1 * math.cos(_ra), c + WEDGE_R1 * math.sin(_ra)),
               fill=col + (int(120 * k),), width=2)
    #: 5 — THE SPECULAR: a THIN sheen along the lit inner edge. The first
    #: cut was a third of the pane wide at alpha 46 and landed as a grey
    #: rectangle sitting on the glass — a highlight you can point at is a
    #: smudge. It belongs against the edge that catches the key, narrow.
    _rs = WEDGE_R0 + (WEDGE_R1 - WEDGE_R0) * 0.17
    d.arc((c - _rs, c - _rs, c + _rs, c + _rs),
          a0i + (a1i - a0i) * 0.10, a0i + (a1i - a0i) * 0.62,
          fill=(255, 255, 255, int(30 * k)),
          width=int((WEDGE_R1 - WEDGE_R0) * 0.12))
    #: 6 — THE LABEL, HORIZONTAL, with the house relief. Placed at the
    #: pane's centroid and shrunk to whatever actually fits there: a wedge
    #: on the flank has only its radial depth to give a horizontal word,
    #: and the honest answer to "it does not fit" is a smaller face, never
    #: a word running off the glass.
    mid = math.radians((a0 + a1) / 2.0)
    rc = (WEDGE_R0 + WEDGE_R1) / 2.0
    tx, ty = c + rc * math.cos(mid), c + rc * math.sin(mid)

    #: HOW WIDE IS THE PANE, HERE? Not a formula — a MEASUREMENT. The
    #: estimate this replaces was generous by a third and every long label
    #: hung over its own edge, which is the exact complaint. Walk outward
    #: from the centroid until a point leaves the annular sector; that
    #: distance is the truth, and it costs 40 point-tests.
    def _inside(x, y) -> bool:
        _r = math.hypot(x - c, y - c)
        if not (WEDGE_R0 + 10 <= _r <= WEDGE_R1 - 10):
            return False
        _a = (math.degrees(math.atan2(y - c, x - c)) - a0) % 360.0
        return _a <= (a1 - a0) - 3.0
    half = 0.0
    for _dx in range(6, 220, 6):
        if _inside(tx - _dx, ty) and _inside(tx + _dx, ty) \
                and _inside(tx - _dx, ty - 13) \
                and _inside(tx + _dx, ty - 13) \
                and _inside(tx - _dx, ty + 13) \
                and _inside(tx + _dx, ty + 13):
            half = _dx
        else:
            break
    avail = max(60.0, half * 2.0)
    f = font
    for _sz in (34, 31, 28, 25, 22, 19):
        f = _font(_sz)
        if d.textlength(name, font=f) <= avail:
            break
    w = d.textlength(name, font=f)
    h = f.size
    d.text((tx - w / 2 + 2, ty - h / 2 + 2), name, font=f,
           fill=(0, 0, 0, int(200 * k)))
    d.text((tx - w / 2, ty - h / 2), name, font=f,
           fill=col + (int(250 * k),))
    d.text((tx - w / 2 - 1, ty - h / 2 - 1), name, font=f,
           fill=(240, 252, 255, int(120 * k)))


#: ── AuraVision ON THE RIM (2026-08-17) ──────────────────────────────────
#: Owner: "can you find an elegant / tasteful way to fill the outer rim of
#: the wedges with AuraVision with a font that hugs the edge of the screen
#: and looks futuristic. and also have it transition the same way as the
#: wedges, this time, letter by letter."
#:
#: THE CASE IS THE BRAND and he asked for it explicitly: AuraVision, not
#: AURAVISION. Two capitals, one word — the same lockup the logo uses.
#:
#: SET ON A PATH, not on a line. Each glyph is rendered on its own and
#: rotated so its baseline is tangent to the circle at its own bearing, so
#: the word bends with the glass instead of being a straight caption near
#: a curve. Centred at twelve o'clock and reading clockwise, which is where
#: the eye starts on a round face.
#:
#: LETTER BY LETTER, ON THE PANES' OWN SCHEDULE. Not a schedule that
#: resembles it — the same `_ui_step`, with each letter mapped
#: proportionally onto the pane sequence so ten letters spread across
#: exactly the span seven panes take. The word therefore finishes
#: condensing at the moment the ring does, and dissolves with it. A
#: wordmark on its own timer would drift the first time either is tuned,
#: which is the mistake this file has already paid for twice.
AUR_MARK_TEXT = "AuraVision"
#: ── ON THE BAND'S OWN CENTRE LINE (2026-08-17, fourth cut) ──────────────
#: Owner: "group the letters closer together, move them closer to the
#: center of the puck to align with the median of the wedges."
#:
#: It was out at 517 — hugging the glass, which is what "hugs the edge of
#: the screen" asked for, and wrong once it moved into the gap BETWEEN the
#: panes: out there it belongs to the bezel, while the panes it sits
#: between are centred 60 px further in. A ring of elements reads as one
#: ring only if they share a centre line. So the mark takes the band's
#: median, derived rather than typed, and moves whenever the band does.
#: a CEILING, not a size -- `_mark_fit_px` solves the real one against the
#: gap and only ever comes down from here. Raised 40 -> 58 when the word
#: lost six letters and the fitter suddenly had room it could not use.
AUR_MARK_PX = 59


def _mark_radius() -> float:
    r0, r1 = wedge_band()
    return (r0 + r1) / 2.0
#: ── WIDE, AND THE SPAN IS MEASURED (2026-08-17) ─────────────────────────
#: The first cut typed a 112 degree span, which at this radius gave each of
#: ten glyphs ninety pixels of arc to sit in — the word came out as ten
#: separate letters drifting apart, and it ran clean over the panes because
#: nothing related the number to the text.
#:
#: The span is derived now: measure the string, add the tracking, and
#: convert that arc length to degrees at AUR_MARK_R. Change the word, the
#: weight or the size and the placement follows on its own.
#: 0.30 -> 0.14 em: at the old tracking, spread across a 96 degree gap,
#: the letters stopped being a word and became ten marks on a rim —
#: "group the letters closer together". Tight enough to read as a lockup,
#: open enough to breathe.
AUR_MARK_TRACK = 0.05
#: -- "AURAVISION INSIDE", AND IT STOPPED BENDING (2026-08-17) ------------
#: Owner, having lived with the radial cut: "I changed my mind about
#: AuraVision, it's too hard to read in the radial way. Make the letters
#: grounded to the direction of the display at the time and have the
#: letters spell out AuraVision Inside and do not skimp on how elegant to
#: make the letters either, every magic trick in the book."
#:
#: He is right, and the reason is worth writing down because "put the words
#: on the rim" is an instinct this file will have again. Text on an arc is
#: legible when the arc is shallow -- a banner across the top of a seal
#: bends a couple of degrees per letter. Ours bent 4.4 degrees per letter
#: and sat in the LOWER half, where the whole word has to be set upside
#: down to face the reader at all. Every letter arrives at a different
#: angle, the eye re-orients for each one, and the word never resolves into
#: a shape. Curved type is a decoration you read second; a wordmark is the
#: thing you read first.
#:
#: So it is one horizontal lockup now, and -- the part that actually
#: answers "grounded to the direction of the display" -- it stays
#: horizontal WHILE THE DIAL TURNS. The face rotates under the finger; the
#: mark counter-rotates so it is upright to the person at every angle,
#: which is what an applied logo on a watch dial does and why one is always
#: readable.
#:
#: That forces the position. A 300 px lockup centred on the band's median
#: at 460 would hang off the glass the moment it stopped bending -- an arc
#: fits things a chord cannot. It moves inboard to the void between the
#: iris rim and the pane band, at six o'clock: the one region of this face
#: that is empty at every rotation, wide enough for the word, and exactly
#: where a dial puts its maker's name.
#: -- "INSIDE" GOES, AND THE WORD GETS THE ROOM (2026-08-17) -------------
#: Owner: "shorten it to AuraVision and make the font larger and bolder and
#: separate Aura from Vision so Aura is bold or something, and spruce it up
#: it's barely legible at this point. And start from south to north with
#: AuraVision, i think it might read easier that way."
#:
#: All four notes are the same note. Sixteen letters in a 126 degree gap
#: forced the fitter down to 31 px, and 31 px of lit relief on a starfield
#: is exactly "barely legible" -- the bevel needs a face to sit on and at
#: that size there is not one. Ten letters in the same gap fit at nearly
#: twice the size, so dropping the companion word IS the legibility fix;
#: the size follows on its own because the fitter derives it.
#:
#: The weight break replaces the hairline rule that used to separate the
#: two words: "Aura" in Medium with a stroke, "Vision" in Regular. It says
#: the same thing the rule said -- these are two words -- without spending
#: a letter's worth of arc on saying it.
AUR_MARK_BOLD_N = 4           # "Aura" carries the weight; "Vision" does not
AUR_MARK_STROKE = 0.055       # em, added to the bold run only
#: -- AND THEN BACK ONTO THE RING, STILL UPRIGHT (2026-08-17) -----------
#: Owner, on the horizontal lockup at six o'clock: "I see the AuraVision
#: Inside and it's a nice contrast in both font and boldness but i wanted
#: it around the ring in some clever way to fill in (subtly) the space
#: between the wedges and the gap they leave on the left."
#:
#: So both things at once, which is the part that took a cut to see. The
#: complaint about the radial version was never that the word was on the
#: rim -- it was that each letter was TURNED to the rim, so the eye had to
#: re-orient sixteen times and the word never resolved. Those are separable.
#: The letters now sit along the gap's arc, at the band's own median, and
#: every one of them stands upright to the reader. The word follows the
#: ring; the reading does not have to.
#:
#: It is laid out from the top of the gap downward, because the gap runs
#: from just past twelve o'clock round to the lower left and that is the
#: direction a column of upright letters is read in.
AUR_MARK_MARGIN2_DEG = 9.0     # air at each end of the gap
#: how much the tracking may open to fill the gap. 1.0 is the word at its
#: natural width, centred; past about 1.9 the letters stop being a word
#: again, which is the failure the first radial cut shipped.
AUR_MARK_FILL_MAX = 1.85
#: half-width of the window either side of due left in which an upright
#: letter still reads as part of a column rather than as a step sideways.
#: 48 degrees puts the last letter's tangent at 42 degrees off vertical,
#: which is about where a stacked lockup stops looking stacked.
AUR_MARK_LEGIBLE_DEG = 48.0
#: rendered at 3x and resolved down. At 40 px the difference between this
#: and direct rasterisation is the difference between "premium" and "a
#: label" -- the bevel is two pixels wide and needs sub-pixel truth to read
#: as an edge rather than as a jagged outline.
AUR_MARK_SS = 3


#: ── IT FILLS THE GAP (2026-08-17) ───────────────────────────────────────
#: Owner: "Aura Vision is landing terribly, not spaced correctly, it should
#: be between the end and the start of the wedges."
#:
#: It WAS between them — centred in the gap — but occupying only a third of
#: it, so ten letters huddled in the middle of a hundred and twenty degrees
#: of empty rim and read as an accident rather than a lockup. Measuring the
#: string was the wrong instinct: that gives the tightest arc that FITS,
#: and what the space asks for is the arc that BELONGS. The word now spans
#: the gap between the last pane and the first, less a margin at each end
#: so it never crowds a corner — and the tracking falls out of that rather
#: than being typed, which is what makes it look set rather than placed.
AUR_MARK_MARGIN_DEG = 15.0


def _mark_gap() -> tuple:
    """(start, end) of the arc the panes leave empty, in degrees."""
    ws = wedges()
    return ws[-1][1], ws[0][0] + 360.0


def _mark_span_deg() -> float:
    """The arc the WORD occupies — measured, and centred in the gap.

    Filling the gap was the previous cut and it was worse: a word stretched
    to fit a space is a word nobody set. Measure the string at its own
    tracking and let it sit in the middle of the arc with air on both
    sides, which is what a lockup on a bezel actually looks like.
    """
    f = face("mark", AUR_MARK_PX)
    d = ImageDraw.Draw(Image.new("L", (8, 8)))
    w = sum(d.textlength(c, font=f) for c in AUR_MARK_TEXT)
    w += AUR_MARK_TRACK * AUR_MARK_PX * max(0, len(AUR_MARK_TEXT) - 1)
    return math.degrees(w / _mark_radius())


def _mark_centre_deg() -> float:
    """The middle of the arc the panes DO NOT occupy.

    The ring leaves this part of the rim deliberately blank, for the tap
    that dismisses it. That is exactly where a wordmark belongs: it fills
    the one part of the rim with nothing on it, and it can never collide
    with a pane because it is DEFINED as the place the panes are not.
    """
    a0, a1 = _mark_gap()
    return ((a0 + a1) / 2.0) % 360.0
_AUR_MARK_CACHE: dict = {}


def _mark_alpha(now: float, i: int, n: int) -> float:
    """Letter i's alpha, on the panes' schedule.

    The letter's position is mapped onto the pane sequence rather than
    given its own: with 7 panes and 10 letters, letter i behaves like pane
    i*(7-1)/(10-1). `_ui_step` takes a float happily, so the profile — the
    stagger AND the per-position duration — is literally the same curve.
    """
    k = i * (len(wedges()) - 1) / max(1, n - 1)
    d, dur = _ui_step(k)
    if not _AUR_UI["vis"]:
        return 0.0
    if _AUR_UI["hide_t0"]:
        #: leaving is the arrival reversed, exactly as the panes do it
        j = (len(wedges()) - 1) - k
        d2, dur2 = _ui_step(j)
        t = now - _AUR_UI["hide_t0"] - d2
        return max(0.0, min(1.0, 1.0 - max(0.0, t) / dur2))
    t = now - _AUR_UI["show_t0"] - d
    return max(0.0, min(1.0, max(0.0, t) / dur))


def _mark_lockup(px_pt: float):
    """The whole wordmark as one lit-metal plate. Cached; built once.

    -- EVERY TRICK IN THE BOOK, AND WHY EACH ONE IS HERE ------------------
    Owner: "do not skimp on how elegant to make the letters either, every
    magic trick in the book, ok?" Six, in the order they matter:

      1. SUPERSAMPLING. Everything below is computed at 3x and resolved
         with Lanczos. The bevel is about two device pixels wide, so every
         other trick here is invisible without it -- this is the one that
         pays for the rest.
      2. A HEIGHT FIELD, not an emboss. The mask is blurred twice, tight
         and wide, into a plateau with a rounded shoulder; normals come off
         its gradient. Same construction as the sub-dial pockets and the
         pane chamfers, which is why it sits in the same room as them.
      3. BLINN-PHONG off the house key at upper-left, with two specular
         lobes -- a tight one for the arris and a broad one for the sheen.
         One lobe gives you plastic; two give you metal.
      4. A GRADIENT DOWN THE FACE. Real applied lettering is brighter at
         the top because it faces a sky. A flat fill under perfect lighting
         still reads as printed.
      5. A CONTACT SHADOW: the mask, blurred and dropped two pixels, and
         SUBTRACTED rather than drawn. Something raised occludes what is
         behind it, and that occlusion is most of what says "raised".
      6. A HAIRLINE RULE between the two words. It is the detail that makes
         a lockup look set rather than typed.

    Returns (rgb, mask, occ, spans) -- spans being each letter's column
    range in final coordinates, so the letter-by-letter arrival survives.
    """
    got = _AUR_MARK_CACHE.get(("lockup", round(px_pt, 1)))
    if got is not None:
        return got
    import numpy as _np
    S = AUR_MARK_SS
    px = int(px_pt * S)
    f = face("mark", px)
    fs = face("markr", px)
    sw = max(1, int(round(AUR_MARK_STROKE * px)))
    tr = AUR_MARK_TRACK * px
    probe = ImageDraw.Draw(Image.new("L", (8, 8)))

    #: lay the two words out first, so the plate is exactly as big as the
    #: thing on it. A plate sized by guesswork is a plate with the word off
    #: its centre, and three previous cuts of this got that wrong.
    items, x = [], 0.0
    for i, ch in enumerate(AUR_MARK_TEXT):
        bold = i < AUR_MARK_BOLD_N
        fo = f if bold else fs
        #: the stroke widens the glyph on both sides, and `textlength` does
        #: not know about it -- so it is added to the advance by hand. Left
        #: out, "Aura" sets tighter than it draws and the bold run crowds
        #: itself, which is the sort of thing that reads as bad kerning
        #: rather than as the bug it is.
        w = probe.textlength(ch, font=fo) + (2 * sw if bold else 0)
        items.append((ch, fo, x, w, sw if bold else 0))
        x += w + tr
    total = x - tr
    pad = px
    W, H = int(total + pad * 2), int(px * 2.4)
    #: the primary's baseline; the companion sits on the SAME one, which is
    #: what makes two sizes read as one line rather than as two things
    base = H * 0.68

    im = Image.new("L", (W, H), 0)
    d = ImageDraw.Draw(im)
    for ch, fo, ox, _w, st in items:
        if st:
            d.text((pad + ox + st, base), ch, font=fo, fill=255, anchor="ls",
                   stroke_width=st, stroke_fill=255)
        else:
            d.text((pad + ox, base), ch, font=fo, fill=255, anchor="ls")

    m = _np.asarray(im, dtype=_np.float32) / 255.0
    b1 = _np.asarray(im.filter(ImageFilter.GaussianBlur(1.0 * S)),
                     dtype=_np.float32) / 255.0
    b2 = _np.asarray(im.filter(ImageFilter.GaussianBlur(2.4 * S)),
                     dtype=_np.float32) / 255.0
    hf = m * 0.56 + b1 * 0.29 + b2 * 0.15
    gy, gx = _np.gradient(hf)
    nx, ny = -gx * (20.0 * S), -gy * (20.0 * S)
    nz = _np.ones_like(nx)
    nl = _np.sqrt(nx * nx + ny * ny + nz * nz)
    nx, ny, nz = nx / nl, ny / nl, nz / nl
    L = _np.array([-0.55, -0.62, 0.56], dtype=_np.float32)
    L /= _np.linalg.norm(L)
    Hv = L + _np.array([0.0, 0.0, 1.0], dtype=_np.float32)
    Hv /= _np.linalg.norm(Hv)
    diff = _np.clip(nx * L[0] + ny * L[1] + nz * L[2], 0.0, 1.0)
    ndh = _np.clip(nx * Hv[0] + ny * Hv[1] + nz * Hv[2], 0.0, 1.0)
    spec = ndh ** 52.0 * 1.20 + ndh ** 8.0 * 0.24
    #: trick 4 -- the sky is up, so the top of the face catches more of it
    yy = _np.linspace(0.0, 1.0, H, dtype=_np.float32)[:, None]
    sky = 1.16 - 0.34 * yy
    body = _np.array([120.0, 137.0, 158.0], dtype=_np.float32)     # platinum
    lit = body[None, None, :] * (0.30 + 1.18 * diff)[..., None]
    lit *= sky[..., None]
    lit += _np.array([248.0, 251.0, 255.0]) * spec[..., None]
    #: the shadowed side takes the room's blue, so it belongs to this face
    lit += _np.array([14.0, 24.0, 40.0]) * (1.0 - diff)[..., None]
    rgb = Image.fromarray(_np.clip(lit, 0, 255).astype("uint8"), "RGB")

    #: trick 5 -- occlusion, carried as its own plane so the caller can
    #: subtract it from the background before screening the metal on top
    occ = im.filter(ImageFilter.GaussianBlur(1.6 * S)).transform(
        im.size, Image.AFFINE, (1, 0, -0.8 * S, 0, 1, -2.0 * S))

    fw, fh = W // S, H // S
    rgb = rgb.resize((fw, fh), Image.LANCZOS)
    mask = im.resize((fw, fh), Image.LANCZOS)
    occ = occ.resize((fw, fh), Image.LANCZOS)
    spans = [((pad + ox) / S, (pad + ox + w) / S)
             for _c, _f, ox, w, _st in items]
    got = (rgb, mask, occ, spans)
    _AUR_MARK_CACHE[("lockup", round(px_pt, 1))] = got
    return got


def _mark_tiles(px_pt: float):
    """The plate, cut into one tile per letter. Cached.

    Cut at the MIDPOINTS between letters rather than at each letter's own
    box, so every column of the plate belongs to exactly one tile and none
    belongs to two. Padded tiles would be simpler and would paint each
    neighbour's ink twice, which on a screen blend shows up as a ghost of
    the next letter riding half an em ahead of it.

    Slicing a single plate — rather than lighting each glyph on its own —
    is what keeps the sky gradient and the specular running continuously
    across the whole word. Sixteen independently lit letters are sixteen
    little objects; one lit plate cut up is a word.
    """
    got = _AUR_MARK_CACHE.get(("tiles", round(px_pt, 1)))
    if got is not None:
        return got
    rgb, mask, occ, spans = _mark_lockup(px_pt)
    cuts = [0]
    for i in range(len(spans) - 1):
        cuts.append(int(round((spans[i][1] + spans[i + 1][0]) / 2.0)))
    cuts.append(mask.size[0])
    tiles = []
    for i in range(len(spans)):
        x0, x1 = cuts[i], cuts[i + 1]
        tm = mask.crop((x0, 0, x1, mask.size[1]))
        #: the INK box, not the tile box. The tile carries the plate's full
        #: height and whatever padding the cut left it; spacing computed
        #: from that would push a lower-case 'i' as far from its neighbour
        #: as a cap. The layout wants to know how much room the mark
        #: actually occupies, and only the bbox knows that.
        bb = tm.getbbox() or (0, 0, 1, 1)
        #: and the ink's CENTRE relative to the tile's, so the layout can
        #: put the mark itself on the arc rather than the box around it —
        #: otherwise a letter with a descender rides high and one without
        #: rides low, and a stacked column shows that as a wobble
        tiles.append((rgb.crop((x0, 0, x1, rgb.size[1])), tm,
                      occ.crop((x0, 0, x1, occ.size[1])),
                      float(bb[2] - bb[0]), float(bb[3] - bb[1]),
                      (bb[0] + bb[2]) / 2.0 - tm.size[0] / 2.0,
                      (bb[1] + bb[3]) / 2.0 - tm.size[1] / 2.0))
    _AUR_MARK_CACHE[("tiles", round(px_pt, 1))] = tiles
    return tiles


def _mark_window():
    """(low, high) bearing the word may occupy, in degrees. None if there
    is no usable one.

    The panes leave about 150 degrees, and the first arc cut used all of
    it. The top of that arc is nearly horizontal, so consecutive upright
    letters step LEFTWARDS there and the word came out mirrored:
    "noisiVaruA". Upright letters read as a column only where the arc is
    steep, so the word is confined to the part of the gap within
    `AUR_MARK_LEGIBLE_DEG` of due left and the shallow top is left as air.

    Which is the right trade anyway. He asked for the space to be filled
    SUBTLY, and a word crammed into every available degree is the opposite
    of subtle -- it was already the failure of the cut before that one.
    """
    ws = wedges()
    g0, g1 = ws[-1][1], ws[0][0] + 360.0
    #: -- EQUIDISTANT FROM BOTH PANE ENDS (2026-08-17) --------------------
    #: Owner: "the phrase should land in between equidistant to where the
    #: last wedge ends and the next wedge begins."
    #:
    #: It was centred in the LEGIBLE WINDOW -- the part of the gap within
    #: 48 degrees of due left -- which is not the same point. The gap runs
    #: 148..274 here, so its own midpoint is 211 and the window's was 180:
    #: the word sat 31 degrees low and had more air above it than below,
    #: which is precisely what he is seeing. The window now IS the gap, so
    #: the centre is the midpoint between the two pane ends by
    #: construction, and it stays that way when a pane moves.
    #:
    #: What that costs is written down rather than quietly prevented: the
    #: gap's upper end runs toward twelve o'clock where the arc goes
    #: shallow, and upright letters placed there step sideways instead of
    #: stacking. AUR_MARK_LEGIBLE_DEG no longer clips the window; it is the
    #: number `scripts/check_wordmark.py` measures the placement against,
    #: so the trade is visible in a test rather than enforced behind his
    #: back. Bigger type with tighter leading is what keeps the word inside
    #: the steep part -- a shorter arc for the same ten letters.
    lo, hi = g0 + AUR_MARK_MARGIN2_DEG, g1 - AUR_MARK_MARGIN2_DEG
    return (lo, hi) if hi - lo >= 20.0 else None


def _mark_step(tiles, px_pt: float, lo: float, hi: float):
    """The arc, in pixels, from one letter's centre to the next.

    -- WHY ONE STEP PER WORD AND NOT ONE PER LETTER ----------------------
    The cut before this one advanced each letter by its own extent along
    the local tangent, which is correct in the sense that nothing collides
    and wrong in every other sense: the tangent is shallow at the ends of
    the arc and steep in the middle, so the ends got half again as much
    room as the middle and the word read as three spaced letters followed
    by a cramped braid. Optical evenness is the whole point of a lockup.

    So: one step for every letter, taken from the tallest of them. Even
    spacing, and a guarantee rather than a hope about collisions.
    """
    #: -- EVALUATED AT DUE LEFT, WHICH IS ALREADY THE WORST CASE ----------
    #: The obvious reading of "worst case over the window" is to take the
    #: largest |cos| AND the largest |sin| and add them, and that is what
    #: the first version of this did. It is worst-case nonsense: those two
    #: maxima occur at different bearings and cannot both apply to one
    #: letter. The result demanded 888 px of arc for 626 px of gap and
    #: shrank the type by a third to fit a constraint that did not exist.
    #:
    #: The real extremum is at due left, where the arc is steep and the
    #: whole of a letter's height has to clear the next one. Off to either
    #: end the tangent tilts, the height term shrinks by cos and the width
    #: term grows by sin, and for this face the sum falls: 48 px at the
    #: window edge against 52 at the centre. So one number, taken at 180,
    #: is both even and safe.
    #: -- LEADING, 1.16 -> 1.02 (2026-08-17) ------------------------------
    #: Owner: "don't distance the letters too far". 1.16 was chosen against
    #: the sixteen-letter lockup, where "Inside" set at half size and the
    #: tallest glyph therefore governed a step most letters did not need.
    #: At ten letters of one size the extremes sit much closer together, so
    #: the same generosity reads as gaps rather than as air.
    #:
    #: Tighter leading also buys arc, and arc is what pays for the third
    #: more type size he asked for in the same breath -- the two notes are
    #: one change, and doing either alone would have missed.
    step = 0.0
    for _g, _m, _o, iw, ih, _cx, _cy in tiles:
        step = max(step, ih * 1.02)
    return step + AUR_MARK_TRACK * px_pt


def _mark_fit_px():
    """The largest type size whose column still fits the gap. Derived.

    Every previous cut typed a size and then discovered whether it fitted,
    which is how a wordmark ends up either overrunning a pane or sitting
    in the middle of an arc it does not fill. The window is set by the
    panes; the panes have moved four times today. So the size is solved
    against the window instead, once, and cached -- move a pane and the
    mark resizes itself rather than needing a fifth pass.
    """
    got = _AUR_MARK_CACHE.get("fitpx")
    if got is not None:
        return got
    win = _mark_window()
    if win is None:
        _AUR_MARK_CACHE["fitpx"] = None
        return None
    lo, hi = win
    r = _mark_radius()
    usable = math.radians(hi - lo) * r          # px of arc
    px = float(AUR_MARK_PX)
    for _ in range(7):
        tiles = _mark_tiles(px)
        need = len(tiles) * _mark_step(tiles, px, lo, hi)
        if need <= usable:
            break
        px = max(13.0, px * (usable / need) * 0.985)
    _AUR_MARK_CACHE["fitpx"] = px
    return px


def _mark_layout(rot_deg: float = 0.0):
    """[(tile, bearing_deg)] plus the radius. One source for the painter
    and for `scripts/check_wordmark.py`, so the test cannot pass while the
    glass shows something else (S15)."""
    win = _mark_window()
    px = _mark_fit_px()
    if win is None or px is None:
        return [], 0.0
    lo, hi = win
    r = _mark_radius()
    tiles = _mark_tiles(px)
    step = _mark_step(tiles, px, lo, hi)
    run = step * len(tiles)
    #: centre the column in the window rather than hanging it from one end
    span = math.degrees(run / r)
    #: -- NORTH TO SOUTH, AFTER TRYING IT THE OTHER WAY -------------------
    #: Owner asked for south-to-north -- "i think it might read easier that
    #: way" -- and then, having looked at it: "i was wrong to north to
    #: south with AuraVision." So it climbs no longer. Which is the older
    #: and better answer: a column of upright letters is read downward
    #: because that is how a column of anything is read, and the fact that
    #: the bearing happens to decrease on the way down is bookkeeping, not
    #: something a reader can perceive. The first letter takes the HIGH end
    #: and the word descends.
    #:
    #: Both directions shipped and both were looked at on the glass, which
    #: is the only reason there is anything to say about it.
    start = (lo + hi) / 2.0 + span / 2.0
    _d = -rot_deg if INVERT else rot_deg
    out, cum = [], 0.0
    for t in tiles:
        mid = cum + step / 2.0
        cum += step
        out.append((t, start - math.degrees(mid / r) + _d))
    return out, r


#: ── THE LISTENING RIBBON (2026-08-17) ───────────────────────────────────
#: What fills the gap the panes leave, now that the wordmark is out of it.
#:
#: THE IDEA. The ring is a row of things you can press. The gap is the part
#: you press to make them go away, so it has to stay visibly empty of
#: controls — anything button-shaped there is a trap. But "empty of
#: controls" is not the same as "empty", and a third of the bezel reading
#: as missing is what he has been unhappy with through five wordmarks.
#:
#: So it gets the one thing this device does that nothing else on the glass
#: shows. The iris reacts to the room in the instant; the panes are state.
#: Neither has any MEMORY. The ribbon is ninety seconds of the room laid
#: along the arc: a hairline on the band's own centre line, continuing the
#: ring's geometry across the gap so the ring reads as a whole circle
#: again, with the level riding it as a waveform. Newest at the top, next
#: to the first pane, so the trace flows up into the ring.
#:
#: WHY IT IS THE RIGHT ANSWER AND A WORDMARK WAS NOT. A brand name is read
#: once. This face is looked at continuously, from across a room, by
#: someone who is doing something else. What belongs in a space like that
#: is something that rewards the second glance — and "was it hearing us
#: while we were talking?" is a question the owner has actually asked out
#: loud, more than once, at this device.
#:
#: WHEN THE ROOM IS SILENT it is a hairline and a drift of dust, which is
#: quieter than the wordmark ever was and is the honest picture: nothing
#: happened, and the device is still there.
#: 108 -> 64. Each slot is one alpha-blended line and the gap is 126
#: degrees, so 64 still puts a stroke every two degrees -- finer than the
#: 2 px stroke can resolve at this radius anyway. The extra 44 were paying
#: for nothing but frame time.
#: ── THE MIDDLE OF THE GAP, NOT THE WHOLE OF IT (2026-08-18) ───────────
#: Owner: "the ribbon should only render within the gap not go around the
#: whole display."
#:
#: Measured before changing anything (scripts/measure_ribbon_span.py), the
#: ribbon already occupied 109 degrees of a 108 degree gap, entirely inside
#: the pane band, at every dial angle. Geometrically it was doing exactly
#: what it was told. The complaint is real anyway: the GAP is 108 degrees —
#: most of a third of the ring — and a faint trace stretched from one pane
#: to the other fills the display's whole left side, which reads as sprawl
#: rather than as an instrument sitting in a space.
#:
#: This is the correction to last night's, and the two are not in conflict:
#: then it was using 78 of 108 degrees but OFF-CENTRE, hard against one
#: pane with all the dead space at the other end, because it had inherited
#: the retired wordmark's window. Filling the gap fixed the lopsidedness
#: and overshot. Centred air at BOTH ends is what was wanted both times.
#:
#: 0.62 with N at 40 is not a coincidence: 64 samples over 108 degrees is
#: 1.69 deg/sample, and 40 over 67 is 1.67. Identical density, same trace
#: to look at, 24 fewer alpha-blended line calls every frame.
#: 0.62 -> 0.78. Owner: "it should be widened out". 0.62 was set when
#: the trace filled its channel edge to edge and read as sprawl; a
#: single scope line does not, so it can have more of the arc back.
#: ── RETIRED, AND WITH IT THE LAST LITERAL IN THE SPAN (2026-08-20) ─────
#: Everything above STANDS WITH ITS DATES — 0.62 and 0.78 were both real
#: judgements about a real picture. What killed the constant is not that
#: either number was wrong, it is that a CENTRED FRACTION cannot express
#: what he asked for on the 20th: "it should be closer to the end wedge and
#: start wedge." A fraction says how much of the gap to use; it says
#: nothing about where the ends land, so every time the ring's radii or
#: angles moved this week the air at the ends moved with them and nobody
#: could see which.
#:
#: Measured the morning it was removed, seven panes, ink at 0.2 deg:
#: 20.80 deg of nothing between the ribbon and the pane at EACH end of a
#: 126 deg gap. That is the gap he is pointing at, and it is 9 (the
#: wordmark's AUR_MARK_MARGIN2_DEG, inherited) plus 11.8 (this fraction).
#: `_aur_ribbon_span` now names its air directly — see AUR_RIB_END_AIR_DEG
#: — so the ends are a stated distance from the wedges rather than
#: whatever two unrelated constants leave over.
#:
#: NOT left defined at 1.0. A constant nothing reads is the next stale
#: number somebody derives a second copy of the geometry from (§15), which
#: is the exact bug this whole block is a history of.
#: ── THE AIR AT EACH END, AND IT IS AIR ON PURPOSE (2026-08-20) ─────────
#: Owner, at the glass: "the default ribbon should still be larger to fill
#: that gap between the wedges ... it doesn't span the whole empty region
#: between the wedges, it should be closer to the end wedge and start
#: wedge."
#:
#: "Closer to", not "touching", and the difference is the whole reason this
#: has a name. A trace that runs flat into the pane's edge reads as ONE
#: object with a bite taken out of it — the ribbon stops looking like an
#: instrument sitting in the gap and starts looking like a wedge that
#: failed to render. A hairline of black at each end is what says the two
#: things are separate and deliberate.
#:
#: 2.0 deg is 16.8 px of arc at r 480 — a line's width, seen from a chair.
#: It is stated here, once, and both ends read it, so the next person finds
#: a named quantity rather than a residue and does not "tidy" it away.
#: ── 2.0 -> 5.5 DEG (2026-08-20, evening) ──────────────────────────────
#: Owner, on the ribbon he otherwise likes: "only adjustment is to create
#: a bit more distance between the both ends of the wedges, give it more
#: space."
#:
#: 2.0 was chosen this morning as "air on purpose" against his earlier
#: "closer to the end wedge and start wedge" — and it landed too close.
#: Both asks are the same axis and this is the second turn of it, so the
#: number is now his rather than mine: 5.5 deg each end, which at r=480 is
#: about 46 px of gap where 2.0 gave 17.
#:
#: Still DERIVED from wedges() at both ends, which is the property that
#: matters — the gap stays equal and stays true the next time the ring's
#: geometry moves. Only the constant changed.
AUR_RIB_END_AIR_DEG = 5.5
#: ── AND FOUR TIMES THE LINE (2026-08-20) ───────────────────────────────
#: Owner, same sentence: "make it 4x thicker a line." Multiplies the track
#: arcs in draw_aurora_ribbon — see the note at the loop for why it is a
#: multiplier over the 7/6/6 taper rather than three new numbers, and for
#: what it costs (+0.14 ms of a 0.9-3.6 ms t:ribbon, measured with the span
#: held fixed so the number is the STROKE and not the longer arc).
AUR_RIB_TRACK_K = 4.0
#: ── ONE HISTORY ROW PER DRAWN SLOT, OR IT STUTTERS (2026-08-18) ────────
#: Owner: "the way it is animating those bars is halting again ... it's just
#: skipping as it goes along the arc."
#:
#: Mine, from this morning. Narrowing the ribbon to 62% of the gap, I took N
#: from 64 to 40 to hold the sample density — and left AUR_RIB_KEEP at 64.
#: The line right below it says "one per drawn slot" and it stopped being
#: true in the same commit.
#:
#: The draw maps slot i onto row `len(h)-1-int((n-1-i)*len(h)/n)`. With 40
#: slots over 64 rows each step advances 1.6 rows, so int() rounds some
#: steps to 1 and some to 2 — the trace lurches along the arc, exactly the
#: skipping he is describing. Worse, _rib_frac scrolls by a fraction of one
#: SLOT while the data arrives one ROW at a time, so the smooth-scroll fix
#: from yesterday was compensating at 1/1.6 of the right rate.
#:
#: They are one number now, and the guard asserts it. This is the second
#: time the scroll has been broken by something that had nothing to do with
#: scrolling, and both times the cause was these two drifting apart.
#: ── HALF THE RATE, AND THE RATE IS NOW IN SECONDS (2026-08-20) ─────────
#: Owner, at the glass: "it's a bit sy[s]chophrenic in the beginning, move
#: the wave forms slower."
#:
#: TWO FAULTS, and "in the beginning" is the clue to the second. Measured
#: with scripts/measure_ribbon_motion.py, which follows the rendered trace
#: and reports DEGREES PER SECOND rather than px/frame:
#:
#:      8 fps   6.24 deg/s   1.54 waves/s   sampled every 0.2500 s (4.00 Hz)
#:      9 fps   7.40 deg/s   1.82 waves/s   sampled every 0.2222 s (4.50 Hz)
#:     12 fps   6.44 deg/s   1.59 waves/s   sampled every 0.2500 s (4.00 Hz)
#:     16 fps  10.87 deg/s   2.68 waves/s   sampled every 0.1875 s (5.33 Hz)
#:     25 fps   9.58 deg/s   2.36 waves/s   sampled every 0.2000 s (5.00 Hz)
#:
#: ONE constant, five different animations, and the device runs at 8-10 fps
#: while the ring is arriving and 16-25 once it is up — which is exactly
#: the two halves of what he is describing, in the order he saw them. The
#: sampler's gate (`now - t < 1/HZ`) is evaluated ONCE PER FRAME, so the
#: real interval is ceil(period / frame) * frame and 6 Hz is not achieved
#: at ANY of these frame rates: 4.00, 4.50, 4.00, 5.33, 5.00. Worse, the
#: painter's `_rib_frac` scrolled against the NOMINAL 6 Hz, so at 8 fps the
#: trace ramped for 0.167 s and then froze for 0.083 s — a third of every
#: cycle dead, then a jump. A rate quantised by the frame clock cannot be
#: anything but frantic, and no value of this constant fixes it.
#:
#: So the sampler now carries a DEADLINE it advances by exactly one period
#: (see aurora_ribbon_sample) and the painter interpolates between arrival
#: and the next due time (see `_rib_frac`), both in seconds. The scroll is
#: the same speed at 8 fps as at 25.
#:
#: THEN the halving, which is the part he actually asked for. 6.0 -> 3.0
#: takes the trace to 5.81 deg/s / 1.43 waves/s at every frame rate. The
#: window lengthens to ~21 s, which is the cost and it is the right one:
#: KEEP == N is load-bearing (the note above), so slots/s IS samples/s and
#: there is no way to slow the scroll without slowing the sampling. At 3 Hz
#: a spoken word still lands on one or two rows; this is an instrument that
#: says how loud the room has been, not a phonetic display.
AUR_RIB_N = 64                # samples drawn across the gap == AUR_RIB_KEEP
AUR_RIB_HZ = 3.0              # history sample rate, in Hz of WALL CLOCK
AUR_RIB_KEEP = 64             # ~21 s at 3 Hz, one per drawn slot
#: her voice runs warm, the room runs cool — the same split the panes use
#: how much of the ribbon's height the ambient baseline may use. 0.16 is a
#: visible stir at arm's length and nowhere near enough to be mistaken for
#: someone talking — speech routinely reaches 1.0 on the same scale.
#: 0.16 -> 0.30. Owner: "make the ribbon line larger so there is always
#: something there." This is the ambient component -- where a sample sits
#: between the quietest and loudest thing in the visible window -- and at
#: 0.16 a quiet room moved the trace about 6 px, which from a chair is a
#: straight line. At 0.30 the room's own breathing is visible without
#: competing with speech, which still saturates well above it.
#: 0.58 -> 0.38. Owner: "the wave form is too schizophrenic, it should
#: be modulated to have lower amplitude." The variance work is what he
#: wanted; the HEIGHT it was expressed at was mine, and a scope trace
#: that fills its channel reads as noise rather than as a reading.
AUR_RIB_FLOOR_K = 0.38
#: the quiet end of the ambient curve. Not zero: "always something
#: there" was the ask one message earlier, and a waveform that reaches
#: zero has gaps in it rather than quiet passages.
AUR_RIB_BASE = 0.08
#: ── AND THE CURVE GOES THE OTHER WAY (2026-08-18) ─────────────────────
#: This was 1.8, on the reasoning that a power curve above 1 separates a
#: quiet sample from a loud one. Measured against the level distribution
#: this actually sees, that is backwards: room tone is strongly skewed
#: LOW, so a gamma above 1 pushes the whole bulk down onto the base and
#: the bars bunch up again — 1.8 gave 1.5x the old spread where 0.6 gives
#: 2.7x, from the same audio.
#:
#: The bulk is where the variance lives. Expanding it upward (gamma < 1)
#: uses the height available; compressing it downward wastes it, however
#: tall the ceiling is. The sweep is in the commit message; K and gamma
#: were chosen together as the pair with the most spread and at most one
#: bar in sixty-four touching the rail.
AUR_RIB_GAMMA = 0.60
AUR_RIB_ROOM = (128, 196, 246)
AUR_RIB_HERS = (246, 206, 140)
_AUR_RIB: dict = {"t": 0.0, "due": 0.0, "h": []}


def aurora_ribbon_sample(now: float) -> None:
    """Take one reading of the room. Cheap, rate-limited, never raises.

    -- IT READS THE STATE, IT IS NOT HANDED IT (2026-08-17) --------------
    The first version took (e, tt, pp) as arguments, copying the signature
    of draw_entity_rings. Those three names exist inside draw_aurora_core,
    where they are unpacked from _AUR["st"]; the compositor's main loop,
    which is where this is called from, has never heard of them. It would
    have raised NameError on the first frame, outside any try, and taken
    the face down on both pucks — a compositor that must never stop,
    stopped by a wordmark replacement.

    Caught by asking whether the names were bound rather than by assuming
    that a call which compiles is a call that runs. Reading _AUR["st"]
    directly is also simply correct: one owner for the room's state, and
    no caller obliged to know what to pass (S15).
    """
    try:
        #: ── A DEADLINE, NOT A GAP SINCE LAST TIME (2026-08-20) ───────────
        #: This was `now - _AUR_RIB["t"] < 1.0 / AUR_RIB_HZ`, which is a
        #: rate expressed PER FRAME however much it looks like seconds: the
        #: test runs once a frame, so the first frame that passes it is the
        #: first WHOLE FRAME after the period, and the real interval is
        #: ceil(period / frame) * frame. Measured across the frame rates
        #: this device actually delivers, 6 Hz came out as 4.00, 4.50, 4.00,
        #: 5.33 and 5.00 Hz — and never as 6. 8 fps and 12 fps both landed
        #: on 0.25 s, one of them by a float hair (2 x 0.08333 is less than
        #: 1/6 by 1e-17, so the 12 fps case waits a third frame).
        #:
        #: Advancing a DUE TIME by exactly one period makes the mean rate
        #: exactly AUR_RIB_HZ at any frame rate above it — the frames still
        #: land where they land, but the error does not accumulate, it
        #: alternates. The resync branch is the anti-spiral: if we are more
        #: than a whole period late (a stalled compositor, a blocked read)
        #: the deadline restarts from now rather than trying to catch up by
        #: firing several times in a row, which would whip the trace.
        #: AND THE DEADLINE IS NEVER FURTHER OFF THAN ONE PERIOD. A stored
        #: absolute time is a bet on a monotonic clock, and this one is not:
        #: the puck gets its date from NTP after the network comes up, so
        #: `now` can step BACKWARDS by minutes on the first boot of the day.
        #: Without this line the ribbon would freeze until real time caught
        #: up — a trace that has stopped is indistinguishable from a crashed
        #: compositor (S1), and it would have been blamed on this change.
        _per = 1.0 / AUR_RIB_HZ
        _due = _AUR_RIB.get("due") or 0.0
        if _due - now > _per * 2.0:
            _due = 0.0
        if now < _due:
            return
        #: -- THE ARRAY, NOT THE ANIMATION (2026-08-17) -------------------
        #: Owner: "the ribbon is doing random things, why not make it geared
        #: towards volume or something that the mic picks up."
        #:
        #: He is right and the first version could not have been anything
        #: else. _AUR["st"]["e"] is not a level: it is 1.0 when
        #: `_pulse_phase` says "hearing" or "thinking" and 0.0 otherwise,
        #: low-passed at 2.4/s for the iris to breathe on. A trace of it is
        #: a rounded square wave whose height carries no information at all
        #: -- it says WHETHER she was listening, never how loud the room
        #: was, so two people talking and one person coughing draw the same
        #: picture. Plotting a state as though it were a magnitude is the
        #: whole of "doing random things".
        #:
        #: puck_ears already publishes the real thing to ROOM_FEED, and
        #: `_room_frac` already log-scales it the way the room meter uses.
        #: `None` there means the array answered nothing, which is NOT a
        #: silent room (S2) -- so it is held, not plotted as zero.
        d0 = _room_now(now)
        frac = _room_frac(d0.get("energy") if d0 else None)
        if frac is None:
            return
        #: ── THE RAW LEVEL, TOO (2026-08-18) ──────────────────────────────
        #: Owner: "ribbon should always at least have a baseline movement to
        #: keep the screen active even if the movement is small... pick up
        #: anything in the ambient noise otherwise it is just sad dead
        #: space."
        #:
        #: `_room_frac` is a SPEECH scale: it returns exactly 0.0 below
        #: ROOM_E0, which is correct for a meter answering "is anyone
        #: talking" and useless for a trace meant to show the room is being
        #: listened to. A quiet room produced a mathematically flat line —
        #: not a small movement, no movement — and a flat line on a dark
        #: arc is indistinguishable from a crashed process.
        #:
        #: So the raw energy is kept alongside it and the drawer scales
        #: against the window's OWN range (see AUR_RIB_FLOOR_K). Room tone,
        #: a fan, a chair — anything the array can hear — moves the trace.
        e = float(frac)
        raw = 0.0
        try:
            raw = float((d0 or {}).get("energy") or 0.0)
        except (TypeError, ValueError):
            raw = 0.0
        pp = 1.0 if _LISTEN.get("answering") else 0.0
        tt = 0.0
        _AUR_RIB["t"] = now
        #: the painter scrolls one slot between `t` and `due`, so this line
        #: is the whole speed of the animation and it is in seconds
        _AUR_RIB["due"] = ((_due + _per) if (now - _due) < _per
                           else (now + _per))
        h = _AUR_RIB["h"]
        #: `pp` is her own voice and it is kept SEPARATELY rather than
        #: summed in. A trace where the loudest peaks are the device
        #: talking to itself is a trace of the wrong thing — the question
        #: this answers is what the ROOM did, and her own speech is the one
        #: part of that the room did not do.
        #: ── EVERY SAMPLE CARRIES ITS OWN NUMBER (2026-08-18) ────────
        #: Owner: "just animate the time it comes out into the ribbon but
        #: keep them static as they move through the ribbon."
        #:
        #: The carrier needs a phase that belongs to the DATA and never
        #: changes afterwards. A monotonic counter does exactly that: a
        #: sample drawn at seq 4021 gets the same waveform shape on every
        #: frame for the eleven seconds it is on screen, so the pattern
        #: translates rigidly along the arc instead of being regenerated.
        #: Any phase derived from window position — which is what the last
        #: two attempts used — reshuffles itself as the window slides.
        _AUR_RIB["seq"] = _AUR_RIB.get("seq", 0) + 1
        h.append((min(1.0, e), min(1.0, pp), raw, _AUR_RIB["seq"]))
        if len(h) > AUR_RIB_KEEP:
            del h[:len(h) - AUR_RIB_KEEP]
    except Exception:                                   # noqa: BLE001
        pass


#: ── ONE OWNER FOR THE RIBBON'S GEOMETRY (2026-08-19) ────────────────────
#: The damage rect below has to know exactly which pixels the trace can
#: reach, and the only honest way to know that is to ask the same code the
#: painter asks. Deriving the bearings twice is §15's bug in miniature: the
#: gap has already moved once this week (AUR_RIB_GAP_FRAC, the retired
#: wordmark's window) and a second copy would have kept the old number and
#: painted a rect that clips the trace at one end — which looks like a
#: rendering bug, not like a stale constant.
#: ── THE RIBBON ARRIVES WITH THE RING (2026-08-19) ──────────────────────
#: Owner: "have the base ribbon expand from small to large to reflect the
#: wedge increase to make it look symmetrical."
#:
#: The seven panes fade and scale in over AUR_UI_ARRIVE_S; the trace used
#: to appear beside them already at full height. Two objects on one arc,
#: one of them animating, which reads as the ribbon being a different KIND
#: of thing — and he is right that it breaks the gesture.
#:
#: DRIVEN FROM THE PANES' OWN ALPHAS, not a second clock. _aurora_ui_alpha
#: is the single source for "how far in is the ring", and it already feeds
#: the panes, the hit-test and the tap gate. A private timer here would be
#: a second definition of arrival, and it would drift the first time the
#: pane count or AUR_UI_ARRIVE_S moves — both of which have already
#: happened (five panes to seven; 4.11 s normalised to 3.00 s).
#:
#: THE MEAN, not per-column. The ribbon spans the whole gap and has no
#: single bearing, so keying each sample to its nearest pane would sweep
#: the expansion around the arc — more interesting, and not what
#: "symmetrical" asks for. The ring grows; the ribbon grows with it.
#:
#: A FLOOR, because zero is not "small". At 0.0 the trace is a hairline on
#: the centreline and the damage rect degenerates to a slot a few pixels
#: tall — and a rect that small is one the stash/blit path has never been
#: measured at. 0.14 keeps a visible seed and a sane box.
AUR_RIB_ARRIVE_FLOOR = 0.14


def _aur_ring_arrival(now: "float | None" = None) -> float:
    """0..1 — how far the ring's arrival gesture has travelled.

    Mean over the panes, the same statistic the tap gate uses for
    `_arrived`, so "the ring is here" means one thing on this face.
    Never raises: a ribbon that vanishes because a helper threw is a
    worse outcome than one drawn at full height.
    """
    try:
        n = len(wedges())
        if not n:
            return 1.0
        t = time.time() if now is None else now
        a = [_aurora_ui_alpha(t, i) for i in range(n)]
        return max(0.0, min(1.0, sum(a) / n))
    except Exception:                                       # noqa: BLE001
        return 1.0


def _aur_ribbon_span(now: "float | None" = None):
    """(lo, hi, mid, half) — the bearings and radii the trace lives in.

    `half` carries the arrival scale, so the trace and the damage rect
    cannot disagree about how tall the ribbon currently is — the same
    reason AUR_RIB_GAP_FRAC is applied here and not at three call sites.

    Returns None when the pane gap is too narrow to draw anything in, which
    is the painter's own early return.
    """
    ws = wedges()
    #: ── IT ENDS WHERE THE WEDGES DO (2026-08-20) ────────────────────────
    #: These were `ws +/- AUR_MARK_MARGIN2_DEG` — the 9 degrees of air the
    #: WORDMARK wanted at each end of its window, which this function
    #: inherited along with everything else the wordmark left behind, and
    #: which has no more reason here than `_mark_window()` did (see the note
    #: in the painter about that one). Nine plus AUR_RIB_GAP_FRAC's share
    #: came to 20.8 measured degrees of nothing at each end.
    #:
    #: WHICH EDGE IS "THE WEDGE" — measured, because the arithmetic has two
    #: plausible answers and the wrong one puts the trace under a pane.
    #: `_aur_wedge` and `_aur_arris_elems` both inset their strokes by 1.4
    #: deg (`a0 + 1.4, a1 - 1.4`), so the obvious reading is that a pane's
    #: visible edge is ws[-1][1] - 1.4. IT IS NOT. The ring on the glass is
    #: the SPRITE, and its footprint is a hard sector: rendering the panes
    #: alone at 0.2 deg resolution puts the last lit bin at exactly 148.0
    #: and the first at exactly 274.0 — the nominal bearings, to the bin, at
    #: alpha thresholds 8, 24 AND 96. The 1.4 deg inset moves the ARRIS,
    #: which lives inside that footprint and is not what the eye reads as
    #: the end of the pane. So the nominal bearing is the anchor, and
    #: AUR_RIB_END_AIR_DEG is measured from it.
    #:
    #: DERIVED, not typed, and that is the point rather than tidiness. The
    #: ring's angles and radii moved four times this week; a literal pair of
    #: bearings goes out of true on the next move and the air at the ends
    #: reopens exactly as it did here. Proof that it is derived: the end
    #: gaps come out 2.0 / 2.0 deg at SEVEN panes (his puck, 126 deg gap)
    #: and 2.0 / 2.0 at FIVE (this workstation's profile, 194 deg gap),
    #: from the same two lines, with nothing conditional on the count.
    lo = ws[-1][1] + AUR_RIB_END_AIR_DEG
    hi = ws[0][0] + 360.0 - AUR_RIB_END_AIR_DEG
    if hi - lo < 20.0:
        return None
    #: keep the middle share of it and leave the rest as air at both ends —
    #: see AUR_RIB_GAP_FRAC. Applied HERE, once, so the hairline, the ticks,
    #: the trace and the damage rect cannot disagree about where the ribbon
    #: begins; three separate call sites deriving their own bearings is how
    #: the wordmark's window leaked into this function in the first place.
    #: (2026-08-20: the fraction is gone, the SENTENCE is why this is still
    #: one function. lo..hi is now the whole span and the air is already in
    #: it, so `half` is simply half the arc.)
    _mid_b = (lo + hi) / 2.0
    _half_b = (hi - lo) / 2.0
    r0, r1 = wedge_band()
    #: ── AND IT SAYS WHERE IT IS (2026-08-19) ────────────────────────────
    #: Owner: "the ribbon is supposed to be subtle and only go between the
    #: left dead space between the wedges." It was, and proving that took
    #: forty minutes of reading a painter that cannot draw outside lo..hi,
    #: because nothing in the log said where lo and hi were. One line, once,
    #: and the next report of this shape is settled by a grep instead:
    #:
    #:   grep -a "ribbon span" ~/aura_face/dj_face.log | tail -1
    #:
    #: If those bearings ever cover more than the gap `wedges()` leaves, the
    #: geometry IS the bug; if they do not, look at the arris and the bloom
    #: (_aur_edge_tint), which is where the circle actually came from.
    _sig = (round(lo, 1), round(hi, 1), len(ws))
    if _AUR_RIB.get("span_said") != _sig:
        _AUR_RIB["span_said"] = _sig
        print(f"aurora: ribbon span {_mid_b - _half_b:.0f}.."
              f"{_mid_b + _half_b:.0f} deg, "
              f"{100.0 * (hi - lo) / 360.0:.0f}% of the "
              f"rim, {AUR_RIB_END_AIR_DEG:.1f} deg of air at each end of "
              f"the {ws[-1][1]:.0f}..{ws[0][0] + 360.0:.0f} deg "
              f"({ws[0][0] + 360.0 - ws[-1][1]:.0f} deg) dead space left by "
              f"{len(ws)} panes spanning {ws[0][0]:.0f}..{ws[-1][1]:.0f}, "
              f"at r {(r0 + r1) / 2.0:.0f}", flush=True)
    #: the RADIAL extent carries the arrival, not the arc length. The
    #: ribbon is ninety seconds of room history along a fixed arc, so
    #: shortening the arc would animate the DATA rather than the object —
    #: the trace would appear to be missing time it actually has. Growing
    #: out of its own centreline is the same move a pane makes into its
    #: pocket, which is the symmetry he asked for.
    #:
    #: Smoothstep, the same ease the panes use (`e = k*k*(3-2k)` in
    #: draw_aurora_menu), so the two curves match rather than merely
    #: finishing together.
    #: ── THE ARRIVAL SCALE IS REMOVED (2026-08-20) ────────────────────
    #: Owner: "ribbon wave form is super jittery again ... it looks nothing
    #: like a sinusoidal wave again, it's too blocky. also the fade in is
    #: not aligned anymore, the highlighting when they fade in does not
    #: correspond to the actual wedges they are offset."
    #:
    #: Both of those are this line, and the mistake is a category error I
    #: should have caught by reading the call site. THE RIBBON IS NOT PART
    #: OF THE RING. It is drawn unconditionally on the home face — there is
    #: no `if vis` above draw_aurora_ribbon — while the ring is summoned
    #: and dismissed. Scaling the trace by the ring's arrival therefore
    #: squashed it to the 0.14 floor for the ENTIRE resting state, which is
    #: most of the time the face is on:
    #:
    #:   * a waveform at 14% height is a few pixels of travel quantised to
    #:     whole pixels — "blocky", and nothing like a sine
    #:   * every summon and dismiss swept it 0.14 -> 1.0 -> 0.14 — "jittery"
    #:   * and _aur_ribbon_span is read TWICE a frame, once by the damage
    #:     rect and once by the trace, each taking its own time.time(). A
    #:     constant `half` made that harmless; a moving one meant the rect
    #:     was stashed at one amplitude and painted at another, which is
    #:     the misalignment he saw during the fade
    #:
    #: What he asked for stands and is not this: "have the base ribbon
    #: expand from small to large to reflect the wedge increase." The
    #: honest version needs the ribbon to be a thing that ARRIVES, and
    #: today it is a thing that is always there. That is a design question
    #: — does the trace belong to the ring or to the face — and it is in
    #: docs/QUEUE.md rather than guessed at a second time.
    return (_mid_b - _half_b, _mid_b + _half_b, (r0 + r1) / 2.0,
            (r1 - r0) * 0.30)


#: How far past the trace's own channel the ribbon's ink can land, as a
#: multiple of `half`. NOT 1.0, and this is the first thing the rect test
#: caught: the trace is clamped to `half` for the ROOM's level and then
#: `amp = max(amp, half * hers * 1.2)` lifts it 20% past the rail whenever
#: SHE is the one speaking. A box sized to the rail clips her own voice —
#: which is the one moment on this face anybody is looking at the ribbon.
AUR_RIB_INK_K = 1.2
#: ...and the flat pad on top, for the stroke widths. The arcs are drawn up
#: to 7 px wide (so ±4 from their own radius) and PIL puts the extra on both
#: sides. MEASURED, not assumed: scripts/test_aurora_rect.py draws the
#: ribbon on black over the whole panel and asserts every lit pixel falls
#: inside the box, and reports the slack on all four sides so the next
#: person can see how much of this is margin and how much is luck.
AUR_RIB_INK_PAD = 10


def _aur_ribbon_box(pad: int = AUR_RIB_INK_PAD):
    """The ribbon's damage rect (x0, y0, x1, y1) in unrotated panel px."""
    span = _aur_ribbon_span()
    if span is None:
        return None
    lo, hi, mid, half = span
    c = SIZE / 2.0
    xs, ys = [], []
    steps = max(2, int(hi - lo) + 1)
    for _s in range(steps + 1):
        _ra = math.radians(lo + (hi - lo) * _s / steps)
        for _r in (mid - half * AUR_RIB_INK_K, mid + half * AUR_RIB_INK_K):
            xs.append(c + _r * math.cos(_ra))
            ys.append(c + _r * math.sin(_ra))
    x0 = max(0, int(min(xs)) - pad)
    y0 = max(0, int(min(ys)) - pad)
    x1 = min(SIZE, int(max(xs)) + pad + 1)
    y1 = min(SIZE, int(max(ys)) + pad + 1)
    if x1 - x0 < 8 or y1 - y0 < 8:
        return None
    return (x0, y0, x1, y1)


def draw_aurora_ribbon(frame: "Image.Image", now: float,
                       rot_deg: float = 0.0,
                       off: tuple = (0, 0)) -> None:
    """Ninety seconds of the room, along the arc the panes leave.

    `off` is the target's top-left in panel coordinates — (0, 0) for the
    full frame, the damage rect's corner when this is drawing into a crop.
    ONE painter serves both, deliberately: a rect with its own copy of the
    trace geometry is a second drawing of the same object that can drift
    from the first, and the pace log would go on reporting rect paints
    while the glass showed a seam.
    """
    try:
        if not _AUR_UI["vis"]:
            return
        #: ── THE RIBBON GETS THE WHOLE GAP (2026-08-18) ──────────────────
        #: Owner: "somehow the ribbon started clipping at the wrong start
        #: point, it leaves all this deadspace on the left side of the
        #: dial's left side."
        #:
        #: It was calling `_mark_window()` — the WORDMARK's window, which
        #: clips the pane gap to within 48 degrees of due left. That
        #: constraint was correct for its owner and is meaningless here: it
        #: existed so a column of UPRIGHT LETTERS would read as a column,
        #: and the wordmark it constrained has been retired. A waveform has
        #: no reading direction, so nothing stops it using the arc it was
        #: given. It inherited a rule from a dead feature, which is the
        #: quiet cost of two things sharing a helper because they happened
        #: to want the same number once.
        #:
        #: The gap is 126 degrees and the ribbon was using 78 of them. The
        #: 48 left over are exactly the dead space he is looking at.
        #: the bearings and radii now come from _aur_ribbon_span(), which
        #: the damage rect also reads — see the note there.
        _span = _aur_ribbon_span()
        if _span is None:
            return
        lo, hi, mid, half = _span
        #: 0.30 -> 0.38: the trace has to be legible from across the room,
        #: and the rails now show the space it is allowed to use, so a
        #: taller waveform reads as filling the channel rather than as
        #: spilling out of nothing. (The 0.30 now lives in
        #: _aur_ribbon_span, so the damage rect sizes itself off the same
        #: number the trace is clamped by.)
        #: -- THE SAME CONVENTION THE PANES USE (2026-08-17) --------------
        #: This was `-rot_deg if INVERT else rot_deg`, copied from the
        #: wordmark, where it was correct BECAUSE the wordmark had to hold
        #: a screen position while the ring turned. The ribbon is part of
        #: the ring: it lives in the gap between two specific panes and has
        #: to stay there. With the sign flipped it travelled the opposite
        #: way from the panes at twice the dial rate, so turning the dial
        #: walked the trace straight across the buttons -- which is the
        #: other half of "doing random things", and only visible if you
        #: touch the dial while it is up.
        #:
        #: ── AND IT MUST ADD NOTHING AT ALL (2026-08-18) ─────────────────
        #: The note above says "draw_aurora_menu adds rot_deg. So does this,
        #: now." That is false, and it was false when it was written. Read
        #: the menu painter: `rot_deg` is in its SIGNATURE and appears
        #: nowhere in its body. The panes turn because the entire composed
        #: frame is rotated once, after both are drawn:
        #:
        #:     draw_aurora_ribbon(frame, now, rot_deg=rot.deg)
        #:     if rot.deg > 0.05:
        #:         frame = frame.rotate(d, ...)      <- the whole face
        #:
        #: So adding it here rotated the ribbon TWICE: once itself and once
        #: with the frame, and the trace walked out of the gap at twice the
        #: dial rate, across and behind the panes. Owner, this morning: "the
        #: ribbon is still not displaying in that exact gap ... it should
        #: only render within the gap not go around the whole display."
        #:
        #: Yesterday's fix changed the SIGN of this term and the symptom
        #: halved, which read as success. It was two bugs — an inherited
        #: window and a doubled rotation — and fixing the first while
        #: halving the second left something that looked right at rest.
        #: Nothing here is screen-pinned, so nothing here corrects for the
        #: dial. The bearings come from `wedges()`, which is what the frame
        #: rotation is applied to.
        _d = 0.0
        #: the dial centre IN THE TARGET's coordinates. `c` stays the panel
        #: centre so every radius below still reads as a panel radius; only
        #: the origin moves. NOT named cx/cy — the trace loop already binds
        #: those to a unit vector, and shadowing them there would put the
        #: whole waveform at the corner of the rect.
        c = SIZE / 2.0
        _kx, _ky = c - off[0], c - off[1]

        #: ── AND THE ARC BOXES ARE FLOORED, WHICH IS NOT PEDANTRY ─────────
        #: These arcs are concentric with the dial, so on the full frame
        #: their bounding boxes are (34.16, 34.16, 1045.8, 1045.8) — all
        #: positive. Drawn into a crop they become NEGATIVE at the top left,
        #: and PIL casts a float box to int by TRUNCATING TOWARD ZERO:
        #: int(34.16) is 34 and int(-8.84) is -8, so the same arc lands one
        #: pixel further down in the rect than in the frame it is supposed
        #: to be indistinguishable from. Measured by test_aurora_rect.py as
        #: 588 pixels differing by up to 17/255 — a visible seam at the top
        #: of the gap, 60 times a second, and it would have been the kind of
        #: shimmer that gets blamed on the panel.
        #:
        #: floor() agrees with truncation for every positive value, so the
        #: full-frame render is byte-for-byte what it was.
        def _abox(_r):
            return (math.floor(_kx - _r), math.floor(_ky - _r),
                    math.floor(_kx + _r), math.floor(_ky + _r))

        d = ImageDraw.Draw(frame, "RGBA")
        h = _AUR_RIB["h"]
        n = AUR_RIB_N

        #: the arrival rides the panes' own schedule, so the ribbon
        #: condenses with the ring instead of appearing beside it
        ka = _mark_alpha(now, n // 2, n)
        if ka <= 0.02:
            return
        ka = ka * ka * (3.0 - 2.0 * ka)

        #: ── THE HAIRLINE ────────────────────────────────────────────────
        #: Drawn first and always, even in silence. This is the piece that
        #: actually fixes the complaint: it continues the pane band's centre
        #: line across the gap, so the eye closes the ring into a circle and
        #: the blank arc stops reading as five missing buttons.
        #: -- THREE ARCS, NOT SIXTY-FOUR LINE SEGMENTS (2026-08-17) -------
        #: Owner: "it's rendering slowly." Measured on the puck: compose
        #: went from 30 ms to 35 ms of a 38 ms budget when this landed, and
        #: this hairline was 64 of the 172 alpha-blended draw calls the
        #: ribbon was making every frame at 26 fps.
        #:
        #: It is a constant-radius arc. PIL will draw one in a single call,
        #: and the only reason it was ever stepped was the taper at the
        #: ends -- which three nested arcs give just as well: a dim outer
        #: pair covering the whole span and the ends, a brighter one inset
        #: from both. 3 calls instead of 64, identical to look at.
        #: ── A TRACK, NOT A HAIRLINE (2026-08-18) ────────────────────────
        #: Owner: "i don't see the fundamental ribbon track thickened at all
        #: so that space is really empty."
        #:
        #: It was three 2 px arcs at alpha 34-46, which is about 18% opacity
        #: on a black ground — at arm's length on a 5 inch panel that is
        #: nothing, and the gap read as a hole in the ring whatever the
        #: trace was doing. It was set that faint deliberately, back when
        #: the wordmark was still in this space and the line's whole job was
        #: to not compete with it. The wordmark is gone and the line
        #: inherited a restraint that no longer has a reason.
        #:
        #: Two changes. The centre line is 4 px at alpha 96, which is a
        #: drawn line rather than a suggestion of one. And it gets RAILS —
        #: two faint arcs at the trace's extremes — so the space reads as a
        #: channel the waveform lives in. That is what makes an empty
        #: instrument look at rest rather than broken: you can see the
        #: extent of what it would show.
        bb = _abox(mid)
        #: ── AND THICKER STILL (2026-08-18) ──────────────────────────
        #: Owner: "thicken the ribbon more, even just the default arc one,
        #: it's way too thin compared to all other UI elements."
        #:
        #: That comparison is the useful part. The panes carry a 3 px arris
        #: and a bloom; the steel rim is an 18 px band. A 4 px line beside
        #: those does not read as furniture of the same object, it reads as
        #: a scratch — which is why it kept disappearing for him however
        #: much its alpha went up. Doubled: 7 px core, 6 px flanks, 2 px
        #: rails.
        #: ── SUBTLE, AND HE HAS NOW SAID SO (2026-08-19) ─────────────────
        #: Owner: "the ribbon is supposed to be subtle." The two notes above
        #: STAND WITH THEIR DATES and are both his — "way too thin compared
        #: to all other UI elements", then the doubling. They were answering
        #: a ribbon in a dimmer ring; the panes have since gained a
        #: permanent arris and a permanent bloom, so "compared to all other
        #: UI elements" now means something else than it did on the 18th.
        #:
        #: WIDTH IS KEPT AND BRIGHTNESS IS SPENT, which is the distinction
        #: those notes were missing. He asked for a track you can see the
        #: extent of; he did not ask for a lit one. The strokes stay 7/6/6
        #: px so the channel still reads as furniture of the same object,
        #: and the alphas come down by roughly half so it stops competing
        #: with the panes for the same glance. If it disappears again, this
        #: is the number — not the widths, which have been round-tripped
        #: twice already.
        #: ── AND FOUR TIMES THAT (2026-08-20) ────────────────────────────
        #: Owner, at the glass: "the default ribbon should still be larger
        #: to fill that gap between the wedges, make it 4x thicker a line."
        #:
        #: A MULTIPLIER, not four rewritten numbers. The 7/6/6 taper is his
        #: from the 18th and the round-trip warning above is still live —
        #: written as 28/24/24 the taper stops being readable as a taper and
        #: the next person adjusting it has no way to see that it was ever
        #: 7/6/6, which is how the widths got round-tripped twice already.
        #: His 4x stays legible AS 4x, on its own line, with his sentence.
        #:
        #: NEARLY FREE, measured rather than assumed, and measured with the
        #: SPAN HELD FIXED — a before/after across two runs moves the arc
        #: length and the stroke width at once and cannot attribute either.
        #: Toggling AUR_RIB_TRACK_K inside one process, 200 renders at 1080
        #: each: median 1.379 ms at 1.0 against 1.517 ms at 4.0. +0.14 ms,
        #: +10%, against a device budget where t:ribbon already ranges
        #: 0.9-3.6 ms. PIL draws an arc in one call whatever its width, so
        #: the ribbon still makes the same five arc calls — the extra is the
        #: alpha blend over four times the pixels, and that is all it is.
        #:
        #: The rails are NOT multiplied. They are the two faint marks that
        #: show the channel's extent (the note above), not the line — at 8
        #: px they would read as a second and third ribbon, and the trace
        #: they exist to be read against would have three things to compete
        #: with instead of one.
        for _rr in (mid - half * 0.94, mid + half * 0.94):
            d.arc(_abox(_rr), lo + _d, hi + _d,
                  fill=(72, 98, 124, int(26 * ka)), width=2)
        for inset, al, w in ((0.0, 32, 6), (0.06, 32, 6), (0.15, 54, 7)):
            a0 = lo + (hi - lo) * inset + _d
            a1 = hi - (hi - lo) * inset + _d
            if a1 <= a0:
                continue
            d.arc(bb, a0, a1, fill=(126, 168, 208, int(al * ka)),
                  width=max(1, int(round(w * AUR_RIB_TRACK_K))))

        #: ── A SCALE, SO SILENCE STILL HAS SHAPE (2026-08-17) ────────────
        #: Owner: "some structure of the ribbon should always be there even
        #: if faint, to fill up the space even if no lines are being
        #: generated to cross it."
        #:
        #: And it answers the other note about the trace being hard to
        #: read, which is the same problem from the other end: a waveform
        #: with nothing behind it has no scale, so a loud room and a quiet
        #: one look equally like "some fuzz". These are TIME ticks — one
        #: every two seconds of history, taller every ten — so the trace is
        #: read against something, and the empty ribbon is a measuring
        #: instrument at rest rather than a blank arc.
        #:
        #: Drawn before the waveform so the trace sits ON the scale, and at
        #: a third of the hairline's alpha: present, never competing.
        _tick_n = max(2, int(AUR_RIB_KEEP / (2.0 * AUR_RIB_HZ)))
        for _t in range(_tick_n + 1):
            _tb = lo + (hi - lo) * _t / _tick_n + _d
            _big = (_t % 5 == 0)
            _tl = (half * 0.62) if _big else (half * 0.30)
            _ra = math.radians(_tb)
            _cx, _cy = math.cos(_ra), math.sin(_ra)
            d.line([(_kx + (mid - _tl) * _cx, _ky + (mid - _tl) * _cy),
                    (_kx + (mid + _tl) * _cx, _ky + (mid + _tl) * _cy)],
                   fill=(88, 112, 136, int((26 if _big else 15) * ka)),
                   width=1)

        if not h:
            return
        #: how far through the current sample period we are, 0..1. Clamped
        #: rather than wrapped: if the sampler stalls (a busy frame, a
        #: blocked read) the trace should stop cleanly at one slot rather
        #: than run away and tear.
        #: ── BETWEEN ARRIVAL AND THE NEXT DUE TIME (2026-08-20) ───────────
        #: This was `(now - t) * AUR_RIB_HZ` — the NOMINAL rate — while the
        #: sampler could only fire on a frame boundary. At 8 fps the rows
        #: arrived every 0.25 s and this ramp finished in 0.167, so the
        #: trace scrolled for two frames and then sat still for one: a
        #: third of every cycle dead, then a jump to catch up. That stall
        #: is the "schizophrenic" half of the complaint and it got worse the
        #: slower the compositor ran, which is why he saw it "in the
        #: beginning" — the ring arrives at 8-10 fps and settles at 16-25.
        #:
        #: The sampler now publishes when the next row is DUE, so this
        #: interpolates from the row that arrived to the row that is coming
        #: and reaches 1.0 exactly as it lands. No stall at any frame rate,
        #: and no second opinion about the rate: the two ends of the ramp
        #: are both written by aurora_ribbon_sample (S15).
        _nxt = _AUR_RIB.get("due") or (_AUR_RIB["t"] + 1.0 / AUR_RIB_HZ)
        _rib_frac = min(1.0, max(0.0, (now - _AUR_RIB["t"])
                                 / max(1e-6, _nxt - _AUR_RIB["t"])))
        #: the window's own dynamic range, recomputed per frame from what
        #: is actually on screen. Adaptive rather than fixed because the
        #: floor moves by a factor of fifty when the fan spins up, and a
        #: constant scale would show either nothing or a full-height mess
        #: depending on the hour.
        _raws = [r[2] for r in h if len(r) > 2]
        _rng_lo = min(_raws) if _raws else 0.0
        _rng_hi = max(_raws) if _raws else 0.0
        #: and a MINIMUM range, so a genuinely dead-silent room does not
        #: get its own sensor noise amplified to full height. If the whole
        #: window spans less than this, there is nothing to show and the
        #: baseline stays flat — which is honest.
        if _rng_hi - _rng_lo < 6e-5:
            _rng_hi = _rng_lo
        #: the envelope is collected first and drawn as one shape after —
        #: see the note at the foot of this loop
        _wave = []
        for i in range(n):
            #: newest at the HIGH bearing, next to the first pane, so the
            #: trace flows up into the ring rather than away from it
            #: ── AND THE PARTIAL WINDOW FILLS, IT DOES NOT STRETCH ───────
            #: This was `len(h) - 1 - int((n - 1 - i) * len(h) / n)`, which
            #: is the SAME rescale the AUR_RIB_N note above says broke the
            #: scroll twice — only here the ratio that drifts is not N
            #: against KEEP, it is `len(h)` against `n` while the history is
            #: still filling. It is a no-op once full (len(h) == n makes the
            #: two expressions identical, which is why it survived), and
            #: before that it is the whole bug:
            #:
            #: with 36 rows over 64 slots each row occupies 1.78 slots, so a
            #: new row RESCALES the picture instead of translating it. The
            #: trace does not scroll, it stretches, and `_rib_frac` slides
            #: the bearings by one SLOT underneath data that moved 1.78 —
            #: measured at 35.4 deg/s where the full window gives 5.8, and
            #: worse the faster the compositor ran (5.2, 14.9, 19.1, 24.6,
            #: 35.4 at 8/9/12/16/25 fps). "It's a bit sychophrenic IN THE
            #: BEGINNING" is this, and it lasts KEEP/HZ seconds from a cold
            #: start — which halving the rate would otherwise have doubled
            #: from 11 s to 21.
            #:
            #: One row per slot, always, and the slots that have no row yet
            #: are simply not drawn (the `continue` below was already there
            #: for exactly this case). An instrument with 8 s of history
            #: shows 8 s of trace and empty channel behind it, which is what
            #: filling up looks like — and it is one moving speed instead of
            #: two, at every stage of the fill.
            k = len(h) - 1 - (n - 1 - i)
            if k < 0:
                continue
            _row = h[k]
            lvl, hers = _row[0], _row[1]
            _raw = _row[2] if len(_row) > 2 else 0.0
            #: rows written before this build have no seq; fall back to the
            #: slot so they draw as something rather than not at all
            _seq = _row[3] if len(_row) > 3 else float(k)
            #: the ambient component: where this sample sits between the
            #: quietest and loudest thing in the visible window. Scaled
            #: small — it is a baseline, not a second waveform — and it
            #: only ever ADDS, so speech still dominates when there is any.
            #: ── VARIANCE, NOT JUST HEIGHT (2026-08-18) ──────────────────
            #: Owner: "it should look almost waveform like, right now they
            #: are almost always the same height ... just up the variance of
            #: them a lot."
            #:
            #: Exactly right, and raising the amplitude alone would not have
            #: fixed it — it would have made a taller flat comb. The ambient
            #: term was a LINEAR map of the window's range into a narrow
            #: band: at FLOOR_K 0.30 every sample landed between 0 and 0.30,
            #: and since room tone rarely spans its own window, in practice
            #: they clustered around the middle of that. A row of bars all
            #: within a few pixels of each other is a comb, not a waveform.
            #:
            #: Two changes, and the gamma is the one that matters — see
            #: its own note above for why it ended up BELOW one rather than
            #: above, which is the opposite of what I first wrote. The small
            #: constant base underneath keeps his earlier ask ("always
            #: something there") true, so the quiet end lands on a few
            #: visible pixels rather than on nothing.
            #: ── AND NOT FOR A ROW THE ARRAY CALLED SILENT (2026-08-20) ──
            #: Owner, at the glass: "the ribbon has just these curious
            #: small wave forms coming out — maybe it's ambient noise, so
            #: cut that out."
            #:
            #: HE IS RIGHT ABOUT THE PICTURE AND WRONG ABOUT THE CAUSE, and
            #: the difference is the whole fix. It is not ambient noise. I
            #: sampled puck-paulchou's own /tmp/aura_face/room.json for
            #: 150 s — 242 publications, the same feed this history is
            #: built from:
            #:
            #:     212 of 242 read EXACTLY 0.0
            #:      30 of 242 ran 34,030 .. 24,606,790
            #:       0 of 242 landed anywhere in between
            #:
            #: The XVF3800 does not report a noise floor; a quiet room is a
            #: hard zero on every beam (puck_ears.DOA_SPEECH_MIN's own note
            #: says so, measured on puck #1). So there is nothing ambient in
            #: the data at all — the wiggle is MANUFACTURED HERE. The moment
            #: one speech sample enters the 21 s window, `_rng_hi > _rng_lo`
            #: becomes true for EVERY row including the silent ones, and a
            #: silent row's `_norm` of 0 still collects AUR_RIB_BASE — 0.08,
            #: lifted to 0.38 * 0.08 = 0.0304 of full height, which the
            #: carrier then draws as a clean little sine. Measured at the
            #: rendered pixels: 3.0 px peak-to-peak of trace on a row the
            #: array reported as silence.
            #:
            #: THE GATE IS ROOM_E0 AND IT IS NOT A NEW NUMBER (S15). That
            #: constant is already this face's single answer to "is the
            #: array hearing a person" — `_room_frac` returns exactly 0.0
            #: below it, and puck_ears gates the bearing on the same 5000.
            #: This is not a second detector in series (S7); it is the
            #: ambient term stopping OVERRIDING the one detector's answer.
            #:
            #: EXPRESSED AGAINST THE MEASURED FLOOR, not in dBFS, and the
            #: separation is not a judgement call: the floor is 0.0 and the
            #: quietest voice seen in 150 s of his actual room is 34,030,
            #: which is 6.8x the gate. Quiet speech is not at risk — a
            #: 34,030 row still normalises to 0.08 of the window and draws
            #: ~3x taller than the flat line beside it.
            if _rng_hi > _rng_lo and _raw > ROOM_E0:
                _norm = (_raw - _rng_lo) / (_rng_hi - _rng_lo)
                _amb = AUR_RIB_BASE + (1.0 - AUR_RIB_BASE) * (
                    _norm ** AUR_RIB_GAMMA)
                lvl = max(lvl, AUR_RIB_FLOOR_K * _amb)
            amp = half * min(1.0, lvl * 1.35)
            #: NO early-continue here any more. It used to skip drawing a
            #: silent slot, which was free when each slot was its own spoke.
            #: An envelope is continuous by definition, so skipping a point
            #: tears a hole in the outline and the polygon closes across the
            #: gap — a silent passage has to be a THIN part of the waveform,
            #: which is what silence looks like in every audio editor.
            #: ── AND THE FLOOR MUST NOT REACH THE CARRIER (2026-08-20) ──
            #: Owner, after the ambient gate shipped: "it is still
            #: displaying very very minute waveforms from the ambient
            #: noise, we have to quash that... we only want the real noise
            #: signals coming through."
            #:
            #: HE IS RIGHT AGAIN AND IT IS STILL NOT AMBIENT NOISE. Sampled
            #: the puck's own room.json 45 times over 50 s tonight: EVERY
            #: reading was exactly 0.0, so the gate above is already
            #: refusing every silent row. The wiggle is this line.
            #:
            #: `amp` is used for TWO different things — the height of the
            #: envelope, and the amplitude of the carrier sine at _r =
            #: mid + amp*sin(...). The 0.6 floor exists for the first
            #: (documented directly above: an envelope is continuous, and
            #: skipping a silent slot tears a hole the polygon closes
            #: across). Applied to the second it makes silence oscillate
            #: +/-0.6 px for the whole length of the trace — invisible at
            #: the old 7 px stroke and plainly visible now the track is 4x
            #: thicker, which is why this arrived the same day as that.
            #:
            #: So the carrier keeps the TRUE amplitude and silence draws
            #: dead flat, which is what silence looks like in every audio
            #: editor. The envelope keeps its floor and its continuity.
            #: One value doing two jobs, separated (§15).
            ampc = amp
            amp = max(amp, 0.6)
            #: ── SCROLL BETWEEN SAMPLES (2026-08-17) ──────────────────────
            #: Owner: "the rendering of the ribbon animation is also halting
            #: too much, match FPS." Exactly right, and the cause is not the
            #: frame rate — the face is drawing this at 26 fps quite
            #: happily. The DATA arrives at 6 Hz, so the trace held still
            #: for four frames and then jumped a whole slot. Four steps a
            #: second is not an animation, it is a slideshow.
            #:
            #: Raising the sample rate would cost real work (an embedding of
            #: the room's level is not free) and would not fix the class of
            #: problem, which is that a discrete series was being drawn at a
            #: continuous rate. So the slots slide: the fraction of a sample
            #: period elapsed shifts every slot backwards by that much of
            #: one step. The trace now moves every frame, at exactly the
            #: speed the data is actually arriving.
            b = lo + (hi - lo) * (i - _rib_frac) / (n - 1) + _d
            ra = math.radians(b)
            cx, cy = math.cos(ra), math.sin(ra)
            col = AUR_RIB_HERS if hers > lvl else AUR_RIB_ROOM
            amp = max(amp, half * hers * 1.2)
            #: age fades the past out — the trace is brightest at now
            age = 1.0 - (n - 1 - i) / (n - 1)
            al = int(ka * (66 + 170 * amp / max(1e-6, half))
                     * (0.34 + 0.66 * age))
            #: `ampc`, not `amp` — the carrier reads this and must be able
            #: to reach zero. The alpha above still uses the floored value,
            #: so a silent stretch is a visible flat line rather than a
            #: gap. See the note at ampc.
            _wave.append((cx, cy, ampc, col, min(255, max(0, al)), _seq))
        #: ── AN ENVELOPE, NOT SIXTY-FOUR SPOKES (2026-08-18) ─────────────
        #: Owner: "can we make it look like a waveform that would be way
        #: cooler."
        #:
        #: It was drawing one radial line per sample, which is a COMB: the
        #: heights were right and the eye had nothing joining them, so it
        #: read as a row of ticks however much variance they had. What makes
        #: an audio waveform legible as one is the CONTINUOUS envelope —
        #: your eye follows the outline, not the individual columns.
        #:
        #: So the same amplitudes become two polylines (mid+amp and mid-amp)
        #: with the space between them filled, which is exactly how a DAW
        #: draws one, wrapped onto an arc.
        #:
        #: CHEAP, and he said an approximation was fine: this is FEWER draw
        #: calls than the comb it replaces — 8 chunks of polygon+2 polylines
        #: against 64 individual lines — because PIL will take a whole point
        #: list in one call. The chunking exists only to keep the age fade,
        #: which a single polyline cannot express: one alpha per call, so
        #: the trace is drawn in 8 pieces from oldest and faintest to
        #: newest and brightest, each overlapping the next by a point so
        #: there is no seam.
        #: ── THE SQUIGGLY KIND (2026-08-18) ──────────────────────────
        #: Owner: "wave form looks so mangled, just a bunch of polygons, i
        #: mean the squiggly lines kind."
        #:
        #: The envelope was the wrong picture. A filled shape between +amp
        #: and -amp is how a DAW draws a MINUTE of audio, where a column is
        #: thousands of samples and only the extremes survive. He means an
        #: oscilloscope: one continuous line crossing a centre, which is
        #: what audio looks like when you can see the waveform itself
        #: rather than its outline.
        #:
        #: THE HONEST PROBLEM, AND THE APPROXIMATION HE AUTHORISED ("even
        #: if you have to approximate it / hack it to save GPU resources
        #: that's fine"). A scope trace needs a SIGN and there is none: the
        #: history is LEVELS, one magnitude every 1/6 s, and the sign was
        #: gone long before this function sees it. So the line is a carrier
        #: — a sine at a fixed rate — with the measured level as its
        #: amplitude envelope. The wiggle is synthetic; the HEIGHT at every
        #: point is real data, which is the part anyone actually reads.
        #:
        #: The cycle count comes from arc length, not taste: at r≈470 the
        #: gap is ~558 px and a scope trace reads as one at roughly 15 px a
        #: cycle. Eight points per cycle — below about six, a sine drawn as
        #: line segments degenerates into the zigzag this replaces.
        if len(_wave) >= 2:
            #: ── THE CARRIER HAS TO TRAVEL WITH THE DATA (2026-08-18) ─
            #: Owner: "it's gotta be a smooth continuous line it still just
            #: looks like poorly rendered moving bars that are also
            #: suspiciously looking halting."
            #:
            #: Both halves of that are one bug. The carrier's phase was
            #: `_j / _M` — a function of SCREEN POSITION. So the envelope
            #: scrolled underneath a wiggle that was nailed to the glass:
            #: every peak stayed at the same pixel while its height changed,
            #: which is precisely a row of bars flickering in place, and it
            #: strobes against the frame rate because nothing about it is
            #: actually moving.
            #:
            #: The phase now comes from the same scrolled sample coordinate
            #: the bearings use (`_u - _rib_frac`), so the whole waveform
            #: travels along the arc as its data does. One thing moving, at
            #: one speed, which is what "continuous" means here.
            #:
            #: And 12 points per cycle rather than 8. At 8 the segments were
            #: visible as facets on a 5 inch panel — the "poorly rendered"
            #: half — and PIL has no antialiasing to hide them, so the fix
            #: is more points plus the soft under-stroke below.
            _arc_px = math.radians(hi - lo) * mid
            #: ── LONGER WAVES (2026-08-18) ─────────────────────────
            #: Owner: "the waveform is still too block, it should be
            #: widened out and smooth." One cycle per 20 px put ~28
            #: cycles in the gap, which at this radius is a dense
            #: comb again — the thing the envelope was replaced to
            #: avoid, in a different costume. One per 34 px is a wave
            #: you can follow with your eye, and at 12 points per
            #: cycle each one is drawn from 12 segments rather than 8,
            #: so widening makes it smoother rather than coarser.
            _cyc = max(4.0, _arc_px / 34.0)
            _M = int(_cyc * 12.0)
            _pts_all = []
            for _j in range(_M + 1):
                _u = _j / _M * (len(_wave) - 1)
                _i0 = min(len(_wave) - 1, int(_u))
                _i1 = min(len(_wave) - 1, _i0 + 1)
                _f = _u - _i0
                _x0, _y0, _av0, _cv0, _l0, _q0 = _wave[_i0]
                _x1, _y1, _av1, _cv1, _l1, _q1 = _wave[_i1]
                _amp = _av0 + (_av1 - _av0) * _f
                _alv = _l0 + (_l1 - _l0) * _f
                #: phase from the sample's OWN number, so the wiggle is
                #: minted once when the sample enters the ribbon and then
                #: only travels. `_rib_frac` still slides the BEARING, so
                #: the whole pattern moves smoothly without reshaping.
                _sq = _q0 + (_q1 - _q0) * _f
                #: ── PER SAMPLE, NOT PER VISIBLE ROW (2026-08-20) ──────
                #: The divisor was `len(_wave) - 1` — how many rows happen
                #: to exist — so the carrier's cycles PER SAMPLE changed
                #: with how full the history was. With 24 of 64 rows it put
                #: 1.30 cycles on every sample against 0.48 when full: the
                #: same trace, drawn 2.7x tighter, scrolling at the same
                #: slots per second, which is 3.9 waves/s past a fixed point
                #: instead of 1.44. That is the last of "a bit sychophrenic
                #: in the beginning", and like the slot map above it is a
                #: no-op once the window is full (len(_wave) == n), which is
                #: exactly why nobody has seen it in a screenshot.
                #:
                #: `n - 1` is the geometry — how many slots the span HAS —
                #: and it does not move. `_cyc` is already derived from arc
                #: length, so the wave keeps one size in degrees whatever
                #: the history is doing.
                _r = mid + _amp * math.sin(
                    2.0 * math.pi * _cyc * _sq / max(1.0, n - 1.0))
                _bx = _x0 + (_x1 - _x0) * _f
                _by = _y0 + (_y1 - _y0) * _f
                _bn = math.hypot(_bx, _by) or 1.0
                _pts_all.append((_kx + _r * _bx / _bn, _ky + _r * _by / _bn,
                                 _cv1, _alv))
            #: chunked only to carry the age fade — one polyline takes one
            #: alpha, and the trace has to be brightest at now
            _CH = 12
            _per = max(2, len(_pts_all) // _CH)
            for _s0 in range(0, len(_pts_all) - 1, _per):
                _seg = _pts_all[_s0:_s0 + _per + 1]   # +1 = shared point
                if len(_seg) < 2:
                    continue
                _aa = int(max(_q[3] for _q in _seg))
                if _aa <= 3:
                    continue
                _cc = _seg[-1][2]
                _xy = [(_q[0], _q[1]) for _q in _seg]
                #: a wide soft stroke under a narrow bright one. PIL draws
                #: no antialiasing at all, so a single 2 px polyline shows
                #: its stair-steps; a 4 px pass at a fifth of the alpha
                #: under a 2 px core reads as a smooth lit line and costs
                #: one extra call per chunk.
                d.line(_xy, fill=_cc + (max(0, int(_aa * 0.22)),),
                       width=4, joint="curve")
                d.line(_xy, fill=_cc + (min(255, _aa),), width=2,
                       joint="curve")
    except Exception as exc:                            # noqa: BLE001
        _AUR.setdefault("said", set())
        if "ribbon" not in _AUR["said"]:
            _AUR["said"].add("ribbon")
            #: ── SAY WHICH LINE, NOT JUST WHICH ERROR (2026-08-20) ────
            #: This printed the message alone and cost twenty minutes:
            #: "TypeError('list indices must be integers or slices, not
            #: float')" in a 440-line painter is a grep, not a diagnosis,
            #: and the two candidate lines a regex found were both already
            #: int-guarded. The painter must not raise — that part is
            #: right — but a swallowed exception that hides WHERE is a
            #: worse trade than the two lines of traceback it saves.
            import traceback as _tb
            print(f"aurora: ribbon failed {exc!r} — gap left blank\n"
                  + "".join(_tb.format_exc()), flush=True)


def draw_aurora_wordmark(frame: "Image.Image", now: float,
                         rot_deg: float = 0.0) -> None:
    """AuraVision Inside down the gap, every letter upright."""
    try:
        if not _AUR_UI["vis"]:
            return
        placed, r = _mark_layout(rot_deg)
        if not placed:
            _AUR.setdefault("said", set())
            if "markwin" not in _AUR["said"]:
                _AUR["said"].add("markwin")
                print("aurora: the pane gap leaves no legible window near "
                      "nine o'clock — wordmark suppressed", flush=True)
            return
        n = len(placed)
        ks = [_mark_alpha(now, i, n) for i in range(n)]
        if max(ks) <= 0.02:
            return
        _d = -rot_deg if INVERT else rot_deg
        c = SIZE / 2.0
        for i, ((t_rgb, t_m, t_o, _iw, _ih, _cx, _cy), deg) in \
                enumerate(placed):
            k = ks[i]
            if k <= 0.02:
                continue
            e = k * k * (3.0 - 2.0 * k)
            m = t_m.point(lambda v, _e=e: int(v * _e))
            o = t_o.point(lambda v, _e=e: int(v * _e))
            g = t_rgb
            #: upright: undo exactly the turn the compositor is about to
            #: apply to the frame, and nothing else. No tangent term -- that
            #: term IS the thing he asked to have taken out.
            if abs(_d) > 0.05:
                g = g.rotate(-_d, resample=Image.BICUBIC, expand=True)
                m = m.rotate(-_d, resample=Image.BICUBIC, expand=True)
                o = o.rotate(-_d, resample=Image.BICUBIC, expand=True)
                #: the ink offset was measured in the tile's own frame, so
                #: it turns with the tile -- otherwise the correction that
                #: centres the mark at rest becomes a displacement that
                #: grows with the dial, which only shows up in a hand
                _ra2 = math.radians(-_d)
                _ca, _sa = math.cos(_ra2), math.sin(_ra2)
                _cx, _cy = (_cx * _ca + _cy * _sa, -_cx * _sa + _cy * _ca)
            ra = math.radians(deg)
            #: put the INK on the arc, not the tile box around it
            x = int(c + r * math.cos(ra) - m.size[0] / 2 - _cx)
            y = int(c + r * math.sin(ra) - m.size[1] / 2 - _cy)
            reg = frame.crop((x, y, x + m.size[0], y + m.size[1]))
            blk = Image.new("RGB", m.size, (0, 0, 0))
            reg = ImageChops.subtract(
                reg, Image.composite(Image.new("RGB", m.size, (10, 16, 24)),
                                     blk, o))
            reg = ImageChops.screen(reg, Image.composite(g, blk, m))
            frame.paste(reg, (x, y))
    except Exception as exc:                            # noqa: BLE001
        _AUR.setdefault("said", set())
        if "mark" not in _AUR["said"]:
            _AUR["said"].add("mark")
            print(f"aurora: wordmark failed {exc!r} — ring only", flush=True)


#: ── AND THE 9.6 ms HAS NO BREAKDOWN (2026-08-19) ──────────────────────
#: `t:menu` is one number for five different operations — seven sprite
#: lookups, seven bloom pastes, seven pane pastes, seven dissolve masks and
#: twenty-eight alpha-blended arcs — and the handoff that raised this as P1
#: says why that matters: the last session spent a change on
#: `draw_aurora_core` because it REASONED about which operation was
#: expensive. So the painter reports its own split, on the same 30 s
#: cadence as the pace line and never per frame. `time.perf_counter()` is
#: ~40 ns here; forty of them against a 9.6 ms function is 0.02%.
#:
#: `n` counts FRAMES THAT DREW A RING, not frames — the ring is up for a
#: fraction of any 30 s window, and dividing by every frame would report a
#: painter three times cheaper than it is at the moment it runs.
_MPH: dict = {"t": 0.0, "acc": {}, "n": 0}


def _mph(name: str) -> None:
    """Close the sub-segment that was running inside draw_aurora_menu."""
    t = time.perf_counter()
    _MPH["acc"][name] = _MPH["acc"].get(name, 0.0) + (t - _MPH["t"])
    _MPH["t"] = t


#: ── AND THE SAME FOR THE EYE (2026-08-19) ──────────────────────────────
#: Owner: "fix the smoothness." The frame is ~40 ms against a 38 ms budget
#: and the pace report says where to the nearest PHASE:
#:
#:     c:core 19.6   t:menu 6.8   tail 9.1   t:ribbon 3.6
#:
#: The menu has been taken apart already (see _MPH above: arris 3.79 ->
#: 2.26, bloom-mask 1.40 -> 0.04) and is now 6.7. The EYE is three times
#: bigger and has never been opened — `c:pre` reads 0.0, so every one of
#: those 19.6 ms is inside draw_aurora_core, in one bucket.
#:
#: Three sessions have now optimised the second-largest thing on this face
#: while the largest sat unmeasured, because the menu was the one with
#: instrumentation. Markers are free; a wrong guess about a 20 ms function
#: is not.
#: ── DEAD CODE, KEPT DELIBERATELY (2026-08-20) ─────────────────────────
#: This is the state ring's body cached as a tile. It works, it is 5.69 ms
#: a frame cheaper, and IT IS NOT USED — pasting it is a different picture
#: from drawing the strokes, by up to 41/255 on 1699 pixels, worst exactly
#: where the ring is brightest. The measurement and the reasoning are at
#: the call site in draw_aurora_core; the proof is
#: scripts/test_state_ring_tile.py, which imports this function.
#:
#: Kept because the 5.69 ms is the largest remaining item on the glass and
#: the next person to find it will reach for exactly this. They should
#: find the attempt, the number, and the reason it failed sitting next to
#: it — that is cheaper than making it twice, and this file has three
#: recorded cases of making it twice.
#: The state ring's body, cached. See the note where it is pasted.
#: Keyed on everything the five strokes read: the radius, the ring's
#: colour, the speech modulation and the speaking level. At rest that is
#: ONE entry, hit on every frame; while she talks it walks a handful.
_AUR_SRING: dict = {}


def _aur_state_ring(r1: int, rk: tuple, rp: float, pp: float):
    key = (int(r1), tuple(rk), int(rp * 64.0), int(pp * 32.0))
    got = _AUR_SRING.get(key)
    if got is not None:
        return got
    #: pad for the +3 shadow offset and the widest stroke's half-width
    pad = 16
    S = 2 * (int(r1) + pad)
    t = Image.new("RGBA", (S, S), (0, 0, 0, 0))
    d = ImageDraw.Draw(t, "RGBA")
    cc = S // 2
    bb = (cc - r1, cc - r1, cc + r1, cc + r1)
    #: IDENTICAL to the strokes this replaces, in the same order, so the
    #: only thing that changes is the surface they land on.
    d.ellipse((bb[0] + 3, bb[1] + 3, bb[2] + 3, bb[3] + 3),
              outline=(0, 0, 0, 150), width=9)              # cast shadow
    d.ellipse((bb[0] - 3, bb[1] - 3, bb[2] + 3, bb[3] + 3),
              outline=(int(20 + 26 * rp), int(40 + 34 * rp),
                       int(58 + 30 * rp)), width=7)         # ambient bed
    d.ellipse(bb, outline=rk, width=3 + int(3 * pp))        # the body
    d.arc(bb, 176, 274, fill=(int(150 + 80 * rp), int(205 + 45 * rp),
                              245, 235), width=2)           # top facet
    d.arc(bb, 356, 454, fill=(14, 30, 46, 210), width=2)    # under-edge
    #: a cap, not a leak: engagement walks `pp` continuously, and a dict
    #: that grows with every value it has ever seen is the bug this file
    #: records at _AUR_BLOOM_MASK.
    if len(_AUR_SRING) > 24:
        _AUR_SRING.clear()
    _AUR_SRING[key] = t
    return t


_CPH: dict = {"t": 0.0, "acc": {}, "n": 0}


def _cph(name: str) -> None:
    """Close the sub-segment that was running inside draw_aurora_core."""
    t = time.perf_counter()
    _CPH["acc"][name] = _CPH["acc"].get(name, 0.0) + (t - _CPH["t"])
    _CPH["t"] = t


#: ── WHAT THE BREAKDOWN SAID (2026-08-19, puck-10634, ring settled) ──────
#: Per frame that actually drew a ring, over 769 of them:
#:
#:     arris       3.79 ms    28 alpha-blended arc/line calls
#:     bloom       2.28 ms    7 pastes of the vapour halo
#:     pane        2.08 ms    7 pastes of the sprite
#:     bloom-mask  1.40 ms    7 LUT builds for the halo's alpha
#:     sprite      0.04 ms    cache hits
#:     dissolve    0.00 ms    never runs once the panes have landed
#:     ------------------------------
#:                 9.59 ms  =  t:menu 9.7   (it sums, which is the check)
#:
#: The suspicion before measuring was the PASTES, because seven RGBA
#: composites is the visible bulk of the function. They are 4.4 ms of it.
#: The single most expensive thing on the ring is its LIT EDGES — PIL
#: rasterises a stroked arc a pixel at a time, and 28 of them across seven
#: panes costs more than every pixel of every pane put together.
#:
#: Two of those six lines are recomputed answers to a question that stopped
#: changing when the last pane landed. `_fl` and `_vk` both carry
#: `sin(pi * k)`, which is EXACTLY ZERO at k = 1 — so a settled pane's
#: arris alpha is AUR_EDGE_FLOOR and its bloom alpha is AUR_BLOOM_FLOOR,
#: frame after frame, for as long as the ring is up. That is 5.19 ms of the
#: 9.59 spent re-deriving two constants.
#:
#: NOT the layer cache that was tried and dropped (see the long note on
#: draw_aurora_menu). That collapsed the whole pane — bloom, sprite, arcs —
#: into ONE layer and blended it once, which changes the arithmetic for
#: every partially transparent pixel and was measured 131/255 different.
#: These two keep every paste and every blend exactly where it was and in
#: the same order; what is cached is the ALPHA MASK handed to an unchanged
#: paste, and a tile whose ink is the same four strokes at the same alpha.
#: scripts/test_aurora_menu_cache.py renders the ring both ways and reports
#: the difference rather than asserting there is none.
_AUR_BLOOM_MASK: dict = {}
_AUR_ARRIS_CACHE: dict = {}


#: Where the arris sits relative to the pane's own band, in px and degrees.
#: Named because they were six literals inherited from a different
#: painter — see the note inside _aur_arris_elems for what that cost.
#: A stroke is 3 px wide, so half of it is 1.5: at that inset the ink
#: lands ON the edge instead of beside it.
#: ── DOES A PANE FLASH AS IT ARRIVES? (2026-08-20) ─────────────────────
#: No. Owner, after seven rounds on it: "just get rid of it, i'm tired of
#: dealing with the initial highlights of the wedges being so
#: discombobulated. the regular fade in and fade out for the initial
#: on-screen unlock works fine."
#:
#: False means a pane's rim and halo hold their RESTING strength for the
#: whole arrival: nothing brightens, nothing decays, nothing to be out of
#: step with anything. The settled ring is unchanged — see the long note
#: where _fl is computed for what this does and does not touch.
AUR_ARRIVE_FLASH = False

AUR_ARRIS_R_IN = 1.5
#: ── AND THE OUTER EDGE CANNOT BE EXACT, FOR A PHYSICAL REASON ─────────
#: 5.5, not 1.5, and this is the one inset that is NOT a mistake inherited
#: from the other painter. scripts/check_glass_margin.py holds bright
#: structure 4 px inside the 540 px glass, and its reason is the puck and
#: not the render: "below that the arris of a pane starts disappearing
#: into the bezel on one side of the puck and not the other, because the
#: glass is not perfectly centred in its housing." A rim that vanishes
#: down one side of the dial looks far more broken than one sitting 4 px
#: in on both.
#:
#: So: 1.5 (half a stroke) + 4.0 (the housing floor). The stroke's outer
#: ink lands at exactly r=536, and the guard passes with 0.0 px to spare
#: by construction rather than by luck. The inner edge and both flanks
#: have no such constraint and are exact.
AUR_ARRIS_R_OUT = 5.5
AUR_ARRIS_DEG = 0.0          # the aurora sprite is a hard sector


def _aur_arris_elems(kx, ky, a0: float, a1: float,
                     bR0e: float, bR1e: float) -> list:
    """The four strokes of a pane's arris: two arcs inside the band, two
    radial flanks. ONE definition of the shape, read by the live draw AND
    by the cached mask below.

    An arriving pane and a settled one drawing the same edge from two
    copies of these numbers is how the sprite's height field and the
    highlight's radii drifted apart twice already — both times because a
    constant that looked like the band was not `wedge_band()`.

    The arc boxes are FLOORED for the reason spelled out in
    draw_aurora_ribbon: the box is concentric with the dial, so on the full
    frame every corner is positive and on a small tile the top-left corner
    is negative — and PIL truncates a float box toward zero, which is not
    the same rounding. floor() agrees with truncation everywhere the live
    path goes, so the frame render is byte-for-byte unchanged.
    """
    #: ── THE RIM WAS A SMALLER SECTOR THAN ITS PANE (2026-08-20) ───────
    #: Owner, sixth report and the first that names a geometry: "the wedge
    #: fade in is still just wrong ... it's just still TOO BIG and
    #: COMPLETELY NOT ALIGNED, THE OFFSET IS WRONG."
    #:
    #: Every previous pass on this argued about timing or brightness. This
    #: is position, and it was wrong on all four sides of all seven panes.
    #: Measured by rendering the arris alone against the pane alone and
    #: comparing their extents in the pane's own polar frame
    #: (scripts/measure_rim_alignment.py):
    #:
    #:     pane       inner    outer    flank lo   flank hi
    #:     BRIEFING   +5.5 px  -6.5 px   +1.00 deg  -1.75 deg
    #:     VOLUME     +4.0     -7.5      +1.25      -1.75
    #:     SETTINGS   +3.0     -8.0      +1.50      -1.50
    #:
    #: Every number inset: the highlight traced a shape smaller than the
    #: wedge it belongs to, on every side at once. From a chair that is not
    #: read as "a thin rim" — it is read as a rim that does not line up
    #: with its pane, which is exactly the sentence he used.
    #:
    #: ALL SIX OFFSETS CAME FROM `_aur_wedge`, THE LEGACY PAINTER. The 1.4
    #: deg is its `a0i = a0 + 1.4`; the 9/5/4/7 px are its stroke insets.
    #: That painter draws the BAKED face, whose panes are a different
    #: shape. The aurora sprite's footprint is a hard sector with NO
    #: angular inset at all — measured independently while fixing the
    #: ribbon's span, which found the last lit bin at exactly 148.0 deg at
    #: alpha thresholds 8, 24 and 96. So the rim was inset against an edge
    #: that was never inset. Third bug this week from a constant that looks
    #: like this ring's geometry and belongs to a different one.
    #:
    #: Now: half a stroke width, so the ink lands ON the edge rather than
    #: beside it, and nothing angular. The outer arc keeps a 2 px inset
    #: rather than 1.5 because `check_glass_margin` measured the ring's
    #: furthest ink at r=540.1 against a 540 px glass, and the housing
    #: clips unevenly — a documented complaint, not a rounding worry.
    out = []
    for _r, _w in ((bR1e - AUR_ARRIS_R_OUT, 3),
                   (bR0e + AUR_ARRIS_R_IN, 3)):
        out.append(("arc",
                    (math.floor(kx - _r), math.floor(ky - _r),
                     math.floor(kx + _r), math.floor(ky + _r)),
                    a0 + AUR_ARRIS_DEG, a1 - AUR_ARRIS_DEG, _w))
    for _ae in (a0 + AUR_ARRIS_DEG, a1 - AUR_ARRIS_DEG):
        _ra = math.radians(_ae)
        out.append(("line",
                    (kx + (bR0e + AUR_ARRIS_R_IN) * math.cos(_ra),
                     ky + (bR0e + AUR_ARRIS_R_IN) * math.sin(_ra),
                     kx + (bR1e - AUR_ARRIS_R_OUT) * math.cos(_ra),
                     ky + (bR1e - AUR_ARRIS_R_OUT) * math.sin(_ra)),
                    None, None, 2))
    return out


def _aur_arris_key(a0: float, a1: float) -> tuple:
    """How much of the key each of the four arris strokes catches, in the
    order `_aur_arris_elems` yields them: outer arc, inner arc, flank at
    a0, flank at a1.

    ── REAL OBJECTS DO NOT GLOW ON EVERY EDGE (2026-08-19, night) ────────
    Owner: "the wedges still look a bit too cartoonish." Four strokes at
    one alpha, on seven panes, is a permanent outline round every pane —
    the single most sticker-like element on the glass, and the layer under
    the near-white circle the evening note found in `_aur_edge_tint`.

    Each stroke gets the outward normal of the edge it sits on, dotted
    against the house key. The sign is the POCKET's, the same one the
    baked arris takes: bright where the normal points AWAY from the lamp,
    because that is the far wall of the recess. So a pane at twelve
    o'clock is lit along its lower-right flank and dark along its upper
    arc, a pane at eight o'clock is lit along a different pair, and the
    ring stops having an outline at all.

    Returned as weights rather than applied here, because the tile cache
    has to key on them — two panes at different bearings must never share
    a tile now that the four strokes are no longer identical.
    """
    _n = math.hypot(AUR_KEY_L[0], AUR_KEY_L[1]) or 1.0
    _lx, _ly = AUR_KEY_L[0] / _n, AUR_KEY_L[1] / _n
    _am = math.radians((a0 + a1) / 2.0)
    #: outward normals: +r at the outer arc, -r at the inner, and the two
    #: flanks perpendicular to their own radius, each pointing out of the
    #: sector (a0's is 90 degrees back, a1's is 90 degrees on).
    _ns = ((math.cos(_am), math.sin(_am)),
           (-math.cos(_am), -math.sin(_am)),
           (math.cos(math.radians(a0 - 90.0)),
            math.sin(math.radians(a0 - 90.0))),
           (math.cos(math.radians(a1 + 90.0)),
            math.sin(math.radians(a1 + 90.0))))
    return tuple(
        AUR_ARRIS_FLOOR + (1.0 - AUR_ARRIS_FLOOR)
        * max(0.0, -(_nx * _lx + _ny * _ly)) ** 1.5
        for _nx, _ny in _ns)


def _aur_arris_draw(d, kx, ky, a0: float, a1: float, fill,
                    bR0e: float, bR1e: float, only: int = None,
                    keys: tuple = None) -> None:
    """Paint the arris through `d`. `fill` is whatever that canvas wants —
    an RGBA tuple on the frame, a bare level on a mask.

    `keys` is the per-stroke share of the key from `_aur_arris_key`. A
    stroke whose share leaves it under 3/255 is SKIPPED rather than drawn
    at nothing, which is also why this is not more expensive than the
    version that drew all four: on a typical pane two of the four are
    below that and never reach PIL at all.
    """
    for _n, (_kind, _geom, _s0, _s1, _w) in enumerate(
            _aur_arris_elems(kx, ky, a0, a1, bR0e, bR1e)):
        if only is not None and _n != only:
            continue
        if keys is not None:
            _k = keys[_n] if _n < len(keys) else 1.0
            if isinstance(fill, tuple):
                _fa = int(fill[-1] * _k)
                if _fa < 3:
                    continue
                fill_n = fill[:-1] + (_fa,)
            else:
                _fa = int(fill * _k)
                if _fa < 3:
                    continue
                fill_n = _fa
            if _kind == "arc":
                d.arc(_geom, _s0, _s1, fill=fill_n, width=_w)
            else:
                d.line(_geom, fill=fill_n, width=_w)
            continue
        if _kind == "arc":
            d.arc(_geom, _s0, _s1, fill=fill, width=_w)
        else:
            d.line(_geom, fill=fill, width=_w)


def _aur_arris_tile(i: int, a0: float, a1: float, ec: tuple, alpha: int,
                    xy: tuple, size: tuple, bR0e: float, bR1e: float,
                    keys: tuple = None):
    """The settled pane's arris, built once, as an RGBA tile to paste.

    ── COVERAGE IS COMPOSED ON A MASK, NOT ON A COLOUR BUFFER ────────────
    The obvious version pre-draws the four strokes straight into a
    transparent RGBA tile. Measured against the live draw by
    scripts/test_aurora_menu_cache.py: **47/255 different on 89 pixels** —
    small, and not nothing, and the 89 are exactly the corners where an arc
    crosses a flank, which is the brightest, most deliberate part of the
    edge he asked for twice. Two overlapping strokes BLEND TWICE against
    the frame in the live path; in a tile the second blends against the
    first over transparent black instead. Same failure as the layer cache
    in the note on draw_aurora_menu, three orders of magnitude smaller.

    Every stroke here has the SAME colour and the SAME alpha, so the only
    thing that varies pixel to pixel is COVERAGE — and `screen` on a grey
    mask is exactly 1-(1-a)(1-b), which is what blending twice computes.
    So coverage is accumulated on an L mask and becomes the tile's alpha.
    Measured back to **1/255 on 23 pixels**, which is integer rounding.

    ── AND THE TILE IS PASTED, NOT FILLED THROUGH. MEASURED, TWICE ───────
    With the mask in hand the tidy call is `paste(colour, box, mask)` — no
    RGB buffer at all. That shipped, and the pace log said **arris 17.2 ms**
    against the live draw's 3.79: four and a half times slower, on the
    device, for strictly less work on paper. `paste(rgba, xy, rgba)` is
    2.23. PIL's fill-through-mask and its RGBA paste do the same arithmetic
    and are not the same code; scripts/bench_aurora_arris.py times all
    three and is the reason this line reads the way it does.

    Keyed on the pane and on the alpha it settles at, so an arrival — where
    the flash is genuinely moving — never fills this and never reads a tile
    minted for a different brightness.
    """
    #: the four strokes no longer share an alpha (see _aur_arris_key), so
    #: the per-stroke shares are part of the identity of the tile. Without
    #: this a pane would happily serve its neighbour a tile lit on the
    #: wrong edge, which is the exact class of bug the `int(bR0e)` in this
    #: key was added for.
    _kq = tuple(int(round(_k * 255.0)) for _k in (keys or (1.0,) * 4))
    key = (i, tuple(ec), alpha, int(bR0e), int(bR1e), size, _kq)
    hit = _AUR_ARRIS_CACHE.get(key)
    if hit is not None:
        return hit
    _c = SIZE // 2
    kx, ky = _c - xy[0], _c - xy[1]
    msk = Image.new("L", size, 0)
    for _n in range(4):
        one = Image.new("L", size, 0)
        _aur_arris_draw(ImageDraw.Draw(one), kx, ky, a0, a1, alpha,
                        bR0e, bR1e, only=_n, keys=keys)
        msk = ImageChops.screen(msk, one)
    tile = Image.new("RGBA", size, tuple(ec) + (0,))
    tile.putalpha(msk)
    _AUR_ARRIS_CACHE[key] = tile
    return tile


#: DIAGNOSTIC ONLY. False reproduces the behaviour the owner reported four
#: times — the lit rim drawn at full pane geometry while the glass is still
#: condensing — and exists so scripts/test_arris_not_before_glass.py can
#: show its assertion FAILING on the old picture as well as passing on the
#: new one. A guard that has never been seen to fail is a guard nobody has
#: reason to trust. Nothing in the running face reads this as anything but
#: True.
AUR_ARRIS_MASKED = True


def _aur_arris_layer(a0: float, a1: float, ec: tuple, alpha: int,
                     xy: tuple, size: tuple, bR0e: float, bR1e: float,
                     keys: tuple = None):
    """The same arris, in the same box, UNCACHED — for a pane that is still
    arriving, whose brightness moves every frame.

    Deliberately not stored: an arrival walks `alpha` through hundreds of
    values and would fill _AUR_ARRIS_CACHE with tiles nothing ever asks for
    again. The reason it is a LAYER rather than four strokes on the frame
    is that a layer can be pasted through the pane's own dissolve mask —
    see the note at the arris block in draw_aurora_menu.

    ── ONE PASS, NOT FOUR. MEASURED (2026-08-20) ─────────────────────────
    _aur_arris_tile builds its coverage by screening four separate strokes,
    because a settled pane's edge is looked at for as long as the ring is
    up and the 89 corner pixels where two strokes cross are its most
    deliberate part. That cost 0.67 ms per pane here — 2.7 ms on the
    device, times up to four panes arriving at once, on the one frame the
    ring is already the most expensive thing on the glass.

    This layer is a FLASH: it is on screen for a fraction of a second, at a
    brightness that moves every frame, under a condensation mask that is
    dissolving it anyway. Drawing all four strokes into one mask in a
    single pass costs 0.25 ms and differs only in that the corners land at
    `alpha` rather than screen(alpha, alpha) — which is exactly what the
    old live path did when it drew straight onto the frame, and nobody has
    ever complained about that corner. §8: the asymmetry is real, and it
    points the other way here than it does for the settled tile.
    """
    _c = SIZE // 2
    msk = Image.new("L", size, 0)
    _aur_arris_draw(ImageDraw.Draw(msk), _c - xy[0], _c - xy[1], a0, a1,
                    alpha, bR0e, bR1e, keys=keys)
    layer = Image.new("RGBA", size, tuple(ec) + (0,))
    layer.putalpha(msk)
    return layer


#: ── THE SETTLED RING IS REPAINTED 25 TIMES A SECOND (2026-08-18) ──────
#: Owner: "it feels less responsive than usual." Measured on the puck from
#: the pace log, the moment the ring appears:
#:
#:   ring down   tail 15.6 ms   compose 37 of a 38 ms budget   25.4 fps
#:   ring up     tail 26.3 ms   compose 47 of a 38 ms budget   21.2 fps
#:
#: +10.7 ms exactly when a finger is on its way to a pane, which is the
#: worst possible moment to lose a third of the frame rate. Timed off
#: device, the split is draw_aurora_menu 5.75 ms against the ribbon's 0.65
#: — the panes, not the trace, and the ribbon was the obvious suspect only
#: because it is the part that moves. I reported it as the cause before
#: measuring it and was wrong.
#:
#: `now` appears in this function's signature and NOWHERE in its body. The
#: ring is a pure function of (alphas, rot_deg): once every pane has landed
#: and the dial is still, every frame composites a pixel-identical image.
#:
#: ── AND A LAYER CACHE DOES NOT WORK HERE. TRIED, MEASURED, DROPPED ────
#: The obvious fix is to draw the settled ring once into an RGBA layer and
#: paste it: 2.0 ms against 5.75, measured, so the arithmetic was there.
#: scripts/test_menu_cache.py compared the cached path against a live draw
#: and it differs by 131 out of 255 across the whole ring — first on a
#: transparent ground, which was the test's fault, and then still on an
#: OPAQUE one, which was not.
#:
#: The reason is in how these panes are composited. Each is a sequence of
#: alpha pastes — the bloom, then the sprite through a dissolve mask, then
#: arcs drawn straight onto the frame — and PIL's `paste(im, box, mask)`
#: blends im's RGB directly rather than premultiplied. Collapse that
#: sequence into one layer and blend the layer once, and the partially
#: transparent pixels (which is the entire bloom, and every chamfer) get
#: different arithmetic. It is not a rounding difference to be tolerated;
#: it is a different picture.
#:
#: It could be made to work with premultiplied alpha_composite throughout,
#: which means rewriting the pane compositing that took a week of his
#: evenings to look right. That trade is his to make, not mine, so the
#: ring is still drawn live and the 5.75 ms stands. Recorded here because
#: the next person will have this idea too, and the measurement that makes
#: it look good (2.0 vs 5.75) is the first thing they will find.
#: ── AND THE PAINTER COUNTS ITS OWN FADE NOW (2026-08-19) ───────────────
#: PRINCIPLES §1, and §4. "The fade in process is gone" was true for a day
#: with nothing in any log saying so, and the fix for that was FIRST
#: written as a line printed at show time from `_ui_step` — which is the
#: SCHEDULE grading its own homework. A schedule that intends 23 frames
#: and a painter that draws 2 look identical from there.
#:
#: So the condensation branch below counts itself, per pane, and the ring
#: reports what it ACTUALLY PAINTED the moment the last pane lands. The
#: two numbers are produced by different code from different inputs; when
#: they agree the arrival is real, and when they disagree the disagreement
#: is the bug, printed.
#:
#: This is also the standing answer to the theory that gets re-formed every
#: time a cache lands on this function — "the settled-pane caches are
#: keyed without the alpha, so an arriving pane hits an opaque tile and the
#: fade is skipped." Both caches are gated on the pane's OWN progress
#: (`e >= 0.995` for the bloom mask, `k >= 0.999` for the arris tile), so a
#: pane that is still arriving cannot reach either. That is an argument
#: from reading the code, which is the weak kind; the counter is the
#: measurement, and a cache that ever did intercept would show up here as a
#: pane that condensed over ZERO frames.
_AUR_ARR: dict = {"on": False, "f": {}, "said": False, "t0": None}


def _aur_arrival_open(alphas) -> None:
    """Begin watching an arrival, if one has just started.

    A HIDE walks the same alphas back down through the same branch, so
    `vis` is what tells the two apart — without it the dissolve-out would
    be reported as a (very healthy) arrival every time the ring closed.

    The watch is identified by `show_n`, a counter bumped once per summon,
    rather than by an `on` flag that has to be cleared correctly on every
    exit. A ring dismissed mid-arrival never reaches the close, and a flag
    left standing would let the NEXT arrival accumulate on top of the
    abandoned one — an over-count, which is the direction that HIDES a
    skipped fade. §9: whoever leaves early owns the cleanup, so there is
    nothing to clean up.

    It is NOT keyed on `show_t0`, which is the obvious choice and was the
    first one: `_aur_ui_stall` moves `show_t0` on any frame the glass did
    not get, so the watch re-opened itself and wiped its own count on
    exactly the frames it exists to measure.
    """
    if not _AUR_UI.get("vis"):
        _AUR_ARR["on"] = False
        return
    _t0 = _AUR_UI.get("show_n") or 0
    if _AUR_ARR["t0"] != _t0:
        #: ── A RE-SUMMON OF A RING ALREADY UP IS NOT AN ARRIVAL ────────
        #: (2026-08-19) `aurora_ui_show` bumps `show_n` even when it
        #: declines to make a sound, because the ring is already fully up
        #: — a nudged dial, a second tap on a pane. `from_a` is then all
        #: 1.0, every alpha starts and stays settled, and this watch would
        #: open and close on the same frame reporting
        #: `[0,0,0,0,0,0,0] ... the fade did not run, it was SKIPPED`.
        #: That is a false alarm in the one instrument this ring is
        #: debugged with, and a session has already spent hours on a
        #: reading of these numbers (§4 — the counter is the independent
        #: witness, so it has to be worth believing). Nothing to condense
        #: means nothing to watch; the id is still taken so it cannot
        #: re-open later in the same summon.
        _AUR_ARR.update(t0=_t0, f={},
                        on=any(a < 0.999 for a in alphas))


def _aur_arrival_close(alphas, fps: float = 0.0) -> None:
    """Report the arrival the frame the last pane lands, once."""
    if not _AUR_ARR["on"] or any(a < 0.999 for a in alphas):
        return
    _AUR_ARR["on"] = False
    got = [_AUR_ARR["f"].get(i, 0) for i in range(len(alphas))]
    #: the names of the ring ACTUALLY on the glass (2026-08-26) — this read
    #: AUR_MENU, so on any non-aurora face the one instrument this ring is
    #: debugged with would have named the wrong panes (§4: the counter has
    #: to be worth believing).
    _nm = pane_names()
    dead = [_nm[i] for i, g in enumerate(got)
            if g == 0 and i < len(_nm)]
    thin = [_nm[i] for i, g in enumerate(got)
            if 0 < g < AUR_ARRIVE_MIN_FRAMES and i < len(_nm)]
    #: the healthy line is said ONCE per process; a bad one is said EVERY
    #: time, because a fade nobody can see is the thing that went unnoticed
    #: for a day and the asymmetry is deliberate (§8).
    if not (dead or thin) and _AUR_ARR["said"]:
        return
    _AUR_ARR["said"] = True
    _held = float(_AUR_UI.get("stalled") or 0.0)
    print(f"aurora: ring ARRIVED — panes condensed over {got} frames "
          f"(the painter's own count, not the schedule's)"
          + (f", schedule held back {_held:.2f}s over frames the glass "
             f"never got" if _held > 0.01 else "")
          + (f"  *** {', '.join(dead)} PAINTED NO CONDENSATION AT ALL: the "
             f"fade did not run, it was SKIPPED — something upstream of "
             f"the dissolve branch is settling the pane in one frame ***"
             if dead else "")
          + (f"  *** {', '.join(thin)} under {AUR_ARRIVE_MIN_FRAMES} "
             f"frames: this reads as the pane appearing, not arriving ***"
             if thin else ""), flush=True)


def draw_aurora_menu(frame: "Image.Image", now: float, alphas,
                     rot_deg: float = 0.0) -> None:
    try:
        if not any(a > AUR_PANE_INK_K for a in alphas):
            return
        _MPH["t"] = time.perf_counter()
        _MPH["n"] += 1
        _aur_arrival_open(alphas)
        #: ONE list, read once, and its length asserted against the
        #: geometry's before either is indexed — see pane_names(). A
        #: mismatch draws NOTHING and says so, because the alternative is
        #: a ring of panes wearing each other's names and no error at all.
        _names = pane_names()
        _wed = wedges()
        if len(_names) != len(_wed):
            _AUR.setdefault("said", set())
            if "names" not in _AUR["said"]:
                _AUR["said"].add("names")
                print(f"aurora: {len(_wed)} wedges but {len(_names)} names "
                      f"— the ring is NOT drawn; a pane under another "
                      f"pane's name is not a smaller bug than a blank ring",
                      flush=True)
            return
        for i, (a0, a1, col) in enumerate(_wed):
            k = alphas[i] if i < len(alphas) else 0.0
            if k <= AUR_PANE_INK_K:
                continue
            sprite, xy, dis, vap = _aur_wedge_sprite(i, a0, a1, col,
                                                     _names[i])
            _mph("sprite")
            #: THE ARRIVAL IS AN EASE, not a linear ramp: slow to start,
            #: quick through the middle, settling at the end. A pane that
            #: fades linearly reads as a value changing; this reads as a
            #: thing arriving.
            e = k * k * (3.0 - 2.0 * k)
            #: ── THE BLOOM PERSISTS (2026-08-17) ──────────────────────────
            #: Owner, twice: "wedges still do not have that same initial
            #: beautiful bloom color when they are transitioned in", and
            #: "those bloom colors are beautiful and they absolutely should
            #: persist after the introduction of the tile, they set each
            #: other apart significantly."
            #:
            #: I fixed the border flash first and that was the wrong thing.
            #: The bloom he means is `vap` — the breath of coloured light a
            #: pane condenses out of — and it was STRUCTURALLY unable to
            #: persist: it lived inside the `else` branch below, the one
            #: that only runs while a pane is still arriving. The moment a
            #: pane reached full alpha the code took the fast path and
            #: painted the sprite with no bloom at all. There was no value
            #: to tune; there was no code that would have drawn it.
            #:
            #: So the bloom is lifted out of the transition and given a
            #: floor. `sin(pi * e)` is zero at both ends, so a fully
            #: arrived pane lands exactly on AUR_BLOOM_FLOOR and keeps a
            #: permanent halo in its own colour — which, now that the
            #: palette is one hue sweep, is what actually sets the seven
            #: apart at a glance. The arrival still peaks well above it, so
            #: the moment is not lost.
            _vk = (AUR_BLOOM_FLOOR if not AUR_ARRIVE_FLASH else
                   AUR_BLOOM_FLOOR + (1.0 - AUR_BLOOM_FLOOR) * (
                       math.sin(math.pi * min(1.0, max(0.0, e))) ** 1.25))
            #: ── AND THE HALO STOPPED OUTRUNNING THE PANE (2026-08-19) ──
            #: This was `k * 4.0`, which puts the bloom at its full
            #: resting strength by k = 0.25 — a ninth of a second into the
            #: first pane's fade. The bloom is the WIDEST and brightest
            #: part of a pane's footprint (it is the pane's silhouette
            #: blurred by 14 px), so from the chair the control has fully
            #: arrived while the glass inside it is still condensing. Half
            #: of "now they are just there" was this, and it is why the
            #: schedule alone would not have fixed it: measured on the
            #: first pane, 28.8% of the pane's box had ink on the FIRST
            #: frame after zero, before one pixel of the sprite was drawn.
            #:
            #: 1.8 lets the halo lead by a little — which is right, the
            #: pane is meant to condense OUT of it — and reach full only
            #: past the halfway point of its pane's own fade.
            #: AUR_BLOOM_FLOOR is untouched: he asked for the resting halo
            #: twice and this changes nothing about where it settles.
            #: with the flash off there is no peak to hold back, so the
            #: halo simply tracks the pane's own presence — see the note
            #: at _fl below. The 1.8 lead only ever mattered because the
            #: bloom used to outrun the glass on its way to a peak.
            _vk *= min(1.0, k * (1.0 if not AUR_ARRIVE_FLASH else 1.8))
            #: ── THE HALO IS AURORA'S, NOT THE RENDERER'S (2026-08-26) ──
            #: `vap` is the pane's own coloured light, blurred wide and
            #: resting permanently at AUR_BLOOM_FLOOR. It belongs to a face
            #: whose panes CONDENSE out of a breath of light on a void
            #: ground, and the owner asked for it three times there. On an
            #: instrument it is the wrong statement twice over: a machined
            #: part does not glow at its edges, and seven — here five —
            #: coloured halos at 66% around a dark dial is precisely the
            #: continuous ring of light _aur_edge_tint's 08-19 note had to
            #: be rewritten to stop. The relief path takes the SURFACE and
            #: leaves the aesthetic.
            if RELIEF_PANES:
                _vk = 0.0
            if _vk > 0.02:
                #: the LUT is a pure function of _vk; a settled pane's _vk
                #: never moves again, so build it once. Quantised to 1/1024
                #: — finer than the LUT can resolve (int(255*0.62/1024) is
                #: 0), so a key collision cannot change a single byte.
                _bkey = (i, int(round(_vk * 1024.0)))
                _bm = _AUR_BLOOM_MASK.get(_bkey)
                if _bm is None:
                    _bm = vap.getchannel("A").point(
                        lambda p, _v=_vk: int(p * 0.62 * _v))
                    #: only a SETTLED pane's mask is kept — an arrival walks
                    #: _vk through hundreds of values and would fill this
                    #: with tiles nothing ever asks for again
                    if e >= AUR_PANE_SETTLED_E:
                        _AUR_BLOOM_MASK[_bkey] = _bm
                _mph("bloom-mask")
                frame.paste(vap, xy, _bm)
            _mph("bloom")
            #: the pane's own condensation mask, kept so the arris below can
            #: be pasted THROUGH it. None once the pane has settled.
            _dmask = None
            if e >= AUR_PANE_SETTLED_E:
                frame.paste(sprite, xy, sprite)
                _mph("pane")
            else:
                #: ── CONDENSATION, NOT A DIMMER ───────────────────────────
                #: A pixel exists once the transition has passed the
                #: moment written for it in the dissolve field. BAND is how
                #: soft the boundary between "not yet" and "here" is: at
                #: 0.0 it is a hard wipe, at 1.0 it is the plain fade this
                #: replaces. 0.42 is a visible mist edge that still lets
                #: the pane read as one object while it forms.
                _BAND = 0.42
                _t = e * (1.0 + _BAND)
                msk = dis.point(
                    lambda p, _t=_t, _b=_BAND:
                    0 if p / 255.0 > _t else
                    255 if p / 255.0 < _t - _b else
                    int(255 * (_t - p / 255.0) / _b))
                msk = ImageChops.multiply(msk, sprite.getchannel("A"))
                #: THE FADE, COUNTED WHERE IT IS DRAWN — see the note above
                #: draw_aurora_menu. One dict increment, ~50 ns, against a
                #: branch that already builds a 250x130 mask.
                if _AUR_ARR["on"]:
                    _AUR_ARR["f"][i] = _AUR_ARR["f"].get(i, 0) + 1
                _mph("dissolve")
                frame.paste(sprite, xy, msk)
                _dmask = msk
                _mph("pane")
            #: ── THE BORDERS FLASH (2026-08-16) ───────────────────────────
            #: Owner: "make the borders flash too they deserve special
            #: treatment." The edge is the part of a pane that is actually
            #: an EDGE — where the chamfer catches the key — so the arrival
            #: lights it: a bright outline that peaks as the pane lands and
            #: decays into the baked arris underneath. Drawn live, on top,
            #: because it belongs to the MOMENT and not to the object.
            #: ── THE EDGE STAYS LIT (2026-08-17) ──────────────────────
            #: Owner: "the highlighting of the tiles with that color that
            #: fades should be more permanent with the tile itself, they
            #: are brighter and differentiated and it's sad after the brief
            #: highlight burst ends because then the wedges are sort of
            #: mundane without life."
            #:
            #: He is describing the arrival flash, which peaked as each
            #: pane landed and then decayed to nothing — so the ring looked
            #: its best for about a second and settled into something
            #: duller. The flash was doing two jobs and only admitting to
            #: one: announcing the arrival, and (accidentally, briefly)
            #: giving each pane a lit rim in its own colour, which is the
            #: part that made them read as seven distinct objects.
            #:
            #: So the decay lands on a FLOOR instead of on zero. The moment
            #: keeps its peak; the pane keeps a permanent arris afterwards.
            #:
            #: And the rim is tinted with the pane's own hue now, not a
            #: fixed near-white. Since the palette became one hue sweep,
            #: that means the edges walk the ramp too — which is the
            #: "brighter and differentiated" he is asking for, carried by
            #: the element best placed to carry it: an edge is thin, so it
            #: can hold much more saturation than a face can without the
            #: ring going gaudy again.
            #:
            #: AND THE RADII WERE WRONG. These four lines read WEDGE_R0 and
            #: WEDGE_R1 — the BAKED face's band, 370..500 — while the
            #: aurora ring has been at 412..532 since this afternoon. The
            #: highlight has been drawing 40 px inside the pane it belongs
            #: to. Exactly the same bug as the sprite's height field two
            #: months of notes above, and for the same reason: a constant
            #: that looks like the band but is not `wedge_band()`.
            #: PER PANE (2026-08-19). The graduated ring gives each pane
            #: its own inner radius, and this is the same class of bug the
            #: paragraph above is about — an arris drawn at the ring's mean
            #: band would float inside the thin panes and hang out of the
            #: thick ones. The arris tile's cache key already carries
            #: int(bR0e), so the tiles cannot be shared across thicknesses.
            _bR0e, _bR1e = wedge_band(i)
            #: ── THE ARRIVAL FLASH IS GONE (2026-08-20) ────────────────
            #: Owner, seventh report, and this one is a decision rather
            #: than a bug report: "the fade in still is totally off. JUST
            #: GET RID OF IT, i'm tired of dealing with the initial
            #: highlights of the wedges being so discombobulated. the
            #: regular fade in and fade out for the initial on-screen
            #: unlock works fine."
            #:
            #: So the flash goes and the pane stays. With
            #: AUR_ARRIVE_FLASH off, a pane's rim and halo sit at the
            #: strength they will settle at, for the whole arrival — no
            #: peak, no decay, nothing that brightens and fades. The pane
            #: mists in through its condensation mask and its edge mists
            #: in with it, arriving at exactly the resting value, so there
            #: is no pop at the end either.
            #:
            #: WHAT IS DELIBERATELY UNTOUCHED: the settled ring. He has
            #: approved the lit rim twice and the resting halo three
            #: times, and none of that changes — AUR_EDGE_FLOOR and
            #: AUR_BLOOM_FLOOR are what a landed pane already wears. The
            #: only thing removed is the moment.
            #:
            #: Kept as a switch rather than deleted because six earlier
            #: reports about this transition were about the flash being
            #: WRONG, not about it being unwanted, and the difference
            #: between "we removed it" and "we can put it back" is worth
            #: one boolean.
            #: ── THE RIM IS BAKED, SO IT IS NOT ALSO DRAWN (2026-08-26) ─
            #: This is the LIVE arris — four coloured strokes at
            #: _aur_edge_tint(col), which is the pane's hue at value 1.0.
            #: On aurora it is the thing that keeps seven near-black panes
            #: distinguishable on a void. A relief pane already carries an
            #: arris in its own bake — the `edge` gaussian at the top of
            #: the chamfer, keyed per edge by which way that edge faces —
            #: and laying a uniform stroke over it is the "sticker"
            #: element twice: the first render of this ring had a
            #: near-white outline round the bone pane and a red one round
            #: LOCK, both complete, both ignoring the lamp. The lit rim
            #: stays; it just comes from the surface rather than from a
            #: pen (§15 — one statement about where the light is).
            if RELIEF_PANES:
                _mph("arris")
                continue
            _fl = AUR_EDGE_FLOOR if not AUR_ARRIVE_FLASH else (
                (AUR_EDGE_FLOOR + (1.0 - AUR_EDGE_FLOOR)
                 * (math.sin(math.pi * min(1.0, k)) ** 1.6))
                * min(1.0, k * 3.0))      # nothing before the pane exists
            if _fl > 0.02:
                _c = SIZE // 2
                _a = int(210 * _fl)
                _ec = _aur_edge_tint(col)
                #: ── INSIDE THE BAND, NOT ON ITS EDGE (2026-08-18) ────
                #: The arris used to be a flash that decayed to nothing, so
                #: where it sat barely mattered. Now it is permanent, and
                #: check_glass_margin measured the ring's furthest ink at
                #: r=540.1 against a glass radius of 540 — touching the
                #: housing, which clips unevenly because the panel is not
                #: perfectly centred in it.
                #:
                #: Drawn 9 px inside the nominal edge rather than 3. The
                #: band keeps the position he asked for twice; the light on
                #: its rim simply stops hanging off the end of it.
                #: A SETTLED PANE'S EDGE IS A PICTURE, NOT A DRAWING
                #: (2026-08-19). Measured at 3.79 ms of the menu's 9.59 —
                #: the most expensive thing on the ring, and every frame of
                #: it redraws the identical four strokes. Once the pane has
                #: landed the tile is minted once and pasted; while it is
                #: still arriving the flash is genuinely moving, so that
                #: path is left exactly as it was.
                #: which of the four strokes the lamp actually reaches —
                #: see _aur_arris_key. Pure arithmetic on two angles, no
                #: allocation, and it lets the live path SKIP the strokes
                #: that would have been drawn at nothing.
                _ak = _aur_arris_key(a0, a1)
                if k >= 0.999:
                    _at = _aur_arris_tile(i, a0, a1, _ec, _a, xy,
                                          sprite.size, _bR0e, _bR1e,
                                          keys=_ak)
                    frame.paste(_at, xy, _at)
                else:
                    #: ── A RIM IS AN EDGE OF SOMETHING (2026-08-20) ────
                    #: Owner, for the fourth time: "the intro fade in is
                    #: still completely off with highlighting the wedges as
                    #: they open" / "oversized highlights over the wedges".
                    #:
                    #: Three fixes went at this sentence before anyone
                    #: RENDERED the arrival and looked at it. What the
                    #: frames show (scripts/preview_wedge_arrival_strip.py,
                    #: which separates the three layers by differencing
                    #: renders with each one suppressed):
                    #:
                    #:   t     pane px   pane mean   arris px  arris mean
                    #:   0.26        0         0.0        162        40.0
                    #:   0.61     3045        12.4       1084        45.0
                    #:   0.87    25737        23.3       1849        60.5
                    #:   1.20    61046        27.6       2904        69.9
                    #:
                    #: At t=0.26 the pane has NOT ONE LIT PIXEL and its rim
                    #: is already drawn at 40. At every later moment the
                    #: rim is two to three times brighter than the glass it
                    #: is supposed to be an edge OF. Rendered, it is
                    #: unmistakable: a bright complete outline of a wedge
                    #: with nothing inside it, filling in afterwards. That
                    #: is not a fade with a highlight on it — that IS the
                    #: highlight, and it is what he has been pointing at.
                    #:
                    #: The cause is one line, `_fl *= min(1.0, k * 3.0)`,
                    #: which puts the rim at full strength by k=0.33 while
                    #: the glass is drawn through a dissolve field that has
                    #: barely started. It is the SAME bug as the halo's
                    #: `k * 4.0` two hundred lines above — fixed there on
                    #: 08-19, left standing here, because the two were
                    #: never seen as one statement about what may lead the
                    #: glass (§15: one owner per shared policy).
                    #:
                    #: DIMMING IT WOULD BE THE WHITELIST ANSWER. A dim
                    #: complete outline around an empty pane is the same
                    #: picture, quieter. The structural answer is that an
                    #: edge cannot exist where its surface does not: the
                    #: rim is drawn into a layer and pasted THROUGH THE
                    #: PANE'S OWN CONDENSATION MASK, so it appears exactly
                    #: where glass has appeared and mists in with it. The
                    #: flash he asked for twice is untouched — same curve,
                    #: same floor, same colour — it simply no longer
                    #: arrives before the thing it is lighting.
                    #: ── AND THE SPATIAL GATE MADE IT LATE (2026-08-20) ─
                    #: Owner, same day, having seen the fix above land:
                    #: "the highlights are both DELAYED and too large."
                    #:
                    #: The delay is this line's doing and it is worth being
                    #: precise about, because the fix above was right and
                    #: its mechanism was one notch too literal. Gating the
                    #: rim on the pane's PER-PIXEL condensation means the
                    #: rim cannot appear until the glass directly under it
                    #: has arrived — and the dissolve field is biased
                    #: OUTWARD by design (`_bias`, so the pane condenses
                    #: from its inner edge out), while the arris draws on
                    #: BOTH edges. So the outer stroke waits for the very
                    #: last region to form. Measured, per pane, as the lag
                    #: between the pane's first lit pixel and its rim's
                    #: (scripts/measure_pane_highlight.py):
                    #:
                    #:     STERLING  0.23 s late     SETTINGS  0.31 s late
                    #:     VOLUME    0.21 s late
                    #:
                    #: A third of a second on a 1.6 s fade, and always on
                    #: the panes with the thinnest bands.
                    #:
                    #: The PROPERTY that had to hold was "no rim where
                    #: there is no glass" — a statement about the pane as a
                    #: whole, not about each of its pixels. So the gate is
                    #: SCALAR now: the fraction of the pane that has
                    #: condensed, applied to the rim's alpha. Nothing
                    #: before the glass, nothing lagging behind it, and
                    #: test_arris_not_before_glass still passes because a
                    #: rim at zero alpha lights nothing.
                    #: `_dmask` is bound in the dissolve branch and read
                    #: here — it is initialised to None above, because a
                    #: name bound in one branch and read in another is how
                    #: the eye went black for a day (the `msc`
                    #: UnboundLocalError, 08-19).
                    _al = _aur_arris_layer(a0, a1, _ec, _a, xy,
                                           sprite.size, _bR0e, _bR1e,
                                           keys=_ak)
                    _am = _al.getchannel("A")
                    if AUR_ARRIS_MASKED and _dmask is not None:
                        _am = ImageChops.multiply(_am, _dmask)
                    frame.paste(_al, xy, _am)
            _mph("arris")
        _aur_arrival_close(alphas)
        return
    except Exception as exc:                        # noqa: BLE001
        _AUR.setdefault("said", set())
        if "menu" not in _AUR["said"]:
            _AUR["said"].add("menu")
            print(f"aurora: menu failed {exc!r} — wedges still tap",
                  flush=True)


#: ── THE STEEL RIM (2026-08-16) ───────────────────────────────────────────
#: Owner: "make the rim around the aura singularity slightly thicker to
#: give more visual space for feedback when it hears you and is thinking,
#: and use the extra space to try to render the steel type 3d look we got
#: good at with the patek."
#:
#: Stroked arcs cannot do this. A machined band is a SURFACE — its
#: luminance is a function of where you are across the bevel AND where you
#: are around the circle relative to the key light, and no number of
#: concentric strokes gets there (the first ring tried, and cost 40 ms).
#: So it is computed per pixel, once, into an RGBA sprite:
#:
#:   height profile   rise from the inner edge, a flat land, fall to the
#:                    outer — the cross-section of a real bezel
#:   normal           from the radial slope of that profile, revolved
#:   diffuse+specular against the house key at upper-left, Blinn-Phong,
#:                    so the top-left flank blazes and the lower-right
#:                    goes to ambient
#:   engraved groove  one dark line with a lit lower lip, which is what
#:                    sells "cut" rather than "printed"
#:
#: Baked once (~0.3 s), pasted with alpha every frame — real occlusion, so
#: stars do not shine through the metal. The state graphics then draw ON
#: this band, which is the visual space the owner asked for.
#: 2026-08-16, owner at the glass: "the ring is too clunky now, shrink it
#: back a bit more and still try to keep the thickness". The band had grown
#: OUTWARD to 292 — bigger than the 268 hairline it replaced — so it read
#: as a hoop around the face instead of a bezel in it. Pulled in 22 px and
#: slimmed 6: the relief needs thickness, the composition needs the void
#: back at the edge.
#: ── THINNED, AND THE EYE TOOK THE ROOM (2026-08-17) ─────────────────────
#: Owner: "thin the circle surround the eye its thickness is overpowering
#: the eye itself." 34 px of steel around a 210 px aperture is a sixth of
#: the whole object given to its frame.
#:
#: The OUTER edge stays at 270 — that is where the face's other furniture
#: is measured from (the state ring, the flare, the progress rail) — and
#: the inner edge moves out to 252. So the band is 18 px instead of 34,
#: and the aperture it opens onto grows by the same 16 px, which is the
#: half of the complaint that is really about the eye rather than the ring.
#: ── 18 px -> 15.3 px OF BAND (2026-08-20) ─────────────────────────────
#: Owner: "thin the ring around the eye in the center by 15%, i want it to
#: be more elegant."
#:
#: THE INNER EDGE MOVES, NOT THE OUTER, and that is not a style choice.
#: _aur_rim() bakes into an AUR_BOX-square image at an ABSOLUTE radius, and
#: AUR_BOX was sized to 2*AUR_RIM_R1 + 12 on 2026-08-20 — so touching R1
#: silently crops the steel band, which is the failure scripts/
#: test_core_box.py was written to catch. Moving R0 outward is the safe
#: direction and also the flattering one: the eye grows by 2.7 px.
#:
#: 252 -> 254.7 is exactly 15% off an 18 px band.
AUR_RIM_R0 = 254.7          # inner edge, box coords
AUR_RIM_R1 = 270.0          # outer edge — 15.3 px of band, was 18, was 34


def _aur_rim() -> "Image.Image":
    if _AUR.get("rim") is not None:
        return _AUR["rim"]
    import numpy as _np
    t0 = time.time()
    N = AUR_BOX
    c = N / 2.0
    y, x = _np.mgrid[0:N, 0:N].astype("float32")
    dx, dy = x - c, y - c
    r = _np.sqrt(dx * dx + dy * dy)
    T = AUR_RIM_R1 - AUR_RIM_R0
    p = _np.clip((r - AUR_RIM_R0) / T, 0.0, 1.0)      # 0 inner .. 1 outer
    #: bevel: rise, land, fall (a trapezoid, smoothed)
    rise = _np.clip(p / 0.26, 0.0, 1.0)
    fall = _np.clip((1.0 - p) / 0.26, 0.0, 1.0)
    h = _np.minimum(rise, fall)
    h = h * h * (3.0 - 2.0 * h)                       # smoothstep
    #: the groove: a dip at 62% across the land
    gr = _np.exp(-((p - 0.62) ** 2) / (2 * 0.028 ** 2))
    h = h - 0.55 * gr
    #: radial slope -> surface normal (revolved), then Blinn-Phong
    slope = _np.gradient(h, axis=1) * (N / T) * 0.09
    inv = 1.0 / _np.maximum(r, 1e-3)
    nx, ny = -slope * dx * inv, -slope * dy * inv
    nz = _np.ones_like(nx)
    nl = _np.sqrt(nx * nx + ny * ny + nz * nz)
    nx, ny, nz = nx / nl, ny / nl, nz / nl
    L = _np.array(AUR_KEY_L, "float32")     # one lamp, stated once (§15)
    L /= _np.linalg.norm(L)
    H = L + _np.array([0.0, 0.0, 1.0], "float32")
    H /= _np.linalg.norm(H)
    diff = _np.clip(nx * L[0] + ny * L[1] + nz * L[2], 0.0, 1.0)
    #: TWO specular lobes, tight and broad — the patek bezel's whole look.
    #: A single exponent gives a soft airbrushed sheen; a hard lobe over a
    #: wide one gives the ARRIS, the bright thread that says the metal was
    #: cut rather than moulded. This is the "sharp relief" the owner asked
    #: for, and it costs nothing: it is baked.
    _ndh = _np.clip(nx * H[0] + ny * H[1] + nz * H[2], 0.0, 1.0)
    spec = _ndh ** 110.0 * 1.35 + _ndh ** 16.0 * 0.34
    #: the metal: a cool steel with her blue in it, never a grey
    base = _np.stack([_np.full_like(diff, 44.0),
                      _np.full_like(diff, 62.0),
                      _np.full_like(diff, 82.0)], axis=-1)
    lit = (base * (0.22 + 0.95 * diff[..., None])
           + _np.array([196.0, 232.0, 255.0]) * spec[..., None] * 0.95)
    #: the groove reads as a cut: dark in the trough, a lit lower lip
    lit *= (1.0 - 0.55 * gr)[..., None]
    lip = _np.exp(-((p - 0.70) ** 2) / (2 * 0.016 ** 2))
    lit += _np.array([120.0, 170.0, 210.0]) * lip[..., None] * 0.45
    #: ── THE TWO ARRIS LINES ──────────────────────────────────────────────
    #: Where a bevel meets the land there is a hairline that catches the key
    #: hard — on the OUTER edge toward the light, and on the INNER edge away
    #: from it (that one lit by the bounce, dimmer and cooler). These two
    #: threads are most of what separates "machined" from "shaded circle".
    ang = _np.arctan2(dy, dx)
    key = _np.clip(_np.cos(ang - math.radians(225.0)), 0.0, 1.0)
    edge_o = _np.exp(-((p - 0.93) ** 2) / (2 * 0.030 ** 2))
    edge_i = _np.exp(-((p - 0.07) ** 2) / (2 * 0.030 ** 2))
    lit += (_np.array([210.0, 236.0, 255.0])
            * (edge_o * (0.30 + 0.85 * key ** 1.4))[..., None])
    lit += (_np.array([120.0, 168.0, 214.0])
            * (edge_i * (0.22 + 0.55 * (1.0 - key) ** 1.2))[..., None])
    a = _np.where((r >= AUR_RIM_R0) & (r <= AUR_RIM_R1), 255.0, 0.0)
    #: one-pixel feather on both edges, or the band aliases into a saw
    a *= _np.clip((r - AUR_RIM_R0 + 1.0) / 1.6, 0.0, 1.0)
    a *= _np.clip((AUR_RIM_R1 - r + 1.0) / 1.6, 0.0, 1.0)
    rgba = _np.zeros((N, N, 4), "uint8")
    rgba[..., :3] = _np.clip(lit, 0, 255).astype("uint8")
    rgba[..., 3] = _np.clip(a, 0, 255).astype("uint8")
    _AUR["rim"] = Image.fromarray(rgba, "RGBA")
    print(f"aurora: steel rim baked — {AUR_RIM_R1 - AUR_RIM_R0:.0f}px band, "
          f"bevel+groove, key upper-left, in {time.time() - t0:.2f}s",
          flush=True)
    return _AUR["rim"]


#: ── THE SHOW (2026-08-16) ────────────────────────────────────────────────
#: Owner: "when i ask for it, it should do the big bang theme where it
#: explodes into the briefing." So a briefing is not a card on this face —
#: it is a SEQUENCE, opened by the detonation and paced by the narration.
#:
#: The contract is one file. puck_conduct writes /tmp/aura_face/show.json
#: as each line begins — {scene, title, sub, i, n, at, secs} — and this
#: engine draws that scene until the next one arrives. The conductor owns
#: the audio and the clock; the face owns the picture and never guesses a
#: duration (`secs` is READ BACK from the rendered wav, per the house rule
#: that a predicted length is a lie by the third beat).
#:
#: Scenes are drawn in this face's own language — void, her blue, relief
#: from the same upper-left key — so a briefing looks like the same object
#: doing something, not like a different app opening.
SHOW_FILE = Path("/tmp/aura_face/show.json")
SHOW_FRESH_S = 900.0
_SHOW: dict = {"mtime": None, "data": None}


def _show_now(now: float):
    try:
        m = SHOW_FILE.stat().st_mtime
    except (FileNotFoundError, NotADirectoryError):
        _SHOW["mtime"] = _SHOW["data"] = None
        return None
    if _SHOW["mtime"] != m:
        _SHOW["mtime"] = m
        try:
            _SHOW["data"] = json.loads(SHOW_FILE.read_text())
        except Exception:                           # noqa: BLE001
            _SHOW["data"] = None
    d = _SHOW["data"]
    if not d or now - float(d.get("at", 0.0)) > SHOW_FRESH_S:
        return None
    if d.get("scene") == "END":
        return None
    return d


#: ── THE CONSTELLATION (2026-08-17, night watch) ──────────────────────────
#: The best moment this product has is the one with no picture: she hears
#: a voice, decides it is YOURS, and says your name. On the glass, nothing
#: happens at all.
#:
#: So: when a known voice is recognised after a quiet spell, the starfield
#: draws that person's own constellation — stars kindling one by one, then
#: lines tracing between them the way a planetarium teaches a shape, held
#: for a moment, then let go. It is placed at their SEAT when one is
#: known (aurora_seat_write), so the sky lights up where the person
#: actually is.
#:
#: THE SHAPE IS DERIVED FROM THE NAME, deterministically — same person,
#: same stars, every night, on every puck in the fleet. That is what makes
#: it theirs rather than decoration: it can be recognised back.
#:
#: It fires on the EDGE, never on the state: once per arrival, with a long
#: refractory period, because a thing that happens every time you speak is
#: wallpaper by the third sentence.
AUR_CONST_S = 6.4                 # the whole ceremony, kindle to fade
AUR_CONST_REFRACTORY_S = 240.0    # once per arrival, not once per sentence
_AUR_CONST: dict = {"who": None, "t0": 0.0, "pts": None, "last": {}}


def _aur_const_points(who: str, bearing: float) -> list:
    """Seven stars, hers alone, arranged around a bearing."""
    import hashlib
    import random as _rnd
    seed = int(hashlib.sha1(who.encode("utf-8")).hexdigest()[:8], 16)
    rng = _rnd.Random(seed)
    c = SIZE / 2.0
    pts = []
    for i in range(7):
        #: spread across a 110-degree arc centred on the bearing, at radii
        #: outside the bezel — the constellation belongs to the sky, not
        #: to the instrument
        a = bearing + rng.uniform(-55.0, 55.0)
        r = rng.uniform(AUR_RIM_R1 + 34.0, 500.0)
        pts.append((c + r * math.cos(math.radians(a)),
                    c + r * math.sin(math.radians(a)),
                    rng.uniform(0.55, 1.0)))
    #: joined in angular order so the line never crosses itself — a
    #: constellation is a path, and a tangle reads as a scribble
    pts.sort(key=lambda p: math.atan2(p[1] - c, p[0] - c))
    return pts


def draw_aurora_constellation(frame: "Image.Image", now: float,
                              rot_deg: float = 0.0) -> None:
    try:
        r = _room_now(now)
        who = (r or {}).get("who")
        known = bool(who) and not re.match(r"^(guest\d+|\?)$", str(who), re.I)
        if known:
            last = _AUR_CONST["last"].get(who, 0.0)
            if now - last > AUR_CONST_REFRACTORY_S:
                _AUR_CONST["last"][who] = now
                ang, seated = _aur_bearing(now, rot_deg)
                if ang is None:
                    ang = -90.0            # no seat known: overhead
                _AUR_CONST.update(who=who, t0=now,
                                  pts=_aur_const_points(str(who), ang))
                print(f"aurora: CONSTELLATION for {who!r} at "
                      f"{ang:.0f} deg ({'seated' if seated else 'overhead'})",
                      flush=True)
        pts = _AUR_CONST["pts"]
        if not pts:
            return
        t = now - _AUR_CONST["t0"]
        if t > AUR_CONST_S:
            _AUR_CONST["pts"] = None
            return
        d = ImageDraw.Draw(frame, "RGBA")
        #: the ceremony: kindle (stars, one by one), trace (lines between
        #: them), hold, release. Each phase overlaps the next slightly, so
        #: it reads as one gesture rather than four.
        fade = 1.0 if t < AUR_CONST_S - 1.6 else \
            max(0.0, 1.0 - (t - (AUR_CONST_S - 1.6)) / 1.6)
        for i, (x, y, mag) in enumerate(pts):
            kt = (t - i * 0.16) / 0.5
            if kt <= 0:
                continue
            k = min(1.0, kt) * fade * mag
            rr = 2.0 + 3.4 * mag
            for g in range(int(rr * 3), 0, -1):
                a = int(58 * k * (1.0 - g / (rr * 3 + 1.0)) ** 2.0)
                if a <= 1:
                    continue
                d.ellipse((x - g, y - g, x + g, y + g),
                          fill=(120, 190, 240, a))
            d.ellipse((x - rr, y - rr, x + rr, y + rr),
                      fill=(226, 246, 255, int(240 * k)))
        for i in range(len(pts) - 1):
            lt = (t - 1.15 - i * 0.20) / 0.42
            if lt <= 0:
                break
            k = min(1.0, lt) * fade
            x0, y0, _ = pts[i]
            x1, y1, _ = pts[i + 1]
            #: the line DRAWS ITSELF from one star toward the next
            xe = x0 + (x1 - x0) * min(1.0, lt)
            ye = y0 + (y1 - y0) * min(1.0, lt)
            d.line((x0, y0, xe, ye), fill=(150, 210, 250, int(150 * k)),
                   width=3)
            d.line((x0, y0, xe, ye), fill=(226, 246, 255, int(90 * k)),
                   width=1)
    except Exception as exc:                        # noqa: BLE001
        _AUR.setdefault("said", set())
        if "const" not in _AUR["said"]:
            _AUR["said"].add("const")
            print(f"aurora: constellation failed {exc!r}", flush=True)


#: ── SCENE BACKDROPS (2026-08-16, night) ──────────────────────────────────
#: Each beat of a briefing can have a volumetric loop rendered for it on
#: the RTX (scripts/render_scene_packs.py) — the same curtain machinery as
#: the centre curtain, bent into that beat's own gesture: level ranks for
#: the wafer, a swell for the island, a step for the wall, a ramp for the
#: climb, a valley for the convergence.
#:
#: Loaded lazily, ONE AT A TIME: six packs resident would be 40 MB of
#: frames the face is not looking at. The scene changes every 8-23 s,
#: which is a very long time to load 48 PNGs, and the miss costs one
#: frame of plain diagram — visible to nobody, and it says so in the log.
AUR_SCENE_DIR = Path.home() / "aura_face" / "packs"
_AUR_SCENE: dict = {"name": None, "frames": None, "loop": 12.0}


def _aur_scene_pack(name: str):
    if _AUR_SCENE["name"] == name:
        return _AUR_SCENE["frames"]
    _AUR_SCENE.update(name=name, frames=None, loop=12.0)
    d = AUR_SCENE_DIR / f"scene_{name}"
    try:
        man = json.loads((d / "manifest.json").read_text())
        fs = sorted(d.glob("frame_*.png"))
        want = int(man.get("frames") or 0)
        if not fs:
            raise FileNotFoundError("no frames")
        if want and len(fs) != want:
            raise ValueError(f"{len(fs)} on disk, manifest says {want}")
        ims = []
        for p in fs:
            im = Image.open(p).convert("RGB")
            im.load()
            ims.append(im)
        _AUR_SCENE.update(frames=ims,
                          loop=float(man.get("seconds_per_loop") or 12.0))
        print(f"aurora: scene backdrop {name!r} — {len(ims)} frames",
              flush=True)
    except (FileNotFoundError, NotADirectoryError):
        print(f"aurora: no backdrop for {name!r} — diagram on the void",
              flush=True)
    except Exception as exc:                        # noqa: BLE001
        print(f"aurora: backdrop {name!r} REFUSED ({exc!r})", flush=True)
    return _AUR_SCENE["frames"]


#: ── THE APERTURE OPENS FOR A BRIEFING (2026-08-17) ──────────────────────
#: Owner, watching the crypto show run: *"we need to maximize the screen.
#: 'THE COST OF WRITING' is clipped by the display. let's have the outer
#: circle of the central eye expand in a dramatic way to the edge of the
#: circular border... maximize the screen space released by that
#: constrained circle so we can display larger more beautiful graphics.
#: after the briefing is done, the circle should collapse back into the
#: default eye center that the home page has."*
#:
#: He is right about the waste: every diagram was drawn inside the eye's
#: aperture — 210 px of radius — on a panel with 540. Three quarters of the
#: glass was bezel and void while the most graphically ambitious thing this
#: device does happened in the middle quarter.
#:
#: HOW THE SCENES GROW WITHOUT BEING REWRITTEN. Fourteen scenes are drawn
#: from hundreds of literal coordinates. Editing every one of them to carry
#: a scale factor is a large diff and a large number of chances to miss one
#: — and a scene that half-scales is worse than one that does not. So the
#: scaling happens at the DRAWING SURFACE instead: `_ScaledDraw` wraps
#: ImageDraw and maps every coordinate outward from the centre, scales
#: stroke widths, and — the reason this beats simply upscaling the finished
#: layer — re-renders text at a LARGER FONT rather than magnifying pixels.
#: The diagrams get bigger; nothing gets softer.
#:
#: `textlength` deliberately returns the UNSCALED width. Every scene does
#: `w = d.textlength(t, f); d.text((c - w/2, y), ...)`, and since `text`
#: maps its position outward from the centre by the same factor it enlarges
#: the glyphs by, centring comes out exact. Returning a scaled width here
#: would double-apply it.
#: How far the eye opens. 1.0 is the resting aperture (inner edge of the
#: steel at 236 box px); 2.30 puts the usable radius at about 500 display
#: px, which is the panel's own edge with a hair of margin. Everything the
#: show draws is measured against `_show_ap()`, so this one number is the
#: whole gesture.
AUR_OPEN_K = 2.30
AUR_OPEN_IN_S = 1.25          # dramatic, but not a wipe
AUR_OPEN_OUT_S = 0.95         # collapsing home is quicker than opening


def _show_open(now: float, want: float) -> float:
    """Ease the aperture toward `want` (1 during a show, 0 otherwise).

    Time-based and integrated, never indexed off a wall clock times a rate
    — the same rule the centre pack's phase follows, and for the same
    reason: a frame that arrives late must not make the iris jump.
    """
    st = _AUR.setdefault("open", {"v": 0.0, "at": 0.0})
    dt = max(0.0, min(0.5, now - (st["at"] or now)))
    st["at"] = now
    dur = AUR_OPEN_IN_S if want > st["v"] else AUR_OPEN_OUT_S
    st["v"] += (want - st["v"]) * min(1.0, dt / max(0.05, dur) * 2.2)
    if abs(st["v"] - want) < 0.002:
        st["v"] = want
    return st["v"]


def _show_scale() -> float:
    """1.0 at home, up to AUR_OPEN_K with the aperture fully open."""
    v = (_AUR.get("open") or {}).get("v", 0.0)
    #: smoothstep, so the opening accelerates and settles rather than
    #: arriving at constant speed — the difference between a shutter and a
    #: cut
    e = v * v * (3.0 - 2.0 * v)
    return 1.0 + (AUR_OPEN_K - 1.0) * e


def _show_ap() -> float:
    """The radius a scene may draw inside, this frame."""
    return (AUR_RIM_R0 - 26.0) * _show_scale()


class _ScaledDraw:
    """An ImageDraw that magnifies everything about a centre point."""

    _XY = ("line", "ellipse", "rectangle", "rounded_rectangle", "arc",
           "polygon", "pieslice", "chord")

    def __init__(self, d, sc: float, cx: float, cy: float):
        self._d, self._sc, self._cx, self._cy = d, sc, cx, cy

    def _p(self, v):
        """Scale one coordinate sequence, in any of PIL's accepted shapes."""
        sc, cx, cy = self._sc, self._cx, self._cy
        if isinstance(v, (int, float)):
            return v
        flat = list(v)
        if flat and isinstance(flat[0], (tuple, list)):
            return [(cx + (p[0] - cx) * sc, cy + (p[1] - cy) * sc)
                    for p in flat]
        out = []
        for i, n in enumerate(flat):
            out.append((cx + (n - cx) * sc) if i % 2 == 0
                       else (cy + (n - cy) * sc))
        return out

    def __getattr__(self, name):
        fn = getattr(self._d, name)
        if name not in self._XY:
            return fn

        def wrapped(xy, *a, **kw):
            if "width" in kw and kw["width"]:
                kw["width"] = max(1, int(round(kw["width"] * self._sc)))
            return fn(self._p(xy), *a, **kw)
        return wrapped

    #: ── TYPE GROWS AT HALF RATE (2026-08-17) ────────────────────────────
    #: Position scales fully — a label has to stay on the thing it labels.
    #: The GLYPHS do not: at the full 2.3x a scene caption became 53 px and
    #: ran off both sides of a round panel at once, which is the same
    #: clipping the owner reported on the titles. Annotations are meant to
    #: be read, not to compete with the diagram, so they take half the
    #: growth. Caught by rendering the open aperture and looking at it.
    _TXT_K = 0.5

    def _font_at(self, font):
        k = 1.0 + (self._sc - 1.0) * self._TXT_K
        try:
            return font.font_variant(size=max(6, int(round(font.size * k))))
        except Exception:                               # noqa: BLE001
            return font

    def text(self, xy, txt, font=None, **kw):
        if font is not None:
            font = self._font_at(font)
        return self._d.text(self._p(xy), txt, font=font, **kw)

    def textlength(self, txt, font=None, **kw):
        #: measured at the size the glyphs will actually be drawn, then
        #: divided back out — the callers centre with `c - w/2` in
        #: UNSCALED space and `text` maps that outward, so returning the
        #: on-screen width here would apply the factor twice.
        if font is None:
            return self._d.textlength(txt, **kw)
        w = self._d.textlength(txt, font=self._font_at(font), **kw)
        return w / max(0.001, self._sc)


def _show_relief(d, xy, text, font, ink, k=1.0):
    """Type with the house relief: an occlusion under-edge, the face, and a
    lit top facet from the upper-left key. Three passes, same as every
    applied element on the watch faces — it is what stops light type on a
    dark ground looking printed on."""
    x, y = xy
    a = int(255 * k)
    d.text((x + 2, y + 2), text, font=font, fill=(0, 0, 0, int(190 * k)))
    d.text((x, y), text, font=font, fill=ink + (a,))
    d.text((x - 1, y - 1), text, font=font,
           fill=(235, 250, 255, int(150 * k)))


def draw_aurora_show(frame: "Image.Image", now: float, show: dict,
                     rot_deg: float = 0.0) -> None:
    """One beat of the briefing. Wrapped whole; a failed scene degrades to
    the title card, which still carries the words being spoken."""
    scene = str(show.get("scene") or "title")
    try:
        t0 = float(show.get("at", now))
        secs = max(0.1, float(show.get("secs", 8.0)))
        u = max(0.0, min(1.0, (now - t0) / secs))     # 0..1 through the beat
        c = SIZE // 2
        d = ImageDraw.Draw(frame, "RGBA")
        #: every scene fades its furniture in over the first 8% and holds —
        #: an element that pops is an element the eye stops trusting
        fin = min(1.0, (now - t0) / max(0.35, secs * 0.08))
        #: everything below this line is drawn through the magnifier when
        #: the aperture is open; at rest _show_scale() is exactly 1.0 and
        #: the wrapper is skipped entirely, so the resting face and the
        #: chip-wars show are byte-identical to before
        _sc = _show_scale()
        #: ── THE BACKDROP, UNDER THE DIAGRAM ──────────────────────────────
        #: Screened (it is light), cross-faded between frames like the
        #: curtain, and faded IN over the beat's first moments so a scene
        #: change is a dissolve rather than a cut. The vector art is drawn
        #: after it and always wins — that is the whole hierarchy.
        _bp = _aur_scene_pack(scene)
        if _bp:
            _bn = len(_bp)
            _bf = ((now - t0) / max(0.1, _AUR_SCENE["loop"])) * _bn
            _bi = int(_bf) % _bn
            _bfr = _bf - math.floor(_bf)
            _bim = _bp[_bi] if _bfr < 0.02 else Image.blend(
                _bp[_bi], _bp[(_bi + 1) % _bn], _bfr)
            _bw = int(_bim.size[0] * _sc)
            if _bw != _bim.size[0]:
                _bim = _bim.resize((_bw, _bw), Image.BILINEAR)
            _bx = c - _bw // 2
            if fin < 0.995:
                _bim = _bim.point(lambda p, _k=fin: int(p * _k))
            _breg = frame.crop((_bx, _bx, _bx + _bw, _bx + _bw))
            frame.paste(ImageChops.screen(_breg, _bim), (_bx, _bx))
        _aur_scene(_ScaledDraw(d, _sc, c, c) if _sc > 1.001 else d,
                   frame, scene, now, u, fin)
        #: ── THE TYPE, COMMON TO EVERY SCENE ──────────────────────────────
        #: ── THE TITLE FITS, MEASURED (2026-08-17) ────────────────────
        #: Owner: "'THE COST OF WRITING' is clipped by the display." It was
        #: set at a fixed 58 px and centred, with nothing checking that the
        #: result still fit inside a ROUND panel — and the widest chord
        #: available at y=96 is not the panel's diameter, it is 2*sqrt(R^2
        #: - (R-96)^2) = about 830 px. Anything wider runs off the glass on
        #: both sides at once.
        #:
        #: So the size is chosen by measurement: start at the design size,
        #: shrink until it fits the real chord at the height it is drawn.
        #: Long titles get smaller; short ones are untouched.
        title = str(show.get("title") or "")
        sub = str(show.get("sub") or "")

        #: ── FIT AGAINST THE WORST ROW, NOT THE MIDDLE (2026-08-17) ───
        #: Round one measured the chord at the text's centre line, which is
        #: the WIDEST row the glyphs occupy. On a round panel the top of a
        #: title is further from the centre than its middle and therefore
        #: has less room — so a line that "fit" by that measure still ran
        #: off the glass at its own cap height. Measured after the fact:
        #: eight of the ten crypto beats clipped, worst at r=553 on a 540
        #: panel, every offending pixel on the title row itself.
        #:
        #: Now the chord is taken at whichever edge of the line box is
        #: further from the centre, and recomputed as the size shrinks
        #: because the box shrinks with it. scripts/check_show_type.py
        #: asserts the result in pixels.
        #: `trk` is the tracking the caller will actually draw with, and
        #: it MUST be part of the fit: 0.16em across twenty characters is
        #: another 180px at this size, which is the difference between a
        #: title that fits and the one he photographed running off the
        #: glass.
        def _fit(txt, size, y, role="title", lo=18, trk=0.0):
            _R = SIZE / 2.0
            while size > lo:
                _f = face(role, int(size))
                _h = size * 1.16                     # line box, ascender+
                _dy = max(abs(y - _R), abs(y + _h - _R))
                #: 26 -> 48: textlength measures the ADVANCE, and what
                #: lands on the glass is the relief — a lit edge and a
                #: contact shadow a pixel or two beyond the box on each
                #: side, plus whatever the glyph's own bearing adds. Four
                #: beats still clipped by 1-3 px with the tighter figure,
                #: which is the whole margin's worth.
                #: 48 -> 96 (2026-08-17): "we need more padding margin
                #: for the text still on the things like the crypto
                #: presentation, it's just overlapping the progress circle
                #: and it looks cramped". Fitting inside the glass was the
                #: bug; sitting comfortably inside it is the design, and
                #: they are not the same number.
                _chord = 2.0 * math.sqrt(max(1.0, _R * _R - _dy * _dy)) - 96.0
                _w = (d.textlength(txt, font=_f)
                      + trk * size * max(0, len(txt) - 1))
                if _w <= _chord:
                    return _f
                size -= 2
            return face(role, lo)

        if title:
            #: the type grows with the aperture, but only half as fast —
            #: at full scale a 58 px title would be 133 px and the diagram
            #: would be competing with its own caption
            #: TRACKED, and the relief drawn per glyph so the letter
            #: spacing and the lit edge belong to the same object.
            #: ── TRACKING IS THE OTHER HALF OF THE TYPE ────────────────
            #: Owner, on the rim mark and it applies here: "elegant is
            #: LIGHT AND WIDE — the weight comes off and the space between
            #: the letters does the work." Four sessions have moved this
            #: title's FACE; none of them moved its spacing, and a contact
            #: sheet that varies only the face cannot show which of the two
            #: he is actually reacting to.
            #:
            #: The module-level default is the shipped value. The override
            #: exists so scripts/preview_title_faces.py can render a real
            #: sweep through the real painter rather than approximating one
            #: — a comparison whose cells are approximations is a sales
            #: pitch, which is the lesson the wedge contact sheet earned.
            _TRK = globals().get("_show_trk_override") or AUR_SHOW_TITLE_TRK
            f = _fit(title, int(62 * (1.0 + (_sc - 1.0) * 0.42)),
                     AUR_SHOW_TITLE_Y, trk=_TRK)
            _t_px = _TRK * f.size
            _tw = (d.textlength(title, font=f)
                   + _t_px * max(0, len(title) - 1))
            _x = c - _tw / 2.0
            for _ch in title:
                _show_relief(d, (_x, AUR_SHOW_TITLE_Y), _ch, f,
                             (206, 238, 252), fin)
                _x += d.textlength(_ch, font=f) + _t_px
        if sub:
            #: the sub takes MORE tracking and less weight — it is the
            #: strapline under the title, and wide-set small caps is what
            #: that has looked like since the first HUD
            _TRK2 = 0.24
            f2 = _fit(sub, int(23 * (1.0 + (_sc - 1.0) * 0.42)),
                      AUR_SHOW_SUB_Y, role="label", trk=_TRK2)
            draw_tracked(d, c, AUR_SHOW_SUB_Y, sub, f2,
                         (108, 176, 220, int(230 * fin * 0.9)),
                         track=_TRK2 * f2.size)
        #: the progress rail: which beat of how many, on the lower arc —
        #: a briefing with no visible end is a briefing people interrupt
        n = max(1, int(show.get("n", 1)))
        i = max(0, int(show.get("i", 0)))
        #: the rail rides just outside whatever the aperture currently
        #: is, so it stays the show's own furniture rather than sliding
        #: under the expanding eye
        #: 14 -> 34 px of clearance from the glass edge, same ask: the
        #: rail was sitting where the panel curves away and reading as
        #: cramped against everything near it.
        rr = int(min(SIZE / 2.0 - 34.0, (AUR_RIM_R1 + 44) * _sc))
        span, gap = 26.0, 5.0
        total = n * span + (n - 1) * gap
        a0 = 90.0 - total / 2.0
        for k in range(n):
            s0 = a0 + k * (span + gap)
            done = k < i or (k == i and u > 0.02)
            fillp = 1.0 if k < i else (u if k == i else 0.0)
            #: ── THICKER (2026-08-17) ────────────────────────────────
            #: Owner: "the thickness of the progress bar for the briefing
            #: has to be thickened". 3/5 px is a hairline at 1080 across,
            #: seen from a sofa — it read as a scratch rather than as a
            #: gauge. 7/11 is still a rail and not a bar, and the FILLED
            #: segment stays visibly heavier than the empty one, because
            #: that difference is the only thing carrying "where am I".
            d.arc((c - rr, c - rr, c + rr, c + rr), s0, s0 + span,
                  fill=(52, 92, 124, int(200 * fin)), width=7)
            if done and fillp > 0:
                d.arc((c - rr, c - rr, c + rr, c + rr), s0,
                      s0 + span * fillp,
                      fill=(150, 214, 250, int(240 * fin)), width=11)
    except Exception as exc:                        # noqa: BLE001
        _AUR.setdefault("said", set())
        key = f"show:{scene}"
        if key not in _AUR["said"]:
            _AUR["said"].add(key)
            print(f"aurora: scene {scene!r} failed {exc!r} — title only",
                  flush=True)


#: ── THE ROWS THE CAPTION OWNS (2026-08-19) ─────────────────────────────
#: Title baseline 88, sub baseline 176, plus the relief a glyph throws
#: below its own box. Anything a scene draws from the centre has to stay
#: inside `c - AUR_SHOW_CAP_BOT`, and scripts/test_show_text_clear.py
#: measures exactly this band — one number, read by the painter and by the
#: guard, so "where does the text live" cannot come to mean two things.
AUR_SHOW_CAP_BOT = 205

#: ── THE BRIEFING TITLE'S LETTER SPACING ───────────────────────────────
#: 0.16 em, the value four sessions of face-swapping never touched. It is
#: a module constant now so it can be swept by
#: scripts/preview_title_faces.py alongside the face, because "sexy and
#: futuristic" is at least as much this number as it is the typeface.
#: ── 0.16 -> 0.304 em (2026-08-20) ─────────────────────────────────────
#: Swept, and the sheet says the same thing his own wordmark note says:
#: almost doubling the spacing does more for "futuristic" than any of the
#: four face swaps did. Set with Ubuntu Thin — see the FACES["title"] note.
#: THE TRADE IS SIZE, and it is deliberate: _fit shrinks the line until it
#: clears the chord, so every em of tracking is paid for in point size. The
#: title is smaller and airier than it was. That is the direction "elegant"
#: points in, and it is the one thing to look at first if he sends it back.
AUR_SHOW_TITLE_TRK = 0.304

#: ── WHERE THE TITLE BLOCK SITS (2026-08-20) ───────────────────────────
#: Owner, on the new face: "it still is too close to the perimeter of the
#: display, we just need to shift it down a bit."
#:
#: NOT a font problem, and worth saying because the face had just changed
#: and that is the obvious suspect. The panel is ROUND. A title's ends are
#: the part nearest the curve, and 0.304 em of tracking pushed the ends
#: outward — so the same baseline that was comfortable at 0.16 em now puts
#: the first and last letters into the curve. Moving DOWN buys a wider
#: chord, which is exactly the geometry he read off the glass by eye.
#:
#: THE Y WAS WRITTEN IN FOUR PLACES — twice for the title (the fit and the
#: draw) and twice for the sub. That is the shape of bug this file has
#: caught three times already (§15), and it is why these are constants now
#: rather than a careful edit of four literals.
#:
#: The sub moves half as far. It is bounded below by AUR_SHOW_CAP_BOT and
#: the caption band, which scripts/test_show_text_clear.py asserts; the
#: title has the room and the sub does not, so the gap between them closes
#: slightly rather than the pair sliding into the rail.
AUR_SHOW_TITLE_Y = 106          # was 88
AUR_SHOW_SUB_Y = 184            # was 176


def _aur_scene(d, frame, scene: str, now: float, u: float, k: float) -> None:
    """The signature graphic for one beat. Each is built from the same
    primitives the face already owns — arcs, relief, her blue — so the show
    reads as this device thinking out loud rather than as a slideshow."""
    c = SIZE // 2
    blue, hot, dim = (96, 186, 244), (215, 245, 255), (44, 86, 120)
    if scene == "wafer":
        #: THE MACHINE: a die grid printing itself, row by row, with one
        #: bright scan line sweeping down it — lithography, drawn.
        #: centred on the aperture, not pushed down: the grid's corners
        #: pass BEHIND the bezel, which is what a wafer under a round
        #: aperture actually looks like — but the +40 offset put the last
        #: row on top of the metal, which just looked broken.
        cols, rows, cell = 9, 9, 42
        gx = c - (cols * cell) // 2
        gy = c - (rows * cell) // 2
        lit = int(u * cols * rows * 1.15)
        for r in range(rows):
            for q in range(cols):
                idx = r * cols + q
                x, y = gx + q * cell, gy + r * cell
                on = idx < lit
                a = int((210 if on else 60) * k)
                col = blue if on else dim
                d.rectangle((x + 3, y + 3, x + cell - 5, y + cell - 5),
                            outline=col + (a,), width=2)
                if on and idx > lit - cols:
                    d.rectangle((x + 7, y + 7, x + cell - 9, y + cell - 9),
                                fill=hot + (int(90 * k),))
        #: the exposure sweep, CLAMPED TO THE APERTURE: the beam is inside
        #: the machine, so it must not run out over the bezel. Half-chord
        #: of the inner circle at this height — the honest width.
        sy = gy + (lit // cols) * cell
        _rr = AUR_RIM_R0 - 8
        _hw = math.sqrt(max(0.0, _rr * _rr - (sy - c) ** 2))
        if _hw > 8:
            d.line((c - _hw, sy, c + _hw, sy),
                   fill=hot + (int(210 * k),), width=3)
            d.line((c - _hw, sy, c + _hw, sy),
                   fill=(120, 190, 240, int(70 * k)), width=11)
    elif scene == "island":
        #: THE ISLAND: one landmass on a strait, with the world's demand
        #: arriving as arcs from every bearing and passing through it.
        for i in range(14):
            a = math.radians(i * 25.7 + now * 3.0)
            r0, r1 = 470, 300
            x0, y0 = c + math.cos(a) * r0, c + math.sin(a) * r0
            x1, y1 = c + math.cos(a) * r1, c + math.sin(a) * r1
            fade = int(120 * k * (0.35 + 0.65 * ((u * 3 + i / 14.0) % 1.0)))
            d.line((x0, y0, x1, y1), fill=(70, 140, 200, fade), width=2)
        #: the strait: two coasts and the water between them, so the island
        #: is somewhere CONTESTED rather than a shape in the middle
        d.arc((c - 300, c - 210, c - 60, c + 210), 300, 60,
              fill=(58, 104, 140, int(190 * k)), width=5)
        d.arc((c + 96, c - 230, c + 400, c + 230), 120, 240,
              fill=(58, 104, 140, int(150 * k)), width=4)
        d.ellipse((c - 92, c - 132, c + 92, c + 132),
                  outline=blue + (int(235 * k),), width=4)
        d.ellipse((c - 78, c - 118, c + 78, c + 118),
                  fill=(28, 62, 92, int(160 * k)))
        d.arc((c - 92, c - 132, c + 92, c + 132), 180, 300,
              fill=(190, 230, 255, int(170 * k)), width=2)   # lit coast
        pulse = 0.5 + 0.5 * math.sin(now * 2.2)
        d.ellipse((c - 26, c - 26, c + 26, c + 26),
                  fill=hot + (int((110 + 90 * pulse) * k),))
        f = _font(44)
        w = d.textlength("90%", font=f)
        _show_relief(d, (c - w / 2, c + 44), "90%", f, (228, 248, 255), k)
    elif scene == "barrier":
        #: THE WALL: a hard arc across the field, particles arriving and
        #: stopping dead against it. The one scene with a hard edge.
        #: CLAMPED TO THE APERTURE, like the exposure sweep: the wall is a
        #: thing inside her, not a line drawn across the bezel.
        wall_y = c + 40
        _rr = AUR_RIM_R0 - 8
        _hw = math.sqrt(max(0.0, _rr * _rr - (wall_y - c) ** 2))
        d.line((c - _hw, wall_y, c + _hw, wall_y),
               fill=(150, 210, 245, int(235 * k)), width=5)
        _n = 9
        for i in range(_n):
            _x = c - _hw + (i + 0.5) * (2 * _hw / _n)
            d.line((_x, wall_y, _x - 18, wall_y + 30),
                   fill=(90, 150, 200, int(150 * k)), width=3)
        for i in range(9):
            ph = (u * 1.6 + i * 0.11) % 1.0
            x = c - _hw + 24 + i * ((2 * _hw - 48) / 8.0)
            _top = c - _rr + 30
            y = _top + ph * (wall_y - 16 - _top)
            if ph > 0.92:
                y = wall_y - 16
                d.ellipse((x - 12, y - 12, x + 12, y + 12),
                          outline=(214, 132, 120, int(200 * k)), width=2)
            d.ellipse((x - 5, y - 5, x + 5, y + 5),
                      fill=blue + (int(225 * k),))
    elif scene == "climb":
        #: THE ANSWER: a curve that bends but keeps rising, drawn as a
        #: stepped climb with the steps lighting in sequence.
        n = 12
        x0, y0 = c - 190, c + 150          # inside the aperture, like the rest
        w, h = 380 / n, 250 / n
        pts = []
        for i in range(n + 1):
            pts.append((x0 + i * w, y0 - (i ** 1.35) * h * 0.55))
        for i in range(n):
            on = (i + 1) / n <= u * 1.15
            a = int((235 if on else 70) * k)
            col = blue if on else dim
            d.line((pts[i][0], pts[i][1], pts[i + 1][0], pts[i][1]),
                   fill=col + (a,), width=4)
            d.line((pts[i + 1][0], pts[i][1],
                    pts[i + 1][0], pts[i + 1][1]),
                   fill=col + (a,), width=4)
            if on:
                d.ellipse((pts[i + 1][0] - 5, pts[i + 1][1] - 5,
                           pts[i + 1][0] + 5, pts[i + 1][1] + 5),
                          fill=hot + (int(200 * k),))
    elif scene == "converge":
        #: WHAT IT MEANS: everything falls back into the core — the show
        #: closing the way it opened, in reverse.
        #: ── AND IT STOPS BELOW THE CAPTION (2026-08-19) ─────────────
        #: Owner, for the second time: "it still overlaps the outside
        #: circle during the briefing." Measured rather than argued about
        #: this time — scripts/test_show_text_clear.py renders each scene
        #: WITHOUT its caption and counts diagram ink in the caption's
        #: rows. Of the six beats in the thermal briefing, five put ZERO
        #: pixels there and the progress rail at its widest puts zero.
        #: This one put 1032, topmost at y=98, straight through a title
        #: whose baseline is 88.
        #:
        #: The cause is not the font and never was: `rr` starts at 580 on
        #: a centre of 540, so at u=0 the spokes reach forty pixels ABOVE
        #: the top of the panel. Two sessions spent on type sizes and
        #: padding could not have fixed a diagram drawn over the type.
        #:
        #: Clamped to a radius DERIVED from where the caption ends rather
        #: than to a number that happens to work at 1080 — the next scene
        #: that reaches upward has AUR_SHOW_CAP_BOT to clamp against, and
        #: the test names it too, so the two cannot drift.
        for i in range(20):
            a = math.radians(i * 18 + now * 8.0)
            rr = min(c - AUR_SHOW_CAP_BOT, 460 * (1.0 - u) + 120)
            x0, y0 = c + math.cos(a) * rr, c + math.sin(a) * rr
            x1, y1 = c + math.cos(a) * (rr * 0.62), \
                c + math.sin(a) * (rr * 0.62)
            d.line((x0, y0, x1, y1),
                   fill=(120, 190, 240, int(160 * k * (1.0 - u * 0.6))),
                   width=3)
        rr2 = int(150 + 120 * (1.0 - u))
        d.ellipse((c - rr2, c - rr2, c + rr2, c + rr2),
                  outline=(150, 214, 250, int(180 * k)), width=3)
    #: ── THE CRYPTO BRIEFING'S EIGHT (2026-08-17) ─────────────────────────
    #: Owner: "can we have more graphics for a crypto related brief... make
    #: it high quality... and make it relatively longer."
    #:
    #: Same grammar as the six above — arcs, ticks, her blue, everything
    #: derived from `u` so the drawing ARGUES ALONGSIDE the sentence rather
    #: than looping behind it. Each one has a single idea it is responsible
    #: for landing, written at the top of its branch; if a scene cannot be
    #: described in one line it is two scenes.
    #:
    #: All of them stay inside `_ap` — the aperture, minus the bezel. The
    #: wafer scene earned that rule the hard way: a row of dies drawn on
    #: the metal just looks broken.
    elif scene == "ledger":
        #: IDEA: each block seals the one before it, so the past cannot be
        #: edited — and at the end, one edited block breaks every link
        #: after it, which is the whole sentence, drawn.
        _ap = AUR_RIM_R0 - 26
        #: FIVE blocks at an 88 px pitch = 352 px across, inside the 456 px
        #: aperture. The first cut used six at 138 and ran the chain out
        #: over the bezel on both sides.
        nb, pitch = 5, 88
        bw, bh = 64, 54
        span = (nb - 1) * pitch
        y = c + 24
        shown = min(nb, int(u * nb * 1.35) + 1)
        #: the tamper fires in the last quarter, on block 1 (an OLD one),
        #: because tampering with the newest block proves nothing
        bad = u > 0.74
        bad_i = 1
        for i in range(shown):
            x = c - span // 2 + i * pitch
            broken = bad and i >= bad_i
            col = (232, 96, 96) if broken else blue
            a = int(210 * k)
            #: the block
            d.rounded_rectangle((x - bw // 2, y - bh // 2,
                                 x + bw // 2, y + bh // 2), radius=9,
                                outline=col + (a,), width=3)
            #: the fingerprint strip — the part that changes when you lie
            for q in range(4):
                _hx = x - bw // 2 + 8 + q * 13
                _lit = ((i * 7 + q * 3 + int(now * 2)) % 5) > 1
                d.rectangle((_hx, y + 8, _hx + 9, y + 17),
                            fill=(col if _lit else dim) + (int(a * 0.8),))
            #: the link into the previous block
            if i:
                x0 = x - pitch + bw // 2
                d.line((x0, y, x - bw // 2, y), fill=col + (a,), width=4)
                if broken:
                    #: a snapped link reads as a GAP, not a red line
                    d.line((x0 + 5, y - 7, x - bw // 2 - 5, y + 7),
                           fill=(232, 96, 96, a), width=3)
            if i == shown - 1 and not bad:
                #: the newest block, still being sealed
                _p = 0.5 + 0.5 * math.sin(now * 6.0)
                d.rounded_rectangle((x - bw // 2 - 5, y - bh // 2 - 5,
                                     x + bw // 2 + 5, y + bh // 2 + 5),
                                    radius=12,
                                    outline=hot + (int(150 * k * _p),),
                                    width=2)
        if bad:
            f = _font(23)
            _t = "EDIT ONE — BREAK EVERY BLOCK AFTER"
            _w = d.textlength(_t, font=f)
            d.text((c - _w / 2, y + 74), _t, font=f,
                   fill=(236, 130, 130, int(220 * k)))
        _ = _ap
    elif scene == "mesh":
        #: IDEA: no head office. A message leaves one node and every other
        #: node hears it, checks it, and passes it on — so the ring of
        #: light IS the consensus, and it starts somewhere different each
        #: time to make the point that no node is special.
        _ap = AUR_RIM_R0 - 30
        pts = []
        for i in range(22):
            #: deterministic scatter: the same constellation every night,
            #: which is what makes it read as a NETWORK and not as noise
            a = i * 2.39996 + 0.7                    # golden angle
            rr = _ap * math.sqrt((i + 0.6) / 22.0) * 0.94
            pts.append((c + math.cos(a) * rr, c + math.sin(a) * rr))
        #: two pulses per beat, each from a different origin
        cyc = (u * 2.0) % 1.0
        src = pts[int(u * 2.0) % 7 * 3]
        wave = cyc * _ap * 2.2
        for i, (x0, y0) in enumerate(pts):
            for j in range(i + 1, len(pts)):
                x1, y1 = pts[j]
                dd = math.hypot(x1 - x0, y1 - y0)
                if dd > 132:
                    continue
                d.line((x0, y0, x1, y1),
                       fill=(58, 108, 150, int(120 * k)), width=1)
        for (x0, y0) in pts:
            dd = math.hypot(x0 - src[0], y0 - src[1])
            lit = max(0.0, 1.0 - abs(dd - wave) / 92.0)
            r = 5 + 5 * lit
            col = tuple(int(dim[q] + (hot[q] - dim[q]) * lit)
                        for q in range(3))
            d.ellipse((x0 - r, y0 - r, x0 + r, y0 + r),
                      fill=col + (int((120 + 130 * lit) * k),))
        if wave < _ap * 2.2:
            d.ellipse((src[0] - wave, src[1] - wave,
                       src[0] + wave, src[1] + wave),
                      outline=(120, 200, 250, int(90 * k * (1.0 - cyc))),
                      width=2)
    elif scene == "hash":
        #: IDEA: writing costs something. A ring of attempts flickering at
        #: a speed you cannot follow, and every so often exactly one lands
        #: and the block is won. The flicker is the electricity.
        _ap = AUR_RIM_R0 - 34
        n_t = 88
        #: won twice per beat, briefly
        wcyc = (u * 2.0) % 1.0
        won = wcyc > 0.86
        win_i = int(u * 2.0) % 3 * 29 + 11
        for i in range(n_t):
            a = math.radians(i * (360.0 / n_t) - 90.0)
            #: deterministic pseudo-flicker — no RNG in a draw path
            fk = ((i * 37 + int(now * 22.0) * 13) % 97) / 97.0
            on = fk > 0.55
            r0 = _ap * 0.60
            r1 = r0 + (26 if on else 12)
            col = blue if on else dim
            aa = int((190 if on else 90) * k)
            if won and i == win_i:
                r1, col, aa = _ap * 0.98, hot, int(240 * k)
            d.line((c + math.cos(a) * r0, c + math.sin(a) * r0,
                    c + math.cos(a) * r1, c + math.sin(a) * r1),
                   fill=col + (aa,), width=3 if not (won and i == win_i)
                   else 5)
        #: the target: a shrinking ring the attempts must land inside
        tr = int(_ap * 0.60)
        d.ellipse((c - tr, c - tr, c + tr, c + tr),
                  outline=(70, 130, 175, int(150 * k)), width=2)
        if won:
            f = _font(30)
            _t = "BLOCK FOUND"
            _w = d.textlength(_t, font=f)
            d.text((c - _w / 2, c - 16), _t, font=f,
                   fill=hot + (int(235 * k),))
    elif scene == "supply":
        #: IDEA: the schedule is written down and nobody can be lobbied.
        #: The issued curve climbs and flattens toward a hard ceiling; the
        #: bars underneath are what each era mints, halving each time.
        _ap = AUR_RIM_R0 - 30
        x0, x1 = c - 190, c + 190
        yb, yt = c + 120, c - 96
        #: the ceiling — the only straight line in the scene
        d.line((x0, yt, x1, yt), fill=(120, 190, 240, int(150 * k)), width=2)
        f = _font(22)
        _t21 = "21,000,000"
        d.text((x1 - d.textlength(_t21, font=f), yt - 30), _t21, font=f,
               fill=(150, 214, 250, int(220 * k)))
        #: the curve: sum of halving eras, so it flattens by construction
        pts, acc = [], 0.0
        for q in range(121):
            t = q / 120.0
            #: four eras, each half the last
            #: cumulative issuance across four halving eras. `era + 1`
            #: started the curve at half height on the first frame, which
            #: drew the schedule as an almost straight line — the one
            #: thing the schedule is not.
            era = t * 4.0
            acc = 1.0 - 0.5 ** era
            pts.append((x0 + (x1 - x0) * t, yb - (yb - yt) * acc))
        upto = max(2, int(len(pts) * min(1.0, u * 1.18)))
        d.line(pts[:upto], fill=(150, 214, 250, int(235 * k)), width=4)
        #: the halving bars, and the drop at each boundary
        for e in range(4):
            bx = x0 + (x1 - x0) * (e + 0.5) / 4.0
            h = 74 * (0.5 ** e)
            lit = u > (e / 4.0)
            d.rectangle((bx - 21, yb + 30 - h, bx + 21, yb + 30),
                        fill=(blue if lit else dim) + (int(150 * k),))
        d.line((x0, yb + 30, x1, yb + 30),
               fill=(70, 130, 175, int(170 * k)), width=2)
        _ = _ap
    elif scene == "peg":
        #: IDEA: a token is worth a dollar because something is held
        #: against it. The bar hunts the line and keeps finding it; the
        #: reserve column below rises to match what has been issued.
        _ap = AUR_RIM_R0 - 30
        yl = c - 62
        d.line((c - 190, yl, c + 190, yl),
               fill=(150, 214, 250, int(200 * k)), width=2)
        f = _font(24)
        d.text((c - 22, yl - 34), "1.00", font=f,
               fill=(160, 220, 252, int(220 * k)))
        #: the price, wobbling tight — the wobble SHRINKS as the beat runs,
        #: which is the peg holding rather than the peg being asserted
        for q in range(56):
            t = q / 55.0
            x = c - 190 + 380 * t
            w = (1.0 - 0.55 * u) * 20.0
            y = yl + math.sin(t * 11.0 + now * 1.7) * w * \
                (0.35 + 0.65 * math.sin(t * 3.1 + 0.6))
            if q:
                d.line((px_, py_, x, y),
                       fill=(120, 200, 250, int(210 * k)), width=3)
            px_, py_ = x, y
        #: issued vs held, side by side, filling together
        for s_, lab, off in ((0, "ISSUED", -104), (1, "RESERVES", 104)):
            h = int(126 * min(1.0, u * 1.25))
            bx, bbase = c + off, c + 128
            d.rectangle((bx - 46, bbase - h, bx + 46, bbase),
                        outline=blue + (int(190 * k),), width=3)
            d.rectangle((bx - 40, bbase - h + 6, bx + 40, bbase - 4),
                        fill=(blue if not s_ else (86, 196, 170))
                        + (int(110 * k),))
            f2 = _font(20)
            w2 = d.textlength(lab, font=f2)
            d.text((bx - w2 / 2, bbase + 12), lab, font=f2,
                   fill=(120, 186, 224, int(215 * k)))
        _ = _ap
    elif scene == "rails":
        #: IDEA: the same payment, two ways. The top one hops through
        #: correspondents and STALLS at each; the bottom one goes. The
        #: race is the argument, so both dots start together.
        _ap = AUR_RIM_R0 - 30
        x0, x1 = c - 176, c + 176
        ya, yb2 = c - 46, c + 74
        for (yy, hops, lab) in ((ya, 4, "CORRESPONDENT BANKS"),
                                (yb2, 0, "PUBLIC LEDGER")):
            d.line((x0, yy, x1, yy), fill=(66, 120, 160, int(150 * k)),
                   width=2)
            for h in range(hops):
                hx = x0 + (x1 - x0) * (h + 1) / (hops + 1.0)
                d.ellipse((hx - 10, yy - 10, hx + 10, yy + 10),
                          outline=(120, 180, 220, int(190 * k)), width=3)
            f2 = _font(19)
            w2 = d.textlength(lab, font=f2)
            d.text((c - w2 / 2, yy - 36), lab, font=f2,
                   fill=(110, 176, 214, int(210 * k)))
        #: the slow one: piecewise, with a dwell at every hop
        seg = min(0.999, u)
        slow_t = 0.0
        stalls = 5
        _s = seg * stalls
        _leg = int(_s)
        _fr = _s - _leg
        slow_t = (_leg + max(0.0, (_fr - 0.55) / 0.45)) / stalls
        sx = x0 + (x1 - x0) * slow_t
        d.ellipse((sx - 9, ya - 9, sx + 9, ya + 9),
                  fill=(232, 176, 96, int(235 * k)))
        #: the fast one: arrives in the first sixth and waits
        fx = x0 + (x1 - x0) * min(1.0, u * 6.0)
        d.ellipse((fx - 9, yb2 - 9, fx + 9, yb2 + 9),
                  fill=hot + (int(240 * k),))
        if u * 6.0 >= 1.0:
            f3 = _font(22)
            _t = "SETTLED"
            _w = d.textlength(_t, font=f3)
            d.text((c - _w / 2, yb2 + 20), _t, font=f3,
                   fill=(150, 230, 200, int(225 * k)))
    elif scene == "flows":
        #: IDEA: money arrived from outside and took a seat inside. Arrows
        #: come in through the bezel; the allocation ring fills as they
        #: land, which is the same gesture as a portfolio being built.
        _ap = AUR_RIM_R0 - 24
        for i in range(11):
            a = math.radians(i * 32.7 - 90.0 + now * 4.0)
            t = min(1.0, max(0.0, u * 1.5 - i * 0.055))
            r_out, r_in = _ap + 150, _ap * 0.66
            rr = r_out + (r_in - r_out) * t
            if t <= 0.0 or t >= 1.0:
                continue
            d.line((c + math.cos(a) * (rr + 44), c + math.sin(a) * (rr + 44),
                    c + math.cos(a) * rr, c + math.sin(a) * rr),
                   fill=(150, 214, 250, int(200 * k)), width=3)
        rr2 = int(_ap * 0.62)
        d.ellipse((c - rr2, c - rr2, c + rr2, c + rr2),
                  outline=(64, 120, 160, int(170 * k)), width=6)
        d.arc((c - rr2, c - rr2, c + rr2, c + rr2), -90.0,
              -90.0 + 360.0 * min(1.0, u * 1.1),
              fill=(150, 214, 250, int(240 * k)), width=8)
        f = _font(26)
        for q, lab in enumerate(("FUNDS", "CUSTODY", "TREASURIES")):
            w = d.textlength(lab, font=f)
            if u > 0.18 + q * 0.24:
                d.text((c - w / 2, c - 34 + q * 34), lab, font=f,
                       fill=(140, 204, 244, int(220 * k)))
    elif scene == "risk":
        #: IDEA: the custodians fell over; the ledger underneath did not.
        #: Three columns topple in sequence and the line beneath them
        #: never breaks — that contrast IS the sentence.
        _ap = AUR_RIM_R0 - 30
        base = c + 96
        names = (("MT GOX", "2014"), ("TERRA", "2022"), ("FTX", "2022"))
        for i, (nm, yr) in enumerate(names):
            bx = c - 132 + i * 132
            fall = max(0.0, min(1.0, (u - 0.12 - i * 0.24) / 0.20))
            h = 150 * (1.0 - fall)
            col = tuple(int(blue[q] + ((232, 108, 108)[q] - blue[q]) * fall)
                        for q in range(3))
            if h > 4:
                d.rectangle((bx - 34, base - h, bx + 34, base),
                            outline=col + (int(210 * k),), width=3)
                for s_ in range(int(h // 24)):
                    d.line((bx - 27, base - 13 - s_ * 24,
                            bx + 27, base - 13 - s_ * 24),
                           fill=col + (int(90 * k),), width=1)
            if fall > 0.05:
                #: rubble, so a fallen column is not merely an absent one
                for s_ in range(5):
                    _rx = bx - 32 + s_ * 14
                    _rh = 5 + (s_ % 3) * 4
                    d.rectangle((_rx, base - _rh, _rx + 10, base),
                                fill=(200, 104, 104, int(150 * k * fall)))
            f2 = _font(21)
            w2 = d.textlength(nm, font=f2)
            d.text((bx - w2 / 2, base + 12), nm, font=f2,
                   fill=(190, 150, 150, int(220 * k)) if fall > 0.5
                   else (140, 196, 232, int(220 * k)))
            f3 = _font(17)
            w3 = d.textlength(yr, font=f3)
            d.text((bx - w3 / 2, base + 36), yr, font=f3,
                   fill=(110, 150, 178, int(200 * k)))
        #: the ledger line, unbroken, brightening as the columns fall
        _ly = base + 66
        _lw = math.sqrt(max(0.0, _ap * _ap - (_ly - c) ** 2)) * 0.92
        d.line((c - _lw, _ly, c + _lw, _ly),
               fill=(150, 230, 200, int((120 + 110 * u) * k)), width=4)
        f4 = _font(20)
        _t = "THE LEDGER KEPT WORKING"
        _w4 = d.textlength(_t, font=f4)
        if u > 0.72:
            d.text((c - _w4 / 2, _ly + 10), _t, font=f4,
                   fill=(150, 230, 200, int(225 * k)))
    #: "ignition" draws nothing here — the detonation IS the scene, and it
    #: is already on the frame from draw_aurora_bang.


#: ── IGNITION: THE BIG BANG (2026-08-16) ──────────────────────────────────
#: Owner, giving this face its through-line: "something simple at first,
#: and then when we get into the meat of things like briefings etc, the
#: whole screen explodes in color and engages the user with rich graphics
#: and the gorgeous Aura voice talking over it."
#:
#: So the resting face is deliberately ONE small light in a void, and the
#: moment she begins to answer, that singularity detonates: a shockwave
#: leaves the core and crosses the whole glass, the mist blooms outward
#: with it, and the palette opens from her single blue into the full
#: aurora spectrum for the length of the expansion. It fires ONCE per
#: answer, on the transition into speaking — an explosion that repeats is
#: a strobe, and this is meant to be an event.
#:
#: Cheap by construction: the shockwave is arcs on the frame that is
#: already being drawn, and the palette opening is a term in the mist's
#: own tint. Nothing new is allocated per frame.
AUR_BANG_S = 2.6


#: ── SEATS: ORIENTATION WITHOUT A TRUSTWORTHY ARRAY (2026-08-16) ──────────
#: The face wants to aim its light at whoever is speaking. The array
#: cannot tell it: doa_cal.json on this unit reads `enabled: false` with a
#: measured fit RMS of 59 degrees against a 20 degree bar, because through
#: the mark5 shell the array reports THE DIRECTION OF THE NEAREST SLOT and
#: not the direction of the talker (PUCK-STANDALONE §13). A bloom drawn on
#: that number points at a wall and calls it a person — §1, in light.
#:
#: So the bearing comes from a SEAT instead: a remembered angle per
#: enrolled voice, set by the one instrument on this device that is exact —
#: a finger. Tap the rim where you sit while seat capture is armed, and
#: that angle belongs to you from then on. When a known voice speaks and
#: has a seat, the face aims there; when it does not, the light stays
#: undirected rather than guessing.
#:
#: This is deliberately a BRIDGE, and the upgrade path is already costed:
#: mark7 cuts real mic ports, puck_doa_calibrate.py refuses to write a
#: calibration worse than 20 degrees, and on the day that file says
#: `enabled: true` this same code path takes the live bearing instead —
#: nothing above it changes.
AUR_SEATS = Path.home() / "aura_face" / "seats.json"
AUR_SEAT_ARM = Path("/tmp/aura_face/seat_arm")
_AUR_SEAT: dict = {"mtime": None, "data": {}}


def _aur_seats() -> dict:
    try:
        m = AUR_SEATS.stat().st_mtime
    except (FileNotFoundError, NotADirectoryError):
        _AUR_SEAT["mtime"], _AUR_SEAT["data"] = None, {}
        return {}
    if _AUR_SEAT["mtime"] != m:
        _AUR_SEAT["mtime"] = m
        try:
            _AUR_SEAT["data"] = json.loads(AUR_SEATS.read_text()) or {}
        except Exception:                           # noqa: BLE001
            _AUR_SEAT["data"] = {}
    return _AUR_SEAT["data"]


def aurora_seat_write(who: str, deg: float) -> bool:
    """Remember where `who` sits. Loud on failure — a seat that silently
    did not save is a demo that points the wrong way with no warning."""
    try:
        d = dict(_aur_seats())
        d[who] = {"deg": round(float(deg) % 360.0, 1), "at": time.time()}
        AUR_SEATS.parent.mkdir(parents=True, exist_ok=True)
        tmp = AUR_SEATS.with_suffix(".tmp")
        tmp.write_text(json.dumps(d, indent=1))
        tmp.replace(AUR_SEATS)
        _AUR_SEAT["mtime"] = None
        print(f"aurora: SEAT saved — {who} at {d[who]['deg']:.0f} deg",
              flush=True)
        return True
    except Exception as exc:                        # noqa: BLE001
        print(f"aurora: SEAT NOT SAVED for {who!r} ({exc!r}) — the face "
              f"will keep aiming wherever it aimed before", flush=True)
        return False


def _aur_bearing(now: float, rot_deg: float):
    """(PIL arc degrees, is_known) for the light to aim at, or (None, False)
    when nobody's seat is known — in which case the caller must draw an
    UNDIRECTED bloom rather than inventing a direction (§2: 'I cannot
    tell' is its own branch)."""
    try:
        r = _room_now(now)
        who = (r or {}).get("who")
        #: guestN is the ears saying they could not tell — never a seat
        if not who or re.match(r"^(guest\d+|\?)$", str(who), re.I):
            return None, False
        s = _aur_seats().get(str(who))
        if not s:
            return None, False
        dg = (-rot_deg if INVERT else rot_deg) if rot_deg > 0.05 else 0.0
        return float(s["deg"]) + dg, True
    except Exception:                               # noqa: BLE001
        return None, False


#: Touched by puck_conduct the instant the acoustic head fires — the same
#: event that plays the click, ~100 ms after the capture closes and BEFORE
#: any transcription. Stat-cached like every other flag on this face.
AUR_FLARE = Path("/tmp/aura_face/wake_flare")
AUR_FLARE_S = 0.85


def _aur_flare(now: float) -> float:
    """0..1 decaying flare, or 0. Consumes the flag on first sight so the
    next wake is a new event rather than a re-trigger of this one."""
    fl = _AUR["flare"]
    try:
        m = AUR_FLARE.stat().st_mtime
        if m != fl["seen"]:
            fl["seen"], fl["t0"] = m, now
            AUR_FLARE.unlink(missing_ok=True)
            print("aurora: WAKE FLARE — heard", flush=True)
    except (FileNotFoundError, NotADirectoryError):
        pass
    except Exception:                               # noqa: BLE001
        pass
    if not fl["t0"]:
        return 0.0
    k = (now - fl["t0"]) / AUR_FLARE_S
    if k >= 1.0:
        fl["t0"] = 0.0
        return 0.0
    #: a hard attack and a soft tail — the shape of a struck bell, which
    #: is what an acknowledgement should feel like
    return max(0.0, min(1.0, (1.0 - k) ** 2.2))


def _aur_bang(now: float, speaking: bool) -> float:
    """0..1 across the detonation, or 0. Rising edge triggered."""
    b = _AUR["bang"]
    if speaking and not b["was"]:
        b["t0"] = now
        print("aurora: IGNITION — the answer begins", flush=True)
    b["was"] = speaking
    if not b["t0"]:
        return 0.0
    k = (now - b["t0"]) / AUR_BANG_S
    if k >= 1.0:
        b["t0"] = 0.0
        return 0.0
    return max(0.0, min(1.0, k))


def draw_aurora_bang(frame: "Image.Image", now: float, k: float) -> None:
    """The shockwave, on the full frame — it has to cross the whole glass,
    which is the one thing the core's own box cannot do."""
    try:
        if k <= 0.0:
            return
        d = ImageDraw.Draw(frame, "RGBA")
        c = SIZE // 2
        ease = 1.0 - (1.0 - k) ** 2.6           # fast out, long settle
        fade = (1.0 - k) ** 1.4
        #: the front: three rings at slightly different speeds, so the wave
        #: has thickness and a chromatic edge (violet outruns blue, as in
        #: any real dispersion — and it is what makes it read as ENERGY)
        for j, (sp, col) in enumerate((
                (1.00, (170, 130, 255)),
                (0.88, (110, 195, 255)),
                (0.74, (215, 245, 255)))):
            rr = int(60 + ease * sp * (SIZE * 0.72))
            a = int(230 * fade * (1.0 - j * 0.18))
            if a <= 3 or rr <= 4:
                continue
            w = max(2, int(26 * fade) + (6 - 2 * j))
            d.ellipse((c - rr, c - rr, c + rr, c + rr),
                      outline=col + (a,), width=w)
            d.ellipse((c - rr - w, c - rr - w, c + rr + w, c + rr + w),
                      outline=col + (a // 4,), width=w * 2)
        #: filaments: rays that flash out with the front and die first, so
        #: the first third of the event is the loudest
        if k < 0.55:
            fa = int(200 * (1.0 - k / 0.55) ** 1.6)
            rr = int(60 + ease * (SIZE * 0.70))
            for i in range(16):
                ang = math.radians(i * 22.5 + now * 6.0)
                x0 = c + math.cos(ang) * rr * 0.55
                y0 = c + math.sin(ang) * rr * 0.55
                x1 = c + math.cos(ang) * rr
                y1 = c + math.sin(ang) * rr
                d.line((x0, y0, x1, y1), fill=(190, 225, 255, fa), width=3)
    except Exception as exc:                        # noqa: BLE001
        _AUR.setdefault("said", set())
        if "bang" not in _AUR["said"]:
            _AUR["said"].add("bang")
            print(f"aurora: ignition failed {exc!r}", flush=True)


#: ── THE RINGS THAT ANSWER (2026-08-17) ──────────────────────────────────
#: Owner: "...and lighting up around the concentric rings when it hears
#: people and is thinking."
#:
#: The entity pack renders six luminous shells and then plays back as
#: fixed frames — beautiful, and completely deaf. Anything that has to
#: respond to the room has to be drawn live, here, on top. So this is the
#: same six rings, at the same radii, read from the pack's own manifest so
#: the live light lands ON the rendered shells rather than near them.
#:
#: Three states, and they are told apart by SHAPE, not brightness — the
#: rule the rim's own state graphics already follow, because a person
#: glancing at a dial from across a room reads shape first:
#:
#:   HEARING   an inward wave. Every shell lifts as the front passes,
#:             outside to in, which is the direction the sound came from.
#:             It repeats slowly for as long as she is listening.
#:   THINKING  a RUNNER on each shell, orbiting at that shell's own rate
#:             and direction from the manifest — so the live arc turns
#:             with the rendered filaments under it, and adjacent rings
#:             counter-rotate. Six things working at different speeds is
#:             what computation looks like.
#:   SPEAKING  every shell burns together, riding the voice. No travel,
#:             no runner: she is not gathering anything, she is emitting.
#:
#: Cheap on purpose: at most two arcs per ring on a frame the compositor
#: was going to hand to the panel anyway.
ENT_RING_C = ((196, 238, 255), (150, 216, 255), (108, 186, 252),
              (86, 158, 246), (72, 132, 238), (96, 112, 232))


def draw_entity_rings(frame: "Image.Image", now: float, e: float,
                      tt: float, pp: float, half: float,
                      rot_deg: float = 0.0) -> None:
    """Light the pack's own shells in response to the room. Never raises."""
    rings = _AUR.get("rings") or ()
    if not rings:
        return                      # baked mist, or a pack without geometry
    lvl = max(e, tt, pp)
    if lvl < 0.02:
        return                      # at rest the rendered shells are enough
    try:
        d = ImageDraw.Draw(frame, "RGBA")
        loop = float(_AUR.get("mist_loop") or 40.0) or 40.0
        n = len(rings)
        for j, rg in enumerate(rings):
            rr = float(rg.get("r") or 0.0)
            if rr <= 0.0:
                continue
            rad = rr * half
            wid = max(2, int(float(rg.get("w") or 0.04) * half * 0.85))
            gain = float(rg.get("gain") or 1.0)
            turns = float(rg.get("turns") or 1.0)
            col = ENT_RING_C[min(j, len(ENT_RING_C) - 1)]
            bb = (AUR_CX - rad, AUR_CY - rad, AUR_CX + rad, AUR_CY + rad)

            #: HEARING — one front, travelling inward, repeating. The 1.15
            #: on radius is what tilts it: outer shells reach their peak
            #: before inner ones, and the eye reads that as arrival.
            ph = (now * 0.46 - rr * 1.15) % 1.0
            wave = math.exp(-(((ph - 0.14) / 0.17) ** 2))
            #: SPEAKING — no travel; the whole set rides the voice.
            voice = pp * (0.55 + 0.45 * math.sin(now * 8.0))
            a = (e * (0.10 + 0.34 * wave) + tt * 0.12 + voice * 0.38) * gain
            #: ── BROKEN ARCS, NOT CIRCLES (2026-08-17, second cut) ────────
            #: The first version stroked complete ellipses and the preview
            #: sheet settled it in one look: six concentric solid rings is
            #: a progress indicator sitting on top of a nebula. Everything
            #: underneath is made of torn filaments; anything drawn over it
            #: has to be made of the same material or it reads as chrome.
            #:
            #: So each shell is four arcs with gaps, the gaps roll slowly at
            #: that shell's own rate and direction, and the segment lengths
            #: are uneven (the 0.62/1.31 pair) so the four never line up
            #: into a dashed circle either.
            base = (turns * 360.0 * ((now % loop) / loop)
                    + j * 61.0 + rot_deg) % 360.0
            if a > 0.012:
                al = int(min(1.0, a) * 132)
                for s in range(4):
                    s0 = base + s * 90.0 + (12.0 if s % 2 else 0.0)
                    s1 = s0 + 58.0 * (0.62 if s % 3 else 1.31)
                    d.arc(bb, start=s0, end=s1, fill=col + (al,), width=wid)

            #: THINKING — the runner. Its rate and SIGN come from the
            #: manifest, so it tracks the filaments rendered underneath it
            #: instead of sliding against them. One per shell, and because
            #: adjacent shells counter-rotate they cross constantly, which
            #: is the whole effect.
            if tt > 0.04:
                span = 18.0 + 26.0 * tt
                r0 = (base * 2.6) % 360.0
                d.arc(bb, start=r0, end=r0 + span,
                      fill=col + (int(150 * tt * (0.55 + 0.45 * gain)),),
                      width=max(2, wid))
                #: ── THE HEAD IS A BEAD, NOT A SHORT ARC (2026-08-17) ─
                #: First cut drew a 5-degree arc at the leading edge to
                #: mark it. PIL strokes an arc as a thick band between two
                #: radii, and five degrees of a thick band is a RECTANGLE —
                #: the full-size preview showed four white bricks sitting
                #: on the iris. A travelling light is a point, so it is
                #: drawn as one: three concentric discs, brightest in the
                #: middle, which is the cheapest soft dot PIL can make.
                _ha = math.radians(r0 + span)
                _hx = AUR_CX + rad * math.cos(_ha)
                _hy = AUR_CY + rad * math.sin(_ha)
                for _k, _al in ((1.55, 0.20), (0.95, 0.48), (0.5, 0.92)):
                    _hr = max(1.0, wid * _k)
                    d.ellipse((_hx - _hr, _hy - _hr, _hx + _hr, _hy + _hr),
                              fill=(206, 236, 255, int(170 * tt * _al)))
    except Exception as exc:                            # noqa: BLE001
        _AUR.setdefault("said", set())
        if "rings" not in _AUR["said"]:
            _AUR["said"].add("rings")
            print(f"aurora: reactive rings failed {exc!r} — pack only",
                  flush=True)


def draw_aurora_core(frame: "Image.Image", now: float,
                     rot_deg: float = 0.0, dim: float = 1.0) -> None:
    """The presence. Wrapped whole — new paint in a compositor that must
    never stop; a failed frame degrades to the void, and says so once."""
    try:
        _CPH["t"] = time.perf_counter()
        _CPH["n"] += 1
        _aur_init()
        st = _AUR["st"]
        ph = None
        try:
            ph = _pulse_phase(now)
        except Exception:
            ph = None
        talking = False
        try:
            talking = bool(_LISTEN.get("answering"))
        except Exception:
            pass
        want_e = 1.0 if (ph in ("hearing", "thinking") or talking) else 0.0
        want_t = 1.0 if ph == "thinking" else 0.0
        want_p = 1.0 if talking else 0.0
        last = st["at"] or now
        dt = max(0.0, min(0.5, now - last))
        st["at"] = now
        k = min(1.0, 2.4 * dt)
        st["e"] += (want_e - st["e"]) * k
        st["t"] += (want_t - st["t"]) * k
        st["p"] += (want_p - st["p"]) * k
        e, tt, pp = st["e"], st["t"], st["p"]
        _AUR["bang"]["k"] = _aur_bang(now, want_p > 0.5)
        #: ── THE WAKE FLARE (2026-08-16) ──────────────────────────────────
        #: Owner: "wire the core's flare so i can test it." The ears score
        #: the acoustic head BEFORE transcription and the conductor clicks
        #: within ~100 ms; this is the same event in light. Deliberately
        #: NOT driven by the pulse phase, which arrives a beat later — the
        #: whole point of §13 is that the acknowledgement is instant, and a
        #: flare that lags its own click is worse than none.
        fl = _aur_flare(now)

        #: ── THE EYE IS NEVER STATIC. SETTLED (2026-08-21) ────────────
        #: Owner, having seen both attempts on the glass: "it should never
        #: be static. it does flare with volume noise but it cannot be
        #: static it has to at least have a default static high quality
        #: pre rendered animation running or something."
        #:
        #: TWO VERSIONS WERE BUILT AND BOTH ARE GONE. The first held the
        #: entire composite at rest: pixel-identical to the frame it
        #: froze, every guard green, and the device looked dead — "the eye
        #: doesn't pulse or move at all". The second held ONLY the baked
        #: curtain and left every reactive layer live, which is smaller
        #: and more defensible, and he rejected it on sight in under a
        #: minute.
        #:
        #: The 828-frame pack IS the "default pre-rendered animation" he
        #: is describing, and it plays continuously. That is a
        #: REQUIREMENT, not an implementation detail to optimise around:
        #: this device sits in a room, and the one thing it must never
        #: look like is switched off.
        #:
        #: SO THE COST STAYS AND MUST BE PAID ELSEWHERE. Measured on his
        #: puck: compositor at 93.8% of a core (top, per-core), compose 44
        #: ms inside a 45 ms budget so the process never sleeps, die in
        #: the mid-80s against a governor target of 87 — which is why any
        #: interaction tips the fan to 255. core:listen is 13.64 ms and
        #: core:mist 5.56 ms. That is the real problem and it is still
        #: open. It will not be solved by stopping the animation, and
        #: anyone reaching for that lever should read this first.
        #:
        #: `_at_rest` survives ONLY to drive the diagnostic below. Nothing
        #: is held.
        #: does not.
        _at_rest = (e < 0.02 and tt < 0.02 and pp < 0.02
                    and fl < 0.01 and _AUR["bang"]["k"] < 0.01)
        #: ── SAY WHEN THE CURTAIN IS LIVE, AND WHY (§1, §5) ───────────
        #: An earlier version of this hold never fired once on the device
        #: and nothing anywhere said which of the five values was holding
        #: it open. Rate-limited to 20 s, printing the actual numbers,
        #: because "it is not holding" is not a fact anybody can act on.
        if not _at_rest and now - _AUR.get("restsaid", 0.0) > 20.0:
            _AUR["restsaid"] = now
            print(f"aurora: curtain LIVE — e={e:.3f} t={tt:.3f} "
                  f"p={pp:.3f} flare={fl:.3f} "
                  f"bang={_AUR['bang'].get('k', 0.0):.3f} "
                  f"(it holds only when all five are under their bars)",
                  flush=True)
        if True:
            box = _AUR["box"]
            box.paste(_AUR["black"], (0, 0))
            _cph("core:ground")
            c = AUR_BOX // 2
            #: the resting breath: slow, small, alive. Engagement widens it.
            breath = 1.0 + 0.05 * math.sin(now * 1.35) + 0.13 * e \
                + 0.07 * pp * math.sin(now * 9.0)

            #: ── LOAD BEFORE ASKING WHAT IS LOADED (2026-08-17) ───────────────
            #: `packname` is set by _aur_pack(), which this function first
            #: reaches ~40 lines below at `mist = _aur_mist()`. So on the FIRST
            #: frame after a start this read `None`, `_ent` was False, and the
            #: four centred sprites painted over a pupil that was about to
            #: exist. One frame, which is exactly long enough to be invisible
            #: in testing and to be the thing someone photographs. The preview
            #: sheet caught it because REST was the first state it drew.
            _aur_pack()
            _ent = _AUR.get("packname") == "entity"

            def put(name, scale, dx=0, dy=0):
                im = _aur_scaled(name, int(_AUR["sprites"][name].size[0] * scale))
                w = im.size[0]
                x, y = int(c + dx - w / 2), int(c + dy - w / 2)
                reg = box.crop((x, y, x + w, y + w))
                box.paste(ImageChops.screen(reg, im), (x, y))
                _cph("core:glow")

            #: ── THE ENTITY BRINGS ITS OWN LIGHT, ALL OF IT (2026-08-17) ──────
            #: halo/glow/core/hot are four centred radial sprites, and every
            #: one of them lands on the pupil. They existed because the baked
            #: mist had no centre worth looking at; this pack's centre is a
            #: VOID with a hot lip, and the void is the point. Suppressed as a
            #: set, not one at a time — the preview sheet caught `glow` first
            #: and `halo` was still filling the hole on the next pass, which is
            #: what fixing these individually looks like.
            if not _ent:
                put("halo", breath * (1.0 + 0.22 * e))
            if tt > 0.05:
                #: thought is violet, and it orbits rather than sits
                #: ── AND THE ENTITY DOES NOT GET ONE (2026-08-17) ──────────
                #: The violet orb is how the mist face said "thinking". This
                #: face says it with six runners orbiting on the shells, which
                #: is both more legible and made of the same material as
                #: everything else. Pushed outward it landed OUTSIDE the steel
                #: (visible in the full-size preview as a purple smear on the
                #: bezel); pulled inward it sits in the pupil. There is no
                #: radius that is right, because the orb is answering a
                #: question this face already answers.
                if not _ent:
                    put("vio", 0.9 + 0.2 * tt,
                        math.sin(now * 2.1) * 30 * tt,
                        math.cos(now * 1.7) * 24 * tt)
            #: ── THE MIST, BETWEEN HALO AND CORE ──────────────────────────────
            #: Its loop runs on VIRTUAL time, so engagement can quicken the
            #: billows without the frames ever stepping: 1.0x at rest, ~2.1x
            #: while she is thinking. Integrated, never indexed by wall-clock
            #: times a rate — the jump that would cause is the exact bug the
            #: centre-pack phase note records.
            mist = _aur_mist()
            mp = _AUR["mistph"]
            _mdt = max(0.0, min(0.5, now - (mp["at"] or now)))
            mp["at"] = now
            mp["t"] += _mdt * (1.0 + 0.55 * e + 0.55 * tt)
            #: CROSS-FADED: the fractional part of the phase blends this baked
            #: frame into the next, so motion is continuous rather than stepped
            #: (see the note at AUR_MIST_N — this is the fix for "poor FPS").
            #: the pack brings its own frame count and pacing; the baked mist
            #: keeps the constants it was built with. Both cross-fade the same
            #: way, so playback code does not care which is loaded.
            _mn = len(mist)
            _ml = _AUR.get("mist_loop", AUR_MIST_LOOP_S)
            _mf = (mp["t"] / _ml) * _mn
            mi = int(_mf) % _mn
            _fr = _mf - math.floor(_mf)
            #: ── REVERTED (2026-08-19 02:40) ──────────────────────────────
            #: This was a resize-then-blend reorder, so the resizes could be
            #: cached. It computed the target width HERE, from `msc` — which is
            #: assigned eighty lines further down. UnboundLocalError on the
            #: first frame, every frame.
            #:
            #: Owner: "the entirety of the central eye on the main aura os puck
            #: is now gone." And I had ALREADY SEEN IT and explained it away:
            #: c:core fell from 19.5 ms to 0.3 ms in the pace report and I
            #: wrote that off as a screen-state change, because the log line
            #: right above it said sterling owned the glass. A 65x drop in the
            #: most expensive phase on the device is not a detail to rationalise
            #: — it is either a triumph or a corpse, and I did not check which.
            #:
            #: draw_aurora_core is wrapped in "never raises", which is correct
            #: — a compositor must not stop — and it turned a fatal typo into a
            #: silently blank centrepiece. The guard did its job; the reporting
            #: is what failed, and `aurora: core draw failed ...` was sitting in
            #: the log the whole time saying exactly this.
            #:
            #: Not re-landed, because it never earned its place: measured on the
            #: puck it moved c:core by nothing (19.7/25.7 before, 19.1-19.7
            #: after). scripts/test_mist_blend.py stands — 3.1x on the operation
            #: is true and irrelevant to the frame. If someone tries this again,
            #: compute the width where `msc` lives, and check the pace report
            #: for a phase that got SUSPICIOUSLY cheap.
            _bk = _AUR["bang"].get("k", 0.0)
            #: ── THE WIDTH IS COMPUTED HERE NOW, ONCE ─────────────────────
            #: `msc` and `_mw` used to be assigned eighty lines below, and the
            #: first attempt at the reorder read `msc` from up here — which is
            #: the UnboundLocalError the note above describes. HOISTED rather
            #: than duplicated: two expressions for one width is how the trace
            #: and the rect came to disagree elsewhere in this file, and the
            #: hoist is free because msc depends only on e, pp and _bk, all of
            #: which are already in hand.
            msc = (1.0 + 0.10 * e + 0.06 * pp
                   + 0.55 * _bk * (1.0 - _bk) * 3.0)   # the bloom, with the wave
            _mw = max(8, int(2.0 * (AUR_RIM_R0 + 8.0) * msc
                             * _show_scale() / 8) * 8)
            #: ── RESIZE THEN BLEND (2026-08-20) ───────────────────────────
            #: `core:mist` is 47.7% of draw_aurora_core warm — about 9.4 ms of
            #: the puck's 19.7, which is a QUARTER OF THE WHOLE FRAME and more
            #: than the entire menu that has been optimised twice.
            #:
            #: The cost is here: the blend runs at the pack's native side and
            #: the resize below then shrinks the result, so the expensive
            #: interpolation runs over the FULL frame every time AND its output
            #: is unique every time (the blend fraction moves continuously),
            #: which is why nothing could be cached.
            #:
            #: Reversed, both operands key on (frame index, width), the width
            #: is already quantised to 8 px, and what remains per frame is one
            #: blend at the SMALLER size. scripts/test_mist_blend.py: worst
            #: single pixel 2/255, 3.1x faster on the operation.
            #:
            #: ── AND IT IS SLOWER ON THE DEVICE. REVERTED (2026-08-20) ────
            #: Measured properly this time, same puck, same screen, one build
            #: apart:
            #:
            #:     before   core:mist 6.20 / 6.23 / 6.65    c:core 20.5
            #:     after    core:mist 9.45 / 8.32 / 7.91    c:core 23.1
            #:
            #: THE CACHE NEVER HITS HERE. `_MIST_RS` was capped at 96 entries
            #: and the installed pack is 828 frames, walked in order once every
            #: 55 s — so by the time a frame comes round again its resize has
            #: long been evicted. With a zero hit rate the reordering is
            #: strictly more work: TWO resizes per frame plus a blend, against
            #: one blend and one resize.
            #:
            #: scripts/test_mist_blend.py said 3.6x FASTER and it was not
            #: lying — it runs against eight images with an uncapped dict, so
            #: it measured a 100% hit rate. Eight versus eight hundred and
            #: twenty-eight is the whole result. That is the SECOND time in one
            #: session this change has been validated on the baked-mist
            #: fallback and shipped to devices running the RTX pack, and the
            #: first time the local profile even reported a phase (`core:glow`)
            #: that pucks never execute.
            #:
            #: THE RULE: a cache is a claim about a WORKING SET, and the
            #: working set lives on the target. Raising the cap is not the fix
            #: either — 828 frames at the aperture width is tens of megabytes
            #: on a device with 15.6 GB shared between everything, to save an
            #: operation measured at 0.65 ms.
            #: ── THE 215 LINES NOBODY WAS TIMING (2026-08-20) ─────────────
            #: `c:core` is 17-33 ms of a 51 ms compose on the device — the
            #: largest single thing on the glass — and its own breakdown only
            #: ever summed to about 11: core:mist 6.0-7.1, core:out 3.8-4.2,
            #: core:ground 0.2. The rest lived between core:ground and
            #: core:mist, where the only marker is core:glow and pucks never
            #: execute that branch (it belongs to the baked-mist fallback; the
            #: note above records that being profiled by mistake, twice).
            #:
            #: So the gap is split three ways rather than guessed at. The queue
            #: entry for this work says it in its own words: "measure inside
            #: centre before touching it, because 'the biggest number' is where
            #: the last three optimisation attempts on this project went wrong
            #: by assuming rather than profiling."
            _cph("core:sprites")
            #: ── THE EYE IS NEVER STATIC. SETTLED (2026-08-21) ─────────
            #: Owner, having seen both attempts on the glass: "it should
            #: never be static. it does flare with volume noise but it
            #: cannot be static it has to at least have a default static
            #: high quality pre rendered animation running or something."
            #:
            #: Two versions were built and both are now removed. The first
            #: held the whole composite at rest — pixel-perfect, every
            #: guard green, and the device looked dead ("the eye doesn't
            #: pulse or move at all"). The second held only this curtain
            #: and left everything reactive live, which is a smaller and
            #: more defensible thing, and he rejected that too, on sight,
            #: in under a minute.
            #:
            #: The 828-frame pack IS the "default pre-rendered animation"
            #: he is describing, and it plays continuously. That is the
            #: requirement, not an implementation detail to be optimised
            #: around: this device sits in a room and the one thing it
            #: must never look like is switched off.
            #:
            #: SO THE COST STAYS AND HAS TO BE PAID ELSEWHERE. `core:mist`
            #: is 5.56 ms and `core:listen` 13.64 ms of a 45 ms budget,
            #: the compositor holds a full core, and that is the real
            #: problem — but it will not be solved by stopping the
            #: animation, and anyone reaching for that lever should read
            #: this and the two failed attempts in the log first.
            mim = mist[mi] if _fr < 0.02 else Image.blend(
                mist[mi], mist[(mi + 1) % _mn], _fr)
            _cph("core:blend")
            #: ── THE BREATH LEFT THE SIZE (2026-08-17) ────────────────────
            #: Owner, three times: "the animation still seems halting."
            #:
            #: Measured rather than reasoned about, finally. The 828-frame pack
            #: steps 4.4 (mean abs, 0-255) between its own consecutive frames.
            #: The COMPOSITE, drawn through this function at the puck's real
            #: 17.8 fps, steps 10.8 — two and a half times the motion the
            #: animation actually contains. The extra is this line.
            #:
            #: `0.05 * sin(now * 0.9)` is a resting breath applied to the paste
            #: WIDTH. The width is quantised to 8 px, the source is 320 px and
            #: lands at ~520, so every time the breath crosses a step boundary
            #: the entire iris is re-resampled at a new scale and every
            #: hair-thin filament in it lands on different pixels. That is not
            #: a breath, it is a texture jumping several times a second — and
            #: on an image made of filaments and motes it reads as exactly what
            #: he kept reporting.
            #:
            #: So the resting breath is a BRIGHTNESS now (see `breath` below,
            #: which already lifts the halo and the core). Size still moves for
            #: the things that should be dramatic — engagement, her own voice,
            #: and the ignition bloom — because those are events, not idle.
            #: `msc` and `_mw` were computed HERE and are now hoisted to the
            #: blend above, because the blend needs the width. One expression,
            #: one place — the alternative is two readers of a moving value,
            #: which is the drift that put a seam between the ribbon's trace
            #: and its damage rect and cost a session to find (§15).
            #: the pack renders at its own side (520 by default) and the baked
            #: mist at AUR_MIST_PX — take the size from the FRAME IN HAND, not
            #: from the constant, or a pack of a different size lands cropped
            #: ── AND THE EYE OPENS WITH THE SHOW (2026-08-17) ─────────────
            #: The same factor the scenes use, so the iris and the diagram
            #: drawn over it are always the same size — this is the "expand in
            #: a dramatic way to the edge of the circular border".
            #: ── THE PACK'S SIZE ON THE GLASS IS NOT ITS SIZE ON DISK ─────
            #: (2026-08-17) This paster used the frame's own width, so the eye
            #: was as big as whatever the renderer happened to output. That
            #: broke the moment the pack traded resolution for FRAMES — 828 at
            #: 320 px instead of 216 at 520, to reach the panel's 18 fps — and
            #: the iris shrank to two thirds of its aperture with a thin ring
            #: around a lot of nothing.
            #:
            #: The eye's size is a property of the FACE: it fills the aperture
            #: the steel opens, whatever resolution the pack was rendered at.
            #: That is what makes "more frames, smaller side" a free trade
            #: rather than a visible one.
            #: a SAFETY NET, not a computation. `_mw` came from the hoisted
            #: expression above and the blend already produced this width from
            #: the cache, so on every ordinary frame this compare is false and
            #: costs nothing. It stays because a resize that silently does not
            #: happen is an eye at the wrong size, and one compare is a cheaper
            #: insurance than trusting that nothing between here and there ever
            #: touches the frame in hand.
            if mim.size[0] != _mw:
                mim = mim.resize((_mw, _mw), Image.BILINEAR)
            _mx = int(c - _mw / 2)
            _reg = box.crop((_mx, _mx, _mx + _mw, _mx + _mw))
            box.paste(ImageChops.screen(_reg, mim), (_mx, _mx))
            _cph("core:mist")
            #: WITH THE RTX CURTAIN LOADED THE CORE STEPS BACK. The baked mist
            #: needed a bright centre to have any structure at all; the
            #: rendered curtain HAS structure, and a hot white dot in front of
            #: it just competes with the thing worth looking at. She is still
            #: lit — the glow and the hot core remain, at about half — so the
            #: face still has a source and the curtain still has somewhere to
            #: come from.
            #: ── AND WITH THE ENTITY LOADED IT STEPS OUT OF THE WAY ENTIRELY ──
            #: (2026-08-17) The aurora pack had light at its middle, so a core
            #: sprite in front of it was merely redundant. The entity pack's
            #: middle is a VOID — a black pupil with a hot lip around it, which
            #: is the whole reason the thing reads as an iris and not a
            #: nebula — and the core/hot sprites paint a white dot exactly
            #: there. Rendering a pupil and then filling it in is not a
            #: compromise, it is undoing the render.
            #:
            #: The glow stays, at a third: it is wide, it sits UNDER the shells
            #: rather than in the hole, and without it the iris has no
            #: atmosphere to sit in.
            _cg = 0.0 if _ent else (0.55 if _AUR.get("pack") else 1.0)
            #: AND THE GLOW GOES TOO, for the entity. It is a centred radial
            #: sprite: at any weight that helps the surround it also puts a
            #: bright ball exactly in the pupil, which the preview sheet caught
            #: immediately. The pack carries its own two-radius bloom, so the
            #: iris already sits in a field and does not need this one.
            if not _ent:
                put("glow", breath * 0.86 * (0.72 if _AUR.get("pack") else 1.0))
            if _cg > 0.01:
                put("core", breath * (1.0 + 0.30 * pp) * _cg)
                put("hot", breath * (1.0 + 0.45 * pp) * _cg)

            #: ── LIGHT FIRST, THEN METAL, THEN THE STATE ON THE METAL ─────────
            #: The order is the order the eye builds the object: the glow is
            #: SCREENED (it is light, it adds), the rim is PASTED WITH ALPHA
            #: (it is steel, it occludes — stars must not shine through it),
            #: and every state graphic is drawn last, ON the band, which is the
            #: visual space the thicker rim exists to give them.
        bk0 = _AUR["bang"].get("k", 0.0)
        #: the flare lifts the WHOLE body — it is the one moment the core
        #: is allowed to be brighter than an answer
        #: `dim` is the SHOW's doing: while a briefing is on the glass the
        #: eye recedes to a glow behind the scene (owner: "fade the central
        #: eye as it gets in the way of the presentation"). It never goes
        #: to zero — she is still the thing doing the talking, and a scene
        #: floating on pure black would belong to some other device.
        bright = (0.82 + 0.18 * max(e, pp) + 0.55 * bk0 * (1.0 - bk0) * 2.4
                  + 0.42 * fl) * dim
        #: The held frame IS a finished box2 — already brightness-scaled
        #: at the moment it was kept. Re-scaling it would darken it again
        #: every frame it survives, so the hold is used as-is and `bright`
        #: is only consulted on a live build. (`bright` cannot have moved
        #: anyway: e, pp, bk0 and fl are all part of the at-rest test, and
        #: `dim` is in the key.)
        box2 = (box if bright > 0.995 else
                box.point(lambda p, b=bright: int(p * b)))
        x0, y0 = AUR_CX - AUR_BOX // 2, AUR_CY - AUR_BOX // 2
        reg = frame.crop((x0, y0, x0 + AUR_BOX, y0 + AUR_BOX))
        frame.paste(ImageChops.screen(reg, box2), (x0, y0))
        _cph("core:out")
        #: THE LIVE RINGS GO ON THE RENDERED ONES, AND UNDER THE STEEL.
        #: `_mw / 2` and not a constant: the pack is pasted at whatever
        #: size the breath scaled it to this frame, so the radii have to
        #: come from the frame IN HAND — the same reason the paste itself
        #: takes its size from `mim` (see the note there).
        #: ── THROB THE COLOUR, NOT THE SIZE (2026-08-18) ──────────────────
        #: Owner: "that circle surrounding auravision used to be thinner it
        #: looks like it throbs now. just throb the colour not the size, the
        #: size at default low volume is much more elegant looking." And
        #: again, to be certain I had it: "the base circle looks really
        #: elegant just keep that bezel just throb the color."
        #:
        #: `_mw` is the eye AFTER the breath multiplier, so passing it here
        #: made every shell's radius AND its stroke width ride the breath.
        #: The shells then swelled through the steel aperture, and from the
        #: chair that reads as the bezel itself thickening and thinning —
        #: which is what he is describing, even though the rim sprite never
        #: moves a pixel.
        #:
        #: So the geometry is pinned to the RESTING aperture. The response
        #: was never carried by size anyway: `a` inside that function is
        #: built from e/tt/pp and drives alpha, and it is untouched. Same
        #: reaction, at a size that holds still.
        _rest_half = (AUR_RIM_R0 + 8.0) * _show_scale()
        draw_entity_rings(frame, now, e, tt, pp, _rest_half, rot_deg)
        #: core:shells measured 12.36 ms on the device — 53% of the eye and
        #: the largest phase on the glass. It covers three different things
        #: (the live rings, the steel rim's alpha paste, the flare), so it
        #: is split before anything is optimised. The whole reason this
        #: phase was worth finding is that a big number with several
        #: authors is the one people guess about.
        _cph("core:rings")
        #: THE BORDER TRAVELS WITH IT. The steel is the eye's edge, so an
        #: iris that opens past a stationary ring would be a picture
        #: escaping its own frame. Resizing a 640 px RGBA every frame is
        #: 6-8 ms, which this compositor does not have, so the scaled rim
        #: is cached at 1% steps — finer than the opening moves between two
        #: frames, and 100 entries at worst.
        _rsc = _show_scale()
        if _rsc > 1.001:
            _rk = int(_rsc * 100)
            _rc = _AUR.setdefault("rimscale", {})
            if _rk not in _rc:
                _rc.clear() if len(_rc) > 24 else None
                _rw = int(AUR_BOX * _rk / 100.0)
                _rc[_rk] = _aur_rim().resize((_rw, _rw), Image.BILINEAR)
            rim = _rc[_rk]
            _rx = AUR_CX - rim.size[0] // 2
            frame.paste(rim, (_rx, _rx), rim)
        else:
            rim = _aur_rim()
            frame.paste(rim, (x0, y0), rim)
        _cph("core:rim")
        if fl > 0.01:
            #: THE FLARE ON THE GLASS: the band lights all the way round —
            #: she heard you, and she has not yet decided anything, so the
            #: light carries no direction. Then a fast ripple leaves the
            #: rim outward, which is what makes it read as an EVENT rather
            #: than a brightness change.
            _d0 = ImageDraw.Draw(frame, "RGBA")
            _rc = int((AUR_RIM_R0 + AUR_RIM_R1) / 2.0)
            _rb = (AUR_CX - _rc, AUR_CY - _rc, AUR_CX + _rc, AUR_CY + _rc)
            _d0.ellipse(_rb, outline=(190, 232, 255, int(210 * fl)),
                        width=int(AUR_RIM_R1 - AUR_RIM_R0) - 8)
            _rr = int(_rc + (1.0 - fl) * 150)
            _d0.ellipse((AUR_CX - _rr, AUR_CY - _rr,
                         AUR_CX + _rr, AUR_CY + _rr),
                        outline=(150, 215, 255, int(170 * fl)),
                        width=max(2, int(16 * fl)))

        d = ImageDraw.Draw(frame, "RGBA")
        c = AUR_CX                       # state graphics are frame-space now
        #: the state lives on the band's centre line
        r1 = int((AUR_RIM_R0 + AUR_RIM_R1) / 2.0 * (1.0 + 0.012 * e))
        bb = (c - r1, c - r1, c + r1, c + r1)
        #: WHILE SHE SPEAKS THE WHOLE RING BURNS, riding her own voice —
        #: listening points (one arc, at you), speaking declares (the full
        #: circle, at the room). Two states that must never be confused at
        #: a glance, so they differ in SHAPE and not only in brightness.
        _rp = pp * (0.55 + 0.45 * math.sin(now * 8.0))
        _rk = int(70 + 150 * _rp), int(132 + 110 * _rp), int(180 + 75 * _rp)
        #: ── THE RING, IN FOUR PARTS (2026-08-16, "more nuance") ──────────
        #: A single stroked circle is a shape; these four make it an OBJECT.
        #: (a) a soft halo just outside it, so it sits IN the glow rather
        #: than on top; (b) the ring proper; (c) a fine inner hairline at
        #: -13px, which is what makes it read as machined; (d) a SHEEN — a
        #: short bright segment that orbits once every ~34 s. The sheen is
        #: the "always alive" the resting face needed: too slow to watch,
        #: impossible to mistake for a dead panel.
        #: ── THE RING IS AN OBJECT WITH A LIT SIDE (2026-08-16) ───────────
        #: Owner: "make everything as perceptually 3d as possible, raised,
        #: recessed, use all the tricks in our magic book." The house key
        #: light is upper-left, so: a CONTACT SHADOW under the lower-right
        #: (something raised casts one), a TOP FACET blazing on the
        #: upper-left arc, and a dimmer under-edge opposite it. Same
        #: grammar draw_numerals uses for applied metal — three tones make
        #: a bevel, one tone makes a drawing.
        #: PIL arcs: 0 deg is 3 o'clock, y down. Upper-left is 180..270.
        #: ── THE BODY IS A PICTURE, NOT FIVE STROKES (2026-08-20) ──────
        #: Owner: "people are complaining about my test videos of the puck
        #: being laggy." Measured down to this, one marker at a time:
        #:
        #:     frame 80 ms against a 62 ms budget, 100% of frames over
        #:     c:core 23.2 ms — the largest thing on the glass
        #:     core:shells 12.4 -> split -> core:rings 0.02, core:rim 1.21,
        #:                                  and 5.69 ms HERE
        #:
        #: Five strokes, three of them FULL CIRCLES at r=262 with widths 9,
        #: 7 and 3, is about 44,000 painted pixels — and at rest they are
        #: pixel-identical frame after frame, because `_rp` is zero when she
        #: is not speaking and `e` moves in steps this quantises away.
        #: Sixteen times a second, to repaint the same picture.
        #:
        #: ── AND THE CACHE WAS BUILT, MEASURED, AND NOT SHIPPED ────────
        #: `_aur_state_ring` above does exactly that and is DEAD CODE on
        #: purpose. This file already records a layer cache for the MENU
        #: that produced "not a rounding difference; a different picture",
        #: because PIL's paste blends non-premultiplied and these five
        #: strokes OVERLAP at alpha 150/210/235 — the exact case.
        #:
        #: Predicted, then measured rather than argued about.
        #: scripts/test_state_ring_tile.py, tile against live strokes on
        #: three grounds including the real face:
        #:
        #:     black       rest 21/255  half 31  speaking 41  (1699 px)
        #:     mid grey    rest  6/255  half 14  speaking 24
        #:     real face   rest 16/255  half 27  speaking 37
        #:
        #: 1699 pixels is small and 41/255 is not, and it is worst exactly
        #: where the ring is brightest — while she speaks. So the five
        #: strokes stay live and the 5.69 ms stays spent. The function and
        #: the test both stay too: the next person to find this number
        #: should find the attempt beside it, or they will make it again.
        #:
        #: The trick that WOULD work is the one _aur_arris_tile uses —
        #: accumulate COVERAGE on an L mask so overlaps screen instead of
        #: blending twice — and it does not apply here, because that
        #: depends on every stroke sharing one colour and these are five
        #: different ones. That is the thing to solve, not the caching.
        d.ellipse((bb[0] + 3, bb[1] + 3, bb[2] + 3, bb[3] + 3),
                  outline=(0, 0, 0, 150), width=9)          # cast shadow
        d.ellipse((bb[0] - 3, bb[1] - 3, bb[2] + 3, bb[3] + 3),
                  outline=(int(20 + 26 * _rp), int(40 + 34 * _rp),
                           int(58 + 30 * _rp)), width=7)    # ambient bed
        d.ellipse(bb, outline=_rk, width=3 + int(3 * pp))   # the body
        d.arc(bb, 176, 274, fill=(int(150 + 80 * _rp), int(205 + 45 * _rp),
                                  245, 235), width=2)       # top facet
        d.arc(bb, 356, 454, fill=(14, 30, 46, 210), width=2)  # under-edge
        #: ── AND THE MIST SITS IN A BORE ──────────────────────────────────
        #: A well is legible only by its FAR wall: light entering from the
        #: upper-left lands on the lower-right of the interior. So the inner
        #: lip is lit at the bottom-right and nearly dark at the top-left —
        #: the same "interior lit backwards" _pocket_relief is built on.
        rh = r1 - 13
        bh = (c - rh, c - rh, c + rh, c + rh)
        d.arc(bh, 340, 470, fill=(int(58 + 46 * e), int(96 + 54 * e),
                                  int(126 + 50 * e), 190), width=3)
        d.arc(bh, 160, 290, fill=(10, 22, 34, 170), width=2)
        d.arc((bh[0] + 5, bh[1] + 5, bh[2] - 5, bh[3] - 5),
              350, 450, fill=(36, 68, 96, 120), width=6)
        #: THE SHEEN, WITH A WAKE (2026-08-16, "make the circle more
        #: dynamic"). A bright segment orbiting the ring, now trailing a
        #: fading wake behind it — the same comet grammar the thinking
        #: state uses, at a tenth the speed, so the resting ring reads as
        #: TURNING rather than as lit in one spot.
        #: ── THE SHEEN IS LIGHT, NOT AN OBJECT (2026-08-16) ───────────────
        #: Owner, testing: "the thing floating around the ring is not
        #: dynamic, it's just moving." Exactly right, and the fault was
        #: physics: a constant-brightness blob orbiting a lit surface is a
        #: sprite on a track. Real specular on a turned ring BLAZES where
        #: the surface faces the key and dies where it faces away — so the
        #: sheen's intensity is now a function of WHERE IT IS, not just a
        #: position. It ignites through the upper-left, gutters out at the
        #: lower-right, and a second, weaker lobe rides opposite it the way
        #: brushed metal always shows two. Same motion, and it stops
        #: looking like a bead on a wire.
        sh = (now * 10.6) % 360.0
        for _lobe, (_off, _gain) in enumerate(((0.0, 1.0), (180.0, 0.42))):
            _sa = (sh + _off) % 360.0
            _al = max(0.0, math.cos(math.radians(_sa - 225.0))) ** 1.5
            _k = (0.10 + 0.90 * _al) * _gain
            if _k < 0.04:
                continue
            for _i in range(6):
                _a = int(120 * _k * (1.0 - _i / 6.0) ** 1.7)
                if _a <= 4:
                    break
                _t = _sa - _i * 7.0
                d.arc(bb, _t - 7.4, _t, fill=(150, 205, 245, _a), width=18)
            d.arc(bb, _sa - 3.5, _sa + 3.5,
                  fill=(225, 245, 255, int(190 * _k)), width=20)
            d.arc(bb, _sa - 3.5, _sa + 3.5,
                  fill=(255, 255, 255, int(150 * _k)), width=5)
        #: A COUNTER-TURNING GRADUATION, very fine and very dim: 72 marks
        #: on an inner radius, rotating the other way. It is below the
        #: threshold of "a thing you look at" and above the threshold of
        #: "the object is alive" — which is the whole brief for this face.
        #: 36, not 72, and no per-mark shimmer: MEASURED at 72 with a sine
        #: per mark the frame cost 44 ms against a 62 ms budget, and the
        #: difference was invisible at this radius. Detail that cannot be
        #: seen is just heat (§6, and the whole of today's thermal work).
        rg = r1 - 26
        bg = (c - rg, c - rg, c + rg, c + rg)
        _sp2 = (-now * 3.1) % 15.0
        for _k in range(24):
            _a0 = _sp2 + _k * 15.0
            d.arc(bg, _a0, _a0 + 3.0, fill=(70, 130, 180, 56), width=3)
        #: ── THE BLOOM, IN THE PATEK RING'S LANGUAGE (2026-08-16) ─────────
        #: Owner: "the animation around the sound detection is cheesy and
        #: cartoonish... borrow from the outer rings that we rendered with
        #: the patek." The first cut was ONE flat arc, and a flat arc is a
        #: cartoon of a glow. draw_listening_ring's grammar instead, which
        #: is the thing on this device that already looks expensive:
        #: SEGMENTS with a falloff envelope, a wide soft pen under a narrow
        #: crisp one, an inner echo for band thickness, and a core drawn
        #: twice so the middle saturates toward white. Same idea here, on
        #: the aurora's own radius and in her blue.
        seat_ang, seat_known = _aur_bearing(now, rot_deg)
        if e > 0.02 and not seat_known:
            #: ── NOBODY'S SEAT IS KNOWN: LIGHT WITHOUT A DIRECTION ────────
            #: The array cannot be trusted here (see AUR_SEATS), so rather
            #: than aim at a number that means nothing, the band lifts
            #: EVENLY — she is plainly listening, and plainly not claiming
            #: to know where you are. A stranger, or an unseated regular,
            #: gets exactly this.
            _lift = int(150 * e * (0.90 + 0.10 * math.sin(now * math.tau
                                                          * 0.55)))
            d.arc(halo0 := (bb[0] - 9, bb[1] - 9, bb[2] + 9, bb[3] + 9),
                  0, 360, fill=(60, 150, 235, _lift // 3), width=30)
            d.ellipse(bb, outline=(96, 186, 244, _lift), width=26)
        if e > 0.02 and seat_known:
            ang = seat_ang
            breath = 0.90 + 0.10 * math.sin(now * math.tau * 0.55)
            peak = 246.0 * e * breath
            #: 8 segments a side at 5 deg, not 11 at 3.6: same 40-degree
            #: bloom, two thirds the arc calls. The falloff does the work,
            #: not the segment count — measured, the envelope is identical
            #: to the eye and the frame is 8 ms cheaper.
            #: OVERLAPPED, or the band shows the seams. At 24-30 px wide
            #: each segment is a visible tile, and a falloff drawn in
            #: tiles reads as a bar chart — the owner would have called it
            #: cartoonish, correctly, for the second time. Narrow steps
            #: with each arc drawn 2x its own width, at a third of the
            #: alpha, so the envelope is the SUM and not the individual.
            segs, step = 14, 2.9
            halo = (bb[0] - 9, bb[1] - 9, bb[2] + 9, bb[3] + 9)
            peak *= 0.52
            for i in range(-segs, segs + 1):
                fall = (1.0 - abs(i) / (segs + 1.0)) ** 1.25
                a = int(peak * fall)
                if a <= 2:
                    continue
                cc = ang + i * step
                a0, a1 = cc - step, cc + step
                #: THE BLOOM LIGHTS THE BAND, it does not sit on it. With a
                #: 40 px rim a 5 px arc vanished into the steel; these fill
                #: the land and spill a halo either side, which is exactly
                #: what draw_listening_ring does to the patek's bezel.
                d.arc(halo, a0, a1, fill=(60, 150, 235, a // 3), width=30)
                d.arc(bb, a0, a1, fill=(96, 186, 244, a), width=26)
                #: the white core is the SAME envelope squared, not a
                #: separate hot/cold decision — a binary one drew a solid
                #: block with two hard ends, which is the tiling artefact
                #: one level up. Squaring concentrates the white in the
                #: middle and lets it die out on its own.
                ah = int(a * fall * fall * 1.35)
                if ah > 3:
                    d.arc(bb, a0, a1, fill=(228, 248, 255, ah), width=9)
        #: ── SPLIT, BECAUSE THIS PHASE SWINGS 3x (2026-08-21) ─────────
        #: Owner: "the rendering feels slow." Three consecutive windows off
        #: his puck, same build, same screen:
        #:
        #:     core:shells  5.74   c:core 19.3   21% of frames late
        #:     core:shells  7.21   c:core 19.3
        #:     core:shells 18.29   c:core 33.0   89% of frames late
        #:
        #: Everything else held still. `core:mist` — the phase two previous
        #: sessions tried and failed to optimise — sat at 5.5-6.6 through
        #: all three. This one tripled and took the frame with it.
        #:
        #: And it can only spike when she is LISTENING or THINKING, because
        #: that is the only time these strokes are drawn at all. So the
        #: glass gets slowest exactly while somebody is talking to it,
        #: which is the one moment its smoothness is being judged.
        #:
        #: Two very different loops share the marker: the seated listening
        #: envelope (14 segments x 3 arcs) and the thinking comet (20
        #: iterations x 2 arcs on a bounding box 30 px LARGER than the
        #: ring, plus a head). Guessing which costs 18 ms is exactly the
        #: mistake recorded at _cph and again at core:shells itself —
        #: "three sessions have optimised the second-largest thing on this
        #: face while the largest sat unmeasured". Close the frame first,
        #: then optimise the half that is actually expensive.
        _cph("core:listen")
        #: ── THE THINKING COMET IS GONE (2026-08-21) ──────────────────
        #: Owner: "forget the comet already just remove it."
        #:
        #: 41 antialiased arc sweeps on a bounding box 30 px larger than
        #: the ring, costing 2.72 ms/frame measured
        #: (scripts/bench_core_shells.py) — about 6% of a 45 ms budget, on
        #: a face that was already missing 21% of its frames idle and 89%
        #: while she was mid-answer.
        #:
        #: THOUGHT IS STILL VISIBLE and this is not a blank screen: the
        #: shells counter-rotate above `tt > 0.04` and six violet runners
        #: orbit above `tt > 0.05`, both drawn out of material this face
        #: already pays for. The comet was a third statement of the same
        #: thing on its own radius.
        #:
        #: `core:think` went with it. A marker whose phase no longer
        #: exists prints a zero forever and reads as "measured, and free",
        #: which is the one thing a profiler must never say about work
        #: that is not being done. `core:listen` stays and is the bigger
        #: half anyway — 5.30 ms against the comet's 2.72.
        #: ── AND THE HALF NOBODY WAS TIMING (2026-08-20) ──────────────
        #: `core:out` was the LAST marker and it is not the last work.
        #: Measured on the device, steady state, ring settled:
        #:
        #:     c:core                                20.5 ms
        #:     core:mist 5.70 + core:out 4.13
        #:       + core:blend 0.47 + core:ground 0.23
        #:       + core:sprites 0.03               = 10.56 ms
        #:
        #: Ten milliseconds a frame — half the largest thing on the glass —
        #: lived after the last _cph call, in the live shells and runners
        #: drawn above. The note at _CPH already says "three sessions have
        #: optimised the second-largest thing on this face while the
        #: largest sat unmeasured"; this is the same mistake one level
        #: down, made by the instrumentation that was added to fix it.
        #:
        #: A profiler whose phases do not sum to its own total is not a
        #: profiler, it is a set of numbers. Close the frame.
        _cph("core:shells")

    except Exception as exc:                    # noqa: BLE001
        _AUR.setdefault("said", set())
        if repr(exc) not in _AUR["said"]:
            _AUR["said"].add(repr(exc))
            print(f"aurora: core draw failed {exc!r} — void held",
                  flush=True)
#: The instrument red — the accent, named again here so the four sites read
#: what they mean rather than "the accent, which happens to be red".
INSTR_RED = _THEME["accent"]
#: ...and the white a car gauge's counterweight is painted. The brand metal's
#: lit flank on ferrari (240,244,250); on a row without the flag nothing
#: reads it.
INSTR_WHITE = _THEME["brand_lit"]

#: ── DIAL_K: THE ROYAL OAK COMPRESSION, 2026-08-06 night ──────────────────
#:
#: Owner, at the glass: "the octagon and the screws are there but it does not
#: READ as a Royal Oak yet, and the reason is proportion ... make the bezel
#: MUCH thicker ... then COMPRESS everything inside it toward the centre to
#: make the room: pull the wedge ring inward, shrink the dial, tighten the
#: ledger block and the reserve gauge together. Losing dial area is the
#: correct trade."
#:
#: home.html's bezel band went from 11.5 viewBox units to 65, so its inner
#: edge came in from 488.5 to 396.94, and every dial element on that page is
#: now inside one <g id="dial"> carrying scale(0.80) about the centre.
#:
#: THIS FILE IS THE OTHER HALF OF THAT MOVE, and it is the same standing
#: contract SLEEP_XY/POWER_XY have always had with that page, with more on it:
#: the wordmark, the live clock, the $LEDGER numeral, the RESERVE range plate,
#: the two live wedges, the enrolment ring, the moonphase and EVERY HIT-TEST
#: on this face are drawn here in display px over that bake. A dial that
#: shrinks in one file and not the other is a face where a wedge lights where
#: nobody pressed — the owner's own last line on the brief, and the silent
#: half of §1: the paint moves, the target does not, and nothing says so.
#:
#: The constants below are written as their MEASURED originals times this
#: factor rather than as fresh numbers, so the measurement each one came from
#: — and the comment that argues it — survives the pass. Two rules, and only
#: two: a RADIUS or a SIZE scales by DIAL_K; a display-px COORDINATE scales
#: about the panel centre, 540 + (v - 540) * DIAL_K. Physical quantities do
#: NOT scale: a fingertip's padding is a fingertip whatever the dial does
#: (§6 — the units that actually apply), and neither does a legibility floor.
# 0.93, 2026-08-07. The 0.80 squeeze cleared an octagon inner edge that
# no longer exists; the ceiling is now the chapter ring at 504 display.
# home.html's #dial scale moves in this same commit. The 5-9-14 failure
# history on this constant predates the geometry that motivates this; the
# type fitter gates it either way.
DIAL_K = 0.93

RINGS_DPS = 4.0            # ambient ring drift, degrees/second
#: 14 -> 8 on 2026-08-06, and this is a THERMAL setting, not a taste one.
#:
#: Measured on the panel, per frame, with the face idle: screen(ocean)
#: 16.3 ms, rings rotate+screen 12.9, bolt point+screen 11.7, wordmark 7.1,
#: desertify 5.5, clock+comets+copy 2.9 — 64.5 ms of compositing against a
#: 71.4 ms budget. `spare` was therefore never positive, the loop never
#: slept, and dj_face sat at 97% of a core: the exact number FAILURES
#: records for 2026-08-04 BEFORE that day's fix, which had brought it to
#: 29.2%. Nothing regressed; the face simply grew a third full-frame
#: screen() blend, and each one costs ~8.3 ms at 1080² on this SoC.
#:
#: The enclosure is the reason this matters rather than the frame rate.
#: FAILURES 2026-08-04: CPU cooks a sealed puck to 96.5C, the SoC
#: throttles, and the FIRST thing to fail is the microphone — Whisper
#: slows 5x, the room floor rises eightfold, and she goes deaf. That entry
#: also records that with everything repaired and load at 0.23 the puck
#: still idles at 84C. There is no thermal path out, so the only lever
#: left is to ask for less work.
#:
#: 8 fps is safe for everything that moves here because none of it is
#: fast: RINGS_DPS is 4 deg/s (0.5 deg per frame — invisible), the swell's
#: periods are 23-53 s, and the bolt's ambient breath is slower still.
#: Anything a finger is driving takes ACTIVE_FPS, which is untouched, so
#: drags, inertia and the tap flare are exactly as smooth as before.
IDLE_FPS = 8.0             # ambient refresh when nobody is touching
ACTIVE_FPS = 40.0          # target while dragging / inertia
#: ── AURORA PAYS FOR ITS OWN FRAME RATE (2026-08-16) ──────────────────────
#: The 8 fps above is a THERMAL budget, argued against a 54-64 ms compose
#: on the watch faces. Aurora composes in 15 ms measured — it skips the
#: ocean, the sky, the duotone, the baked bezel and all five wedge
#: tenants — so the same wattage buys twice the frames, and mist that
#: steps at 8 fps is not mist. Applied ONLY on this face, and only
#: because its own cost was measured first (§6).
#: 18, and the number moved twice for reasons worth keeping. It was 16,
#: then 14 when the relief pushed the compose to 47 ms (80% duty on a box
#: that idles at 89C with no thermal path — today's enclosure work), and
#: now 18 because caching the drifting ground gave 15 ms back: the ground
#: was being rebuilt six times before it changed by a pixel. 34 ms in a
#: 56 ms budget. The MIST's smoothness is not bought here in any case —
#: cross-fading (AUR_MIST_N) makes it rate-independent.
#: ── 18 -> 26 (2026-08-17) ────────────────────────────────────────────────
#: The note above sets 18 against a 34 ms compose in a 56 ms budget. Two
#: costs came off this face today: the baked rings/bolt layers are no
#: longer composited on aurora (they belong to the watch dials and had
#: silently gained ink, costing 11-17 ms a frame), and the ground cache
#: still holds. Measured after: compose 29 ms.
#:
#: 29 ms fits inside a 38 ms budget with room to spare, and the owner has
#: reported the eye as halting three times. Every other lever was measured
#: and found not to be the cause — the pack is not too slow (828 frames,
#: 15 fps, 0.87 deg a frame), the compositor is not stalling (0% identical
#: frames in the real draw path), and the resting breath was not it either
#: (10.8 -> 10.35). What is left is the honest answer: 18 fps of anything
#: moving reads as 18 fps.
#:
#: THIS IS A THERMAL SPEND and the die on this puck idles at 86C. If tj
#: climbs or the fan governor starts holding the ears deaf, this number is
#: the first thing to give back.
#: ── 26 -> 16: WE WERE COMPOSITING 25 fps OF A 15 fps ANIMATION ─────────
#: Owner: "we must be doing something stupid." tegrastats on the puck, at
#: rest, with the ring down and nobody speaking:
#:
#:     CPU [3%, 3%, 1%, 0%, 100%, 0%, 0%, 0%]  all @1984MHz
#:     GR3D_FREQ 0%          VDD_IN 12.4 W     tj 88C
#:
#: One core pinned, seven idle, the GPU doing NOTHING, and the governor
#: holding every core at full clock because of the one. That is the heat
#: and that is the fan — not transcription, which measured 51 ASR runs and
#: 70.9 s of GPU in an hour (a 2% duty cycle), and not inference, which a
#: menu command never reaches.
#:
#: And the only thing moving at rest is the eye:
#:
#:     pack content   828 frames / 55 s = 15.05 fps
#:     ribbon         6 Hz
#:     ring           only while arriving
#:     compositor     26 fps
#:
#: So roughly 40% of frames were a full 1080x1080 recomposite that produced
#: a BYTE-IDENTICAL eye, because the pack had not advanced. Against the
#: earlier finding that only 10% of pixels change per frame, the face was
#: doing several times the work the panel could show.
#:
#: 16, one frame above the pack's 15.05 so the two never beat against each
#: other. The note above says this number "is the first thing to give back"
#: if tj climbs or the fan starts holding the ears deaf. tj is 88C and the
#: fan is at PWM 180, which is past the level measured to deafen the array.
#: This is that debt being paid.
#:
#: NOTHING THAT ANIMATES FASTER LOSES FRAMES: `busy` in the frame loop now
#: covers the ring's arrival and dissolve and a playing briefing, all of
#: which take ACTIVE_FPS. What runs at 16 is the resting face, where 16 is
#: one more than the content has.
#: ── 16 -> 22: THE CAP WAS THE LAG (2026-08-20, evening) ───────────────
#: Owner: "people are complaining about my test videos of the puck being
#: laggy." A day of profiling the painter, and the painter was never the
#: problem. With the frame-time histogram fixed (see _FT_EDGES — its first
#: version put a bucket edge on the budget and reported every on-time
#: frame as late), the idle face measures:
#:
#:     mean 62.6 ms, worst 63, 0 of 480 frames over the 62.5 ms budget
#:     compose 26 ms of that budget
#:
#: Not one late frame, and 36 ms of every frame spent asleep. The glass
#: looks laggy because it is DELIBERATELY SLOW: this constant went 26 -> 16
#: this morning to hold the fan down, and 16 fps on a phone camera is what
#: a person calls laggy.
#:
#: So it is a dial and this is a deliberate turn of it, not a fix. 22 fps
#: needs a 45 ms budget against a 26 ms compose, which fits with room. The
#: cost is heat: one core was at 38% and tj at 87.1 C, which is already
#: the fan governor's target, so the fan will work harder to hold it —
#: measured after the change rather than predicted, because the fan and
#: the microphone share this box (PWM 187 takes the mic floor to 0.054,
#: which is deaf).
AUR_IDLE_FPS = 8.0

#: ── WHAT A SEALED FACE COSTS (2026-08-21) ───────────────────────────────
#: Owner: "the fan is just going bonkers fast right now what the hell is
#: taking up so much compute." Measured the same minute on his puck: the
#: compositor at 81% of a core, 18m55s of CPU, die 88.1C, fan pinned at
#: 255/255. It is the largest consumer on the device by an order of
#: magnitude, and most of the day it is painting a LOCK SCREEN.
#:
#: 8, not 1. The starfield still drifts and the iris still breathes, so it
#: reads as a device awake and waiting rather than one that has crashed
#: with a picture on it — which is the whole reason the lock screen
#: animates at all. Anything `busy` (a ceremony, the menu, an answer, a
#: show) is unaffected, and a touch or a voice clears the lock on the very
#: next frame.
AUR_LOCK_IDLE_FPS = 8.0
#: ── 2026-08-12: A SLOWER DIAL BUYS A FASTER MOVEMENT ──────────────────────
#: The budget arithmetic at TOURB_RECT_FPS assumes a 54 ms compose leaving
#: room for two 33 ms rect slots — "8 full frames plus 16 rect paints", 24 fps
#: at the aperture. MEASURED on both pucks with the pace counter at the bottom
#: of main(), it was never close: the compose is ~105 ms of the 125 ms budget,
#: so ~20 ms survives, less than one slot. The chopard puck managed 13.6 fps
#: (7.3 full + 6.2 rect) and the patek 16.3 (7.6 + 8.7).
#:
#: The note says the only lever is to shrink the compose. There is a second
#: one it did not consider: SPEND FEWER FULL FRAMES. Every full frame costs
#: 105 ms to repaint a dial whose slowest-changing elements move at minute
#: resolution, and buys ONE aperture update; the 20 ms it leaves behind buys
#: half of another. Lengthening the budget to 167 ms costs 2 full frames a
#: second and returns 8 rect paints. Measured on the chopard puck, same pack,
#: same build, one constant changed:
#:      8 fps budget:  13.6 fps to the glass  (7.3 full + 6.2 rect)
#:      6 fps budget:  20.1 fps to the glass  (5.5 full + 14.7 rect)
#:
#: ONLY WHERE A PACK IS LOADED, and that is not caution, it is the reason the
#: trade is safe. The 8 fps figure is load-bearing for the DRAWN tourbillon —
#: TOURB_BAL_AMP_DEG and TOURB_BAL_HZ were chosen to be honest at exactly that
#: rate, and a balance sampled slower than it was tuned for will alias. A pack
#: has no such contract: it is 900 pre-rendered frames of a 30 s loop, 30 fps
#: of content that was being sampled at 13. So the longer budget applies when
#: centre_pack_load has actually loaded frames, and every live-drawn face
#: keeps the cadence it was tuned at.
PACK_IDLE_FPS = 6.0        # ...when the aperture is fed by an RTX pack
#: ── 2026-08-07: THE APERTURE GETS ITS OWN RATE ────────────────────────────
#:
#: 8 fps is a limit on painting the WHOLE PANEL, not a limit on motion, and
#: those were the same thing only because blit() has always written all 1080
#: rows. Between full frames the tourbillon's ~276px window (206 before the
#: aperture grew, 2026-08-07) is repainted on
#: its own, by writing just those rows (blit_rect) — cost scales with pixels
#: touched, so a small window can move at a rate the whole face cannot.
#:
#: MEASURED, NOT ASSUMED (PRINCIPLES §6), on the puck's own panel at stride
#: 8192, 2026-08-07 (fb_blit.py --bench, which can be re-run there):
#:   full 1080x1080  17.99 ms median (min 16.69, max 22.77, n=15)
#:   rect  200x200    0.76 ms median (min 0.73, max 0.93, n=15)
#: 3.4% of the pixels, 4.3% of the time — proportional, the overhead being
#: 200 seeks instead of one write. End to end (build the sprite, composite it
#: over the kept background, write the rect) it is 1.24 ms median, p95 1.45,
#: over 5390 paints at 30 Hz for three minutes: 3.8% of one core.
#:
#: AND IT DOES NOT UNDO THE THERMAL CAP, which was the thing to check. Across
#: that run, on top of the live face: SoC 80.1-80.3C before, 80.3-80.5C
#: during, 80.2-80.4C after — flat inside the sampling noise. The 8 fps
#: full-frame cap is untouched and still does the work it was put there for.
#:
#: WHAT ACTUALLY REACHES THE EYE IS 24 UPDATES A SECOND, NOT 30, and the
#: reason is worth writing down: the compose costs 54 ms of CPU per frame
#: (13.05 s over 30 s at 8 fps, measured off /proc), so only ~71 ms of the
#: 125 ms budget is free and two 33 ms grid slots fit in it. 8 full frames
#: plus 16 rect paints. Raising this constant will not change that; shrinking
#: the compose would.
#:
#: THE BEAT RATE IS NOT CHANGED HERE. TOURB_BAL_AMP_DEG/TOURB_BAL_HZ are
#: still the numbers chosen to be honest at 8 fps; this only removes the
#: reason they had to be. Raising them is the owner's springier-balance
#: brief and belongs in its own change, with its own look at the glass.
TOURB_RECT_FPS = 30.0      # aperture-only repaints per second while idle
#: ── 2026-08-19: THE AURORA RIBBON'S OWN GRID, AND ITS PRICE ──────────────
#: The rect measured on puck-10634 is ~14% of the glass and ~7 ms end to end
#: (copy the ground, draw the trace, write the rows) against a 33 ms full
#: frame after the menu caches. So the grid can run much faster than the
#: tourbillon's 30 Hz — 16.7 ms is comfortably longer than the paint.
AUR_RECT_FPS = 60.0
#: ── AND THE TRADE IS REAL, MEASURED, AND NOT TAKEN ──────────────────────
#: A rect slot only exists in the gap between the compose and the deadline,
#: and after the menu caches this face has 3 ms of gap: 35 ms of compose in a
#: 38 ms budget, against a ~7 ms ribbon paint. Buying slots means lengthening
#: the budget, which means FEWER FULL FRAMES — and on THIS face a full frame
#: is what moves the IRIS, which is the centrepiece and the thing he points a
#: camera at. Both settings were run on puck-10634 with the ring up:
#:
#:     AUR_RECT_IDLE_FPS 26   25.6 fps to the glass (25.4 full + 0.2 rect)
#:                            — everything at 25.6, tj 88.0C
#:     AUR_RECT_IDLE_FPS 12   35.7 fps to the glass (12.0 full + 23.7 rect)
#:                            — ribbon at 35.7, IRIS AT 12, tj 86.7C
#:
#: 35.7 is the bigger number and it is the worse picture: it buys a smooth
#: waveform by halving the frame rate of everything else on the glass. The
#: watch dials take this trade because their full frames carry a STILL bezel
#: and the only moving thing is inside the aperture the rect repaints. That
#: is not this face. Left equal to AUR_IDLE_FPS, so the path is armed and
#: fires only in genuine spare time — which is a real, if small, number in
#: the pace line rather than a promise. Change this ONE constant to take the
#: trade; docs/PUCK-SHOW.md (2026-08-19) carries the working.
#: same trade, same reason as AUR_IDLE_FPS above: one frame
#: above the pack's own 15.05 fps.
#: raised with AUR_IDLE_FPS above, or the rect path's own cap
#: silently holds the face at 16 whenever the ribbon rect is
#: armed — which is most of the time.
AUR_RECT_IDLE_FPS = 8.0
#: What the pace loop actually achieved, reported every 30 s — see the
#: note at the bottom of main(). Never per frame.
#: ── AND A FRAME-TIME HISTOGRAM, BECAUSE fps IS AN AVERAGE ─────────────
#: Owner, 2026-08-19: "people are complaining about my test videos of the
#: puck being laggy. what can we do to get the low hanging fruit and PROVE
#: a level of smoothness."
#:
#: The pace line above reports frames per second over thirty seconds, and
#: that is exactly the statistic the complaint is invisible in. 22 fps
#: made of frames all 45 ms apart is smooth; 22 fps made of 30 ms frames
#: and the occasional 200 ms one is not, and they print the same number.
#: The eye reads the worst frames, not the mean of them.
#:
#: So the loop also buckets the WALL-CLOCK GAP between consecutive paints
#: — what the glass actually did, not what the compose cost — and reports
#: p50 / p95 / worst and how many frames missed the budget. One
#: subtraction and one increment per frame.
#:
#: Edges in milliseconds, chosen around the budgets this face runs at
#: (62 ms at 16 fps, 38 ms at 26) so a bucket boundary means something
#: rather than being a round number.
#: ── AND A BUCKET EDGE ON THE BUDGET IS A LIE (2026-08-20) ─────────────
#: The first cut of these edges ended ...50, 62, 80. The idle budget is
#: 1/16 s = 62.5 ms. So a frame delivered EXACTLY ON TIME fell in the
#: "<80" bucket, p50 was reported as that bucket's upper edge — 80 — and
#: the over-budget count, derived from the buckets, said 100% of frames
#: missed. I reported that to the owner as "frames take 80 ms against a
#: 62 ms budget". It is an artefact of putting a boundary on the number
#: being tested.
#:
#: Two fixes, and the second is the one that matters. Finer edges around
#: the budgets this face runs at, AND the over-budget count is now taken
#: EXACTLY at measurement time against the frame's own budget rather than
#: inferred from which bucket it landed in. A histogram is for shape; a
#: threshold question deserves a comparison, not a bucket lookup.
_FT_EDGES = (20.0, 30.0, 40.0, 50.0, 58.0, 63.0, 68.0, 75.0, 90.0,
             110.0, 150.0, 220.0, 400.0)
_PACE = {"said": 0.0, "frames": 0, "rects": 0, "compose": 0.0,
         "ft": [0] * (len(_FT_EDGES) + 1), "last": 0.0, "ftmax": 0.0,
         "over": 0, "ftsum": 0.0, "ftn": 0}


def _ft_note(now: float, budget: float = 0.0) -> None:
    """Bucket the gap since the previous paint. Cheap enough to be
    unconditional — a measurement you have to switch on is a measurement
    nobody has when they need it."""
    _l = _PACE["last"]
    _PACE["last"] = now
    if _l <= 0.0:
        return
    _ms = (now - _l) * 1000.0
    #: a gap longer than a couple of seconds is the face having been
    #: parked — sleep, the brick, a briefing owning the glass — not a
    #: slow frame, and charging it to the histogram would make every
    #: report look catastrophic for reasons nobody can act on.
    if _ms > 2000.0:
        return
    if _ms > _PACE["ftmax"]:
        _PACE["ftmax"] = _ms
    _PACE["ftsum"] += _ms
    _PACE["ftn"] += 1
    #: exact, against this frame's own budget — see the note at _FT_EDGES
    if budget > 0.0 and _ms > budget * 1000.0 + 0.5:
        _PACE["over"] += 1
    for _i, _e in enumerate(_FT_EDGES):
        if _ms < _e:
            _PACE["ft"][_i] += 1
            return
    _PACE["ft"][len(_FT_EDGES)] += 1


def _ft_pct(p: float) -> float:
    """The p-th percentile frame time, read off the histogram. Reported as
    the bucket's UPPER edge, so it is an over-estimate and never flatters
    the result — the direction an honest performance number should err."""
    tot = sum(_PACE["ft"])
    if not tot:
        return 0.0
    want = p * tot
    run = 0
    for i, c in enumerate(_PACE["ft"]):
        run += c
        if run >= want:
            return (_FT_EDGES[i] if i < len(_FT_EDGES)
                    else _PACE["ftmax"])
    return _PACE["ftmax"]
#: What a damage-rect paint actually costs, per painter, measured as it runs
#: — the tourbillon aperture and the aurora ribbon differ by an order of
#: magnitude and the gap arithmetic has to know which one it is holding. See
#: the deadline guard at the bottom of main().
_RECT_COST: dict = {}
#: ── 2026-08-12: WHERE THE 105 ms ACTUALLY GOES ───────────────────────────
#: The pace counter says a full frame costs ~70-105 ms and that this is now
#: the ceiling on how fast the aperture can move. It does not say WHICH
#: part, and the guesses available are all plausible: desertify measured at
#: 2.1 ms on the dev box years ago, the bezel is a 1080px RGBA paste, the
#: wedge overlays each build a tile. Plausible is what costs hours here, so
#: the loop is segmented and reports its own breakdown beside the rate.
#: time.time() is ~100 ns; eight of them against a 100 ms frame is noise.
_PH = {"t": 0.0, "acc": {}, "dump": False}
PHDUMP = Path("/tmp/aura_face/phdump")


def _ph(name: str, frame=None) -> None:
    """Close the segment that was running and open the next.

    With a frame and /tmp/aura_face/phdump present, also writes the frame as
    it stands AT THIS POINT — one set, then the trigger is removed. Finding
    which stage introduces a mark by bisecting the source is guesswork; this
    is the frame itself, and it is how the r=455 copper ring was finally
    pinned after ten attempts aimed at other objects.
    """
    t = time.time()
    _PH["acc"][name] = _PH["acc"].get(name, 0.0) + (t - _PH["t"])
    _PH["t"] = t
    if frame is not None and _PH.get("dump"):
        try:
            frame.convert("RGB").save(f"/tmp/aura_face/ph_{name}.png")
        except Exception:
            pass
FRICTION = 3.4             # 1/s — at 1.4 a flick coasted for
                           # seconds after the finger left
                           # ('drifts way after my fingers are
                           # off', owner, 12:54). ~0.9s settle.
INERTIA_MIN_DPS = 12.0     # flicks slower than this just stop
STOP_DPS = 2.0             # momentum below this is dead
#: Flick cap. Was 720 — a hard flick whipped the face around two full
#: turns before friction caught it, which read as "unnatural" (owner,
#: 2026-08-02 morning). Half a turn per second is the fastest a real
#: turntable nudge plausibly produces; anything beyond is clamped at
#: gesture release, not during the drag (tracking stays direct).
MAX_DPS = 120.0

#: Center deadzone + radial gain (owner, 2026-08-02 morning: "super
#: sensitive touching in the center, much slower outside"). Rotation is
#: angle-based, so near the hub a few pixels of finger travel sweeps a
#: huge angle — the dial went hyperactive under a centered thumb. Below
#: ROT_DEAD_R (display px from center) rotation gestures are ignored
#: outright; gain ramps linearly to exact 1:1 at ROT_FULL_R, so inner
#: touches rotate gently and the rim keeps its approved direct feel.
ROT_DEAD_R = 120.0
ROT_FULL_R = 250.0

#: Tap vs drag: a press that moves less than this and releases within
#: TAP_MAX_S is a tap (the old GUI's deferred press, drag_threshold=12px).
#: Loosened 18/0.45 -> 24/0.60 (2026-08-01): the owner needed several tries
#: to land the BRIEFING wedge — a slightly slow or sliding fingertip must
#: still count as a tap on a 1080px round panel.
TAP_MAX_PX = 24.0
TAP_MAX_S = 0.60
#: The BRIEFING wedge, in the face's own coordinates (see home.html MENU):
#: angles are degrees from 3 o'clock, positive downward (atan2 with y down).
BRIEFING_A0, BRIEFING_A1 = -62.0, -28.0
#: Display px — the same viewBox/display correction as WEDGE_R0/WEDGE_R1
#: (see the note there). flash_overlay strokes the BRIEFING sector's own
#: edges, so an 8% error here drew the flare inside the wedge it was
#: flaring.
#: x DIAL_K, 2026-08-06 night — 362.9/494.6 were the measured band and stay
#: written that way. See DIAL_K.
#: 2026-08-06 late night: 362.9 -> 397.4 with the ring's inner edge (336 ->
#: 368 viewBox). This is the SAME band as WEDGE_R0/WEDGE_R1 and always has
#: been; the flare strokes the BRIEFING sector's own edges, so it moves with
#: them or it flares a ring that is not there.
BRIEFING_R0, BRIEFING_R1 = 397.4 * DIAL_K, 494.6 * DIAL_K
#: Conductor handshake files. A tap on the wedge REQUESTS a briefing; the
#: RTX conductor answers by writing scene.png (we display it) and removes
#: it when done. A tap during a scene requests an abort.
REQ = Path("/tmp/aura_face/briefing_requested")
ABORT = Path("/tmp/aura_face/briefing_abort")
SCENE = Path("/tmp/aura_face/scene.png")            # legacy single-frame path
SCENE_BASE = Path("/tmp/aura_face/scene_base.png")  # layered scenes: backdrop
SCENE_DATA = Path("/tmp/aura_face/scene_data.png")  # ...and the marks, on black

#: Scene cinema tunings. The reveal wipes the data marks in left-to-right,
#: the crossfade bridges scene changes, the drift is a slow Ken Burns zoom,
#: and the pulse breathes the data layer afterwards. All local; the RTX
#: only ships stills.
REVEAL_S = 1.1
XFADE_S = 0.55
#: 26 clipped the frame's own ring and kicker at slide start — the drift
#: begins fully zoomed and relaxes, so every slide opened visibly cropped
#: for its first seconds (owner, live, 2026-08-01: "it was quick but it was
#: definitely clipped ... again on the next slide"). 10px keeps the motion
#: and stays inside the ring's 26px inset at maximum zoom.
DRIFT_SPAN = 10            # px of extra zoom-crop across DRIFT_S
DRIFT_S = 24.0
SCENE_FPS = 13.0

#: Pre-show countdown (the unveil). countdown.json holds {"target": epoch};
#: the backdrop is a pushed still and the digits render HERE, once a second,
#: with a heartbeat ring pulsing beneath them. A tap skips the wait.
COUNT = Path("/tmp/aura_face/countdown.json")
PRESHOW_BASE = Path("/tmp/aura_face/preshow_base.png")
SKIP = Path("/tmp/aura_face/preshow_skip")
FONT_PATH = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"

#: ── The type ramp ─────────────────────────────────────────────────────
#: Every word on this face used to be DejaVu Sans BOLD — labels, status
#: lines, names, numbers, one weight for all of it. Owner, live
#: 2026-08-02: "make the fonts more elegant for the whole voice auth
#: page, it's clunky, font wise and elegance wise compared to the rest of
#: the Aura OS." A single bold weight cannot make a hierarchy; it can
#: only make everything shout equally.
#:
#: The puck already carries the URW base35 set (verified on the device,
#: /usr/share/fonts/opentype/urw-base35/), which is a real Helvetica-class
#: family. So: Nimbus Sans REGULAR carries body and status, Nimbus Sans
#: BOLD is reserved for the name and the key numbers, Nimbus Sans NARROW
#: carries the wide-tracked small-caps labels (narrow + big tracking is
#: the whole trick — the letters get slim as the gaps get wide).
#:
#: PRINCIPLES §1 — no silent substitution. If a face is missing we drop
#: to DejaVu and SAY SO on stdout, once per role. A page that quietly
#: renders in the old clunky face would look exactly like a deploy that
#: never landed, and nobody would know to look.
_URW = "/usr/share/fonts/opentype/urw-base35/"
_DEJAVU = "/usr/share/fonts/truetype/dejavu/"
FACES = {
    "text":  (_URW + "NimbusSans-Regular.otf", _DEJAVU + "DejaVuSans.ttf"),
    "bold":  (_URW + "NimbusSans-Bold.otf", FONT_PATH),
    "label": (_URW + "NimbusSansNarrow-Regular.otf",
              _DEJAVU + "DejaVuSans.ttf"),
    #: The same narrow small-caps face in BOLD (2026-08-09). Owner, on the
    #: sub-dial captions: "make them BIGGER ... and heavier in weight." The
    #: ramp had no heavy NARROW: "bold" is Nimbus Sans proper, which is a
    #: different width class, so a caption that swapped roles would have
    #: changed shape as well as weight and stopped matching the register
    #: beside it. This is the SAME family and the same tracking trick, one
    #: weight up — the only thing that moves is the stroke.
    #: ── THE BRIEFING TITLE (2026-08-17) ─────────────────────────────────
    #: Owner: "make the font for the titles more elegant." First answer was
    #: P052 — URW's Palatino — on the reasoning that a briefing is editorial
    #: rather than instrumentation. Wrong reading of "elegant", corrected at
    #: the glass within the hour: *"no i don't like the title font, more
    #: futuristic, not newspaper past type fonts."*
    #:
    #: URWGothic is the Avant Garde Gothic geometric: circular bowls, a
    #: single-storey `a`, almost no stroke contrast — the typeface of every
    #: 1970s vision of the future, and the one on this box that belongs
    #: next to a particulate blue iris. Demi rather than Book because these
    #: are set over a lit backdrop and Book disappears into it.
    #:
    #: Set TRACKED (see the title's draw call): geometric caps without
    #: letter-spacing read as a logo, and with it they read as a title
    #: card. That spacing is most of the "futuristic", more than the
    #: drawing of any single letter.
    #: ── AND URW GOTHIC WAS FLAT (2026-08-17) ────────────────────────────
    #: Second correction in an hour: *"pick yet another better cooler
    #: futuristic font, it's too flat right now as a font."* He is right —
    #: Avant Garde is a monoline geometric, every stroke the same weight,
    #: every bowl a circle. It reads as futuristic in the way a 1970s title
    #: card does, which is to say as a period reference, and it has no
    #: texture at display size.
    #:
    #: Ubuntu has the character it was missing: stems that flare where they
    #: meet the bowl, terminals cut at an angle rather than square, bowls
    #: that are not quite circles. Set in caps and tracked it reads as
    #: contemporary technical rather than retro-geometric. Medium, not
    #: Bold — Bold plus tracking at this size is a shout.
    #:
    #: Chosen by setting the same title in all six display faces the puck
    #: actually carries and looking at the sheet, rather than by naming a
    #: font from memory (which is how the last two were picked).
    #: ── THE WORDMARK'S OWN FACE (2026-08-17) ────────────────────────────
    #: Owner, on the rim mark: "make the font elegant and futuristic."
    #:
    #: Elegant, on a brand lockup, is LIGHT AND WIDE — the weight comes off
    #: and the space between the letters does the work. It is the opposite
    #: instinct to a title, which needs presence; a mark on a rim needs to
    #: be noticed second and never shouted. Ubuntu Light keeps the family's
    #: angled terminals and squared bowls (so it belongs beside the titles)
    #: at a weight that reads as engraved rather than printed.
    #: -- LIGHT WAS NOT ON THE DEVICE (2026-08-17) -----------------------
    #: Ubuntu-L.ttf exists on the workstation and NOT on either puck, whose
    #: ubuntu directory holds exactly M, R, RI and Th. So every preview I
    #: judged was set in Light and every frame the owner actually saw was
    #: set in Regular -- two different typefaces, one of them never once
    #: looked at. That is the artefact-versus-patch rule in its purest
    #: form: the fallback ramp did its job silently, and the silence was
    #: the bug.
    #:
    #: Medium first now, and it is the right weight anyway: this glyph is
    #: lit as a relief surface, and a hairline stroke has no face for the
    #: light to land on -- it comes out as two arrises with nothing between
    #: them, which is precisely how the fourth cut read.
    #: the LIGHTER of the two weights in the wordmark. Ubuntu-B is not on
    #: either puck -- M, R, RI and Th is the whole set -- so the contrast
    #: between "Aura" and "Vision" is built from M against R, with a stroke
    #: on the M to open the gap further. Weight contrast made of fonts that
    #: are on the device beats weight contrast made of a font that is not.
    "markr": ("/usr/share/fonts/truetype/ubuntu/Ubuntu-R.ttf",
              "/usr/share/fonts/truetype/ubuntu/Ubuntu-M.ttf",
              _URW + "NimbusSans-Regular.otf"),
    "mark": ("/usr/share/fonts/truetype/ubuntu/Ubuntu-M.ttf",
             "/usr/share/fonts/truetype/ubuntu/Ubuntu-R.ttf",
             _URW + "URWGothic-Book.otf",
             _URW + "NimbusSansNarrow-Regular.otf"),
    #: ── THIN AND WIDE, AND THE AXIS NOBODY HAD MOVED (2026-08-20) ───────
    #: Owner, fifth request about this type: "the briefing title has to be
    #: more sexy and futuristic."
    #:
    #: Four previous answers changed the TYPEFACE and none of them changed
    #: the TRACKING, which is the axis his own approved note names: "Elegant
    #: is LIGHT AND WIDE — the weight comes off and the space between the
    #: letters does the work." So the sheet
    #: (scripts/preview_title_faces.py) varied both, on whole beats, in
    #: faces confirmed present on puck-10634.
    #:
    #: URW GOTHIC WAS NOT ELIGIBLE, and that is worth writing down because
    #: it is the obvious answer and it is on the sheet twice. He saw it on
    #: 08-17 and sent it back inside the hour — "it's too flat right now as
    #: a font" — for the reason recorded above: Avant Garde is monoline, so
    #: it has no texture at display size. Tracking does not fix monoline.
    #: A candidate the owner has already rejected is not a candidate.
    #:
    #: Ubuntu THIN, tracked to 0.304 em. It stays in the family the rest of
    #: the face uses (the angled terminals and squared bowls that made
    #: Medium right in the first place), at the weight his own definition of
    #: elegant asks for, with the spacing doing the work. Th is one of the
    #: four Ubuntu weights that actually exist on both pucks — M, R, RI, Th
    #: — which is the whole point of the note two screens up.
    #:
    #: The Light-on-a-relief-surface warning in that note does NOT apply
    #: here: it is about the rim MARK, which is lit as a machined surface
    #: where a hairline has no face for the light to land on. A briefing
    #: title is drawn flat over a backdrop.
    "title": ("/usr/share/fonts/truetype/ubuntu/Ubuntu-Th.ttf",
              "/usr/share/fonts/truetype/ubuntu/Ubuntu-M.ttf",
              "/usr/share/fonts/truetype/ubuntu/Ubuntu-B.ttf",
              "/usr/share/fonts/truetype/ubuntu/Ubuntu-C.ttf",
              _URW + "URWGothic-Demi.otf",
              _URW + "NimbusSansNarrow-Bold.otf"),
    "label-b": (_URW + "NimbusSansNarrow-Bold.otf",
                _DEJAVU + "DejaVuSans-Bold.ttf"),
    #: Farsi (2026-08-05, owner by voice: "translate everything on the
    #: screen, my home screen, to Farsi"). NOT part of the ramp above, and
    #: it cannot be: the URW base35 set carries no Arabic script at all —
    #: every Persian glyph out of Nimbus renders as a zero-width notdef, so
    #: "label" would have painted an empty pill and looked like a clock that
    #: had stopped. DejaVu is the only face on both machines with the block.
    "farsi": (_DEJAVU + "DejaVuSans-Bold.ttf", FONT_PATH),
    #: CJK (2026-08-06). Same reasoning as "farsi" one line up and the same
    #: trap: neither the URW ramp NOR DejaVu carries a single Han glyph, so
    #: 休眠 out of any other role is a row of notdef boxes — a face that
    #: looks like a deploy that half-landed. Noto Sans CJK is the only
    #: family on this machine with the block; Droid Sans Fallback is the
    #: second, and is named as the fallback because it is the one a Jetson
    #: image is likeliest to have when Noto is absent. If BOTH are missing
    #: face() drops to DejaVu and SAYS SO — visibly wrong beats silently
    #: wrong (PRINCIPLES §1).
    "cjk":   ("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
              "/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf"),
}
_FACE_CACHE: dict = {}
_FACE_WARNED: set = set()
#: Roles that have been handed a non-int size — see face(). Separate from
#: _FACE_WARNED because a float size and a missing font file are different
#: faults and the old code reported the first one as the second.
_FACE_FLOAT_WARNED: set = set()

#: The auth page's own ink. Bright for the name, steel for everything
#: that is chrome, and the two accents it already used.
AUTH_INK = (238, 246, 255)
AUTH_STEEL = (138, 168, 196)
#: ── A PALETTE, NOT A COLOUR (2026-08-18) ───────────────────────────────
#: Owner, of the auth rings: "vary the color and give them more professional
#: treatment as to texture, they look cartoonish right now."
#:
#: Every moving element on that screen was one of three near-identical
#: cyans, drawn flat and 3-6 px wide. That combination is a marker pen, and
#: a marker pen is what "cartoonish" means here. These five are chosen to
#: sit at different TEMPERATURES rather than different brightnesses of the
#: same hue — ice, steel, slate, a cold violet, and one genuinely warm grey.
#: The warm one matters most: a screen with no warm pixel anywhere in it
#: reads as a rendering, and one warm element among four cold ones is what
#: makes the rest look like lit metal instead of coloured line art.
AUTH_ICE = (206, 230, 246)
AUTH_SLATE = (78, 112, 144)
AUTH_VIOLET = (118, 108, 168)
AUTH_WARM = (168, 150, 128)
AUTH_RINGS = (AUTH_SLATE, AUTH_VIOLET, AUTH_STEEL)
#: how far above the circle's centre the level meter sits. One number,
#: because the waveform stage and the spectrum stage must land at the
#: same altitude or the readout appears to jump between stages.
AUTH_METER_DY = 96
#: the confirmation green, named rather than repeated as a literal at
#: each of the three places that draw the seal
AUTH_OK = (53, 208, 127)

_AUTH_VEIL: dict = {}


def _auth_veil() -> "Image.Image":
    """A soft radial darkening of the iris, so the readout owns the centre.

    Built once. It is a smooth falloff rather than a flat disc because a
    hard-edged shadow over the eye reads as a bug — a panel with a dead
    circle in it — where a gradient reads as the aperture stopping down,
    which is the thing that is actually happening while she listens.
    """
    v = _AUTH_VEIL.get("img")
    if v is not None:
        return v
    #: ── IT HAS TO CLEAR THE WORDMARK, NOT THE RIM (2026-08-18) ─────────
    #: First cut used AUR_RIM_R1 (270), which is the iris rim and the
    #: obvious radius to reach for. Rendered and looked at: the middle went
    #: dark and "AURA" and "SION" survived on either side, so the readout
    #: landed as "AURA 33% SION" — worse than not veiling at all.
    #:
    #: preview_lock.py prints the answer and has for weeks: "wordmark ink
    #: spans 706 px", i.e. it reaches r=353, well past the rim it sits
    #: inside. A veil sized to the circle was never going to cover the text.
    #: 380 with a flat core to 0.66 covers the glyphs completely and still
    #: feathers out before the progress ring at 330 — checked, not assumed.
    r = 380
    a = Image.new("L", (SIZE, SIZE), 0)
    px = a.load()
    c = SIZE / 2.0
    for y in range(int(c - r), int(c + r) + 1):
        dy = y - c
        for x in range(int(c - r), int(c + r) + 1):
            d2 = math.hypot(x - c, dy) / r
            if d2 >= 1.0:
                continue
            #: flat and opaque over the glyphs, then feathered to nothing
            k = 1.0 if d2 <= 0.66 else ((1.0 - d2) / 0.34) ** 0.9
            #: 242 left the glyphs legible as a grey ghost behind the
            #: number — 5% of a bright wordmark on black still reads as
            #: letters. 253 is the point where it stops being text.
            px[x, y] = int(253 * k)
    v = Image.merge("RGBA", (Image.new("L", (SIZE, SIZE), 3),
                             Image.new("L", (SIZE, SIZE), 5),
                             Image.new("L", (SIZE, SIZE), 9), a))
    _AUTH_VEIL["img"] = v
    return v
AUTH_CYAN = (56, 200, 255)
AUTH_SEAL = (53, 208, 127)

#: Login sequence: {"name","start","verify_s","briefing_at"} — a scanning
#: animation while she says she's checking the voice print (she really is:
#: the room loop identified the speaker before this file was ever written),
#: then the welcome. FLASH pulses the BRIEFING wedge afterwards.
LOGIN = Path("/tmp/aura_face/login.json")
FLASH = Path("/tmp/aura_face/flash_briefing")

#: The lock screen: deep space and her name. Present while LOCKED exists;
#: a successful login removes it — authenticating IS unlocking the system
#: (owner: "it's weird to get authenticated when you are already at the
#: home screen"). Stars are drawn here so they can truly twinkle.
LOCKED = Path("/tmp/aura_face/locked")
#: when the first of a double tap landed on the lock screen
_LAST_LOCK_TAP = [0.0]
#: when the first of a double tap landed on the deaf (muted) face
_LAST_DEAF_TAP = [0.0]


#: ── THE ONLY TWO INSTRUCTIONS ON THE PRODUCT (2026-08-17) ───────────────
#: Owner: "put DOUBLE TAP TO UNLOCK above the circle and 'OR JUST SAY HI
#: AURA TO GET STARTED' below the circle."
#:
#: These are the entire user manual. Nothing else on this device tells
#: anyone what to do, and they are read by someone who has never seen it —
#: so they are set QUIET: small, widely tracked, around half white. An
#: instruction that shouts reads as a warning, and the first thing a
#: stranger should feel about this object is that it is calm.
#:
#: The second line is the more important one and is deliberately the
#: softer: double-tapping is a thing people try anyway, whereas "you may
#: simply speak to it" is the fact that changes what the object IS. It is
#: placed where the eye lands after the wordmark rather than competing
#: with it.
LOCK_HINT_TOP = "DOUBLE TAP TO UNLOCK"
LOCK_HINT_BOT = "OR JUST SAY HI AURA TO GET STARTED"
LOCK_HINT_TRACK = 0.34          # em, wide — this is small-caps signage
LOCK_HINT_GAP = 46              # px clear of the circle, both sides


#: ── AND THE HINT IS THE THEME'S INK (2026-08-26) ────────────────────────
#: (150,196,224) is a pale blue for deep space, and on plaster it is the
#: comet-on-opaline inversion for the fourth time this week: a light ink
#: laid on a light ground. A row that owns its door owns the writing on
#: it. Default unchanged, so every starfield face keeps its blue.
LOCK_HINT_INK = tuple(_THEME.get("lock_hint_ink") or (150, 196, 224))


def _lock_hint_line(d, text: str, px: int, cy: float, alpha: int,
                    ink: tuple = None) -> float:
    """One tracked line, centred. Tracking is drawn per glyph because PIL
    has no letter-spacing — the same trick the rim wordmark used.

    `ink` and the returned width are for the health mark, which is the same
    typography in a different colour and needs to know where its own line
    starts so the pip can sit beside it. The default is the lock hints' own
    blue and both existing callers are unchanged.
    """
    ink = LOCK_HINT_INK if ink is None else ink
    f = face("label", px)
    tr = LOCK_HINT_TRACK * px
    w = sum(d.textlength(c, font=f) for c in text) + tr * max(
        0, len(text) - 1)
    x = (SIZE - w) / 2.0
    for ch in text:
        d.text((x, cy), ch, font=f, fill=tuple(ink) + (alpha,),
               anchor="lm")
        x += d.textlength(ch, font=f) + tr
    return w


def draw_lock_hint(frame: "Image.Image", now: float) -> None:
    """The two lines that say the glass is alive and how to come in.

    Drawn after the rotate on purpose — everything else on this screen
    turns with the dial, and this is the exception for the same reason the
    volume captions were: it is an instruction, and an instruction upside
    down is worse than none. It breathes, because a still hint on a still
    screen is indistinguishable from a frozen device.
    """
    try:
        d = ImageDraw.Draw(frame, "RGBA")
        #: the circle they sit around is the iris' outer rim
        #: ── AND A FACE-DOOR NEEDS ITS OWN RADIUS (2026-08-26) ────────
        #: 300 is measured against a starfield, which is empty everywhere,
        #: so the two lines could sit wherever read best. A LOCK_FACE door
        #: is the dial itself, and the dial already has a baked wordmark at
        #: exactly that height — the first render put "DOUBLE TAP TO
        #: UNLOCK" straight through "AURA VISION". Push both lines out to
        #: the plaster margin outside the chapter ring, which is the only
        #: band on this face that carries nothing.
        r = (AUR_RIM_R1 if AURORA_BLOB
             else LOCK_FACE_R if LOCK_FACE else 300.0)
        c = SIZE / 2.0
        breathe = 0.5 + 0.5 * math.sin(now * 1.6)
        #: ── A THIRD LARGER (2026-08-18) ─────────────────────────────────
        #: Owner: "increase the font of the outside text 'double tap...'
        #: 'or just say...' by 33%." 22 -> 29 and 19 -> 25, which keeps the
        #: two a size apart. They were set small partly to stay out of the
        #: way of the in-circle hint that this commit removes; with the
        #: circle clear they can be read from across a room, which is where
        #: someone standing up to a locked puck actually is.
        _lock_hint_line(d, LOCK_HINT_TOP, 29, c - r - LOCK_HINT_GAP,
                        int(120 + 70 * breathe))
        #: the lower line is quieter and a size down: it is the gentler of
        #: the two facts and should not compete with the instruction above
        #: the circle or with the wordmark inside it
        _lock_hint_line(d, LOCK_HINT_BOT, 25, c + r + LOCK_HINT_GAP,
                        int(88 + 46 * breathe))
    except Exception:                                   # noqa: BLE001
        pass


#: ── AND A PERSON HAS TO SEE IT WITHOUT GOING LOOKING (2026-08-20) ────────
#:
#: A SYSTEM page is only ever found by somebody who already suspects. The
#: whole failure is that nobody knew to suspect: Bob's puck sat deaf in his
#: kitchen for twelve hours and looked, from the chair, exactly like the
#: mornings it worked. So the resting face itself has to say it.
#:
#: QUIET, AND NOT AN ALARM. No red, nothing that flashes, nothing that
#: moves fast — this device is supposed to feel calm, and a machine that
#: shouts about its own plumbing is a machine people stop believing. It is
#: the lock hints' exact typography (small tracked caps, breathing at their
#: rate, `_lock_hint_line`) in the amber this face already uses for "not
#: wrong, but not right either". Two lines: WHAT, then WHERE.
#:
#: IT SAYS NOTHING AT ALL WHEN EVERYTHING IS FINE, which is ~100% of the
#: time and is the only reason it may live permanently on the resting face
#: without becoming furniture. And nothing while the poller has not
#: answered yet — a boot must not accuse itself (§2).
#:
#: WHERE IT LIVES, AND IT IS ANCHORED RATHER THAN CONSTANT. The first
#: version was y=892 flat, which was measured on the AURORA face — eye rim
#: 270, panes from 420, 150 px of empty annulus and the bottom of it free.
#: It is wrong on every other row in the fleet: the baked watch faces put
#: their wedge ring at WEDGE_R0 (369.6), fifty pixels further in, so the
#: same y lands the second line straight across the baked panes. Bob's puck
#: wears a baked face, and Bob's puck is the one this mark exists for.
#:
#: So the block hangs from the RING the face actually has, and the type
#: shrinks to fit the chord available at its own radius (`_health_fit`) —
#: no number here needs re-tuning when a theme moves its panes. The lock
#: screen anchors to LOCK_HINT_BOT instead, because that screen has no
#: panes and does have two lines of small print this must not crowd.
HEALTH_MARK_CLEAR = 26          # air between the block and the pane ring
HEALTH_MARK_LEAD = 36           # pitch between the two lines
HEALTH_MARK_PX = 24
HEALTH_MARK_HINT_PX = 18
HEALTH_MARK_HINT = "SETTINGS  ›  SYSTEM"
#: Amber, one step calmer than SET_AMBER's (255,176,46): this is signage
#: seen from across a room at rest, not a value on a dense page.
HEALTH_MARK_INK = (236, 172, 84)


def _health_ring_r() -> float:
    """The inner edge of whatever pane ring this face is wearing."""
    return AUR_WEDGE_R0 if AURORA_BLOB else WEDGE_R0


def _health_fit(d, text: str, px: int, cy: float, ring_r: float) -> int:
    """The largest size at which this line still clears the ring.

    The glass is round, so the width available at a given y is a chord, and
    it shrinks fast as the line moves outward. Solved rather than tuned:
    the alternative is a constant that is correct on the face it was
    measured on and runs under the panes on the other four.
    """
    dy = abs(cy - SIZE / 2.0)
    half = math.sqrt(max(1.0, ring_r * ring_r - dy * dy)) - 10.0
    while px > 15:
        f = face("label", px)
        tr = LOCK_HINT_TRACK * px
        w = sum(d.textlength(c, font=f) for c in text) \
            + tr * max(0, len(text) - 1)
        if w / 2.0 <= half:
            break
        px -= 1
    return px


def draw_health_mark(frame: "Image.Image", now: float,
                     where: str = "home") -> None:
    """What is down, and where to look — or nothing at all.

    The pointer is dropped at the lock screen: SETTINGS cannot be reached
    from behind the door, and naming a control somebody cannot press is
    worse than the two instructions that screen already carries.

    Wrapped whole — a health mark is never worth a stopped compositor.
    """
    try:
        faults = health_faults()
        if not faults:
            return
        #: The worst one, NAMED; the rest counted. This is a sign, not a
        #: report — its whole job is "something is wrong, go and look", and
        #: the page it points at enumerates properly. Keeping it to one
        #: short line is also what keeps it inside the chord (see
        #: _health_fit): "CONDUCT FAILED +5" is the longest it can be.
        msg = faults[0] if len(faults) == 1 \
            else f"{faults[0]} +{len(faults) - 1}"
        d = ImageDraw.Draw(frame, "RGBA")
        lock = where == "lock"
        if lock:
            #: draw_lock_hint's own circle and gap, plus a line's worth of
            #: air, so this reads as the third line of that column.
            r = AUR_RIM_R1 if AURORA_BLOB else 300.0
            y_msg = SIZE / 2.0 + r + LOCK_HINT_GAP + 44
            ring_r = SIZE / 2.0 - 24.0          # only the glass constrains it
            y_hint = None
        else:
            ring_r = _health_ring_r()
            bottom = SIZE / 2.0 + ring_r - HEALTH_MARK_CLEAR
            y_hint = bottom - 9.0
            y_msg = y_hint - HEALTH_MARK_LEAD
        # The lock hints' own breath, half a beat slower: this is a
        # standing condition, not an invitation.
        breathe = 0.5 + 0.5 * math.sin(now * 1.1)
        a = int(132 + 62 * breathe)
        px = _health_fit(d, msg, HEALTH_MARK_PX, y_msg, ring_r)
        w = _lock_hint_line(d, msg, px, y_msg, a, HEALTH_MARK_INK)
        # A small solid pip at the head of the line, so it reads as a MARK
        # rather than as one more instruction. Solid, because the one thing
        # about this line that must survive a glance is that it is there.
        pipx = (SIZE - w) / 2.0 - 24
        d.ellipse([pipx - 6, y_msg - 6, pipx + 6, y_msg + 6],
                  fill=HEALTH_MARK_INK + (min(255, a + 40),))
        if y_hint is not None:
            hpx = _health_fit(d, HEALTH_MARK_HINT, HEALTH_MARK_HINT_PX,
                              y_hint, ring_r)
            _lock_hint_line(d, HEALTH_MARK_HINT, hpx, y_hint,
                            int(a * 0.60), HEALTH_MARK_INK)
    except Exception:                                   # noqa: BLE001
        pass


LOCK_IMG = Path("/tmp/aura_face/lock.png")
#: ── A THEME MAY OWN ITS OWN DOOR (2026-08-26) ────────────────────────────
#: See the branch in the compositor. Without the key nothing changes: the
#: starfield is still what a row that has not asked for anything gets.
LOCK_FACE = bool(_THEME.get("lock_face"))
LOCK_FACE_DIM = float(_THEME.get("lock_face_dim", 0.52))
LOCK_FACE_BREATH = float(_THEME.get("lock_face_breath", 0.05))
#: where the two hint lines sit on a face-door. Outside the wedge ring and
#: the wordmark, on the bare plaster margin.
#: 452 -> 418: at 452 the two lines land ~500 px out, and this
#: display is ROUND — the plaster disc is essentially the whole
#: screen, so anything past its edge is off the glass rather than
#: on a margin. 418 keeps both lines on plaster: the top one above
#: the baked wordmark, the bottom one below the wedge ring.
LOCK_FACE_R = float(_THEME.get("lock_face_r", 418.0))
LOCK_FACE_FLAT = float(_THEME.get("lock_face_flat", 0.62))

#: Director-card highlight during answers: {"schedule":[...]} (or legacy
#: {"names","until"}). Positions are the portrait centres on scene 8 —
#: MEASURED from the rendered slide by brightness clustering, not derived
#: from grid arithmetic: the derived x for the right column was 60px left
#: of the actual photos, visibly wrong on camera (PRINCIPLES §6 — measure
#: in the environment that applies).
HIGHLIGHT = Path("/tmp/aura_face/highlight.json")
DIRECTOR_POS = {"okafor": (274, 462), "whitfield": (692, 460),
                "vasquez": (274, 637), "raman": (692, 638),
                # Market pack movers (2026-08-01): same card grid as the
                # directors, so the measured centres carry over 1:1 —
                # MSFT/AMZN top row, AAPL/META bottom, reading order.
                "microsoft": (274, 462), "amazon": (692, 460),
                "apple": (274, 637), "meta": (692, 638),
                # Intl pack movers (2026-08-02): the world-affairs rewrite
                # names people, not tickers. Same 2x2 grid, same centres.
                # An unknown mark draws NOTHING (silent absence) — the old
                # intl pack ran with no highlight ring at all because its
                # keys were never added. Keys must match the pack's
                # canned.marks exactly.
                "bin salman": (274, 462), "rubio": (692, 460),
                "zelensky": (274, 637), "teodoro": (692, 638)}


# ---------------------------------------------------------------------------
# The touch panel
# ---------------------------------------------------------------------------
#: ── A MISSING PANEL IS NOT A REASON TO STOP PAINTING (2026-08-21) ─────────
#: `find_touch` raised SystemExit, and it was called ONCE, above the loop.
#: So a Waveshare that had not enumerated yet took the whole compositor
#: down before it drew a single frame, and systemd restarted it straight
#: back into the same absent device. The Ferrari puck's dj_face.log tail is
#: 93 copies of `no touchscreen found` (FAILURES 2026-08-20, where it also
#: cost time as a false lead — an append-only log with no timestamps cannot
#: tell you WHEN, and that tail was two days old).
#:
#: Worse, `touch.read()` in the loop was unguarded, so a USB re-enumeration
#: — which this hardware does — raised OSError out of the input pass and
#: killed a compositor that had been running perfectly for days.
#:
#: A face that cannot take a finger is still worth painting. The clock, the
#: health mark, the briefing and the red deaf face are all still TRUE with
#: no touchscreen attached, and a person in the room can then SEE what is
#: wrong instead of standing in front of a dark puck — which is §1 in its
#: visual form: a black panel and a crashed process look identical, and
#: this face has already taught the owner that lesson once ("the gui
#: froze"). The panel usually comes back, so the answer is to keep drawing,
#: keep looking, and say so on the glass while it is away.
TOUCH_RETRY_S = 3.0
#: The lozenge that says it, in panel coordinates. Low on the glass and
#: clear of both damage rects — the tourbillon aperture is centred and the
#: ribbon rides the ring's arc — so a rect-only repaint cannot half-erase
#: it. scripts/test_touch_survives.py asserts that separation rather than
#: trusting it, because "the fast path ate the warning" is precisely the
#: kind of silent success this file keeps paying for.
TOUCH_NOTE_BOX = (250, 872, 830, 952)

#: dev is the panel or None; gone_since dates the outage; said keeps the
#: retry from printing the same line three times a second; armed is False
#: in every off-device harness, so a preview never wears the banner.
_TOUCH: dict = {"dev": None, "next_try": 0.0, "gone_since": 0.0,
                "said": False, "armed": False}


def find_touch():
    """The Waveshare panel, or None. NEVER raises, never exits.

    Returning None rather than raising is the whole point: the only caller
    is a retry loop now, and a function that exits the process cannot be
    retried.
    """
    try:
        paths = evdev.list_devices()
    except Exception:                                       # noqa: BLE001
        return None
    for path in paths:
        try:
            d = evdev.InputDevice(path)
        except Exception:                                   # noqa: BLE001
            continue                        # enumerating; try again next pass
        try:
            caps = dict(d.capabilities().get(evdev.ecodes.EV_ABS, []))
            if evdev.ecodes.ABS_MT_POSITION_X in caps \
                    and TOUCH_NAME_HINT.lower() in d.name.lower():
                return d
        except Exception:                                   # noqa: BLE001
            pass
        #: CLOSED, because this runs every TOUCH_RETRY_S forever now
        #: instead of once at startup. An InputDevice left open per
        #: non-matching device per retry is a file-descriptor leak that
        #: ends in EMFILE on a device whose job is to run for weeks.
        try:
            d.close()
        except Exception:                                   # noqa: BLE001
            pass
    return None


def touch_acquire(now: float) -> None:
    """Look for the panel, at most every TOUCH_RETRY_S.

    Cheap when it succeeds (returns on the first line) and cheap when it
    fails (one enumeration every three seconds), so this can be called from
    the top of the input pass every frame.
    """
    if _TOUCH["dev"] is not None or now < _TOUCH["next_try"]:
        return
    _TOUCH["next_try"] = now + TOUCH_RETRY_S
    dev = find_touch()
    if dev is None:
        if not _TOUCH["said"]:
            _TOUCH["said"] = True
            if not _TOUCH["gone_since"]:
                _TOUCH["gone_since"] = now
            print(f"touch: NO PANEL (want ABS_MT + name ~ {TOUCH_NAME_HINT}) "
                  f"— the face keeps painting and says so on the glass; "
                  f"retrying every {TOUCH_RETRY_S:.0f}s", flush=True)
        return
    gone = now - _TOUCH["gone_since"] if _TOUCH["gone_since"] else 0.0
    _TOUCH.update(dev=dev, gone_since=0.0, said=False)
    print(f"touch: {dev.path} ({dev.name}) invert={INVERT}"
          + (f" — back after {gone:.0f}s with no panel" if gone else ""),
          flush=True)


def touch_lost(why) -> None:
    """The panel went away mid-read. Drop it and start looking again.

    LOUD, once per outage: a compositor that quietly stops accepting touch
    is indistinguishable from one that is ignoring the person in front of
    it, and that report has already cost this project a session.
    """
    dev, _TOUCH["dev"] = _TOUCH["dev"], None
    now = time.time()
    _TOUCH.update(gone_since=now, next_try=now + TOUCH_RETRY_S, said=True)
    try:
        if dev is not None:
            dev.close()
    except Exception:                                       # noqa: BLE001
        pass
    print(f"touch: PANEL LOST ({why!r}) — not exiting; the face keeps "
          f"painting and retries every {TOUCH_RETRY_S:.0f}s", flush=True)


def _touch_note(im: "Image.Image") -> "Image.Image":
    """Stamp the missing-panel notice onto a finished frame.

    Copies rather than draws in place: the caller's image is very often a
    cached layer (the brick ground, an ember, a pack frame), and painting
    into one of those would leave this notice burnt into every later frame
    long after the panel came back.
    """
    try:
        out = im.convert("RGB") if im.mode != "RGB" else im.copy()
        d = ImageDraw.Draw(out)
        x0, y0, x1, y1 = TOUCH_NOTE_BOX
        d.rounded_rectangle(TOUCH_NOTE_BOX, radius=22, fill=(30, 7, 7),
                            outline=(208, 76, 64), width=3)
        msg = "NO TOUCH PANEL"
        f1, f2 = face("text", 34), face("label", 21)
        d.text(((x0 + x1 - d.textlength(msg, font=f1)) / 2, y0 + 8),
               msg, font=f1, fill=(255, 138, 126))
        gone = time.time() - (_TOUCH["gone_since"] or time.time())
        age = f"{gone / 60:.0f}m" if gone >= 90 else f"{gone:.0f}s"
        #: WHAT STILL WORKS IS THE POINT of a fault notice — but only when
        #: it is TRUE. On the deaf face "she still hears you" would be a
        #: sentence contradicting the padlock two inches above it, and this
        #: glass has already told the owner one confident lie (`tap to
        #: wake`, on a screen whose taps were being eaten, FAILURES
        #: 2026-08-17). One state answers, so the notice cannot disagree
        #: with the face it is stamped on.
        sub = (f"looking for it  ·  {age}" if deaf_now()
               else f"she still hears you  ·  looking for it  ·  {age}")
        d.text(((x0 + x1 - d.textlength(sub, font=f2)) / 2, y0 + 48),
               sub, font=f2, fill=(198, 120, 110))
        return out
    except Exception:                                       # noqa: BLE001
        return im                       # a warning must never eat the frame


# ---------------------------------------------------------------------------
# Framebuffer
# ---------------------------------------------------------------------------

def fb_stride() -> int:
    #: ── OFF-DEVICE IMPORT (2026-08-17) ───────────────────────────────────
    #: This module is imported on the workstation by render and preview
    #: tools (scripts/preview_aurora_wedges.py) that build sprites and
    #: never go near the panel — but STRIDE is computed at import, so on a
    #: machine with no readable /dev/fb0 the import died and the only way
    #: to check a visual change was to ship it to a puck and squint.
    #:
    #: The hatch is OPT-IN and explicit. A puck never sets AURA_FB_STRIDE,
    #: so the real ioctl still runs there and a guessed stride cannot reach
    #: a device by accident — which matters, because this panel's stride is
    #: 8192 and not the 4320 the geometry implies, and getting it wrong
    #: paints diagonal garbage rather than failing.
    _env = os.environ.get("AURA_FB_STRIDE")
    if _env:
        return int(_env)
    with open(FB, "rb") as fb:
        f = fcntl.ioctl(fb, 0x4602, b"\x00" * 80)   # FBIOGET_FSCREENINFO
    return struct.unpack("I", f[48:52])[0]


STRIDE = fb_stride()
WIDTH_BYTES = SIZE * 4
PAD = b"\x00" * (STRIDE - WIDTH_BYTES)


def _glow_ring(im: "Image.Image") -> "Image.Image":
    """Full-circle amber breath at the outer edge, mirroring the LED ring.

    Gated on /tmp/aura_face/glow_ring.json (written ~12 Hz by the ring driver).
    Stale (>3 s) or absent -> the frame is returned untouched, so normal
    operation is unaffected. Brightness breathes on the WALL CLOCK with the
    driver's period, so this panel ring and the physical LED ring pulse in
    lock-step.
    """
    import os, json, time, math
    try:
        st = os.stat("/tmp/aura_face/glow_ring.json")
        if time.time() - st.st_mtime > 3.0:
            return im
        d = json.load(open("/tmp/aura_face/glow_ring.json"))
    except Exception:
        return im
    try:
        per = float(d.get("period", 4.5)) or 4.5
        rgb = d.get("rgb", [255, 140, 20])
        r0, g0, b0 = int(rgb[2]), int(rgb[1]), int(rgb[0])  # panel blit is BGRX -> pre-swap R/B
        br = 0.28 + 0.72 * (0.5 + 0.5 * math.sin(2.0 * math.pi * time.time() / per))
        base = im.convert("RGBA")
        ov = Image.new("RGBA", base.size, (0, 0, 0, 0))
        dd = ImageDraw.Draw(ov)
        c = base.size[0] // 2
        R = int(c * 0.966)
        peak = int(225 * br)
        for dr, wp in ((6, 0.35), (3, 0.60), (0, 1.0), (-3, 0.60), (-6, 0.30)):
            a = max(0, min(255, int(peak * wp)))
            if a <= 0:
                continue
            rr = R + dr
            dd.ellipse((c - rr, c - rr, c + rr, c + rr),
                       outline=(r0, g0, b0, a), width=3)
        return Image.alpha_composite(base, ov).convert("RGB")
    except Exception:
        return im


_NXTOK_FONT = None
def _nx_token_overlay(im):
    """Live NX token counter in the bottom-left black corner. Reads the meter
    summary (/tmp/aura_face/nx_tokens.json); the caller wraps this in
    try/except so it can never break a frame."""
    import json as _json
    from PIL import ImageDraw as _ID, ImageFont as _IF
    global _NXTOK_FONT
    try:
        d = _json.load(open("/tmp/aura_face/nx_tokens.json"))
    except Exception:
        return
    tot = int(d.get("total", 0)); tpm = int(d.get("tpm", 0))
    if _NXTOK_FONT is None:
        for _f in ("/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf",
                   "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"):
            try:
                _NXTOK_FONT = _IF.truetype(_f, 20); break
            except Exception:
                pass
        if _NXTOK_FONT is None:
            _NXTOK_FONT = _IF.load_default()
    txt = "NX  " + format(tot, ",") + " tok   " + str(tpm) + "/min"
    dr = _ID.Draw(im)
    x, y = 20, im.size[1] - 34
    dr.text((x + 2, y + 2), txt, font=_NXTOK_FONT, fill=(0, 0, 0))
    dr.text((x, y), txt, font=_NXTOK_FONT, fill=(233, 164, 74))
    dr.text((x, y - 22), "NX LOCAL LLM", font=_NXTOK_FONT, fill=(110, 100, 86))


def blit(im: Image.Image) -> None:
    #: EVERY screen wears the missing-panel notice, not just the home face:
    #: this is the one funnel every full frame goes through, so the ember,
    #: the brick, the lock screen and the briefing all say it without a
    #: list for someone to forget to join (three separate bugs in this file
    #: came from exactly such a list — see _GLASS_OWNERS). Two dict lookups
    #: on the hot path when the panel is present; the copy is only paid
    #: while it is missing.
    if _TOUCH["armed"] and _TOUCH["dev"] is None:
        im = _touch_note(im)
    # One C pass: the raw encoder emits BGRX with the row stride baked in.
    # Byte-identical to the old split/merge/PAD.join path (proved on this
    # panel: visible rows equal, pad bytes zero, X byte zero) and 14.63 ->
    # 2.99 ms per frame there — perf round three, 2026-08-08.
    if im.mode != "RGB":
        im = im.convert("RGB")
    im = _glow_ring(im)
    try:
        _nx_token_overlay(im)
    except Exception:
        pass
    FB.write_bytes(im.tobytes("raw", "BGRX", STRIDE, 1))


def blit_rect(im: Image.Image, x: int, y: int) -> None:
    """ONE rectangle of the panel: seek to each row, write that row only.

    Same write pattern as fb_blit.blit_rect (which carries the bench and can
    be run standalone); it lives here too because this loop keeps STRIDE
    cached and must not pay an ioctl per paint.

    MEASURED ON THE PUCK, 2026-08-07 (see TOURB_RECT_FPS): 0.76 ms for a
    200x200 rect against 17.99 ms for the full 1080x1080 frame — 4.3% of the
    time for 3.4% of the pixels. Out of bounds raises rather than wrapping
    into the next row, which would smear ink somewhere else on the panel.
    """
    w, h = im.size
    if x < 0 or y < 0 or x + w > SIZE or y + h > SIZE:
        raise ValueError(f"rect {w}x{h} at ({x},{y}) leaves the panel")
    r, g, b = im.convert("RGB").split()
    a = Image.new("L", (w, h), 0)
    raw = Image.merge("RGBA", (b, g, r, a)).tobytes()   # BGRX
    row_bytes = w * 4
    with open(FB, "r+b") as fb:
        for row in range(h):
            fb.seek((y + row) * STRIDE + x * 4)
            fb.write(raw[row * row_bytes:(row + 1) * row_bytes])


# ---------------------------------------------------------------------------
# Layers
# ---------------------------------------------------------------------------

#: The coastline the bolt layer traces since 2026-08-06 — Te Ika-a-Māui and
#: Te Waipounamu as (lon, lat), coarse on purpose: ~35 points an island is
#: all that survives a 1-pixel line under a jitter of ±7, and every extra
#: vertex is drawing time at every layer push. Stewart Island is left out
#: for the same reason it vanishes on a car sticker: at this scale it is
#: three pixels and reads as a smudge, not an island.
_NZ_COAST = (
    # North Island, clockwise from Cape Reinga
    ((172.68, -34.43), (173.05, -34.42), (173.55, -34.95), (174.32, -35.72),
     (174.80, -36.30), (175.42, -36.48), (175.55, -36.90), (176.17, -37.68),
     (176.95, -37.55), (177.90, -37.60), (178.55, -37.69), (178.30, -38.20),
     (178.02, -38.66), (177.90, -39.30), (176.90, -39.48), (176.60, -40.30),
     (176.20, -40.90), (175.29, -41.61), (174.90, -41.42), (174.78, -41.29),
     (174.85, -40.60), (175.05, -39.93), (174.30, -39.55), (173.75, -39.28),
     (174.07, -39.06), (174.60, -38.60), (174.82, -38.07), (174.65, -37.55),
     (174.50, -37.00), (174.55, -36.40), (173.90, -35.95), (173.40, -35.40),
     (173.16, -35.17), (172.95, -34.80)),
    # South Island, clockwise from Cape Farewell
    ((172.68, -40.50), (173.15, -40.85), (173.28, -41.27), (173.85, -40.95),
     (174.33, -41.02), (174.05, -41.42), (174.27, -41.72), (173.70, -42.42),
     (173.05, -43.05), (172.75, -43.55), (173.10, -43.80), (172.40, -43.85),
     (171.90, -44.10), (171.25, -44.40), (171.00, -45.10), (170.65, -45.87),
     (169.80, -46.45), (168.90, -46.60), (168.35, -46.60), (167.70, -46.35),
     (166.95, -46.20), (166.55, -45.95), (166.75, -45.35), (167.30, -44.80),
     (168.10, -44.30), (168.60, -43.97), (169.50, -43.45), (170.30, -43.10),
     (170.96, -42.72), (171.35, -42.20), (171.60, -41.75), (172.10, -40.95),
     (172.40, -40.70)),
)

#: How much of the panel's height the map spans. 0.78 keeps the southern tip
#: and Cape Reinga well inside the ROUND glass: at y = 0.11H the visible
#: half-width is 324 px, and the widest the coast gets up there is ~160.
_NZ_HEIGHT = 0.78

#: OFF with the Patek pass (2026-08-06 evening) — a map of another country
#: drawn in lightning is not furniture a watch dial has. SWITCHED, NOT
#: DELETED: the projection, the aspect correction at 40°S and the per-push
#: jitter are the part that cost the time, and the next room to ask for a
#: themed dial wants them back as one line rather than as an afternoon.
#: The CENTRAL bolt is baked in home.html and is untouched by this — it keeps
#: BOLT_SURGE_GAIN and the tap acknowledgement, and against a blue-black dial
#: in rose gold it reads as a crack of light rather than as a storm.
_COAST_ON = False


def _widen_bolt(im: Image.Image) -> Image.Image:
    """Round 3 (2026-08-02, third request): "make the lightning things
    more randomly jagged to cover the width of the screen randomly.
    they are all the same just in parallel right now" — round 2's offset
    echoes WERE parallel copies, and the owner's eye caught it. Now:
    independent procedural strikes, each its own random walk down the
    face with occasional branches, regenerated fresh at every layer
    push (~20s), so the storm never repeats. Still once-per-push, never
    per-frame.

    Round 4 (2026-08-06, spoken with the New Zealand pass — "make the
    outline, that lightning outline in the background, an outline of
    [Aotearoa]"): the random walks are gone and the strikes now trace the
    two islands. Everything else is deliberately unchanged — same two-pass
    glow, same colours (which desertify() converts to pounamu anyway, so
    only their LUMINANCE matters here), same once-per-push regeneration.
    The jitter is re-rolled at every bake, so the coast crackles instead
    of sitting still, and a few sparks still fly off it: the owner asked
    for the outline to become a map, not for the lightning to stop.

    Round 5 (2026-08-06, evening, with the Patek pass): _COAST_ON is False
    and this returns the pushed layer UNCHANGED — the bolt.png the RTX baked,
    which is the central fracture on its own. Everything below is left
    standing behind that switch for the reason the constant's note gives."""
    if not _COAST_ON:
        return im
    import random
    W, H = im.size
    canvas = Image.new("RGB", im.size, (0, 0, 0))
    dd = ImageDraw.Draw(canvas)
    # Fit both islands into a centred band at the map's OWN aspect: a degree
    # of longitude at 40S is cos(40.5) = 0.76 of a degree of latitude, and
    # without that correction the country comes out visibly fat.
    lons = [p[0] for isl in _NZ_COAST for p in isl]
    lats = [p[1] for isl in _NZ_COAST for p in isl]
    lon0, lon1 = min(lons), max(lons)
    lat0, lat1 = min(lats), max(lats)
    span_y = H * _NZ_HEIGHT
    span_x = span_y * ((lon1 - lon0)
                       * math.cos(math.radians((lat0 + lat1) / 2.0))
                       / (lat1 - lat0))
    ox, oy = (W - span_x) / 2.0, (H - span_y) / 2.0

    def _xy(lon, lat):
        return (ox + (lon - lon0) / (lon1 - lon0) * span_x,
                oy + (lat1 - lat) / (lat1 - lat0) * span_y)

    for isl in _NZ_COAST:
        ring = [_xy(*p) for p in isl]
        ring.append(ring[0])                             # close the coast
        pts = []
        for (ax, ay), (bx, by) in zip(ring, ring[1:]):
            steps = max(1, int(math.hypot(bx - ax, by - ay) / 26.0))
            for i in range(steps):
                f = i / steps
                pts.append((ax + (bx - ax) * f + random.uniform(-7, 7),
                            ay + (by - ay) * f + random.uniform(-7, 7)))
        pts.append(pts[0])
        # AS BRIGHT AS THE CENTRAL BOLT (owner, 2026-08-06: "make the new
        # zealand outline as bright as the central lightning bolt").
        #
        # MEASURED, because the hue here is decorative and the LUMINANCE is
        # not: desertify() re-maps this whole frame through a duotone, so
        # only L survives to the glass. The central bolt in bolt.png runs
        # p75=246, p90=249, max=249 — it is essentially a white line with a
        # dimmer halo. The coast was (95,142,205), L=135, which is why it
        # read as a ghost beside it.
        #
        # (232,246,255) is L=244, inside the bolt's own range rather than
        # past it: brighter than the bolt would make the decoration louder
        # than the subject. Width goes 1 -> 2 for the same reason the bolt
        # is not hairline — a 1px line at this luminance shimmers under the
        # per-push jitter instead of reading as a coastline.
        col = (232, 246, 255)
        dd.line(pts, fill=(52, 104, 150), width=5)       # soft glow pass
        dd.line(pts, fill=col, width=2)
        for _ in range(random.randint(2, 4)):            # sparks off the coast
            sx, sy = random.choice(pts)
            spts = [(sx, sy)]
            for _b in range(random.randint(1, 3)):
                sx = max(0.0, min(float(W), sx + random.uniform(-45, 45)))
                sy = max(0.0, min(float(H), sy + random.uniform(-45, 45)))
                spts.append((sx, sy))
            dd.line(spts, fill=(120, 170, 210), width=1)
    return ImageChops.screen(im, canvas)


#: Ignore a stray value or two when deciding where a layer's ink actually
#: is. Once the capture stopped baking #030308 into the overlays (see the
#: layer-capture note in home.html) they are genuinely black outside their
#: marks, but a lone 1 from PNG rounding must not drag the box out to the
#: full canvas — which is exactly what it did while the floor was there.
_INK_FLOOR = 2

#: Grow the measured box by a few pixels before trusting it. Cheap, and it
#: means a rounding difference between one capture and the next cannot clip
#: an edge that was inside the box yesterday.
_INK_PAD = 6


#: Returned by _ink_box when the overlay has NO marks at all. See §2 in the
#: note there: "all black" and "not worth cropping" are different answers and
#: they used to share a return value.
INK_EMPTY = "empty"


def _ink_box(im: Image.Image):
    """Where this overlay actually has marks; INK_EMPTY if it has none;
    None if it has marks but boxing them buys nothing.

    Only meaningful for the SCREEN-BLENDED overlays. Black contributes
    nothing to a screen blend, so everything outside this box is a full-frame
    operation computing `x screen 0 == x`, which was 8.3 ms of every frame
    at 1080 square on the panel — for rings and bolt both.

    ── 2026-08-12: THREE OUTCOMES, AND THE MISSING ONE WAS THE COMMON CASE ──
    This returned None for "the layer is entirely black" AND for "the box is
    nearly the whole canvas", and the caller read None as *composite the full
    frame*. So a layer with NOTHING ON IT took the most expensive branch
    available — the exact case that needs no work at all got the most.

    It is not hypothetical and it was not rare. Measured on the live fleet:
    rings.png is entirely black on BOTH pucks and bolt.png is entirely black
    on the chopard one — max channel value 0, not "nearly" black. The chopard
    puck was spending 24.6 ms screening an empty rings layer and 15.2 ms
    screening an empty bolt layer, 40 ms of a 91 ms frame, computing
    `x screen 0` a million times per layer per frame. The log line even
    announced it: "layer bolt: ink fills the canvas — compositing full
    frame", about an image with no ink in it.

    PRINCIPLES §2, exactly: a test with three real answers was given two
    return values, and the uncertain one fell into whichever branch the
    arithmetic happened to produce."""

    box = im.convert("L").point(
        lambda p: 255 if p >= _INK_FLOOR else 0).getbbox()
    if box is None:
        return INK_EMPTY
    x0, y0, x1, y1 = box
    box = (max(0, x0 - _INK_PAD), max(0, y0 - _INK_PAD),
           min(im.width, x1 + _INK_PAD), min(im.height, y1 + _INK_PAD))
    # A box that is nearly the whole canvas buys nothing and costs a crop,
    # so say so and let the caller keep the simple path.
    w, h = box[2] - box[0], box[3] - box[1]
    if w * h > 0.92 * im.width * im.height:
        return None
    return box


def _base_bake_path() -> Path:
    """The FILE the standing bake actually comes from, for this theme.

    ── ONE PLACE STATES IT (2026-08-26, §15) ────────────────────────────
    Layers.refresh has resolved this since 08-22 and was the only thing
    that knew: a BAKE_FINAL row ships finished pixels beside dj_face or
    under packs/, everything else takes home.html's bake out of /tmp. The
    relief panes' type sampler has to read THE SAME FILE the compositor is
    drawing — sampling one bake and compositing another would raise a
    label that is not the label on the glass, and it would look exactly
    right until the two disagreed.

    It answers with a path whether or not the file exists; the caller
    decides what a missing bake means, because the two callers mean
    different things by it.
    """
    if BAKE_FINAL:
        _here = Path(__file__).resolve().parent
        for _cand in (_here / _THEME["base"], _here / "packs" / _THEME["base"]):
            if _cand.exists():
                return _cand
    return LAYERS / "base.png"


class Layers:
    def __init__(self) -> None:
        self.base = self.rings = self.bolt = None
        #: Ink boxes for the two screen-blended overlays, recomputed on every
        #: load because the RTX re-bakes these files every 20s.
        self.rings_box = self.bolt_box = None
        self.rings_empty = self.bolt_empty = False
        self.rings_ink = self.bolt_ink = None
        self.mtimes = {}

    def _load(self, p: Path):
        im = Image.open(p).convert("RGB")
        if im.size != (SIZE, SIZE):
            im = im.resize((SIZE, SIZE))
        return im

    def refresh(self) -> bool:
        """Reload any layer whose file changed. True if something loaded."""
        changed = False
        for name in ("base", "rings", "bolt"):
            p = LAYERS / f"{name}.png"
            #: ── A BAKE_FINAL THEME BRINGS ITS OWN BASE (2026-08-22) ────
            #: Same two homes as the themed bezel (bezel_steel's note):
            #: beside dj_face.py on a puck, under packs/ in the repo. A
            #: theme that names a base and cannot find it FALLS THROUGH to
            #: /tmp's bake and SAYS SO — a gallery face silently wearing
            #: another face's dark bake would be the wrong picture with
            #: nothing in the log (§1).
            #: the resolution itself is _base_bake_path (§15, 2026-08-26);
            #: what stays here is what THIS caller does when the named bake
            #: is nowhere, which is to say so once and carry on.
            if name == "base" and BAKE_FINAL:
                p = _base_bake_path()
                if p == LAYERS / "base.png" \
                        and not self.mtimes.get("base_missing_said"):
                    self.mtimes["base_missing_said"] = True
                    print(f"layer base: theme names {_THEME['base']!r} "
                          f"and it is NOWHERE — falling through to "
                          f"{LAYERS}/base.png, which is another face's "
                          f"bake", flush=True)
            try:
                m = p.stat().st_mtime
            except FileNotFoundError:
                continue
            if self.mtimes.get(name) != m:
                try:
                    im = self._load(p)
                    if name == "bolt":
                        im = _widen_bolt(im)
                    setattr(self, name, im)
                    if name in ("rings", "bolt"):
                        self._measure_ink(name, im)
                    self.mtimes[name] = m
                    changed = True
                    if name == "base" and BAKE_FINAL:
                        # which FILE, not just "loaded" — landing on the
                        # fallback looks identical otherwise (§1)
                        print(f"layer base: {FACE_THEME} wears its own "
                              f"finished bake — {p}", flush=True)
                except Exception as e:      # half-written file: try next tick
                    print(f"layer {name}: {e!r}", flush=True)
        if self.base is None and LEGACY_FRAME.exists():
            try:
                m = LEGACY_FRAME.stat().st_mtime
                if self.mtimes.get("legacy") != m:
                    self.base = self._load(LEGACY_FRAME)
                    self.mtimes["legacy"] = m
                    changed = True
            except Exception:
                pass
        return changed

    def _measure_ink(self, name: str, im: Image.Image) -> None:
        """Work out, once per bake, which part of an overlay is worth
        compositing. Logged, because a box that quietly became the whole
        canvas is the difference between 61% of a core and 98%."""
        box = _ink_box(im)
        # RINGS IS MEASURED NOW, FOR EMPTINESS ONLY. The note at the rings
        # composite rejects CROPPING it — a centred crop rotated about its own
        # centre is not equivalent to rotating the full frame, measured at up
        # to 62 levels apart — and that rejection stands. Skipping a layer
        # that is entirely black is a different claim and an exact one:
        # `x screen 0 == x` for every pixel, at every angle, and rotating an
        # all-black image gives an all-black image. So rings may be SKIPPED
        # but never CROPPED, and it never gets a box.
        setattr(self, f"{name}_empty", box is INK_EMPTY)
        if name == "rings":
            box = None
        if box is INK_EMPTY:
            box = None
        ink = im.crop(box) if box else None
        setattr(self, f"{name}_box", box)
        setattr(self, f"{name}_ink", ink)
        if getattr(self, f"{name}_empty"):
            print(f"layer {name}: NO INK AT ALL — skipped entirely, not "
                  f"composited (saves a full-frame screen every frame)",
                  flush=True)
        elif box is None:
            print(f"layer {name}: ink fills the canvas — compositing full "
                  f"frame", flush=True)
        else:
            pct = (box[2] - box[0]) * (box[3] - box[1]) * 100.0 / (SIZE * SIZE)
            print(f"layer {name}: ink box {box} = {pct:.0f}% of the frame",
                  flush=True)


# ---------------------------------------------------------------------------
# Touch → rotation physics
# ---------------------------------------------------------------------------

class Rotation:
    def __init__(self) -> None:
        self.deg = 0.0
        self.vel = 0.0
        self.dragging = False
        self.inertia = False
        #: Per-mode: the home face's 1.4 was owner-approved by feel, but
        #: the countdown screen with the same value reads as frictionless
        #: ("spin speed is really fast... doesn't have enough friction").
        #: The main loop sets this per screen.
        self.friction = FRICTION
        self.finger_ang = 0.0       # last raw finger angle, SCREEN frame
        self.finger_r = 0.0         # last finger radius from center, px
        self.finger_xy = (0.0, 0.0)  # last finger position, for slide gestures
        self._last_a = 0.0          # previous sample's raw finger angle
        self._acc = 0.0             # gain-scaled degrees travelled this drag
        self._hist: list = []       # (t, _acc) ring buffer for flick speed

    @staticmethod
    def _ang(x: float, y: float) -> float:
        return math.degrees(math.atan2(y - SIZE / 2, x - SIZE / 2))

    @staticmethod
    def _gain(r: float) -> float:
        """Angular gain by touch radius (2026-08-02 morning). Dead inside
        ROT_DEAD_R, ramping to exact 1:1 at ROT_FULL_R — see the constants
        for the owner quote. Applied per-delta, so it also tames the flick
        velocity a centered finger can impart."""
        if r < ROT_DEAD_R:
            return 0.0
        return min(1.0, (r - ROT_DEAD_R) / (ROT_FULL_R - ROT_DEAD_R))

    def press(self, x: float, y: float) -> None:
        self.dragging, self.inertia, self.vel = True, False, 0.0
        self.finger_ang = self._ang(x, y)
        self.finger_r = math.hypot(x - SIZE / 2, y - SIZE / 2)
        self._last_a = self.finger_ang
        self._acc = 0.0
        self._hist = [(time.time(), 0.0)]
        self.press_t = time.time()
        self.press_xy = (x, y)
        self.finger_xy = (x, y)
        self.moved = 0.0

    def move(self, x: float, y: float) -> None:
        if not self.dragging:
            return
        self.moved = max(self.moved, math.hypot(x - self.press_xy[0],
                                                y - self.press_xy[1]))
        self.finger_xy = (x, y)
        a = self._ang(x, y)
        now = time.time()
        # Incremental deltas (2026-08-02) instead of the old grab-angle
        # model: each step scales with the touch-radius gain, which a
        # fixed grab offset cannot express. The deferred press survives —
        # deltas inside the tap threshold are dropped, so a possible tap
        # still does not rotate and there is no jump on crossing it.
        delta = (a - self._last_a + 540.0) % 360.0 - 180.0
        self._last_a = a
        self.finger_ang = a
        self.finger_r = math.hypot(x - SIZE / 2, y - SIZE / 2)
        if self.moved >= TAP_MAX_PX:
            step = delta * self._gain(self.finger_r)
            self.deg = (self.deg + step) % 360.0
            self._acc += step
        self._hist.append((now, self._acc))
        while self._hist and now - self._hist[0][0] > 0.09:
            self._hist.pop(0)

    def release(self):
        """Returns (x, y) if this press was a TAP, else None."""
        if not self.dragging:
            return None
        self.dragging = False
        if self.moved < TAP_MAX_PX \
                and time.time() - self.press_t < TAP_MAX_S:
            return self.press_xy
        v = 0.0
        if len(self._hist) >= 2:
            (t0, a0), (t1, a1) = self._hist[0], self._hist[-1]
            if t1 > t0:
                v = (a1 - a0) / (t1 - t0)   # _acc never wraps; plain diff
        # Clamp AFTER release only (2026-08-02): the drag itself stays
        # direct, but the momentum a flick hands over is capped at a
        # speed a real dial could plausibly carry.
        v = max(-MAX_DPS, min(MAX_DPS, v))
        if abs(v) >= INERTIA_MIN_DPS:
            self.vel, self.inertia = v, True
        return None

    def tick(self, dt: float) -> None:
        if self.inertia:
            self.deg = (self.deg + self.vel * dt) % 360.0
            self.vel *= math.exp(-self.friction * dt)
            if abs(self.vel) < STOP_DPS:
                self.vel, self.inertia = 0.0, False

    @property
    def moving(self) -> bool:
        return self.dragging or self.inertia


#: A tap that will open a mode, once the bolt has had its moment.
_PENDING = {"wedge": None, "at": 0.0, "deg": 0.0}
#: Long enough to SEE the flare (it decays over BOLT_SURGE_S = 0.6s), short
#: enough that it reads as the device responding rather than lagging.
WEDGE_OPEN_DELAY_S = 0.42


def open_pending(rot: "Rotation") -> None:
    """Open the mode a tap asked for, after the pause. Called every frame."""
    wedge = _PENDING["wedge"]
    if not wedge or time.time() - _PENDING["at"] < WEDGE_OPEN_DELAY_S:
        return
    _PENDING["wedge"] = None
    deg = _PENDING["deg"]
    if wedge == "lock":
        # Remember where we bricked from, so waking restores it. THE
        # ORIGIN IS THE WHOLE DIFFERENCE between this and a voice mute —
        # see deaf_origin. Same one deaf state either way.
        deaf_enter("lock" if LOCKED.exists() else "home")
        print("tap: BRICKED — going red and deaf", flush=True)
    elif wedge == "sterling":
        # A modal screen, not a 6s card — it stays until DONE or a takeover.
        _STERLING.update(view_deg=0.0, view_prev_ang=None, grab_deg=deg)
        _sterling_set(True, "tap on the STERLING wedge")
    elif wedge == "requests":
        _REQ_CARD.update(view_deg=0.0, view_prev_ang=None, grab_deg=deg)
        _requests_card_set(True, "tap on the REQUESTS wedge")
    elif wedge == "patients":
        _PAT_CARD.update(view_deg=0.0, view_prev_ang=None, grab_deg=deg)
        _patients_card_set(True, "tap on the PATIENTS wedge")
    elif wedge in ("world", "iran"):
        # The reading surface for the headlines ALREADY EXISTS: the
        # briefing card the conductor writes while she reads. Same file,
        # same modal law (any tap closes, ~4 min freshness cap), no third
        # card to keep in step with two others. Either outcome is said
        # out loud — a tap that opens nothing must say why (§1).
        #
        # Both news tenants of the free arc come through here (the IRAN
        # watch joined on 2026-08-09): one card, one freshness rule, and
        # the topic on it is whichever wedge was under the finger.
        try:
            _wb = _world_brief() if wedge == "world" else _iran_brief()
        except Exception:                       # noqa: BLE001
            _wb = None
        if _wb:
            try:
                BRIEFING_CARD.write_text(json.dumps(
                    {"topic": _wb["topic"], "lines": _wb["lines"],
                     "at": time.time()}))
                print(f"tap: {wedge.upper()} — headlines on the glass",
                      flush=True)
            except Exception as e:              # noqa: BLE001
                print(f"{wedge}: card not written {e!r}", flush=True)
        else:
            print(f"{wedge}: no brief to open — tap ignored", flush=True)
    elif wedge == "settings":
        _settings_open(rot)
    elif wedge == "volume":
        _VOL["level"] = _read_volume()
        # In RING positions (0..12), not table indices — the two are not the
        # same thing and conflating them is what capped the dial at 77%.
        _VOL["detent"] = pct_detent(_VOL["level"])
        _VOL["open"] = True
        #: hold the card while the dial is up — see _click_open. A detent
        #: tick cannot afford a 164 ms process spawn, and nothing else
        #: speaks while a modal volume dialog owns the glass.
        _click_open()
        _VOL["view_deg"] = 0.0
        _VOL["view_prev_ang"] = None
        _VOL["drag_role"] = None
        _VOL["grab_deg"] = deg
        print(f"tap: volume mode ({_VOL['level']}%)", flush=True)


#: ── WHO OWNS THE GLASS RIGHT NOW ──────────────────────────────────────
#: One entry per full-screen overlay: (name, predicate). The MODAL LAW in
#: handle_tap's docstring says every tap belongs to whatever is open, and
#: this is where "whatever is open" is actually defined.
#:
#: Ordered loosely by how absolute the claim is — a bricked or sleeping
#: device outranks a card — but the order only affects which NAME is
#: reported, since any hit means the ring keeps its hands off.
#: 2026-08-21: "bricked" and "muted" are now two NAMES FOR ONE STATE, not
#: two states — both answer from deaf_now(), and what separates them is the
#: only thing that ever did: whether an origin screen is remembered. They
#: stay as two rows because this is what the log line names when a screen
#: eats a tap, and "bricked" (somebody shut this puck) versus "muted"
#: (somebody told her to be quiet) is worth having in the journal at 2am.
#: Neither can now be up without the other's screen agreeing, which is what
#: the collapse was for.
_GLASS_OWNERS = (
    ("bricked", lambda now: deaf_now() and bool(deaf_origin())),
    ("muted", lambda now: deaf_now()),
    ("sleeping", lambda now: SLEEPING.exists()),
    ("locked", lambda now: LOCKED.exists()),
    ("countdown", lambda now: COUNT.exists()),
    ("scene", lambda now: SCENE.exists()),
    ("login", lambda now: LOGIN.exists()),
    ("briefing", lambda now: _show_now(now) is not None),
    ("power-confirm", lambda now: _POWER["until"] > now),
    ("power-error", lambda now: _POWER["error_until"] > now),
    ("volume", lambda now: bool(_VOL["open"])),
    ("settings", lambda now: bool(_SET["open"])),
    ("sterling", lambda now: bool(_STERLING["open"])),
    ("requests-card", lambda now: bool(_REQ_CARD.get("open"))),
    ("patients-card", lambda now: bool(_PAT_CARD.get("open"))),
    ("topup", lambda now: bool(_TOPUP.get("open"))),
)


def glass_owner(now: float) -> "str | None":
    """Which overlay owns the glass, or None for the home face.

    Never raises: a predicate that throws must not take the tap handler
    with it, and the safe answer when we cannot tell is "somebody does" —
    a tap that reaches nothing costs one repeat, a ring that steals a
    power-off confirmation costs the thing he was trying to do.
    """
    for name, pred in _GLASS_OWNERS:
        try:
            if pred(now):
                return name
        except Exception as exc:                            # noqa: BLE001
            _AUR.setdefault("said", set())
            _k = f"owner:{name}"
            if _k not in _AUR["said"]:
                _AUR["said"].add(_k)
                print(f"tap: glass_owner({name}) raised {exc!r} — assuming "
                      f"it owns the glass", flush=True)
            return name
    return None


def handle_tap(xy, rot: "Rotation") -> None:
    """A tap: request a briefing from the BRIEFING wedge, abort during one.

    On the aurora face this ALSO raises the wedge ring out of the void —
    every tap, whatever it turns out to mean, because a hand on the glass
    is the one unambiguous request for controls (see AUR_UI_HOLD_S).

    Hit-testing happens in the FACE's coordinates: undo the display rotation
    on the touch point before comparing against the wedge sector. The sign
    of that correction is empirical (panel + PIL conventions stacked); if
    taps log the right radius but a mirrored angle, flip TAP_ANG_SIGN.

    MODAL LAW (round 2, 2026-08-02): while any overlay mode is open —
    volume, settings, the Sterling screen, a power prompt — EVERY tap
    belongs to it and returns from its branch. The wedge ring underneath
    is unreachable, so no second mode can stack on the first, and every
    exit lands on the HOME face. The owner hit the gap this closes: the
    old Sterling card had no tap branch at all, so a tap "outside the
    boundary" opened settings ON TOP of it, and exiting settings landed
    back on the card instead of home.
    """
    x, y = xy
    #: ── ACKNOWLEDGE BEFORE DECIDING (2026-08-17, §13) ────────────────────
    #: FIRST line of the handler, before a single branch has worked out what
    #: this tap means — because the acknowledgment is not a report of the
    #: outcome, it is a report that the glass felt the finger. A tap that
    #: turns out to do nothing still gets the tock; a tap on a pane that is
    #: still arriving still gets it. Both of those were reported today as
    #: the device ignoring him, and in both cases it had heard perfectly
    #: well and simply said nothing.
    _ui_sound("tap")
    #: ── THE RING BLOCK MUST NOT EAT ANOTHER SCREEN'S TAPS (2026-08-17) ───
    #: This is the bug behind two separate complaints today, and it is
    #: PRINCIPLES §7 in its purest form: two gates on one signal, the first
    #: silently vetoing, and the symptom in both cases being "the data
    #: never arrived".
    #:
    #: The owner, on the muted screen: "i am still stuck on my lock screen
    #: no touch will remove it." It was not the lock screen — the panel was
    #: showing BRICKED, which wears a padlock and the words NOT LISTENING /
    #: tap to wake. His taps were arriving. The log said what happened to
    #: them:
    #:     tap: aurora ring summoned (screen=-95 logical=-122)
    #:     tap: aurora ring dismissed (screen=-6 logical=-34)
    #:     tap: aurora ring summoned ...
    #: The unbrick handler is 120 lines below this block, and this block
    #: RETURNS on every tap that is not on a pane. So the screen that owned
    #: the glass never saw a finger, and the one instruction printed on it
    #: — tap to wake — was a lie the device told him repeatedly.
    #:
    #: The same veto is why DONE could not be pressed: with the volume
    #: overlay up, a tap off the wedge sectors was consumed here as a
    #: "dismiss" and the volume branch below was never reached. Everything
    #: measured about angles and frames this morning was measured on taps
    #: that were already gone.
    #:
    #: So: the ring is a HOME-FACE control, and it only gets the tap when
    #: the home face is what is on the glass. The list is the same one the
    #: compositor uses to decide it is `blocked`, plus the overlays that
    #: each own the whole glass by the modal law in this docstring.
    #: a running briefing owns the glass too — see the branch below
    _show_up = _show_now(time.time()) is not None
    #: ── AND THE POWER CONFIRM OWNS IT TOO (2026-08-18) ──────────────────
    #: Owner: "power slide still is being interfered with by the underlying
    #: GUI." The log is this bug's own docstring, one screen later:
    #:
    #:     power: confirm overlay armed, from the wedge
    #:     tap: aurora ring dismissed (screen=-129 logical=149)
    #:     tap: aurora ring summoned [...]
    #:     power: confirm expired — cancelled
    #:
    #: The overlay armed correctly. Every tap after it went to the RING,
    #: because the power confirm was the one full-glass overlay missing
    #: from this list, so `_owned` stayed False and the block above ate
    #: them. The confirm then timed out having never been touched.
    #:
    #: There IS a power branch in this handler and it is 500 lines below —
    #: unreachable for exactly the reason the note above describes for the
    #: volume DONE button and the BRICKED screen. Third time: an overlay
    #: that owns the glass must be named HERE, or its taps never arrive.
    #: The list is the fix and the list is also the flaw — every new
    #: overlay has to remember to join it, and two have now failed to.
    #: ── THE LIST IS THE FLAW; ASK THE REGISTRY (2026-08-18) ─────────────
    #: Three separate bugs have now come from an overlay not being named
    #: here: the volume DONE button, the BRICKED screen's tap handler, and
    #: this morning's power confirm. Each time the fix was "add it to the
    #: list", and each time the list was the thing that failed.
    #:
    #: `glass_owner()` is the single question now, and every overlay
    #: registers its own predicate NEXT TO ITS OWN STATE rather than in a
    #: boolean five hundred lines away. Adding an overlay and forgetting to
    #: come here is still possible — but scripts/test_modal_taps.py can now
    #: enumerate the registry and say which screens are covered, which is
    #: what turns "we forgot" from a live bug into a failing test.
    #:
    #: It also names the owner instead of returning a bare True, so the log
    #: line says WHICH screen ate a tap. Every one of the three bugs cost
    #: time because the symptom was "the ring reacted" with no clue as to
    #: who should have got it instead.
    _owner = glass_owner(time.time())
    _owned = _owner is not None
    if _show_up:
        #: ── A FINGER STOPS THE BRIEFING (2026-08-17) ────────────────────
        #: The same signal his voice uses. BARGE_FLAG is what `player.play`
        #: in puck_conduct watches to kill the clip in hand, and what
        #: run_show now watches to end the whole show — so a tap and "hey
        #: aura, wait a second" travel the same wire and cannot disagree
        #: about what stopping means.
        #:
        #: Single tap, not double: this is the one gesture where being too
        #: eager costs a briefing you can restart with a sentence, and
        #: being too reluctant means sitting through three more minutes you
        #: asked twice to stop (§8).
        try:
            BARGE_FLAG.parent.mkdir(parents=True, exist_ok=True)
            BARGE_FLAG.touch()
            print("tap: BRIEFING interrupted by touch", flush=True)
        except Exception as exc:                        # noqa: BLE001
            print(f"tap: could not interrupt the briefing ({exc!r})",
                  flush=True)
        return
    if _owned and _owner:
        _AUR.setdefault("said", set())
        _k = f"yield:{_owner}"
        if _k not in _AUR["said"]:
            _AUR["said"].add(_k)
            print(f"tap: ring stands down — {_owner} owns the glass",
                  flush=True)
    if TAP_WEDGES and not AURORA_BLOB and not _owned:
        #: ── THE BAKED FACE GETS AURORA'S GRAMMAR (2026-08-24) ────────────
        #: Owner: "there is no fade in fade out for the wedges when you
        #: press the screen." On aurora a tap summons a hidden ring and
        #: does nothing else; a tap on a visible pane presses it. The baked
        #: faces had no such state — the wedges are in the bake, so they
        #: were simply always there.
        #:
        #: Same grammar here, driven through the veil: hidden -> reveal and
        #: SWALLOW the tap, so calling the controls up does not also press
        #: one. That was the "bizarre transition behaviour" aurora had in
        #: August and there is no reason to reintroduce it.
        if not baked_ui_visible():
            baked_ui_show(time.time())
            print("tap: wedges summoned (baked face)", flush=True)
            return
        #: visible: fall through to the normal handling, but keep them up
        #: — touching the glass is exactly when they should not time out.
        baked_ui_show(time.time())
    if AURORA_BLOB and not _owned:
        #: ── ONE TAP DOES ONE THING (2026-08-16) ──────────────────────────
        #: A tap used to summon the ring AND fire whatever wedge it landed
        #: on, so calling the controls up also pressed one — the "bizarre
        #: transition behaviour". Now: hidden ring, a tap only summons;
        #: visible ring, a tap on a pane presses it and a tap ANYWHERE
        #: ELSE dismisses. That is the whole grammar, and it matches what
        #: a person expects from a menu that had to be asked for.
        #: ── THIS BLOCK OWNS ITS OWN GEOMETRY (fixed 2026-08-17, 00:27) ───
        #: It first used `logical` and `r`, which are computed FURTHER DOWN
        #: this function — so the first tap after the aurora HUD shipped
        #: raised NameError, handle_tap died, and the compositor with it.
        #: The owner's report was "i just talked to my puck and the gui
        #: froze": the panel holds the last frame when the process exits,
        #: so a dead face and a still one look identical from the chair.
        #:
        #: The angle and radius are three lines of arithmetic; taking them
        #: here rather than reaching down the function is both the fix and
        #: the reason it cannot happen again.
        #:
        #: TWO ANGLES, AND THEY ARE NOT INTERCHANGEABLE (2026-08-17):
        #:   _ang  — where the finger is ON THE GLASS. The seat block below
        #:           wants this one, because a seat is a real direction in
        #:           the room and does not turn when the dial does.
        #:   _lang — the same point in the DIAL's frame. The wedges want
        #:           this one, now that the ring paints before the rotate
        #:           and turns with the bezel. Same formula as `logical`
        #:           further down; deliberately the same, so there is one
        #:           convention on this face and not two.
        _ang = math.degrees(math.atan2(y - SIZE / 2, x - SIZE / 2))
        _rad = math.hypot(x - SIZE / 2, y - SIZE / 2)
        _rd = (-rot.deg if INVERT else rot.deg)
        _lang = (_ang + TAP_ANG_SIGN * _rd + 180.0) % 360.0 - 180.0
        #: ── ONE TOUCH, NOT TWO (2026-08-17) ──────────────────────────
        #: Owner: "it still takes two times for me to touch the perimeter
        #: before the wedges come out." The log showed his taps alternating
        #: dismissed / summoned / dismissed / summoned — every other one
        #: spent undoing a state he could not see.
        #:
        #: The cause: `vis` was true while the panes were still arriving
        #: (or had been left up and unnoticed), so the first touch took the
        #: DISMISS branch and the second summoned. A dismissal is only a
        #: meaningful gesture against something fully present, so that is
        #: now the condition: the ring must have FINISHED arriving before a
        #: tap can send it away. Anything earlier re-summons, which is what
        #: a person reaching for controls means every time.
        #: ── ONE LAGGING PANE MUST NOT DISABLE THE RING (2026-08-18) ────
        #: Owner, first thing: "the touch screen doesn't work anymore, I
        #: can't click on the wedges." The diagnostic added last night said
        #: it outright:
        #:
        #:   a=[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.82]  arrived=0
        #:
        #: Six panes fully arrived and the seventh sitting at 0.82. `all(...
        #: >= 0.999)` therefore never became true, `_vis` was permanently
        #: False, every tap took the summon branch, and NOTHING on the ring
        #: could be pressed. An AND across seven independent animations is
        #: a switch that any one of them can hold down forever.
        #:
        #: The condition exists so a dismissal only counts against a ring
        #: that is really there — a good rule, badly quantified. The MEAN
        #: says that just as well and cannot be vetoed by a single pane:
        #: at 0.9 the ring is unmistakably present, and six-of-seven at
        #: full with one at 0.82 averages 0.97.
        _alphas_now = [_aurora_ui_alpha(time.time(), _k)
                       for _k in range(len(wedges()))]
        _arrived = (sum(_alphas_now) / max(1, len(_alphas_now))) >= 0.90
        #: ── OR THE ONE PANE HIS FINGER IS ACTUALLY ON (2026-08-19) ──────
        #: Measured with the current seven-pane schedule:
        #:
        #:     pane 0 landed 0.44s ... pane 6 landed 3.00s
        #:     ring mean reaches 0.90 at 2.33s
        #:
        #: So a pane that finished arriving in under half a second could
        #: not be pressed for another 1.9 s, because a RING-level average
        #: decided whether any tap counted as being on the ring at all.
        #: Tapping it re-summoned the ring instead — which looks like the
        #: glass ignoring him, and is the same complaint as the queue item
        #: about VOLUME ("a pane cannot be pressed until it has arrived").
        #:
        #: The per-pane gate downstream is the one he asked for and it is
        #: right: "make sure you can only activate it after each wedge is
        #: done." This is the other half of that sentence — EACH wedge,
        #: not all of them. If the pane under the finger has arrived, the
        #: ring is present enough to be touched, and the downstream check
        #: still refuses a pane that has not.
        #:
        #: The mean is kept for everything else, because the DISMISS rule
        #: genuinely is about the ring as a whole: a tap in the deadspace
        #: should only count against a ring that is really there.
        _pane_now = next((_k for _k, (a0, a1, _c) in enumerate(wedges())
                          if 0.0 <= (_lang - a0) % 360.0 <= (a1 - a0)), None)
        _bR0n, _bR1n = wedge_band()
        _pane_ready = (_pane_now is not None
                       and _bR0n - 20 <= _rad <= _bR1n + 20
                       and _alphas_now[_pane_now] >= 0.90)
        #: ── AN EXIT IN PROGRESS IS NOT "NOT VISIBLE" (2026-08-17) ────────
        #: Owner: "weird behavior my touches no longer make the widgets
        #: fade." Nine `aurora ring summoned` in the log and not one
        #: `dismissed` — the mirror of the bug the note above describes.
        #:
        #: `hide_t0` is set for the whole 5.7 s of the dissolve, and the
        #: test below folds that into `not _vis`, so a second tap during
        #: the fade RE-SUMMONS. Tap to dismiss, see almost nothing happen,
        #: tap again — and the ring comes back. It never gets to leave.
        #:
        #: Somebody tapping again mid-dissolve is not asking for the ring;
        #: they are asking harder for it to go. So it hurries instead:
        #: restart the exit from where the panes actually are, at the fast
        #: scale. Restarting rather than rescaling because `_ui_step`
        #: scales the delay too, and dropping the scale under a running
        #: clock jumps every alpha — a snap, not a hurry.
        #: ── AND IT ATE EVERY TAP (2026-08-17, reverted within the hour) ──
        #: The branch that stood here hurried a running exit instead of
        #: re-summoning, and returned. It is deleted, and the reason is a
        #: better lesson than the fix was:
        #:
        #: `aurora_ui_hurry_exit` RESTARTS the exit clock — that is what
        #: makes it smooth. So tapping during a dissolve set `hide_t0` to
        #: now, which left the dissolve permanently in progress, which made
        #: the very next tap take this same branch, which restarted the
        #: clock again. The condition guarding the early return was reset
        #: BY the early return. After two taps the ring could never finish
        #: leaving and every touch on the glass vanished into this line —
        #: owner: "NONE of my taps work on the screen outside of rotation".
        #:
        #: A self-perpetuating guard is worse than the bug it fixes, and
        #: the bug it fixed (a tap mid-dissolve re-summons the ring) is a
        #: mild annoyance. Ship the annoyance; the panes come back and
        #: everything on the glass responds again. If it is worth fixing
        #: later it needs a latch that a tap cannot re-arm — a deadline
        #: captured once when the exit STARTS, not recomputed per touch.
        _vis = (_AUR_UI["vis"] and not _AUR_UI["hide_t0"]
                and (_arrived or _pane_ready))
        if not _vis and not AUR_SEAT_ARM.exists():
            #: -- SAY WHICH OF THE THREE IT WAS (2026-08-17) --------------
            #: Owner: "i can't dismiss the wedges anymore by tapping in the
            #: deadspace", and the log said `summoned` ten times running.
            #: `_vis` is three conditions ANDed together and the line only
            #: reported the conclusion, so ten identical lines narrowed
            #: nothing down. Three characters of state cost nothing and
            #: turn the next report into a diagnosis instead of a guess.
            #: `age` is how long the current ARRIVAL has been running,
            #: captured BEFORE the summon: printing them after meant the
            #: age was always 0.0 and the alphas were the ones the summon
            #: had just re-seeded. A diagnostic that reports its own side
            #: effects is worse than none — it cost a wrong hypothesis
            #: this morning before the alphas gave the real answer.
            _age0 = time.time() - _AUR_UI['show_t0']
            _a0 = [round(_v, 2) for _v in _alphas_now]
            aurora_ui_show()
            print(f"tap: aurora ring summoned [vis={int(_AUR_UI['vis'])} "
                  f"hiding={int(bool(_AUR_UI['hide_t0']))} "
                  f"arrived={int(_arrived)} "
                  f"age={_age0:.1f}s "
                  f"a={_a0}] (screen={_ang:.0f} "
                  f"logical={_lang:.0f})", flush=True)
            return
        _pane_i = next((_k for _k, (a0, a1, _c) in enumerate(wedges())
                        if 0.0 <= (_lang - a0) % 360.0 <= (a1 - a0)), None)
        _bR0, _bR1 = wedge_band()
        _on_pane = _pane_i is not None and _bR0 - 20 <= _rad <= _bR1 + 20
        if not _on_pane and not AUR_SEAT_ARM.exists():
            #: by_user: a dismiss by hand outranks the dial re-summoning it
            aurora_ui_hide(by_user=True)
            print(f"tap: aurora ring dismissed (screen={_ang:.0f} "
                  f"logical={_lang:.0f})", flush=True)
            return
        #: ── A PANE IS NOT A BUTTON UNTIL IT HAS FINISHED ARRIVING ────────
        #: Owner, at the glass (2026-08-17): "it's touchable even before the
        #: wedge itself for volume renders. make sure you can only activate
        #: it after each wedge is done."
        #:
        #: The hit-test was pure geometry — the sector existed the instant
        #: the ring was summoned, while the pane was still at alpha 0.2 and
        #: sliding in. So the last pane in the sequence (VOLUME, which by
        #: the new symmetric schedule is also the slowest to arrive) could
        #: be fired by a finger that had not yet been shown it. Pressing a
        #: control you cannot see is the same class of thing as §1: the
        #: device did something nobody could have known they asked for.
        #:
        #: Gated on the SAME alpha the pane is painted with, so "done" means
        #: exactly what the eye saw — not a second timer that agrees with it
        #: today (§15). Consumed rather than passed on, because falling
        #: through would dismiss the ring the finger was reaching into; the
        #: idle timer is refreshed, so reaching for a pane keeps it up.
        if _on_pane and not AUR_SEAT_ARM.exists():
            _a_now = time.time()
            _pa = _aurora_ui_alpha(_a_now, _pane_i)
            if _pa < 0.999:
                _AUR_UI["last"] = _a_now
                print(f"tap: pane {_pane_i} still arriving "
                      f"(alpha={_pa:.2f}) — ignored, not dismissed",
                      flush=True)
                return
        _AUR_UI["last"] = time.time()
        #: ── SEAT CAPTURE (2026-08-16) ────────────────────────────────────
        #: Armed by voice ("remember my seat"), consumed by the next tap:
        #: the finger's angle IS the answer, which is why this beats the
        #: array — a person pointing at where they sit cannot be 59 degrees
        #: wrong. Consumed before anything else can claim the tap, and the
        #: flag is removed either way so a stale arm cannot eat a later tap.
        try:
            if AUR_SEAT_ARM.exists():
                _who = (AUR_SEAT_ARM.read_text().strip() or "?")
                AUR_SEAT_ARM.unlink(missing_ok=True)
                #: the HUD is screen-pinned, so the seat is stored in
                #: SCREEN degrees and no rotation term belongs here — the
                #: earlier `- _dg` was left over from the dial-space cut
                #: and would have written the seat off by whatever the dial
                #: happened to be spun to at capture time.
                if aurora_seat_write(_who, _ang):
                    Path("/tmp/aura_face/wake_flare").touch()
                return
        except Exception as exc:                    # noqa: BLE001
            print(f"aurora: seat capture failed {exc!r}", flush=True)
    if SLEEPING.exists():
        # Wake outranks everything, the brick included: a dark screen
        # that ignores the finger that woke it reads as dead hardware.
        # LOCKED is untouched — waking returns to locked or home,
        # whichever was current when the screen went off.
        SLEEPING.unlink(missing_ok=True)
        _SLEEP["tap_woke"] = True
        print("sleep: woken by touch", flush=True)
        return
    # A BRIEFING IS A MODE, AND EVERY MODE OWNS THE GLASS (see MODAL LAW).
    #
    # It was drawn as an overlay with no tap branch, so the wedge ring
    # underneath stayed live: the owner tapped "outside the boundary" to get
    # out of a briefing and opened the VOLUME overlay on top of it. Exactly
    # the failure the modal law was written for, reintroduced by the newest
    # screen — the same shape as the old Sterling card.
    #
    # Any tap dismisses it and nothing else happens. The audio is a separate
    # concern (the conductor owns the speaker); this is about not being
    # trapped on a screen you cannot leave, which is how it read when the
    # narration failed and the slides sat there for four minutes.
    if _briefing_card(time.time()) is not None:
        BRIEFING_CARD.unlink(missing_ok=True)
        _BRIEF["mtime"] = _BRIEF["data"] = None
        print("tap: briefing dismissed", flush=True)
        return
    if deaf_now():
        # Any touch wakes a deaf puck — back to WHEREVER IT WAS BRICKED
        # FROM. The brick is a mute, not a logout: the owner locked from
        # his authenticated session, tapped awake, and landed at the auth
        # page he'd cleared minutes earlier ("quick notes: lock and tap to
        # wake bring me back to the auth page", 2026-08-01 19:26).
        # A voice mute carries no origin, so it just wakes in place.
        #
        #: ── THE TEMP FLAG IS A PROJECTION, NOT THE STATE (2026-08-20) ──
        #: This unlinked only /tmp/aura_face/muted, and aura-ears' own
        #: ExecStartPre re-creates that file from ~/aura_face/mute at every
        #: start. So the tap worked, the ears logged "UNMUTED, listening
        #: again", the person used the puck all day — and it silently
        #: re-muted itself at the next restart. That is FAILURES
        #: 2026-08-17 exactly, eleven hours of Bob's device, and it was
        #: diagnosed as five days of deafness before the owner corrected
        #: it. Clearing one half of a two-file state is a silent success
        #: with a delayed fuse (§1).
        #:
        #: 2026-08-21: all four of those steps — read the origin, clear
        #: both flags, clear the persistent mute, restore the lock — are
        #: deaf_wake() now, so the one place that knows how to undo this
        #: state is the place that defines it. THIS BRANCH HAS NOT MOVED.
        #: It sits exactly where it did, below the ring block's guard, and
        #: anything inserted above it re-opens the 90-minute lockout of
        #: 2026-08-17 (FAILURES: "no touch will remove it").
        #:
        #: ── DOUBLE TAP, LIKE EVERY OTHER DELIBERATE EXIT (2026-09-01) ──
        #: Owner: "the mute should last indefinitely and only be released
        #: by a physical double tap." Any-touch-wakes meant a sleeve or a
        #: graze unmuted a puck someone had deliberately silenced — Bob
        #: muted his and it "wouldn't shut up". A mute is the one state a
        #: person chose ON PURPOSE; leaving it must take the same
        #: two-taps-inside-1.2s decision the lock screen and the briefing
        #: already require. The face's own affordance line says "double
        #: tap to wake" (_brick_sub), so the first tap is not silent.
        _dt = time.time()
        if _dt - _LAST_DEAF_TAP[0] <= 1.2:
            _LAST_DEAF_TAP[0] = 0.0
            dest = deaf_wake()
            print(f"tap: unmuted by double tap -> {dest or 'in place'}",
                  flush=True)
        else:
            _LAST_DEAF_TAP[0] = _dt
            print("tap: muted — once more within 1.2s to wake", flush=True)
        return
    if LOGIN.exists():
        # The ceremony owns the glass (2026-08-02): there are no visible
        # controls during the voice-print theatre, but the wedge ring is
        # still underneath — the same fall-through class that fired a
        # phantom BRIEFING from volume mode. Consumed, and LOGGED: a
        # swallowed tap that leaves no trace is a silent success
        # (PRINCIPLES §1).
        print("tap: ignored during login ceremony", flush=True)
        return
    if LOCKED.exists():
        # The LOCK SCREEN has no tappable controls — its wedges are behind
        # the curtain, but the hit-tests weren't: an edge tap muted the
        # office from the intro screen, first tap of the run (owner,
        # 09:59: "make sure those are deactivated").
        #
        #: ── BUT A HAND MUST BE ABLE TO OPEN IT (2026-08-17) ─────────────
        #: Owner: "i can't get out of the lock screen with a touch." Voice
        #: being the intended door does not make it acceptable to be the
        #: ONLY door — he was holding a device that would not respond to
        #: his hand, which is indistinguishable from a device that has
        #: crashed (and this face has taught him that lesson once already,
        #: the day a dead compositor was reported as "the gui froze").
        #:
        #: DOUBLE TAP, not single, and that is the whole point: the reason
        #: single taps were disabled is a sleeve brushing the rim. Two taps
        #: inside 1.2 s is a decision — the same idiom, and the same
        #: interval, that aborting a briefing already uses. The hint is
        #: drawn on the screen, because an undiscoverable gesture is not a
        #: door either (§1).
        _lt = time.time()
        if _lt - _LAST_LOCK_TAP[0] <= 1.2:
            _LAST_LOCK_TAP[0] = 0.0
            LOCKED.unlink(missing_ok=True)
            print("tap: UNLOCKED by double tap at the lock screen",
                  flush=True)
            return
        _LAST_LOCK_TAP[0] = _lt
        print("tap: at the lock screen — once more to unlock "
              "(or say her name)", flush=True)
        return
    if COUNT.exists():
        SKIP.touch()
        print("tap: skip pre-show", flush=True)
        return
    if SCENE.exists() or SCENE_DATA_PRESENT():
        # Deliberate exits only. A single tap used to abort, and the owner's
        # touch-to-rotate gesture landed as one — it threw him out of his own
        # briefing mid-show (2026-08-01 17:09). Two taps within 1.2s is a
        # decision; one is often just a hand arriving on the glass.
        nowt = time.time()
        if nowt - _LAST_SCENE_TAP[0] <= 1.2:
            _LAST_SCENE_TAP[0] = 0.0
            ABORT.touch()
            print("tap: abort briefing (double tap)", flush=True)
        else:
            _LAST_SCENE_TAP[0] = nowt
            # SAY IT ON THE GLASS, not just here. The double-tap rule is
            # right — a single tap used to throw the owner out of his own
            # briefing when his touch-to-rotate gesture landed as one — but
            # the first tap produced NOTHING a person could see, so from the
            # chair the screen had simply stopped responding. Owner,
            # 2026-08-10: "it's impossible to exit right now." It was not;
            # it was silent, which is the same thing to whoever is holding
            # it (S1). The face reads this flag and draws the prompt.
            _flag_write(SCENE_EXIT_HINT, "%.3f" % nowt)
            print("tap: one more tap exits the briefing", flush=True)
        return
    if _VOL["open"]:
        # Volume mode owns the WHOLE glass while it is up. Its taps used
        # to fall through to the wedge hit-tests underneath, and a
        # phantom "BRIEFING requested" fired while the owner was
        # adjusting volume (2026-08-02 morning). DONE is the one exit —
        # round 2 killed the ~8s inactivity expiry (it was the screen
        # "just disappearing after no action"); a tap near the ring sets
        # the detent under the finger; anything else is consumed.
        #
        # Placed BELOW the countdown/scene branches on purpose: those
        # screens render over the volume overlay, so while one is up the
        # volume mode is invisible — and an invisible mode that eats the
        # tap meant for the briefing is exactly the silent-success trap
        # (PRINCIPLES §1). Still ABOVE the wedges, which is the bug.
        # Taps arrive in SCREEN coords; the overlay may be view-rotated
        # toward the user, so undo that first (see _unrotate_pt).
        _vw = _view_used("vol")
        vx, vy = _unrotate_pt(x, y, _vw)
        #: ── DONE IS ACCEPTED IN EITHER FRAME (2026-08-17) ────────────
        #: §8, asymmetric costs. A DONE that fires when he meant to nudge
        #: the volume costs one tap to reopen. A DONE that does not fire
        #: leaves him locked inside a modal screen with no way out, which
        #: he has now reported twice. So the exit is tested against BOTH
        #: the unrotated point and the raw screen point, and either one
        #: lets him out. Nothing else on this screen gets that latitude —
        #: it is the only control whose failure is unrecoverable.
        #: RAW screen distance is the real test now that the button is
        #: painted after the rotate. The rotated one is kept only so a tap
        #: aimed at where the button USED to be still gets him out (§8);
        #: it costs nothing and it cannot fire anything else.
        _d_raw = math.hypot(x - VOL_DONE_XY[0], y - VOL_DONE_XY[1])
        _d_rot = math.hypot(vx - VOL_DONE_XY[0], vy - VOL_DONE_XY[1])
        #: and say the numbers out loud, so the next disagreement between
        #: paint and touch is one grep rather than an afternoon (§12)
        print(f"volume: tap screen=({x:.0f},{y:.0f}) view={_vw:.1f} "
              f"-> frame=({vx:.0f},{vy:.0f}) done_d={_d_rot:.0f}/"
              f"{_d_raw:.0f} r={math.hypot(vx - SIZE / 2, vy - SIZE / 2):.0f}",
              flush=True)
        #: ── THE ESCAPE HATCH (2026-08-17) ───────────────────────────
        #: The button turns with the screen, so `_d_rot` is the real test.
        #: `_d_raw` accepts a tap at the button's UNROTATED position too —
        #: bottom centre of the glass, where it sits before the screen has
        #: been turned. Nothing is drawn there once it has been, and that
        #: is deliberate: it is not a feature, it is the thing that makes
        #: being locked inside this modal impossible (§8, and four rounds
        #: of "done still does not work"). It logs when it fires, because
        #: a hidden control nobody can see firing is how you end up not
        #: knowing whether it ever worked.
        if _d_rot <= VOL_DONE_HIT_R:
            _VOL["open"] = False
            _click_close()
            print(f"volume: DONE ({_VOL['level']}%)", flush=True)
        elif _d_raw <= VOL_DONE_HIT_R:
            _VOL["open"] = False
            print(f"volume: DONE via the unrotated escape hatch "
                  f"({_VOL['level']}%, view={_vw:.0f}) — the button was "
                  f"drawn elsewhere and he reached for where it starts",
                  flush=True)
        else:
            r = math.hypot(vx - SIZE / 2, vy - SIZE / 2)
            #: BOUNDED at the outside as well as the inside. A tap on the
            #: bare rim used to land here and slam the level to 100% —
            #: twice in his log — when what he was reaching for was the
            #: edge of the glass to turn it.
            if VOL_SET_R0 <= r < VOL_RIM_R:
                det = _detent_from_angle(
                    math.degrees(math.atan2(vy - SIZE / 2, vx - SIZE / 2)))
                if det != _VOL["detent"]:
                    _VOL["detent"] = det
                    _VOL["level"] = detent_pct(det)
                    _set_volume(_VOL["level"])
                    _click()
                print(f"volume: tap set {_VOL['level']}%", flush=True)
            else:
                print("volume: tap consumed", flush=True)
        return
    if _SET["open"]:
        # Settings mode owns the WHOLE glass — the volume-mode lesson
        # verbatim: a tap that falls through to the wedge ring underneath
        # fires a phantom BRIEFING. Every tap in here is consumed, and
        # every consumed tap logs what it did (PRINCIPLES §1). The book
        # may be view-rotated; hit-tests happen in its own frame.
        _settings_tap(*_unrotate_pt(x, y, _view_used("set")))
        return
    if _STERLING["open"]:
        # Same modal law. The OLD card was the one overlay with no tap
        # branch at all — the stacked-screens bug the owner reported
        # walked in through here. DONE exits; everything else is
        # consumed and logged.
        # ANY TAP FINISHES. The owner, looking at it: "do we really need a
        # DONE thing on sterling?" No. The modal law requires an EXIT, not a
        # button — the briefing card has dismissed on any tap since it
        # shipped, and a desk you finish with by putting a finger anywhere on
        # the glass is less furniture and a bigger target than a 64px circle
        # somebody has to aim at.
        #
        # A DRAG IS NOT A TAP. `rot.release()` returns None when the finger
        # moved, so the orientation gesture cannot close the desk by
        # accident — which is the only thing the DONE button was protecting.
        _sterling_set(False, "tap anywhere")
        return
    if _REQ_CARD["open"]:
        # Same modal law, same exit. The queue is something you GLANCE at —
        # there is nothing on it to press, so making you aim at a button to
        # leave would be the DONE button the owner already ruled out.
        _requests_card_set(False, "tap anywhere")
        return
    if _PAT_CARD["open"]:
        # The clinic list is a reading surface too, and it leaves the same
        # way its neighbour does. Written as its own branch rather than
        # folded into the one above so that the modal law stays greppable:
        # one card, one branch, one logged exit.
        _patients_card_set(False, "tap anywhere")
        return
    if _TOPUP["open"]:
        # THE TIERS ARE TARGETS, so they are tested BEFORE the cancel: a thumb
        # landing on a plate means "that one", never "never mind" (owner:
        # "large targets a thumb can hit without aiming"). Raw screen coords —
        # the card is painted after the display rotate, and _topup_tier_box is
        # the same function that painted them.
        #
        # Selecting is NOT confirming and cannot be: it moves the amount and
        # leaves the card up, exactly as the dial does. Only the slide says
        # yes, which is the whole reason that gesture was asked for.
        for _i in range(len(TOPUP_TIERS)):
            _bx0, _by0, _bx1, _by1 = _topup_tier_box(_i)
            if _bx0 <= x <= _bx1 and _by0 <= y <= _by1:
                if _i != _TOPUP["tier"]:
                    _TOPUP["tier"] = _i
                    _click()
                print(f"ledger: tier ${TOPUP_TIERS[_i]} selected by tap",
                      flush=True)
                return
        # MODAL LAW, and the cheap direction (§8): everywhere else on the
        # offer, a tap cancels it.
        _TOPUP["open"] = False
        _TOPUP["slide"] = 0.0
        print("ledger: top-up cancelled by tap", flush=True)
        return
    if _TOPUP["filed_until"] > time.time() \
            or _TOPUP["error_until"] > time.time():
        _TOPUP["filed_until"] = 0.0
        _TOPUP["error_until"] = 0.0
        print("ledger: top-up notice dismissed", flush=True)
        return
    if _POWER["until"] > time.time():
        # Confirm ring hit-test in RAW screen coords: the overlay was
        # armed at rot.deg ~ 0 (the POWER button only accepts taps near
        # home), and if the dial has moved since, a missed ring lands on
        # the CHEAP side — cancel. PRINCIPLES §8: the expensive direction
        # (an irreversible power-off) stays the narrow one.
        # A TAP CAN NO LONGER POWER THE DEVICE DOWN. Only the slide does.
        # Any tap on this overlay is a cancel — which is the cheap direction,
        # and therefore the one a stray touch should land on.
        _POWER["until"] = 0.0
        _POWER["slide"] = 0.0
        print("power: cancelled by tap", flush=True)
        return
    if _POWER["error_until"] > time.time():
        # The "STILL RUNNING" notice is an overlay too (round 2 audit):
        # a tap on it must not reach the wedges underneath. Tapping
        # dismisses it — acknowledged, logged, home.
        _POWER["error_until"] = 0.0
        print("power: error notice dismissed", flush=True)
        return
    d = (-rot.deg if INVERT else rot.deg)     # PIL angle applied to display
    ang = math.degrees(math.atan2(y - SIZE / 2, x - SIZE / 2))
    r = math.hypot(x - SIZE / 2, y - SIZE / 2)
    logical = (ang + TAP_ANG_SIGN * d + 180.0) % 360.0 - 180.0
    #: ── AURORA'S HUD WAS PINNED TO THE SCREEN, AND IS NOT ANY MORE ───────
    #: 2026-08-16 this said: "icons must not arrive upside down, and a
    #: control that moves because you nudged the dial is a control you have
    #: to hunt for", so `logical = ang` forced the aurora branch to test in
    #: screen coordinates to match a screen-pinned paint.
    #:
    #: 2026-08-17 the owner overruled it at the glass — "the wedges have to
    #: rotate when i rotate the screen, right now they are fixed" — and the
    #: menu now paints BEFORE the rotate with everything else. So the
    #: override is gone and aurora tests in the same logical frame as every
    #: other theme's wedges. The old note is still the right warning, just
    #: pointed the other way: paint and hit-test must agree about the
    #: rotation, and the cost of them disagreeing was "the touch mappings
    #: are wrong", measured at a 172-degree spin.
    print(f"tap: r={r:.0f} screen={ang:.0f} logical={logical:.0f}", flush=True)
    # Padded hit box: fingers are round and the panel is glass. A near-miss
    # on a wedge is a miss the user experiences as "not responsive".
    wedge = None
    # The outer gate is the LIVE PANELS' reach, which is the bezel's opening
    # since they were cut straight (PANEL_CLEAR) — a panel that is painted
    # out to the glass and only tappable to the old arc is a control that
    # ignores half the taps aimed at it (§1). The five BAKED wedges are
    # still the arc plus a fingertip, which is the gate inside the loop.
    if (wedge_band()[0] - 30) <= r <= (_opening_r(logical) + 30):
        _keys = AUR_WEDGE_KEYS if AURORA_BLOB else WEDGE_KEYS
        for (a0, a1, _c), key in zip(wedges(), _keys):
            if r <= (wedge_band()[1] + 30) and (a0 - 8) <= logical <= (a1 + 8):
                wedge = key
                break
        # The REQUESTS wedge is live-drawn and comes and goes (see the
        # REQUESTS section). It is tappable ONLY while it is painted:
        # a hit box over empty glass would open an empty card from a
        # place with nothing in it, which is a control nobody can find
        # twice. Same padded box, same logical frame, so it behaves
        # exactly like the five baked ones while it is there.
        if wedge is None and _req_wedge_live() \
                and (REQUESTS_A0 - 8) <= logical <= (REQUESTS_A1 + 8):
            wedge = "requests"
        # THE CLINIC LIST, in the SAME arc and therefore strictly after it.
        # PAT_A0/PAT_A1 *are* REQUESTS_A0/REQUESTS_A1 — the two take turns in
        # the one free slot — so the order of these two branches is the whole
        # of the pre-emption: while a concierge wedge is up it owns the arc,
        # and the clinic list is only reachable when it is the thing actually
        # painted there. Both gates are liveness checks for the same reason:
        # a hit box over empty glass is a control nobody can find twice.
        if wedge is None and _pat_wedge_live() \
                and (PAT_A0 - 8) <= logical <= (PAT_A1 + 8):
            wedge = "patients"
        # THE WORLD BRIEF, third tenant of the same arc, strictly after its
        # two neighbours: the order of these branches IS the pre-emption,
        # and the liveness gate keeps a hit box off empty glass.
        if wedge is None and _world_wedge_live() \
                and (WORLD_A0 - 8) <= logical <= (WORLD_A1 + 8):
            wedge = "world"
        # THE IRAN WATCH, fourth tenant of that same arc and therefore last:
        # the order of these branches IS the pre-emption, and its liveness
        # gate carries all three neighbours' complements.
        if wedge is None and _iran_wedge_live() \
                and (IRAN_A0 - 8) <= logical <= (IRAN_A1 + 8):
            wedge = "iran"
    if wedge is not None:
        # Tap-ack surge (round 2): the bolt flares hard and decays —
        # the across-the-room acknowledgment for every wedge, on top of
        # the meetings-only ripple below.
        _BOLT_SURGE[0] = time.time()
    if wedge == "meetings":
        REQ.touch()
        # Instant acknowledgment: the curtain takes seconds to spool over
        # ssh, and a silent gap after a tap reads as a dead button (owner,
        # live: "the breathing-like button touch is still unresponsive" —
        # while the log showed the tap had worked). The ripple is the
        # "yes, I felt that", from disk, at frame rate.
        _RIPPLE[:] = [time.time(), x, y]
        print("tap: BRIEFING requested", flush=True)
    elif wedge == "sleep":
        #: the pane does exactly what the machined cap did — see the
        #: SLEEP_XY branch above for why locking comes with it
        SLEEPING.touch()
        LOCKED.touch()
        _PUSHER["which"], _PUSHER["press_until"] = "sleep", time.time() + 0.35
        print("tap: SLEEP wedge (sleeping + locked)", flush=True)
    elif wedge == "power":
        _PUSHER["which"], _PUSHER["press_until"] = "power", time.time() + 0.35
        _POWER["until"] = time.time() + 15.0
        _POWER["slide"] = 0.0
        print("power: confirm overlay armed, from the wedge", flush=True)
    elif wedge in ("lock", "sterling", "settings", "volume", "requests",
                   "patients", "world", "iran"):
        # HOLD THE BEAT SO THE BOLT CAN BE SEEN.
        #
        # The owner, by voice to the puck: "even though you can bring up
        # those toggles immediately, it'd be cool if you pause so you can
        # see the lightning effect and pulsate it — so it's an artificial
        # delay but it looks cool, before you bring them to the lock screen
        # or the setting screen or the volume screen."
        #
        # The tap already flares the bolt (see _BOLT_SURGE), and nobody has
        # ever seen it: the overlay replaced the face in the same frame. The
        # flare decays over ~0.6s and was being painted for one tenth of it.
        #
        # This is §10 turned around. Usually a wait is covered because it is
        # unavoidable; here a SHORT one is added on purpose, because the
        # acknowledgement is the nicest thing on the device and it was
        # happening behind the curtain. The screen still changes well inside
        # the time it takes to look up from your finger.
        _PENDING["wedge"] = wedge
        _PENDING["at"] = time.time()
        _PENDING["deg"] = rot.deg
        print(f"tap: {wedge} — holding {WEDGE_OPEN_DELAY_S:.2f}s for the bolt",
              flush=True)
    elif wedge is None and not LOCKED.exists():
        # The off-ring buttons rotate WITH the baked face, so the tap is
        # mapped into the LOGICAL frame first — the exact transform the
        # wedges use, which is why they worked and these didn't. The old
        # shortcut only accepted taps with the dial near zero; once DoA
        # glide and finger sovereignty made rotation the resting state,
        # the buttons were dead most of the day ("i for some reason
        # can't hit sleep or power ... the other wedges work", 10:44).
        _la = math.radians(logical)
        x = SIZE / 2 + r * math.cos(_la)
        y = SIZE / 2 + r * math.sin(_la)
        if math.hypot(x - SLEEP_XY[0], y - SLEEP_XY[1]) <= BTN_R:
            # SLEEP SHUTS THE DOOR AS WELL AS THE SCREEN.
            #
            # Owner, 2026-08-05: "i want this to really be a dual sleep /
            # unlock mode. so you have to have the person say something that
            # matches the voice print of the session."
            #
            # Sleep used to leave LOCKED alone by design — waking returned
            # you to whatever was current. But the button is pressed from
            # the HOME face, where nothing is current except being open, so
            # the old behaviour was: darken the glass, and let the next
            # finger — anyone's — walk straight back into an unlocked
            # device. The screen was asleep and the device never was.
            #
            # Now the two are one state. A tap still wakes the panel,
            # because a puck that ignores the finger that woke it reads as
            # dead hardware, but it wakes to the LOCK screen and the only
            # thing that opens it is a voice with a print (puck_conduct).
            SLEEPING.touch()
            LOCKED.touch()
            _PUSHER["which"], _PUSHER["press_until"] = \
                "sleep", time.time() + 0.35
            print("tap: SLEEP button (sleeping + locked)", flush=True)
        elif math.hypot(x - POWER_XY[0], y - POWER_XY[1]) <= BTN_R:
            # 5s was sized for "tap the ring". A slide needs time to read
            # the warning, find the knob and drag it.
            _PUSHER["which"], _PUSHER["press_until"] = \
                "power", time.time() + 0.35
            _POWER["until"] = time.time() + 15.0
            _POWER["slide"] = 0.0
            print("power: confirm overlay armed (5s)", flush=True)
        elif _ledger_hit(x, y):
            # THE FUEL GAUGE IS THE BUTTON — the $LEDGER block and the
            # reserve sub-dial it is bracketed to, which are one instrument
            # (see the complication's own note). LAST in this chain and after
            # every wedge above it, so nothing that was tappable yesterday
            # answers differently today; the nearest existing target is POWER,
            # 192px away against a combined radius of 170.
            _TOPUP["open"] = True
            _TOPUP["slide"] = 0.0
            _TOPUP["grab_deg"] = rot.deg
            # PRESELECT THE WEEK. The gauge already knows the burn rate, so
            # the card opens on the tier that restores roughly a week of range
            # rather than on a house default — and it says in the log which
            # one it chose and on what reading, because a preselection nobody
            # can account for is a number that appears to have been decided
            # for you.
            _led_open = _ledger_now(time.time())
            _TOPUP["tier"] = _topup_preselect(_led_open)
            _TOPUP["turn_prev_ang"] = None
            _TOPUP["turn_acc"] = 0.0
            _sel_usd = TOPUP_TIERS[_TOPUP["tier"]]
            print(f"ledger: top-up card opened — ${_sel_usd} preselected "
                  f"(buys {_topup_buys(_led_open, _sel_usd) or 'unknown range'}"
                  f", target {TOPUP_TARGET_DAYS:.0f}d)", flush=True)


TAP_ANG_SIGN = 1.0
_LAST_SCENE_TAP = [0.0]


def SCENE_DATA_PRESENT() -> bool:
    return SCENE_DATA.exists()


def draw_tracked(d, cx: float, y: float, text: str, font, fill,
                 track: float = 0.0) -> float:
    """Centred text with LETTER-SPACING, which PIL has no notion of.

    Set capitals with no tracking read as shouting; the space between them
    is most of what makes caps look composed rather than loud. Returns the
    width drawn so a caller can measure what it just set.
    """
    widths = [d.textlength(ch, font=font) for ch in text]
    total = sum(widths) + track * max(0, len(text) - 1)
    x = cx - total / 2.0
    for ch, w in zip(text, widths):
        d.text((x, y), ch, font=font, fill=fill)
        x += w + track
    return total


def face(role: str, size: int) -> ImageFont.FreeTypeFont:
    """A face from the ramp, cached per (role, size).

    Falls back DOWN the tuple in FACES and then to FONT_PATH, and prints
    the first fallback it takes for each role. The print is the point:
    a missing font file is otherwise indistinguishable from "the new
    typography didn't deploy", and the whole page would silently render
    in the weight the owner asked us to get rid of (PRINCIPLES §1).
    """
    #: ── 2026-08-12: A FLOAT SIZE IS INVISIBLE HERE AND FATAL ON THE GLASS ─
    #: The pucks run Pillow 9.0.1; this workstation runs 12.x. 9.0.1 raises
    #: TypeError("'float' object cannot be interpreted as an integer") on a
    #: float size and 12.x renders it without complaint — so this whole class
    #: of bug CANNOT be reproduced in development (PRINCIPLES §6: measure in
    #: the environment that will actually apply).
    #:
    #: Worse, the fallback chain below cannot help with an argument fault. It
    #: tried all three paths, failed identically on each because the fault was
    #: never the path, and raised "no face at all for role 'label'" — which
    #: reads as a missing font file and sent a session looking at the ramp.
    #: So: coerce, and SAY SO ONCE per role, because a caller passing floats
    #: is still a bug worth finding and a silent round is a silent success
    #: (§1). script_size() was the first one and it is fixed at source.
    if not isinstance(size, int):
        if role not in _FACE_FLOAT_WARNED:
            _FACE_FLOAT_WARNED.add(role)
            print(f"font: role {role!r} asked for a non-int size {size!r} "
                  f"— rounding to {int(round(size))}; Pillow 9.0.1 on the "
                  f"pucks would have raised TypeError here", flush=True)
        size = int(round(size))
    key = (role, size)
    got = _FACE_CACHE.get(key)
    if got is not None:
        return got
    #: ── THE RAMP IS ANY LENGTH (2026-08-17) ──────────────────────────────
    #: This unpacked exactly two paths, while the docstring above promises
    #: it "falls back DOWN the tuple" — true of every role until the title
    #: face arrived with four (Palatino, Century Schoolbook, narrow sans,
    #: DejaVu serif) and the whole draw died on `too many values to unpack`.
    #: A ramp that is capped at two is not a ramp; now it walks whatever it
    #: is given and still ends at FONT_PATH.
    _ramp = tuple(FACES.get(role, FACES["text"]))
    err = None
    for path, why in ([(_ramp[0], "")]
                      + [(_p, f"fell back {_i} step(s)")
                         for _i, _p in enumerate(_ramp[1:], 1)]
                      + [(FONT_PATH, "every face in the ramp is missing")]):
        try:
            got = ImageFont.truetype(path, size)
        except Exception as e:
            err = e
            continue
        if why and role not in _FACE_WARNED:
            _FACE_WARNED.add(role)
            print(f"font: role {role!r} -> {path} ({why}: {err!r})",
                  flush=True)
        _FACE_CACHE[key] = got
        return got
    raise RuntimeError(f"font: no face at all for role {role!r}: {err!r}")


#: ── The wordmark ──────────────────────────────────────────────────────
#: AURAVISION. One word, no space; the COLOUR is the differentiator, at the
#: owner's direction: "have no spaces between AURA and VISION, use the color
#: to be the differentiator".
#:
#: DRAWN HERE RATHER THAN BAKED INTO base.png, and that move is the point.
#: The puck only ever sees frozen screenshots of home.html, so a CSS
#: animation on the wordmark renders as one arbitrary frame of itself
#: forever. Anything that must MOVE has to be drawn on the device.
#:
#: WHY IT BREATHES TOWARD WHITE — the owner's idea, and better than a fixed
#: colour. A saturated blue on black carries almost no LUMINANCE contrast:
#: human vision weights blue at ~11% against green's ~59%, and luminance is
#: exactly what a small IPS panel sheds off-axis. He views this puck "45%
#: askew". Cycling toward a near-white blue restores luminance contrast
#: periodically, and motion is a third perceptual channel on top of hue and
#: brightness — three ways to be seen instead of one.
#: TRUE CENTRE, and higher. The old value was inherited from the baked SVG
#: (x=515 in a 1000-wide viewBox) and never re-derived for the 1080 canvas,
#: so the wordmark sat 25px left of centre. And the two-line block —
#: wordmark plus the wake hint below it — spanned roughly y500..y660, whose
#: midpoint is 580 against a canvas centre of 540: the whole block hung low.
#: The owner, from his angle: "it feels like ... the entire two line block
#: ... is not centered on the screen, it has to be moved up higher."
#:
#: At 71px the glyphs run ~y460..532 and the hint sits at 585..620, putting
#: the block's midpoint on 540 exactly.
#: 460 -> 513. This is the TOP of the text, not its centre, so at 460 a
#: 71px wordmark sat centred on y≈486 — 54px above the middle of the glass,
#: which on a round screen reads as "slipped upwards". The owner, out loud
#: to the room: "just adjust the AuraVision setting in the home page, it's a
#: little bit too high, it doesn't look centered ... move it down a little
#: bit so that's centered on the screen."
#:
#: 513 puts the text's centre on y=540 — the middle of a 1080 disc, and the
#: same line the SLEEP button sits on, which is what he asked for: "roughly
#: in line with the sleep icon, it just looks better that way."
#: ── IT HAD TO SHRINK WITH THE DIAL, 2026-08-06 night ─────────────────────
#: This block's size was settled by three rounds of the owner's own judgement
#: (88 -> 79 -> 71) and nothing here reopens that: 71 was right for the dial
#: it was set on. It is a MEASUREMENT against a dial that has since moved.
#: AURAVISION sets 705px at 71/18, half-width 352, against a wedge ring whose
#: inner edge is now 290.3 display px — so left alone it would run 62px UNDER
#: the wedges on both flanks, over live tap targets, on a face whose whole
#: brief this pass was proportion. x DIAL_K keeps the relationship the owner
#: approved: 705 -> 564 against a ring that came in by the same fraction.
WORDMARK_XY = (540, 540 + (513 - 540) * DIAL_K)
#: 88px to match the ORIGINAL lock-screen wordmark, which was the biggest
#: of the two baked copies (lock.html: 88px/44px tracking; home.html: 66/30).
#: The owner, seeing the 54px version: "make the AURAVISION font as large as
#: the original AURA font size, it's too small".
#:
#: Tracking comes DOWN to 18 because the word is now ten characters, not
#: four. At the original 44px tracking AURAVISION measures ~1030px across a
#: 1080px panel — it would touch both bezels. At 18 it sets 705px, which
#: fills the face the way AURA at 88/44 used to (~700px) without crowding it.
#: 79px — 88 read as heavy rather than elegant once it was actually on
#: the glass. The owner: "decrease the font size just a tad, maybe 10%
#: lower in size. it no longer looks that elegant." Tracking holds at
#: 18: the airiness is what makes a wordmark read as a wordmark, and
#: shrinking both at once would just make it small.
#: 71px — another 10% down; 79 still read heavier than it needed to.
#: x DIAL_K with the Royal Oak compression (see WORDMARK_XY): 71 -> 57,
#: 18 -> 14.4. The three sizes the owner walked down to 71 are the record
#: of what looked right on the old dial and are kept in the note above.
WORDMARK_SIZE = round(71 * DIAL_K)
WORDMARK_TRACK = 18.0 * DIAL_K
#: ── 2026-08-07: THE CONTRAST IS MEASURED, NOT CHOSEN ─────────────────────
#: Owner, at the glass: "it needs more contrast in font colour vs the blue
#: background, it's lost right now. The Royal Oak has AP in white against the
#: blue. I'm not saying pure white, but it has to stick out more." He also
#: ruled out the cheap fix by name — a larger wordmark at the same tone is a
#: bigger thing that is still lost — so SIZE IS UNTOUCHED here.
#:
#: SAMPLED THROUGH THE SHIPPED RAMP rather than eyeballed, because a colour on
#: a blue ground is exactly what the eye's own dark adaptation misjudges (§6:
#: an absolute number is meaningless without the floor it competes against).
#: The ground under the wordmark is home.html's tapisserie, which now runs
#: edge to edge, so the ink sits on the raised square TOPS: source L=35 in
#: that page's own TAPISSERIE note, through _dial_metal / desertify's duotone
#: (DESERT_BLACK -> DESERT_MID) that is (27, 42, 63) — Rec.601 luma 39.9,
#: the Bleu Nuit ground the colourway notes below promise.
#:
#: WCAG relative luminance both sides, ratio (L1+.05)/(L2+.05):
#:   ground  (27, 42, 63)     Y 0.0225
#:   AURA    (222,182,90)     Y 0.4972   7.55:1   <- the old gold, at the line
#:   VISION  (26,140,245) lo  Y 0.2557   4.22:1   <- THIS is what was lost
#:   VISION  (150,210,255) hi Y 0.5980   8.94:1
#: So the word that disappears is VISION at the bottom of its breath, and the
#: gold was clearing 7:1 by half a point. Both are fixed; the floor asked for
#: is 7:1 and both ends of the cycle now hold it.
#:   AURA    (235,238,245)    Y 0.8540  12.47:1
#:   VISION  (60,200,255) lo  Y 0.4949   7.52:1
#:   VISION  (150,210,255) hi Y 0.5980   8.94:1  (unchanged — already clear)
#: The hairline chamfer over each square (source L=68 -> (53,82,122)) is the
#: one thing on the dial nothing short of paper-white clears 7:1 against, and
#: it is a 1.5-unit line rather than a ground; the ratios above are against
#: the field the letters actually stand on.
#:
#: 235,238,245 IS THE OWNER'S OWN NUMBER and it is a champagne, not a white —
#: blue-minus-red +10, so it reads as applied metal rather than printed paper,
#: which is the distinction he drew. It replaces the rose-gold (222,182,90)
#: that arrived with the Royal Oak pass; that triple is kept above so a future
#: session can see what was traded and for how much.
#: ── 2026-08-07, amendment 2: APPLIED GOLD, NOT CHAMPAGNE TYPE ─────────────
#: Owner: "the colors are still too uniformly drab ... AURA VISION pops,
#: tastefully." The wordmark becomes APPLIED GOLD type — the shadow / face /
#: top-facet rendering draw_numerals' headstone preserves, in the accent
#: family the tourbillon cage already wears — so it reads as metal letters
#: catching light rather than yellow text. The champagne above is superseded
#: (its triple and its arithmetic stand, per the house rule).
#: THE ARITHMETIC, same ground (27,42,63), Y 0.0225:
#:   AURA    (212,175,92)      Y 0.4545   6.96:1   B-R -120
#:   VISION  (228,195,115) lo  Y 0.5674   8.52:1   B-R -113
#:   VISION  (247,227,170) hi  Y 0.7727  11.35:1   B-R  -77
#: All three clear 6:1 and every ink is warm. The two words still never
#: match: VISION's breath bottoms out 16 counts brighter than AURA's face
#: and only climbs from there.
#: THE CALLERS MOVED WITH THE COLOUR: on the home face this is now drawn
#: AFTER desertify() (see main) — gold before the duotone arrives as the
#: dial's blue. The lock screen never duotones and needed no move.
#: 2026-08-09, themes: the reach-across becomes a TABLE LOOKUP. This was
#: "= TOURB_GOLD, written out" because that constant is defined ~9000 lines
#: down; it is now `brand_ink` from the theme row (the fourth-pass note at
#: _THEMES), which is the same champagne gold on patek and royal-oak and
#: brushed aluminium on ferrari — the wordmark is the METAL, not the accent,
#: and those two stopped being one colour when the ferrari row landed.
AURA_INK = _THEME["brand_ink"]
#: A DEEPER BLUE, and a peak that is no longer near-white. The first pass
#: breathed #4FC3F7 -> #DCEEFF, and the owner's verdict on the glass was that
#: it read as one colour: "make the blue a bit more distinct it's not very
#: noticeable right now, very close to the WHITE either way in the
#: transition".
#:
#: He is right and the arithmetic says so. #4FC3F7 is already 76% of the way
#: to white in the green channel and 97% in blue — against AURA's #F2F4FA it
#: differs mostly in RED, which is the channel carrying the least perceptual
#: weight of the three. So it was a white with the red pulled down, not a
#: blue.
#:
#: Dropping red and green hard makes it unmistakably blue; keeping the peak
#: SHORT of white preserves the contrast against AURA at every point in the
#: cycle, so the two words never momentarily match. The earlier worry about
#: off-axis luminance is handled by the peak, not by desaturation.
#: 2026-08-07: THE LOW END WAS THE ONE THAT VANISHED. (26,140,245) measures
#: 4.22:1 against the dial ground (arithmetic at AURA_INK), and a wordmark
#: that spends half of every 5.9s cycle under 4.5:1 is a wordmark that is
#: intermittently absent — which is what "it's lost right now" describes. The
#: paragraph above stands: the peak must stay SHORT of white so the two words
#: never momentarily match, and that matters MORE now AURA is a champagne.
#: So the LOW end climbs and the peak does not move.
#: (60,200,255) is the bluest triple that clears 7:1 — blue-minus-red +195
#: against the old +219, so it gives up 24 counts of hue separation to take
#: the ratio 4.22 -> 7.52. It is still unmistakably a blue and not a tinted
#: white, which is the whole point of the note above.
#: 2026-08-07, amendment 2: THE BREATH SURVIVES THE GOLD, RE-CUT. With the
#: wordmark gone applied gold (see AURA_INK) a blue VISION fights the metal
#: read outright — so the breath is KEPT and re-voiced in the gold family:
#: face gold up toward the tourbillon's own specular, which reads as light
#: moving on metal rather than as a second colour. The blues above stand as
#: the record of what was traded.
#: 2026-08-07, amendment 3: VISION IS BLUE AGAIN. Owner: "for AURA VISION
#: have just AURA gold and VISION the regular blue as a contrast." The gold
#: breath above lasted one pass; the pairing is the point — gold metal
#: beside living blue light, the same two-material contrast the dial runs
#: on. The blues are the re-cut ones from earlier today ((60,200,255) lo
#: 7.52:1, (150,210,255) hi 8.94:1 — arithmetic at AURA_INK) and the breath
#: returns with them. VISION also sheds the gold shadow/facet in
#: _draw_wordmark_flat — light is not applied metal, so only AURA keeps the
#: three-draw treatment. The amendment-2 gold triples were
#: (228,195,115)/(247,227,170); they stand in the note above.
#: 2026-08-08, themes: the pair rides the theme table (_THEMES, top of
#: file). Royal-oak keeps these exact blues; patek wears WARM STEEL at the
#: same weights — no AP blue on a Patek (docs/PREMIUM.md identity
#: doctrine). Every note above stands as the argument for the royal-oak row.
VISION_LO = _THEME["vision_lo"]  # royal-oak (60,200,255) — notes above
VISION_HI = _THEME["vision_hi"]  # royal-oak (150,210,255), short of white
VISION_HZ = 0.17                 # ~5.9s per cycle — alive, not blinking

#: A word space between AURA and VISION. Set as ONE wordmark still — the
#: colour remains the differentiator — but "AURAVISION" at 18px tracking ran
#: the two words together into a single ten-letter block. Owner: "have a
#: space between aura and vision, it's too close."
#: x DIAL_K, 2026-08-06 night — the word space rides the wordmark.
WORDMARK_GAP = 34.0 * DIAL_K

#: ── THE BRAND, ON THE DIAL, 2026-08-06 late night ─────────────────────────
#:
#: Owner, at the glass: "AURA VISION spans the middle of the dial in large
#: type and no watch does that — a brand sits SMALL under twelve o'clock and
#: the centre belongs to complications. Shrink it hard and move it up under
#: the twelve. This frees the largest single area on the face and it is more
#: authentic, not less."
#:
#: HE IS DESCRIBING THE HOME FACE AND ONLY THE HOME FACE, so this is a
#: second layout rather than a new value for the one above. draw_wordmark is
#: called from two branches: here, over a dial that is a watch, and over the
#: LOCK screen, where the wordmark plus the wake hint is the entire content
#: of a starfield and was centred by his own instruction ("the remaining
#: AURAVISION should re-orient to be centre mass on the screen"). Shrinking
#: it to a quarter of the glass there would answer a brief nobody gave.
#: Every figure above is therefore left standing and unread on this path.
#:
#: 0.42 IS A WIDTH, NOT A TASTE. At the full size AURA VISION sets 494px on
#: a 1080 panel — 46% of the face, straight through the middle, which is the
#: sentence he opened with. At 0.42 it sets 208, so it spans a fifth of the
#: glass; the type lands at 24px, which is larger than the live clock (19)
#: and the wedge subs (~15) and is the smallest thing on this face that is
#: still the biggest thing in its own band.
# 0.55, from 0.42 — the owner: "aura vision font has to be a bit bolder,
# font size has to increase by 30%". 0.42 * 1.3 = 0.546, rounded to the
# ramp's step. The weight change is in _draw_wordmark_flat: the brand
# variant now sets in the bold face, the lock screen keeps the light one —
# at lock-screen size the bold reads as shouting, at dial size the light
# reads as lost, and that pair of facts is why it is a per-variant choice.
WORDMARK_BRAND_K = 0.55
# 2026-08-07: THE BOLD OVERSHOT. Owner, three ways in an hour: "make AURA
# VISION less bold, it's not elegant right now", "decrease or make the font
# more elegant", "it still looks clunky". The brand variant goes BACK to the
# light face (_draw_wordmark_flat) and buys the presence back with TRACKING
# instead of weight — letterspacing up 50%, and the word gap rides with it
# so the space between the words stays wider than the space inside them.
# The size holds at the +30% the owner asked for. Dial-side only; the lock
# screen never left the light face.
WORDMARK_BRAND_TRACK_K = 1.5
WORDMARK_BRAND_SIZE = round(WORDMARK_SIZE * WORDMARK_BRAND_K)
WORDMARK_BRAND_TRACK = WORDMARK_TRACK * WORDMARK_BRAND_K * WORDMARK_BRAND_TRACK_K
WORDMARK_BRAND_GAP = WORDMARK_GAP * WORDMARK_BRAND_K * WORDMARK_BRAND_TRACK_K
#: WHERE "UNDER THE TWELVE" IS, and it is a clearance rather than a
#: proportion. Above it: the baked time pill, whose live digits are covered
#: to y=184, and the scroll chevron under it, whose lowest ink is y=210.
#: Beside it: the upper-left REQUESTS wedge, whose sector reaches x=403 at
#: this height, against this block's left edge at 540-104 = 436. So 262 is
#: the ink's CENTRE line — MEASURED off the rendered layer, the block is
#: x 436..643 by y 253..271 — with 43px of air to the chevron above and 33
#: to the live wedge beside it. It sits at 0.59 of the way from the dial's
#: centre to its ceiling, which is where a dial prints a name.
#:
#: ── 2026-08-07: 262 -> 320, INBOARD. THE NOTE ABOVE STANDS, DATED ─────────
#: Owner, twice: it is "not dignified and is almost spilling out of the centre
#: circle", then "it needs to be closer to the centre". Both are the same
#: measurement and the clearances quoted above are the ones that moved: 262
#: was set against a wedge ring whose inner edge was 290.3 display px, and
#: WEDGE_R0 is now 397.4 x DIAL_K = 317.9 with the dial gone circular. At 262
#: the block inked y 253..271 at a half-width of 103.5, so its own corner sat
#: at r = sqrt(103.5^2 + 278^2) = 296.6 — 21px inside the ring, which is ink
#: riding an edge, exactly as he read it.
#:
#: 320 IS THE MIDDLE OF THE EMPTY BAND, not a nudge. Above the wordmark the
#: lowest fixed ink is the scroll chevron at y=210; below it the tourbillon
#: aperture opens at 540 - TOURB_R = 445. The block inks y 311..329 there, so
#: it has 101px of air above and 116 below, and its corner falls back to
#: r = sqrt(103.5^2 + 229^2) = 251.3 — 66.6 clear of the wedge ring instead of
#: 21. It is 0.29 of the way down the dial's own diameter, which is the upper
#: third a watch prints a name in, with air all round it.
# 356, from 320 — "closer to the center but also more contrast" and, on
# the day before, "not dignified and is almost spilling out of the center
# circle". At 356 the block's lowest ink sits ~52px clear of the
# tourbillon aperture's top (540 - 90 - shadow), and its top clears the
# time pill's y=210 by more than the old layout cleared anything.
# 356 -> 308, 2026-08-07: "AURA VISION is crossing the complications'
# circular border" — at 356 the block's descent reached y~384 and the
# reserve/room flanges top out near 360; at 308 the lowest ink stops ~336,
# clear of today's flanges AND of the enlarged ones the pending brief asks
# for (REG_R 192->214, RIM 88->106 puts their tops at ~348).
# 308 -> 292 with the K change: flanges grew to 102.3, reserve's top now
# reaches y=326, and descent from 292 ends ~320 — six clear.
WORDMARK_BRAND_Y = 292

#: The wake hint, drawn WITH the wordmark so the two stay a single block.
#:
#: It used to be baked into lock.png, which meant it rotated with the dial
#: while the wordmark did not — the owner: "the rotation of the lock screen
#: breaks the orientation of the JUST SAY AURA line, which stays fixed
#: compared to AURA VISION". Anything that must stay level with the wordmark
#: has to be drawn where the wordmark is drawn: after the rotate.
#:
#: 27px, down 10% from the baked 30 at his request. Tracked, because it is
#: set in caps and caps without air are a wall.
HINT_TEXT = 'JUST SAY "HI AURA" TO GET STARTED'
#: x DIAL_K, 2026-08-06 night: the hint is set BELOW the wordmark and reads
#: as one block with it, so it moves with it or the block comes apart.
#: 27 -> 22, and the drop 125 -> 100.
HINT_SIZE = round(27 * DIAL_K)
HINT_TRACK = 8.0 * DIAL_K
HINT_DY = round(125 * DIAL_K)    # below the wordmark's top edge
HINT_INK = (226, 238, 255)

#: THE TEXT TURNS TOWARD THE TALKER; THE SKY DOES NOT.
#:
#: Written by puck_ears from the array's own beam. The owner had been turning
#: the puck by hand and enjoying that the starfield rotated while the text
#: stayed level — then asked for the other half: "so that the text rotates to
#: the DOA? and the sky just stand still ... otherwise i can't rotate the
#: text to my orientation."
#:
#: SMOOTHED HARD, because a bearing is noisy and type that twitches is
#: unreadable. The beam wanders a few degrees between reads even from a still
#: talker, so this eases toward the target and ignores movements under a few
#: degrees entirely. It should look like the wordmark turning to face you,
#: not like it tracking a cursor.
DOA_FILE = Path("/tmp/aura_face/doa")
DOA_DEADBAND_DEG = 6.0       # ignore jitter smaller than this
DOA_EASE = 0.06              # per-frame approach to the target
#: PER-UNIT, AND IT MUST HAVE BEEN MEASURED ON THIS UNIT.
#:
#: 2026-08-04 afternoon: `DOA_OFFSET_DEG = 105.0` used to live here, guessed
#: from a single probe, and the wordmark rotated on it unconditionally. It
#: was never calibratable, because the number it was correcting is not a
#: measurement. Walked round this puck at two heights, the array reports the
#: SAME bearing from opposite sides — 12 o'clock 141.4 deg and 6 o'clock
#: 141.4 deg, MAD 0.0 over 149 consecutive reads while the owner spoke. The
#: identical script on the RTX's BARE array separates the same two positions
#: by 134 deg. Both units, same firmware, same room, within the hour.
#:
#: 2026-08-02 had already condemned it — "it sat at 162-200 from every
#: position" — and disabled face rotation behind doa_cal.json's `enabled`
#: flag, on the condition "re-enable when the ears live in the puck". The
#: ears moved in on 2026-08-03 and rotation came back on 2026-08-04 morning
#: as the constant above. But that condition was shorthand for "when the
#: bearing is real", and moving the ears did not make it real.
#:
#: So the offset now comes from a file that only a MEASUREMENT writes, per
#: unit, outside git (the pucks are not interchangeable and the RTX's
#: calibration is not this one's). No file, no rotation, and a log line
#: saying so — a wordmark quietly holding 0 is indistinguishable from a
#: wordmark that is working, which is how this survived two sessions.
#: Write it with scripts/puck_doa_calibrate.py, and only when the residuals
#: in that fit are honest.
DOA_CAL = Path("/home/ledger/aura_face/doa_cal.json")
DOA_CAL_RECHECK_S = 10.0
_DOA = {"target": 0.0, "now": 0.0, "at": 0.0}
#: `off`/`sign` are only consulted when `on` is True. `checked` is the last
#: time the file was stat()ed, `said` whether the decline has been logged.
_DOA_CAL = {"on": False, "off": 0.0, "sign": 1.0, "checked": 0.0,
            "mtime": None, "said": False}


def _doa_cal(now: float) -> dict:
    """Per-unit bearing calibration, re-read when the file changes."""
    if now - _DOA_CAL["checked"] > DOA_CAL_RECHECK_S:
        _DOA_CAL["checked"] = now
        try:
            mt = DOA_CAL.stat().st_mtime
            if mt != _DOA_CAL["mtime"]:
                _DOA_CAL["mtime"] = mt
                d = json.loads(DOA_CAL.read_text())
                _DOA_CAL["on"] = bool(d.get("enabled"))
                _DOA_CAL["off"] = float(d.get("offset", 0.0))
                _DOA_CAL["sign"] = float(d.get("sign", 1.0))
                print(f"doa: calibration loaded enabled={_DOA_CAL['on']} "
                      f"offset={_DOA_CAL['off']:.1f} "
                      f"sign={_DOA_CAL['sign']:+.0f}", flush=True)
                _DOA_CAL["said"] = _DOA_CAL["on"]
        except FileNotFoundError:
            _DOA_CAL["on"] = False
        except Exception as exc:
            _DOA_CAL["on"] = False
            print(f"doa: calibration unreadable ({exc!r}) — not rotating",
                  flush=True)
        if not _DOA_CAL["on"] and not _DOA_CAL["said"]:
            _DOA_CAL["said"] = True
            print(f"doa: wordmark rotation OFF — no measured bearing "
                  f"calibration for this unit at {DOA_CAL}. The array here "
                  f"reports one constant bearing from every position; see "
                  f"docs/PUCK-STANDALONE.md and run "
                  f"scripts/puck_doa_calibrate.py.", flush=True)
    return _DOA_CAL


def _doa_angle(now: float) -> float:
    """Smoothed screen angle for the wordmark, degrees. 0 = upright."""
    cal = _doa_cal(now)
    if not cal["on"]:
        return 0.0
    if now - _DOA["at"] > 0.5:
        _DOA["at"] = now
        try:
            raw = float(DOA_FILE.read_text().strip())
            want = ((cal["sign"] * raw - cal["off"] + 180.0) % 360.0) - 180.0
            if abs(want - _DOA["target"]) > DOA_DEADBAND_DEG:
                _DOA["target"] = want
        except Exception:
            pass
    # shortest-way easing, so it never spins the long way round
    delta = ((_DOA["target"] - _DOA["now"] + 180.0) % 360.0) - 180.0
    _DOA["now"] += delta * DOA_EASE
    return _DOA["now"]


#: ── Comets ────────────────────────────────────────────────────────────
#: Shooting stars across the starfield. Asked for three times before they
#: existed — the owner: "where the hell are those comets / random star
#: streaks in the star background i asked for? i want that home screen to be
#: living, dynamic, etc. just like vision is changing color".
#:
#: The face already had drifting rings, twinkling stars and a breathing bolt,
#: and every one of those is PERIODIC — they repeat on a fixed cycle, which
#: the eye stops seeing within a minute. A comet is the opposite: rare,
#: aperiodic, and gone before you can look straight at it. That is what makes
#: a background feel inhabited rather than animated.
#:
#: Cheap on purpose. At 10 fps the whole effect is a handful of short lines
#: per frame, and comets are retired the moment they leave the glass — a
#: puck runs this for days at a time and a leaking list would be a slow
#: death rather than a crash.
#: 7.0 -> 4.2s. The owner asked for "30% more frequent" after watching an
#: empty screen for half a minute — but the real reason he saw none was
#: the geometry bug below, not the rate. Both are fixed: 40% more often,
#: and every one of them now actually crosses the glass.
#: 4.2 -> 11.0, and the speed with it. At 4.2s mean gap against a ~4.5s
#: crossing there is essentially always one on the glass and often several —
#: the owner counted five at once. That is a weather system, not a rare
#: event, and a rare event is the entire reason comets are here (everything
#: else on this face is periodic; see the note above).
#:
#: 11.0s against a ~6.2s crossing puts the expected number on screen near
#: 0.5: usually empty, sometimes one, occasionally two. "i like it on the
#: home screen but it should be more sporadic".
#: ── 11 -> 26, BECAUSE THE GROUND IS NO LONGER STILL (2026-08-12) ────────
#: Owner: "lower the incidence of the comets / flying stars thing, with the
#: gears moving in the background it is now too busy, but keep them in, just
#: more infrequent and rarer."
#:
#: Nothing about the comets changed — the DIAL did. The RM ghost train turns
#: now (#17), so the face gained a second continuous motion, and two of them
#: at once is a busy screen however sparse each is on its own. This is the
#: arithmetic he is reacting to: at an 11s mean gap against a ~6.2s crossing
#: the expected number on the glass is 0.56, and a turning ground underneath
#: it reads as constant activity.
#:
#: 26s puts the expectancy at 0.24 — roughly one comet in view a quarter of
#: the time, against a background that is always gently moving. Rarer is the
#: whole point of the object: everything else on this face is periodic, and
#: the comet is the only thing that is not. A surprise that arrives twice a
#: minute is a schedule.
COMET_MEAN_GAP_S = 26.0     # average seconds between comets; Poisson, not a metronome
#: Belt and braces on the Poisson tail: two arrivals can still land close
#: together, and three at once reads as a shower rather than a surprise.
#: 2 -> 1. With arrivals this rare the Poisson tail is what would put two on
#: the glass together, and two at once is precisely the "shower" reading he
#: is asking to remove. One at a time, always.
COMET_MAX_ON_SCREEN = 1
#: 780 -> 540 px/s. At the first speed they were gone before the eye could
#: land on them — the owner: "make them slightly slower and have them glow /
#: pulse brightly". A comet you cannot follow reads as a glitch.
#: 540 -> 300 px/s. Twice now the owner has watched one and called it too
#: quick: "streaking shouldn't be that quick and that small, something a bit
#: more dramatic". A comet crossing a 1080px face at 540px/s is gone in two
#: seconds; at 300 it takes nearly four, which is long enough to notice,
#: turn toward, and watch finish.
#:
#: This is a taste call, not a measurement, and he said so — which makes his
#: eye the instrument. Recorded so nobody "optimises" it back later.
#: 300 -> 210 px/s. Third time of asking — "they are still really really
#: fast". At 210 a full crossing takes about six seconds.
#: 210 -> 150. Slower, so a single one is something you watch cross
#: rather than something you catch the end of. Lifetime is computed
#: FROM this and the chord length, so the crossing stays complete.
COMET_SPEED_PX = 150.0      # travel, px/sec
#: Bigger in every dimension: a longer tail, a fatter core, a wider halo.
#: "barely perceptible to me from the screen" — from four feet, at 45
#: degrees, on a 150mm panel, a 3px line is a scratch rather than an event.
COMET_LEN_PX = 420.0        # tail length
#: The head pulses as it crosses. Not a fade — a fade is just the envelope
#: ending; this is a live flicker on top of it, so the thing looks like it is
#: burning rather than being dimmed by a slider.
COMET_PULSE_HZ = 3.4
COMET_PULSE_DEPTH = 0.35
COMET_GLOW_W = 20           # soft halo drawn under the head
COMET_SEGMENTS = 20         # more segments: a longer tail needs finer falloff
COMET_HEAD = (236, 246, 255)
COMET_TAIL = (90, 150, 235)
_COMETS: list = []
_COMET_NEXT = [0.0]


def _spawn_comet(now: float) -> dict:
    """One comet on a CHORD across the visible disc.

    The first version picked an edge and an angle and gave the comet a fixed
    lifetime. On a ROUND 1080px panel that was wrong twice over: a fifth of
    them crossed only the corners, which are not glass; and speed x lifetime
    was often less than the distance needed to get across, so a comet would
    spawn 420px off-screen, reach the left third, and expire mid-fade. The
    owner watched for thirty seconds and saw none — correctly.

    So: pick an entry point on the circle, pick an exit roughly opposite, and
    size the LIFETIME to the distance. Every comet now enters, crosses the
    middle where a person is looking, and leaves.
    """
    import random
    r = SIZE / 2.0
    a0 = random.uniform(0.0, math.tau)
    # Opposite side, +/-55 deg, so paths sweep the centre rather than
    # clipping a rim.
    a1 = a0 + math.pi + math.radians(random.uniform(-55.0, 55.0))
    pad = COMET_LEN_PX * 0.6          # start with the tail still outside
    x0 = r + (r + pad) * math.cos(a0)
    y0 = r + (r + pad) * math.sin(a0)
    x1 = r + (r + pad) * math.cos(a1)
    y1 = r + (r + pad) * math.sin(a1)
    dist = math.hypot(x1 - x0, y1 - y0)
    return {"x": x0, "y": y0,
            "dx": (x1 - x0) / dist, "dy": (y1 - y0) / dist,
            "born": now,
            # Sized to the crossing, not guessed. Plus a beat so the tail
            # clears the far rim instead of vanishing on it.
            "life": dist / COMET_SPEED_PX + 0.5,
            "bright": random.uniform(0.7, 1.0)}


def draw_comets(frame: "Image.Image", now: float) -> None:
    """Advance, draw and retire the comets. Safe to call every frame."""
    import random
    if _COMET_NEXT[0] == 0.0:
        _COMET_NEXT[0] = now + random.expovariate(1.0 / COMET_MEAN_GAP_S)
    if now >= _COMET_NEXT[0]:
        # Skip the arrival rather than queue it: a comet held back and
        # released later would cluster them, which is the thing being fixed.
        if len(_COMETS) < COMET_MAX_ON_SCREEN:
            _COMETS.append(_spawn_comet(now))
        # Exponential gaps: a Poisson process, so they arrive in the
        # irregular way real ones do instead of on a beat.
        _COMET_NEXT[0] = now + random.expovariate(1.0 / COMET_MEAN_GAP_S)
    if not _COMETS:
        return
    d = ImageDraw.Draw(frame)
    for c in list(_COMETS):
        age = now - c["born"]
        if age > c["life"]:
            _COMETS.remove(c)
            continue
        # Fade in fast, out slow — a streak that pops into existence at full
        # brightness reads as a dead pixel.
        k = min(1.0, age / 0.12) * (1.0 - (age / c["life"]) ** 2)
        k *= c["bright"]
        # Burning, not dimming: a flicker rides on top of the envelope.
        k *= 1.0 - COMET_PULSE_DEPTH * (0.5 + 0.5 * math.sin(
            (now + c["born"]) * math.tau * COMET_PULSE_HZ))
        hx = c["x"] + c["dx"] * COMET_SPEED_PX * age
        hy = c["y"] + c["dy"] * COMET_SPEED_PX * age
        # Lifetime is sized to the chord, so expiry alone retires them.
        # A soft halo under the head — this is what reads as GLOW rather
        # than a bright line. Drawn first so the head sits on top of it.
        if k > 0.05:
            gl = tuple(int(v * k * 0.45) for v in COMET_TAIL)
            d.line([hx, hy, hx - c["dx"] * COMET_LEN_PX * 0.35,
                    hy - c["dy"] * COMET_LEN_PX * 0.35],
                   fill=gl, width=COMET_GLOW_W)
        # A hot core at the head. Without it the brightest thing on screen is
        # the END OF A LINE, which the eye reads as a drawing artefact rather
        # than something travelling.
        if k > 0.05:
            cr = 6.0 * k
            core = tuple(int(v * min(1.0, k * 1.15)) for v in COMET_HEAD)
            d.ellipse([hx - cr, hy - cr, hx + cr, hy + cr], fill=core)
        for i in range(COMET_SEGMENTS):
            f0 = i / COMET_SEGMENTS
            f1 = (i + 1) / COMET_SEGMENTS
            # brightness falls off along the tail
            g = k * (1.0 - f0) ** 2
            if g <= 0.02:
                continue
            col = tuple(int(t_ + (h - t_) * (1.0 - f0))
                        for h, t_ in zip(COMET_HEAD, COMET_TAIL))
            col = tuple(int(v * g) for v in col)
            d.line([hx - c["dx"] * COMET_LEN_PX * f0,
                    hy - c["dy"] * COMET_LEN_PX * f0,
                    hx - c["dx"] * COMET_LEN_PX * f1,
                    hy - c["dy"] * COMET_LEN_PX * f1],
                   fill=col, width=7 if f0 < 0.18 else (5 if f0 < 0.45 else 3))


def _vision_ink(now: float):
    """VISION's colour this frame: a slow breath from blue toward white.

    RETIRED 2026-08-08, refile three (note at STEEL_RIM): VISION is
    embossed blue-steel now, stamped once like the gold AURA, and a
    once-stamped sprite cannot breathe. No callers remain; the function
    stands with its date, per the append-never-rewrite rule."""
    k = 0.5 + 0.5 * math.sin(now * math.tau * VISION_HZ)
    return tuple(int(lo + (hi - lo) * k)
                 for lo, hi in zip(VISION_LO, VISION_HI))


#: ── THE TIME PILL IS RETIRED — 2026-08-07 ────────────────────────────────
#:
#: Owner, by voice at the puck: "the complications should start actually
#: doing something." The moonphase register at six is a 24-HOUR DIAL now,
#: and the digital HH:MM is set inside it, under the pivot — both drawn
#: live in _moon_register. What stood here: draw_clock, the cached cover
#: patch (_CLOCK_PATCH) built from the baked pill's own interior, and the
#: fit-on-a-probe sizing — the real time painted every frame over the
#: stopped baked one (the 2026-08-04 "11:14 AM at half past four" lesson).
#: All of it served a pill that home.html no longer bakes, so it goes in the
#: SAME COMMIT as that markup: removing only one half leaves either a ghost
#: pill with no digits or digits floating on bare texture. The technique is
#: not lost — draw_ledger below is the same cover-and-redraw with a counter
#: in it — and the pill's measured history (Persian widths, the DIAL_K
#: rescales, the 24-hour decision) is in git at this spot.
#:
#: THE FOUR CONSTANTS BELOW ARE KEPT FOR ONE READER ONLY:
#: tests/test_type_fitting.py probes fit_size against the pill's measured
#: box (its "floor is a TARGET" case needs a real tight box, and this was
#: the tightest on the face). Nothing in this file draws with them any
#: more. When that test grows its own probe box, these go too — one commit.
CLOCK_BOX = (475, 97, 607, 126)     # the digits, not the pill outline
CLOCK_SIZE = round(24 * DIAL_K)     # 22px in a 1000-wide viewBox, x DIAL_K
CLOCK_CAP = round(34 * DIAL_K)
#: 3px, not the house 9. MEASURED: the widest Persian time (۱۰:۰۰ ب.ظ) sets
#: 134.75px against the box's 142, so the pill was designed with ~3px of
#: slack each side.
CLOCK_MARGIN = 3.0 * DIAL_K


#: ── THE $LEDGER COMPLICATION, DRAWN LIVE (2026-08-06, night) ─────────────
#:
#: Owner, by voice at the puck: "the LEDGER is the most important number on
#: this face and right now it is the dullest. Watching the credits accrue IS
#: the point ... on the glass it JUMPS in steps instead of climbing. Draw it
#: LIVE in dj_face the way the clock is drawn live over its baked pill ... A
#: number that flows is satisfying; a number that jumps is a receipt."
#:
#: This is draw_clock's argument with a counter in it, and the diagnosis in
#: the room was exactly right: home.html integrates the rate between polls,
#: but the puck sees ONE STILL every ~20s, so the browser's smooth climb
#: arrives here as a staircase. Same fix, same shape: the baked figure is
#: covered with a patch of its own background and the real one is drawn over
#: it at frame rate.
#:
#: THE NUMBERS ARIVE IN THE PICTURE. dj_face has no route to /status — the
#: puck must work with the RTX off (standing rule) and the only thing that
#: crosses is the pusher's three PNGs — so home.html stamps the figures into
#: six patches of colour in the frame's top-left corner, outside the round
#: glass, and this decodes them. See the #ledger-stamp note there for the
#: encoding and why the corner is free; the two halves move in one commit,
#: like every other pair across these files.
#:
#: WHAT IT DOES WITH NO STAMP: nothing at all, and says so once. An old
#: base.png then keeps showing its own baked figure — jumping, but present —
#: which is the failure worth having (PRINCIPLES §1/§2).
#: 'R' -> 'S', 2026-08-07 ledger amendment. The block moved (see
#: LEDGER_SEARCH / LEDGER_BAND below) and home.html goes live the moment it
#: is saved while this file redeploys later — a stale reader with a valid
#: stamp would draw the live counter at the old band beside the baked one at
#: the new, the owner's doubled $LEDGER a third time. The magic is the
#: version pin: mismatched halves stand down loudly (§1) and the baked
#: figure stands alone until they match. home.html's stampLedger moves in
#: this same commit.
#: 'S' -> 'T', 2026-08-08 premium pass, same argument again: the block went
#: RIGHT-anchored on one shared edge (see LEDGER_RIGHT_X) and a stale
#: reader would draw its left-anchored counter beside the moved bake.
LEDGER_STAMP_MAGIC = (76, 71, 84)      # 'L','G','T'
LEDGER_STAMP_VB = 12.0                 # patch pitch, home.html viewBox units
LEDGER_STAMP_Y = 6                     # sample row, display px
VB_PX = 1080.0 / 1000.0                # home.html's viewBox -> this panel
#: How long the counter may keep climbing past the still it came from. The
#: pusher's cadence is 20s, so 90 covers a few missed frames; past it the
#: number HOLDS rather than running away on figures nobody is feeding it —
#: and the hold is logged, because a frozen counter and a dead pusher look
#: identical on the glass (§1).
LEDGER_HOLD_S = 90.0
#: WHERE THE BAKED NUMERAL CAN BE — and the cover is MEASURED inside it, per
#: bake, rather than declared. The clock can declare its box because a pill is
#: a fixed aperture; this row is centred type whose width changes with the
#: number in it, and a declared box big enough for the widest case is a box
#: that erases the guilloché either side of the narrow one. The first cut did
#: exactly that and it showed as a dark rectangle behind the digits — the same
#: failure the clock's donor-column patch exists to avoid, in the other axis.
#:
#: The search window stops at x=238 and y=368 on purpose: the bracket up from
#: the RESERVE sub-dial crosses just past both, and folding it into the cover
#: would cut the one line that ties the two halves of this instrument
#: together. If the ink ever reaches those edges the cover is short and this
#: says so (§1) rather than quietly clipping.
#: x DIAL_K, 2026-08-06 night: the whole $LEDGER block is baked inside
#: home.html's #dial and came in with it. Was (90, 328, 238, 368).
# Window widened + rescaled 2026-08-07: measured baked counter ink runs
# x 121..339, y 320..378 at DIAL_K 0.93. The old window missed part of the
# figure, the bbox came back short, and the live counter drew beside a
# half-covered baked one — the owner's doubled $LEDGER, twice.
# x -35 with the block, 2026-08-07 14:49: the baked ledger went 32 viewBox
# units left (home.html) and LEDGER_MID_X 240 -> 205; the baked ink's left
# edge lands ~86 and the old window started at 100, which is the doubled
# $LEDGER again. Left edge 65 keeps the measured 21px margin and stays 18
# clear of the chapter ring's ink at x=47.
# (65, 312, 329, 384) -> (60, 345, 250, 380), 2026-08-07 amendment 2, with
# the left-justify (see LEDGER_LEFT_X), and the window NARROWS to the
# figure row's own band on a measured fault: at y0=312 the window also saw
# the baked "$LEDGER" caption (ink y 322..339) and, since the r=208 move,
# the RESERVE's F letter — the cover was erasing a caption nothing redraws
# and clipping a letter it does not own, and warned "cover short" on every
# bake. MEASURED off the moved bake: the figure inks y 350..375 (comma tail
# included) from x 73; the caption ends at 339; the reserve's rim arc and
# end-tick enter this neighbourhood at x>=254 within this band, so the
# right edge stops at 250 — the flange guard in home.html's LG fit caps the
# baked figure's row short of the flange, so ink cannot reach 250 either.
# (60, 345, 250, 380) -> (60, 298, 250, 334), 2026-08-07 ledger amendment:
# the whole block rose 45 display px (home.html #ledger-text -31 -> -76) so
# the counter clears the r=235 reserve, whose flange now tops out at y=332
# (measured: first flange ink row 332; the F terminal reaches x=297 over
# rows 320..331). MEASURED off the moved bake, ink-row profile as before,
# never derived: figure inks y 304..329 (comma tail included) from x 74,
# right edge 184; the gold caption above ends at 294; nothing else enters
# x<250 inside this band. y1=334 stays under the flange's top row and
# x1=250 stays 47 short of the F.
# (60, 298, 250, 334) -> (105, 336, 254, 368), 2026-08-07 amendment 4: the
# owner caught the block crossing the ring's ink, so the whole group moved
# 48 right and 40 down (home.html #ledger-text (-103,-76) -> (-55,-36); the
# measurement is in that markup note). MEASURED off the moved bake, ink-row
# profile as before, never derived: figure inks y 339..364 from x 122,
# right edge 233; the gold caption above ends 334; the reserve's flange ink
# enters this band at x=263, so x1=254 stays 9 clear of it.
# (105, 336, 254, 368) -> (105, 338, 250, 368), 2026-08-08 premium pass:
# the whole block is END-anchored on one shared right edge now (home.html
# #ledger note; LEDGER_RIGHT_X below). MEASURED off the moved bake,
# ink-row profile as before, never derived: the 7-char figure inks
# y 343..364 from x 143, right edge 235; the gold caption above ends 333;
# the reserve flange's ink enters this band at x=266, so x1=250 keeps the
# measured 15 clear of it and 15 clear of the figure's own edge.
LEDGER_SEARCH = (105, 338, 250, 368)
#: MEASURED separation, not a guess: the baked type sits at L≈238, the
#: guilloché under it tops out at L=42, and the block's background is L=6.
#: Anything in between would do; 90 is the middle of the empty half.
LEDGER_INK_L = 90
LEDGER_COVER_PAD = 3
#: ── THE GOLD BRAND LINE, 2026-08-07 ledger amendment ─────────────────────
#: Owner: a "$LEDGER" caption above the counter, in the GOLD accent —
#: "people care about that and so do we and there is margin." It is BAKED
#: (home.html right-justifies it to the burned row's edge), and desertify()
#: opens with convert("L") — gold laid on that side arrives as the dial's
#: blue. So the caption is re-inked through its own measured mask after the
#: duotone: the F/E letters' technique verbatim (_gold_fe_sync), pointed at
#: one word. The window is the caption row's own band, measured off the
#: moved bake like LEDGER_SEARCH beside it: caption ink y 277..294 from
#: x 83, right edge 184, nothing else above threshold inside the window.
#: The threshold is a measured separation (§3): the baked gold reads L≈177,
#: the guilloché under this rim tops out at 42 and the block background at
#: 6 — 110 splits them with room on both sides. An empty mask says so and
#: the caption stays steel that bake (§1).
# (60, 270, 250, 299) -> (105, 312, 288, 337), 2026-08-07 amendment 4, with
# the block's 48-right/40-down move (see LEDGER_SEARCH). MEASURED off the
# moved bake: caption ink y 320..334, x 152..233 (right-justified to the
# block's widest row now, so its left edge follows the live figure's width);
# the F terminal enters this band at x=297, so x1=288 stays 9 clear.
# (105, 312, 288, 337) -> (105, 312, 250, 337), 2026-08-08 premium pass,
# with the block's right-anchor move. MEASURED off the moved bake: caption
# ink y 321..333, x 157..234 (end-anchored on the shared edge with the
# other three rows, so its right edge no longer follows the live figure's
# width); nothing else above threshold enters x<250 in this band, and the
# narrower window no longer reaches toward the reserve's F terminal.
LEDGER_CAP_SEARCH = (105, 312, 250, 337)
LEDGER_CAP_INK_L = 110
_GOLD_CAP: list = []
#: The whole row's own band — what the LIVE numeral is fitted and centred in,
#: which is wider than any cover because its ink may sit over the guilloché.
#: Measured on a current base.png: the chapter ring reaches x=47 at y=375, the
#: block's caption ends at y=324 and AURA CREDITS USED starts at y=390.
# x (0.93/0.80) about centre with DIAL_K, 2026-08-07 — hand-measured at
# 0.80; unscaled it drew the live counter beside the baked bracket and
# the owner saw $LEDGER twice.
# MEASURED off the rendered base layer 2026-08-07 (ink-row profile of a
# fresh :8321 shot), not derived: derivation about the wrong anchor is
# how the counter drew beside its own bracket twice today. Counter ink
# spans y 350..374; caption above ends 338; credits line starts 380.
# (346, 378) -> (300, 333), 2026-08-07 ledger amendment, MEASURED off the
# moved bake (ink-row profile of a fresh :8321 shot), not derived: counter
# ink spans y 304..329, the gold caption above ends 294, AURA CREDITS USED
# starts 357. The band's bottom sits at 333 against the reserve flange's
# first ink row at 332 — but the flange has no ink left of x=316 up there
# and the widest live figure stops at 240 (LEDGER_FIT_W from LEDGER_LEFT_X),
# so the drum aperture and the ring share no pixels; measured gap on the
# bake is 113px, worst-case live 57.
# (300, 333) -> (336, 368), 2026-08-07 amendment 4, MEASURED off the moved
# bake (ink-row profile of a fresh :8321 shot): figure ink spans y 339..364,
# the gold caption above ends 334, AURA CREDITS USED starts 394. The flange
# ink enters this band at x=263; the widest live figure stops at 254
# (LEDGER_FIT_W from LEDGER_LEFT_X), 9 clear.
# UNMOVED by the 2026-08-08 premium pass, re-measured rather than assumed:
# on the right-anchored bake the figure inks y 343..364, the caption ends
# 333 and AURA CREDITS USED starts 388 — the band still clears both. The
# live figure now stops at LEDGER_RIGHT_X=236.7 against flange ink at 266
# in this band, 29 clear.
#: (336,368) -> (334,377), 2026-08-14, owner: "$LEDGER … too small to
#: read and we need to make it special as our users care about that
#: amount quite a bit." The band grows 32 -> 43px — up 2 to the label's
#: clearance, down 9 to an 11px gap over the baked caption — and the fit
#: boxes below grow with it. Right anchor unchanged; a bigger figure
#: walks its LEFT edge into the block's own whitespace by design.
LEDGER_BAND = (334, 377)
#: ── 2026-08-07, amendment 2: LEFT-JUSTIFIED, NOT NUDGED ──────────────────
#: Owner, superseding the 32-left: "there is plenty of margin to the edge
#: of the circumference" — LEFT-JUSTIFY the block. Figure, caption and rate
#: line move together in home.html (all four rows go text-anchor="start" at
#: one x) and the LIVE figure grows RIGHTWARD from the same edge here.
#: The edge, measured twice because there are two floors: the baked ring
#: furniture reaches x=45 at the counter's row, but the steel bezel overlay
#: (bezel_steel.png, pasted after this counter is drawn) carries the
#: chapter ring's inner hairline at r=504 display, which crosses this
#: column at y≈358 — a left edge at the spoken 70 puts the first digit's
#: top corner UNDER that hairline. 73 (within the spoken 3px) keeps the
#: digit ink inside r<503 over the whole band and still clears the baked
#: furniture by 28.
#: 2026-08-07 ledger amendment: at the RAISED band the r<503 claim above no
#: longer holds and cannot — the ring hairline crosses this column at
#: y≈350, so every row above it is outside r=504 at x=73. MEASURED on
#: bezel_steel.png: the overlay's inner hairline sweeps x 82..95 over the
#: counter's rows (302..330) and x 107..115 over the caption's, so the
#: block's upper-left corner runs under it. Accepted, stated rather than
#: discovered later: the owner pinned both this edge ("left edge stays at
#: the 70") and the band above the reserve flange, no row clears both, and
#: the reserve collision was the loud one.
#: 73.0 -> 121.0, 2026-08-07 amendment 4: the accepted cost above is
#: retracted by the owner — the block must CLEAR the ring's ink, so the
#: left pin at 70 is released and the group moved 48 right / 40 down (the
#: measurement is in home.html's #ledger markup note). MEASURED off the
#: moved bake: baked figure ink from x 122; every row's worst corner sits
#: at r<=464 against the ring ink's inner edge at 477, 13px clear.
#: ── 2026-08-08 premium pass: RIGHT-ANCHORED, NOT LEFT ────────────────────
#: Owner: "one composed instrument ... right edges aligned through the
#: stack." All four baked rows are END-anchored on one shared edge in
#: home.html and the live figure grows LEFTWARD from the same edge here —
#: LEDGER_LEFT_X stops being the draw anchor and becomes the FLOOR the
#: figure may reach (the ring bound above: at the band's top row y=339,
#: r=465 crosses this column at x=120.7, so 121 stands). The shared edge
#: is the FLANGE'S number, not a taste: the reserve flange ink crosses the
#: rate row's bottom ink row at x≈246.5 and the house 9 of air puts the
#: stack's edge at 236.7 (local 253 in home.html, through #dial's 0.93
#: scale and centring translate). MEASURED off the moved bake: all four
#: rows' right edges land 234/235/235/235 — 1px spread.
LEDGER_LEFT_X = 121.0
LEDGER_RIGHT_X = 236.7
LEDGER_MID_X = 177                     # was 120, was 205 (240 - 35, 14:49),
                                       # was 240. The block's record, not
                                       # the draw anchor (amendment 2):
                                       # the moved bake MEASURES figure ink
                                       # 122..233, mid 177; it drifts right
                                       # as the day's figure grows a digit.
#: The room the live numeral has, which is WIDER than the cover: ink may sit
#: over the guilloché to the right and stops short of the chapter ring on the
#: left (measured: ring ink reaches x=47 at y=375, the block's caption ends at
#: y=324 and AURA CREDITS USED starts at y=390).
#: x DIAL_K with everything else in the block: a numeral fitted to the old
#: room would overflow a band that is now 20% narrower, and layout_rows
#: would shrink it to fit anyway — badly, and without saying why.
# 180*DIAL_K (167.4) -> 133.0, 2026-08-07 amendment 4: the moved block sits
# deeper in the flange's belt. MEASURED off the moved bake: reserve flange
# ink enters the counter's band at x=263, so the live figure from
# LEDGER_LEFT_X=121 stops at 254, 9 clear — the same air home.html's LG
# fitter keeps.
# 133.0 -> 115.7, 2026-08-08 premium pass: the room is LEDGER_RIGHT_X -
# LEDGER_LEFT_X now — a right edge shared with three lower rows cannot
# reach the old 254, because the RATE row's bottom corner meets the flange
# guard first (the derivation is at LEDGER_RIGHT_X). The figure gives up a
# few points of size for the aligned stack, which is the brief.
LEDGER_FIT_W = 150.0
LEDGER_FIT_H = 67.0 * DIAL_K
LEDGER_WANT = round(60 * DIAL_K)
LEDGER_CAP = round(68 * DIAL_K)
#: NEUTRAL GREY, NOT A COLOUR, because this is drawn BEFORE desertify() and
#: therefore wears the colourway like every other ambient element: L=198 lands
#: at (233,190,164) through the rose-gold ramp — metal, and a clear step
#: brighter than the block's baked caption at L=225-ish only because that one
#: is small. The wordmark is near-white and stays the loudest thing on the
#: dial; this is deliberately the second (owner: "the second strongest thing
#: on the dial after the wordmark").
# RETIRED 2026-08-08 (premium pass) WITH _led_glyph BELOW, kept dated: the
# figure is applied BLUE-STEEL now — VISION's own emboss, drawn on the far
# side of desertify() in draw_ledger_figure — so the neutral-grey argument
# above no longer applies to it. These three and _led_glyph stand as the
# only pre-colourway applied-type example, the same reason draw_numerals
# stands.
LEDGER_INK = (182, 182, 182)
LEDGER_HI = (238, 238, 238)            # the applied numeral's top facet
LEDGER_SHADOW = (16, 18, 24)           # ...and the ground it stands on
#: One digit's roll. Short: at IDLE_FPS this is two frames, and a longer one
#: would still be turning when the next credit lands.
LEDGER_ROLL_S = 0.22
#: The flash the baked counter had (owner, 2026-08-02: "flash the number when
#: it changes") kept, and it had to be re-aimed: serve.py alternated a class
#: per ~20s serve, but a live counter changes several times a SECOND and a
#: strobe is not a flash. So the lift fires when a digit at the hundreds place
#: or above turns — every ~25s at the show floor of 240/min — while the units
#: carry their change in the roll itself.
LEDGER_FLASH_S = 0.6
#: ── THE STEPPED CADENCE, 2026-08-07 (refile — the first run of this brief
#: died on a session limit, not on the work) ───────────────────────────────
#: Owner, by voice: HOLD the displayed figure and STEP it on a jittered
#: 115-140s interval. Each step blinks the number (the flash above, reused —
#: no second blink was built) and throbs the gold caption for 1.5s (table at
#: _LEDGER_THROB_TABLE, drawn in draw_gold_strikes). The scheduler tops out
#: at 139 rather than 140: a step lands on the first FRAME at or after its
#: due time, so up to a frame of lag rides on every interval, and 1s of
#: headroom keeps the MEASURED gap — which is what the log is checked
#: against — inside the owner's band.
LEDGER_STEP_MIN_S = 115.0
LEDGER_STEP_MAX_S = 139.0
LEDGER_THROB_S = 1.5
_LED = {"mtime": None, "have": False, "shown": 0.0, "rate": 0.0,
        "real": 0.0, "rate_real": 0.0, "ts": 0, "said": "", "narrow": False,
        "cover": None, "cells": [], "flash": 0.0, "held": False,
        "step_val": 0.0, "step_at": 0.0, "step_next": 0.0, "throb": 0.0}
_LEDGER_PATCH = [None]


def _stamp_rgb(base: "Image.Image", k: int):
    """One stamp patch, sampled at its middle (never within 6px of an edge)."""
    x = int(round((k * LEDGER_STAMP_VB + LEDGER_STAMP_VB / 2.0) * VB_PX))
    return base.getpixel((x, LEDGER_STAMP_Y))[:3]


def _stamp_int(base: "Image.Image", k: int) -> int:
    r, g, b = _stamp_rgb(base, k)
    return (r << 16) | (g << 8) | b


def _ledger_sync(base, mtime) -> None:
    """Read the stamp out of a freshly landed base.png. Called once per bake,
    from the compose loop — the cover patch is sampled from the same picture
    and has to be dropped with it."""
    if base is None or mtime == _LED["mtime"]:
        return
    _LED["mtime"] = mtime
    # The cover: this bake's own background over exactly the baked numeral,
    # found by MEASURING its ink (see LEDGER_SEARCH) and built ROW BY ROW from
    # a donor column 8px to its left — the same technique and the same reason
    # as _CLOCK_PATCH, since a flat fill in the wrong black reads as a
    # rectangle. Built from base.png rather than from the composited frame so
    # the ocean can be screened back on per frame instead of frozen into it.
    _LED["cover"] = None
    try:
        sx0, sy0, sx1, sy1 = LEDGER_SEARCH
        mask = base.crop(LEDGER_SEARCH).convert("L").point(
            lambda p: 255 if p > LEDGER_INK_L else 0)
        bb = mask.getbbox()
        if bb is not None:
            if bb[0] <= 0 or bb[2] >= (sx1 - sx0) or bb[3] >= (sy1 - sy0):
                print("ledger: the baked figure reaches the edge of the "
                      "search window — the cover will be short", flush=True)
            p = LEDGER_COVER_PAD
            box = (max(8, sx0 + bb[0] - p), sy0 + bb[1] - p,
                   sx0 + bb[2] + p, sy0 + bb[3] + p)
            patch = Image.new("RGB", (box[2] - box[0], box[3] - box[1]))
            for y in range(box[1], box[3]):
                patch.paste(base.crop((box[0] - 8, y, box[0] - 7, y + 1))
                            .resize((box[2] - box[0], 1)), (0, y - box[1]))
            _LED["cover"] = box
            _LEDGER_PATCH[0] = patch
    except Exception as e:
        _LED["cover"] = None
        print(f"ledger: cover not sampled {e!r}", flush=True)
    # The reserve's F/E gold masks ride the same fresh bake (amendment 2 —
    # see _gold_fe_sync), and before the stamp check on purpose: the
    # letters are baked whether or not the stamp reads.
    _gold_fe_sync(base)
    # ...and the caption's, the same technique for the same reason — the
    # brand line is baked whether or not the stamp reads, and its gold has
    # to be re-struck after the duotone (see LEDGER_CAP_SEARCH).
    _GOLD_CAP[:] = []
    try:
        m = base.crop(LEDGER_CAP_SEARCH).convert("L").point(
            lambda p: 255 if p > LEDGER_CAP_INK_L else 0)
        if m.getbbox() is None:
            print(f"ledger: no caption ink in {LEDGER_CAP_SEARCH} — the "
                  "brand line stays steel this bake", flush=True)
        else:
            # APPLIED, NOT PRINTED (2026-08-08 premium pass): the caption
            # gets the wordmark's relief pair, derived from its own ink
            # mask once per bake — top edge rows for the bright rim, under
            # edge rows for the occlusion line, the _aura_embossed
            # arithmetic pointed at a mask instead of a glyph. The face
            # fill stays the strike gold (and the step's throb keeps
            # modulating it alone — the machinery is untouched).
            down = m.transform(m.size, Image.AFFINE, (1, 0, 0, 0, 1, -1))
            up = m.transform(m.size, Image.AFFINE, (1, 0, 0, 0, 1, 1))
            _GOLD_CAP[:] = [(LEDGER_CAP_SEARCH, m,
                             ImageChops.subtract(m, down),
                             ImageChops.subtract(m, up))]
    except Exception as e:                      # noqa: BLE001
        print(f"ledger: caption mask not sampled {e!r}", flush=True)
    try:
        magic = _stamp_rgb(base, 0)
    except Exception as e:                     # a half-written or odd frame
        print(f"ledger: stamp unreadable {e!r}", flush=True)
        return
    if tuple(magic) != LEDGER_STAMP_MAGIC:
        _LED["have"] = False
        if _LED["said"] != "nostamp":
            _LED["said"] = "nostamp"
            print("ledger: base.png carries no $LEDGER stamp "
                  f"(corner reads {tuple(magic)}) — the BAKED figure stands. "
                  "home.html older than this file?", flush=True)
        return
    _LED["shown"] = float(_stamp_int(base, 1))
    _LED["rate"] = float(_stamp_int(base, 2))
    _LED["real"] = float(_stamp_int(base, 3))
    _LED["rate_real"] = float(_stamp_int(base, 4))
    _LED["ts"] = _stamp_int(base, 5)
    if not _LED["have"]:
        print(f"ledger: stamp found — {int(_LED['shown']):,} credits at "
              f"{int(_LED['rate'])}/min, drawing live", flush=True)
    _LED["have"] = True
    _LED["said"] = ""


def _ledger_age(now: float) -> float:
    """Seconds since the figures were read, from a 24-bit stamp.

    Signed, so a puck clock a few seconds behind the RTX's reads as a small
    negative age and not as 194 days (which is what the low 24 bits wrap to).

    AND FRACTIONAL, which is the whole errand: the stamp is whole seconds, so
    an age in whole seconds would step the counter once a second — a smaller
    staircase than the 20s one this pass exists to remove, but the same shape.
    The sub-second part of the puck's own clock carries the climb between
    them.
    """
    d = (int(now) - _LED["ts"]) % (1 << 24)
    if d > (1 << 23):
        d -= (1 << 24)
    return float(d) + (now - int(now))


def _ledger_now(now: float):
    """The figures at THIS instant, or None if there is no reading.

    The counter integrates the SHOWN rate (the one the owner asked to keep
    moving) and the reserve integrates the HONEST one, which is the split
    home.html already made and states at length beside PR_DAY_CREDITS.
    """
    if not _LED["have"]:
        return None
    age = _ledger_age(now)
    held = age > LEDGER_HOLD_S or age < -5.0
    if held != _LED["held"]:
        _LED["held"] = held
        print(f"ledger: {'HOLDING' if held else 'live again'} — "
              f"the still is {age:.0f}s old", flush=True)
    age = max(0.0, min(LEDGER_HOLD_S, age))
    return {"shown": _LED["shown"] + _LED["rate"] * age / 60.0,
            "real": _LED["real"] + _LED["rate_real"] * age / 60.0,
            "rate": _LED["rate"], "rate_real": _LED["rate_real"],
            "held": held}


def _led_glyph(d, x: float, y: float, ch: str, f, ink) -> None:
    """One APPLIED numeral: a shadow it stands on, the face, a top facet.

    Three draws rather than one because that is the whole difference between
    a printed digit and an applied one, and applied is what a dial like this
    wears.

    UNREFERENCED since 2026-08-08 (premium pass): the figure is embossed
    blue-steel now, pasted from sprites in draw_ledger_figure (_led_paste).
    Kept with LEDGER_INK above as the pre-colourway applied-type example,
    the draw_numerals argument.
    """
    d.text((x + 2, y + 2), ch, font=f, fill=LEDGER_SHADOW)
    d.text((x, y), ch, font=f, fill=ink)
    d.text((x - 1, y - 1), ch, font=f, fill=tuple(
        min(255, int(c * 1.18)) for c in ink))


def draw_ledger(frame: "Image.Image", now: float) -> None:
    """The counter's cover and its step machinery — the colourway side.

    SPLIT 2026-08-08 (premium pass): the figure itself is applied
    BLUE-STEEL now — VISION's metal — and steel laid before desertify()
    arrives as the dial's blue (the draw_gold_strikes argument, pointed at
    steel). So this half keeps everything that must ride the colourway —
    the cover patch over the baked figure, the hold-and-step scheduler,
    the odometer cells — exactly as it was, and draw_ledger_figure lays
    the metal on the far side of the duotone. Two calls, one instrument;
    main() makes both."""
    led = _ledger_now(now)
    if led is None:
        return
    # THE HOLD-AND-STEP (see LEDGER_STEP_MIN_S): the figure on the glass is
    # _LED["step_val"], not the live integral — it stands still between
    # steps. Re-seated silently if the integral moves BACKWARD (a fresh
    # stamp after a re-bake), because holding a figure the ledger no longer
    # supports would overstate the owner's own money.
    if _LED["step_next"] == 0.0 or led["shown"] < _LED["step_val"]:
        _LED["step_val"] = led["shown"]
        _LED["step_at"] = now
        _LED["step_next"] = now + random.uniform(LEDGER_STEP_MIN_S,
                                                 LEDGER_STEP_MAX_S)
    elif now >= _LED["step_next"]:
        gap = now - _LED["step_at"]
        _LED["step_val"] = led["shown"]
        _LED["step_at"] = now
        _LED["step_next"] = now + random.uniform(LEDGER_STEP_MIN_S,
                                                 LEDGER_STEP_MAX_S)
        _LED["flash"] = now  # the number's blink: the flash it already has
        _LED["throb"] = now  # ...and the caption's swell (draw_gold_strikes)
        print(f"ledger: STEP to {int(_LED['step_val']):,} after {gap:.1f}s "
              f"— next in {_LED['step_next'] - now:.0f}s", flush=True)
    txt = f"{int(_LED['step_val']):,}"
    cover = _LED["cover"]
    if cover is not None and _LEDGER_PATCH[0] is not None:
        # THE OCEAN GOES BACK ON. The patch is base.png's background, but the
        # frame under this call is screen(base, ocean) and the swell drifts —
        # a cover carrying one frame's swell forever would sit on the dial as
        # a faint rectangle that breathes out of step with everything around
        # it. ocean_overlay is cached on its own key and the compose loop has
        # already asked for this same `now`, so this is a dict hit.
        frame.paste(ImageChops.screen(
            _LEDGER_PATCH[0], ocean_overlay(now).crop(cover)), cover[:2])
    # ── the odometer ────────────────────────────────────────────────────
    # Cells are keyed from the RIGHT, because that is the end that stays put:
    # when the counter grows a digit, position 0 is still the units.
    cells, old = [], _LED["cells"]
    flash = False
    for i, ch in enumerate(reversed(txt)):
        prev = old[i] if i < len(old) else None
        if prev is None:
            cells.append({"ch": ch, "prev": ch, "at": 0.0})
        elif prev["ch"] != ch:
            cells.append({"ch": ch, "prev": prev["ch"], "at": now})
            if i >= 2 and ch.isdigit():
                flash = True
        else:
            cells.append(prev)
    _LED["cells"] = cells
    if flash:
        _LED["flash"] = now


def _led_paste(dst: "Image.Image", d, gx: float, gy: float, ch: str, f,
               k: float = 1.0, lift: float = 0.0) -> None:
    """One APPLIED blue-steel numeral, pasted from a cached embossed sprite.

    VISION's exact relief (_aura_embossed, refile three): top-edge rim,
    under-edge occlusion, vertical face gradient, one overhead light — so
    the figure and the wordmark read as struck by the one bezel light.
    Eleven glyph sprites per size (digits and the comma; positions rounded
    to keep fx=0, or every step would mint a fresh sprite per subpixel).
    `k` is the roll's weight — the arriving digit brightens INTO the
    settled metal, never past it, the strobe lesson _led_glyph's headstone
    keeps — and `lift` is the step flash; either modulates a copy small
    enough that the point() costs nothing at a cell's size.
    """
    spr, px, py = _aura_embossed(
        d, ch, f, 0.0, VISION_LO, max(1.5, f.size / 24.0),
        float(round(gx)), float(round(gy)),
        (STEEL_FACE_TOP, STEEL_FACE_BOT, STEEL_RIM, STEEL_UNDER))
    if k < 1.0 or lift > 0.0:
        def mod(p, _k=k, _l=lift):
            p = p + (255 - p) * 0.55 * _l
            return int(p * (0.45 + 0.55 * _k))
        r, g, b, a = spr.split()
        spr = Image.merge(
            "RGBA", (r.point(mod), g.point(mod), b.point(mod), a))
    dst.paste(spr, (px, py), spr)


LEDGER_COIN = Path.home() / "aura_face" / "pushers" / "ledger_coin.png"
#: v3 (owner): the medallion joins the jewels' own arc — SAME diameter
#: as SLEEP and POWER (128), SAME radius (408), and the third stop on an
#: equally-spaced run: power at 145.2 deg, sleep at 174.2, the coin at
#: 203.3 — 29 degrees apart each, three pieces of case furniture on one
#: invisible circle. Derived, not eyeballed.
LEDGER_COIN_XY = (165, 379)
LEDGER_COIN_D = 128
_COIN = {"im": None}


def _ledger_coin_im():
    if _COIN["im"] is None:
        if not LEDGER_COIN.exists():
            _COIN["im"] = False
        else:
            im = Image.open(LEDGER_COIN).convert("RGBA")
            im = im.resize((LEDGER_COIN_D, LEDGER_COIN_D), Image.LANCZOS)
            r, g, b, a = im.split()
            #: the blank renders pale champagne; strike coinage is warmer
            #: v2: barely warm (owner: "the color is tacky" — the brassy
            #: tint went; the coin now wears the bezel band's own pale
            #: champagne, which is what old money looks like)
            im = Image.merge("RGBA", (r,
                                      g.point(lambda v: int(v * 0.985)),
                                      b.point(lambda v: int(v * 0.90)), a))
            _COIN["im"] = im
            print("ledger: medallion blank loaded", flush=True)
    return _COIN["im"] if _COIN["im"] is not False else None


_COIN_SYNC = {"mtime": None}


def _coin_stamp_sync() -> None:
    """The medallion reads its own stamps, straight off the landed bake.

    The layers-plumbed _ledger_sync has a silent early-return this theme
    was hitting (no log line either way — §1's exact shape). The coin
    does not inherit that: one stat, one read, and BOTH outcomes say so
    in the log."""
    try:
        pth = Path("/tmp/aura_face/base.png")
        mt = pth.stat().st_mtime
        if _COIN_SYNC["mtime"] == mt:
            return
        _COIN_SYNC["mtime"] = mt
        base = Image.open(pth).convert("RGB")
        if tuple(_stamp_rgb(base, 0)) != LEDGER_STAMP_MAGIC:
            _LED["have"] = False
            print("coin: base.png carries no ledger stamp", flush=True)
            return
        _LED["shown"] = float(_stamp_int(base, 1))
        _LED["rate"] = float(_stamp_int(base, 2))
        _LED["real"] = float(_stamp_int(base, 3))
        _LED["rate_real"] = float(_stamp_int(base, 4))
        _LED["ts"] = _stamp_int(base, 5)
        _LED["have"] = True
        print(f"coin: stamp read — {int(_LED['shown']):,} credits at "
              f"{int(_LED['rate'])}/min", flush=True)
    except Exception as e:
        print(f"coin: stamp sync failed {e!r}", flush=True)


def draw_ledger_coin(frame: "Image.Image", now: float) -> bool:
    """The balance as a STRUCK MEDALLION (owner: "a very new radical
    treatment that is differentiated and beautiful … BE CREATIVE").
    Credits are minted money: the RTX renders the blank (reeded rim,
    domed field — scripts/render_ledger_coin.py), and the live value is
    struck into the metal here as incuse lettering — dark cut, lit lower
    edge, the way a die leaves a coin. One object replaces three text
    rows, which is the editing-down direction applied to the thing users
    care about most."""
    coin = _ledger_coin_im()
    _coin_stamp_sync()
    val = _ledger_now(now)
    if coin is None or val is None:
        return False
    cx, cy = LEDGER_COIN_XY
    frame.paste(coin, (cx - LEDGER_COIN_D // 2, cy - LEDGER_COIN_D // 2),
                coin)
    d = ImageDraw.Draw(frame)
    txt = f"{int(_LED.get('step_val') or val['shown']):,}"
    #: v3: the figure FITS ITSELF to the coin face (owner: "the number is
    #: overflowing the medallion") — probed on the widest digits so the
    #: size never breathes as they turn, largest size that stays inside
    #: 74% of the diameter. The strike stays deep.
    _probe = re.sub(r"\d", "8", txt)
    _fw = LEDGER_COIN_D * 0.74
    _sz = 40
    while _sz > 16:
        if d.textlength(_probe, font=face_for(_probe, "bold", _sz)) <= _fw:
            break
        _sz -= 2
    f_num = face_for(txt, "bold", _sz)
    f_cap = face_for("$LEDGER", "label", 16)
    for label, font, dy in (("$LEDGER", f_cap, -30), (txt, f_num, 4)):
        w = d.textlength(label, font=font)
        bb = font.getbbox(label)
        x0, y0 = cx - w / 2.0, cy + dy - (bb[1] + bb[3]) / 2.0
        #: incuse strike: lit lower-right edge first, then the dark cut
        d.text((x0 + 2.0, y0 + 2.4), label, font=font,
               fill=(255, 248, 224, 235))
        d.text((x0, y0), label, font=font, fill=(30, 20, 6, 255))
    return True


def draw_ledger_figure(frame: "Image.Image", now: float) -> None:
    if _THEME.get("ledger_coin") and draw_ledger_coin(frame, now):
        return
    """The credits themselves, in applied blue-steel — VISION's metal.

    AFTER desertify(), unlike the cover it stands on (see draw_ledger's
    split note): ONE size fitted on the widest-digit probe, ONE tabular
    advance, right-anchored to the stack's shared edge. The step-pulse
    machinery — hold-and-step, the flash, the caption throb, the roll —
    is draw_ledger's and is untouched; this half only lays the metal."""
    if _ledger_now(now) is None or not _LED["cells"]:
        return
    txt = f"{int(_LED['step_val']):,}"
    y0, y1 = LEDGER_BAND
    d = ImageDraw.Draw(frame)
    # SIZED ON A PROBE OF THE WIDEST DIGITS, exactly as the clock is, and for
    # the clock's reason doubled: a counter fitted to "111,111" would be a
    # different size from one fitted to "888,888", so the numeral would
    # breathe as the digits turned — the kind of thing you notice and cannot
    # name. The probe also keeps fit_size's cache warm; fitting the live
    # string would miss it on every single frame.
    probe = re.sub(r"\d", "8", txt)
    size = fit_size(d, probe, "bold", LEDGER_FIT_W, LEDGER_FIT_H,
                    want=LEDGER_WANT, cap=LEDGER_CAP, who="$LEDGER counter")
    f = face_for(txt, "bold", size)
    # TABULAR BY CONSTRUCTION: every digit gets the widest digit's advance, so
    # a 1 turning into an 8 moves nothing to its left. A proportional counter
    # jitters, and a jittering number is unreadable at the 45 degrees this
    # dial is drawn for.
    w_dig = max(d.textlength(c, font=f) for c in "0123456789")
    w_sep = d.textlength(",", font=f)
    adv = [w_sep if c == "," else w_dig for c in txt]
    total = sum(adv)
    cover = _LED["cover"]
    # Right-anchored since the 2026-08-08 premium pass: both figures END at
    # the same edge, so "narrower than the cover" now only ever shows at
    # the LEFT end.
    if cover is not None and (LEDGER_RIGHT_X - total) > cover[0] \
            and not _LED["narrow"]:
        # The live figure is normally WIDER than the baked one it hides, which
        # is the whole point of the pass. If it ever comes out narrower the
        # baked digits show at the ends, and that is worth a line in the log
        # rather than a mystery on the glass.
        _LED["narrow"] = True
        print(f"ledger: {txt} sets {total:.0f}px against a cover from "
              f"x {cover[0]} — the baked figure may show at the left end",
              flush=True)
    # Vertically centred in the BAND on the probe's ink, so the row holds
    # still while the digits turn (a per-digit bbox would bounce on commas).
    bb = f.getbbox(probe)
    ybase = (y0 + ((y1 - y0) - (bb[3] - bb[1])) / 2.0 - bb[1])
    lift = max(0.0, 1.0 - (now - _LED["flash"]) / LEDGER_FLASH_S)
    roll_h = float(y1 - y0)
    cells = _LED["cells"]
    # RIGHT-JUSTIFIED (premium pass, superseding amendment 2's left edge —
    # the argument that the units end must hold still survives the flip:
    # cells are keyed from the right, and the right IS the anchor now, so
    # a grown digit walks the LEFT edge into the block's own whitespace).
    x = LEDGER_RIGHT_X - total
    for j, ch in enumerate(txt):
        cell = cells[len(txt) - 1 - j]
        w = adv[j]
        u = 1.0 if not cell["at"] else (now - cell["at"]) / LEDGER_ROLL_S
        if u >= 1.0:
            gw = d.textlength(ch, font=f)
            _led_paste(frame, d, x + (w - gw) / 2.0, ybase, ch, f,
                       1.0, lift)
        else:
            # A ROLL, CLIPPED TO ITS OWN CELL. Drawn on a crop of the frame
            # (which already carries the cover) so the two glyphs can run off
            # the top and bottom of the window without painting on the dial —
            # the drum turns behind an aperture, which is what makes it read
            # as an odometer rather than as a dissolve.
            box = (int(x), y0, int(x + w) + 1, y1)
            cellimg = frame.crop(box)
            oy = ybase - y0
            for glyph, dy, k in ((cell["prev"], -u * roll_h, 1.0 - u),
                                 (ch, (1.0 - u) * roll_h, u)):
                gw = d.textlength(glyph, font=f)
                _led_paste(cellimg, d, (w - gw) / 2.0, oy + dy, glyph, f,
                           k, lift)
            frame.paste(cellimg, box[:2])
        x += w


#: ── ...AND ITS OTHER HALF, THE RESERVE ───────────────────────────────────
#:
#: Owner, same breath: "make it a FUEL GAUGE, because that is what it is.
#: Unite it with the RESERVE arc — they are one quantity in two forms,
#: credits accrued and credits remaining ... A fuel gauge tells you RANGE,
#: not level: show time remaining, computed from the balance and the burn
#: rate. And it has a reserve light."
#:
#: The sub-dial, its scale, its hand and the bracket up to the $LEDGER block
#: are all BAKED — home.html's #reserve, whose comment measures every
#: clearance on it. Three things are added here and nothing there moves: the
#: RANGE plate under the gauge, and the lamp, which is the zone arc and the
#: rim lit up as the hand comes down onto E.
#:
#: GEOMETRY IS home.html's, x1.08. Pivot (301,615) viewBox, track r=72, rim
#: r=80, scale from 90 deg (E, straight down) through 120 deg to F.
#: x DIAL_K, 2026-08-06 night. home.html still draws this sub-dial at
#: (301,615) r=72/80 — every clearance its comment measures is a ratio and
#: survives the scale untouched — but #dial's transform lands it at
#: (340.8, 592.0) r=57.6/64.0 in viewBox, and THAT is where the range plate
#: and the reserve lamp have to find it.
#:
#: ── 2026-08-06, night: THE 5712 CLUSTER — THIS GAUGE GOES TO TEN O'CLOCK ─
#: Owner, by voice, EXPLICITLY superseding the even spacing set out in the
#: ROOM note below: "do NOT space the three complications evenly. Look at
#: the Patek reference 5712 — its complication layout is deliberately
#: ASYMMETRIC and clustered ... a POWER RESERVE as a fan gauge upper-left,
#: around ten o'clock ... the wedge ring already owns the right side, so
#: clustering the complications left and low puts them exactly where the
#: space is."
#:
#: The pivot goes 301,615 -> 324,407 viewBox, which #dial's transform lands
#: at display (387.9, 459.7): r=172.0 from the dial centre on a bearing of
#: 207.9 deg. Ten o'clock and four minutes.
#:
#: 172 IS A CEILING, NOT A CHOICE, and it is the whole reason this gauge did
#: not simply slide out to the rim. The $LEDGER block owns this bearing
#: OUTBOARD of here and cannot move — it carries a tap target. Its numeral
#: is fitted to LEDGER_FIT_W about LEDGER_MID_X in the band LEDGER_BAND, so
#: its inboard corner is (316, 412), r=243 from the centre at 198.8 deg. The
#: rim (69.1) clears that corner by 17.2 at r=172 and touches it at r=194.
#:
#: AND THE FAN HAD TO TURN, which is the one piece of internal geometry this
#: move changed. At a0=90 the F terminal and its letter sat at 210 deg —
#: pointing straight up-left INTO that same numeral, 7px off it. a0=130
#: swings the scale round to 130..250 so it opens OUTWARD along the pivot's
#: own bearing (208 deg, the arc's midpoint is 190): E lands at (335.7,
#: 521.8) in open glass above the RANGE plate and F at (360.2, 383.3), 38.2
#: clear of the numeral. The sentence home.html's own note makes — FULL IS
#: UP, EMPTY IS DOWN — survives it exactly: F at 250 is up, E at 130 is
#: down-left, and the hand still falls as the day burns.
#:
#: Everything INSIDE the register is untouched — track, rim, thirteen
#: graduations, the two crossing terminals, the broad flat baton, the 24
#: degrees of reserve zone — so every clearance measured in home.html's
#: #reserve comment is a ratio about this pivot and still holds. What is new
#: is the neighbourhood, and it is measured here: SLEEP's disc 113 clear,
#: POWER's 200+, the wedge ring's padded inner edge (287.9) 46.8 clear of
#: the furthest ink, the quiet centre 102.9 clear of the rim. The $LEDGER
#: TAP CIRCLE rides RES_PIVOT and therefore moves with the instrument it is
#: drawn on — it now reaches r=252 against that 287.9, where at 7 o'clock it
#: reached 278.5, so it is strictly further from every wedge than it was.
#:
#: ── 2026-08-07: NINE, THREE AND SIX, AND ALL THREE THE SAME SIZE ─────────
#:
#: Owner, by voice, from the Royal Oak Chronograph 41 in front of him and
#: EXPLICITLY superseding the 5712 cluster above: "see the way the three
#: complications are situated BELOW the AUDEMARS PIGUET font ... the wordmark
#: lives at the TOP ... the three complications then hang BELOW it: one at
#: nine and one at three, both sitting on the horizontal centreline, and the
#: third at six, below centre. They form a downward-pointing triangle ...
#: ALL THREE ARE THE SAME SIZE ... it is what separates this from the Patek
#: 5712, where the registers differ in size deliberately. Equal diameters,
#: equal ring weight, equal treatment. The symmetry is the point: it is what
#: makes the dial look engineered rather than arranged."
#:
#: So both halves of the 5712 note are dead — the asymmetric CLUSTER and the
#: three deliberate SIZES — and they are left standing above with their date
#: because the argument in them (the wedge ring owns the right side, so the
#: space is left and low) is the argument this layout has to answer. It
#: answers it by measurement, below.
#:
#:     RESERVE   pivot (348, 540)   nine o'clock, on the centreline
#:     ROOM      pivot (732, 540)   three o'clock, on the centreline
#:     MOONPHASE pivot (540, 732)   six o'clock, below centre
#:
#: ONE RADIUS AND ONE FLANGE FOR ALL THREE, and they are the MOONPHASE's own
#: (r=192, rim=88) rather than an average: that register is the only one of
#: the three whose interior is fitted — a 124x84 lens, a 31-day track and a
#: pointer, each measured off a render — so equalising downward would have
#: re-cut the showpiece to answer a brief about symmetry. Equalising UPWARD
#: costs nothing but room, and the room is there.
#:
#: EVERY CLEARANCE THE NEW RING OF THREE HAS TO PROVE, in display px:
#:   outward     192 + 88 = 280 against the wedge ring's padded inner edge at
#:               287.9 — 7.9, which is exactly what the MOONPHASE has had
#:               since it grew, on all three flanks now instead of one.
#:   inward      192 - 88 = 104 against the tourbillon's furthest ink at
#:               97.3 — 6.7, where the three used to give 5.6 / 6.5 / 42.
#:               See TOURB_R: that radius is a ceiling and this raises it.
#:   between     adjacent pivots are 192·sqrt2 = 271.5 apart against two
#:               flanges of 88 — 95.5 of open dial between each pair.
#:   $LEDGER     its numeral's inboard corner (316, 412) is 131.9 from the
#:               nine o'clock pivot, so 43.9 clear of that flange, where the
#:               ten o'clock cut had 17.2. The block does not move.
#:   SLEEP       (191, 575), disc 44.8: 160.9 centre to centre, 28.1 clear.
#:   POWER       (252, 740), disc 44.8: 155 clear of the six o'clock flange.
#:   wordmark    the brand block inks y 253..271 and the highest flange top
#:               is y 452 — the wordmark is alone above the three, which is
#:               the composition the owner is describing.
#:
#: THE $LEDGER TAP CIRCLE rides RES_PIVOT and moves with it: it now reaches
#: r=272 from the dial centre against the padded band at 287.9, and it clears
#: SLEEP's own circle by 21.9. Nothing new becomes tappable. The one overlap
#: worth stating is that the flange's ink passes 1.2px inside the corner of
#: LEDGER_TAP_BOX — which is the SAME target, so there is nothing to resolve.
#:
#: WRITTEN IN home.html's UNITS, as this pair always has been: PR.cx/cy/r/rim
#: on that page carry 277.8 / 500 / 92.6 / 101.9 and land here through
#: #dial's scale(0.80) and VB_PX. They move in one commit or the range plate
#: and the reserve lamp paint where the gauge used to be.
#: Every internal number of the gauge — a0, the sweep, the zone, the thirteen
#: graduations, the crossing terminals, the baton — is a RATIO about the
#: pivot and survives the move and the growth untouched.
#:
#: ── 2026-08-07, later: 120 DEGREES APART, ON THE ONE CIRCLE ──────────────
#:
#: Owner, at the glass, on the arrangement immediately above: "move the
#: reserve and room volume up, we want symmetry here. those 4 complications
#: should look elegantly equally spaced."
#:
#: NINE, THREE AND SIX ARE NOT EVENLY SPACED, which is the thing he can see
#: and the thing the note above did not check: 180, 0 and 90 degrees are gaps
#: of 180, 90 and 90. It is a downward triangle, but a lopsided one. On a
#: circle of three, "elegantly equally spaced" has exactly one geometric
#: reading — 120 degrees — and it is reachable by moving both of the two that
#: CAN move UP by 30, which is also the word he used. The MOONPHASE holds at
#: six: its 31-day track and pointer are read at the bottom of the dial and
#: it is the only one of the three whose interior is fitted.
#:
#:     RESERVE   r=192.0 at 210 deg   (was 180 — up 30)
#:     ROOM      r=192.0 at 330 deg   (was   0 — up 30)
#:     MOONPHASE r=192.0 at  90 deg   (unmoved)
#:
#: ONLY THE BEARINGS MOVE, and that is the half of the note above this change
#: leans on rather than replaces. One radius, one flange, one track still —
#: so every clearance measured in RADIUS is the same number it was: 7.9
#: outward to the wedge ring's padded inner edge at 287.9, 6.7 inward to the
#: tourbillon's furthest ink at 97.3. What improves is the gap between
#: neighbours: adjacent pivots are now 2 x 192 x sin(60) = 332.6 apart
#: against two flanges of 88, i.e. 156.6 of open dial between each pair,
#: where the right-angled layout gave 95.5.
#:
#: MEASURED OFF THE CONSTANTS BELOW rather than off the intent, because that
#: is what was asked for — centres (373.74, 444.01), (706.28, 444.01) and
#: (540, 732); radii 191.98, 192.00 and 192.00, a spread of 0.02 px; bearings
#: 210.00, 330.00 and 90.00, gaps 120.00 / 120.00 / 120.00.
#:
#: THE FANS STILL OPEN OUTWARD, so RES_A0 and ROOM_A0 hold: the RESERVE's
#: scale runs 130..250 about a midpoint of 190 against a pivot bearing of
#: 210, and FULL IS UP / EMPTY IS DOWN is unchanged. (The ROOM's own note
#: still describes its scale as the RESERVE's mirrored; it has not been that
#: since RES_A0 went 90 -> 130, and this change does not make it so.)
#:
#: WHAT ELSE MOVED, AND WHAT DID NOT:
#:   RANGE plate  follows its gauge, but NOT to 100 straight below the new
#:                pivot — see RANGE_XY, where straight down now points at
#:                the tourbillon.
#:   ROOM's rows  the NAME row's left corner is now (654, 540), which is 114
#:                from the dial centre — 16.7 clear of that 97.3, where at
#:                three o'clock it had 80. It is the tightest thing this
#:                move creates and it is still positive.
#:   F terminal   (339.5, 349.9), r=276.3 — 11.6 inside the padded band.
#:   $LEDGER      DOES NOT MOVE. It is baked, it carries a tap target, and
#:                its place is stated in five constants here plus a
#:                transform in home.html. THE COST, measured rather than
#:                hidden: the widest fitted numeral inks to (316, 410) and
#:                the RESERVE's new flange reaches x=292.5 on that row, so
#:                the last ~23px of the WIDEST figures now sit over the
#:                pocket's edge. Figures at the ordinary width (~110px) set
#:                to x≈299 and clear it. This is the one clearance the
#:                layout loses; fixing it means moving the block, which is
#:                its own change and not this one.
#:   wordmark     the brand block still inks y 311..329 alone above all
#:                three; the highest flange top is now y=356, so 27px of air
#:                where nine/three gave 123.
#:
#: home.html's PR.cx/cy carry the RESERVE's half of this and move in the same
#: commit, exactly as they have through every previous move of this gauge.
REG_R = 223.2                          # 222.2 home units x 0.93 x 1.08
# 90, 2026-08-07: the owner, at the glass with the grown flanges: "shrink
# the 3 complications to be roughly the same size as the flywheel." The
# tourbillon aperture is ~90px; equal weights across the four is the
# composition he keeps asking this face for.
REG_RIM = 90.0
REG_TRACK = 80.0                       # scaled with the 90px flange
#: (277.8, 500) -> (307.57, 388.9), 2026-08-07 later: 222.2 home units from
#: the dial centre — the radius it already had — swung to 210 deg. See the
#: note above; home.html's PR.cx/cy carry the same two numbers.
#: (307.57, 388.9) -> (336.2, 405.4), 2026-08-07 14:49: MEASURED off the
#: live panel — RESERVE r=212.2 at 209.3 deg against ROOM 189.3 / MOON
#: 191.2, so the margins to the tourbillon were not equidistant. In to
#: r=190 on the same 210-degree ray, display (375.5, 445.0). home.html's
#: PR.cx/cy carry the same two numbers.
#: (336.2, 405.4) -> (320.7, 396.5), 2026-08-07 amendment: ALL THREE
#: subdials equidistant at r=208 from the dial centre, on their existing
#: rays — the owner: the reserve closer to the centre, the ROOM and the
#: moon-time OUT, "they have plenty of margin and they are crowding the
#: center right now." His "closer" is against the measured 212.2 above;
#: from the r=190 this constant has held since 14:49 the move is OUTWARD,
#: to display (359.9, 436.0). ROOM_PIVOT and MOON_XY take the same radius
#: in this commit; home.html's PR.cx/cy carry the same two numbers. Inner
#: edges land at r=118 against the tourbillon's ~95. The one clearance
#: that worsens: the flange's left edge on the $LEDGER numeral row goes
#: x=292.5 -> ~274, which the standing brief's ledger-left move clears.
#: (320.7, 396.5) -> (297.4, 383.0), 2026-08-07 amendment 2: FURTHER OUT —
#: the owner, superseding the radius above: "the 3 complications are still
#: too close to the center, move them outwards more." ALL THREE subdials to
#: r=235 display on their existing rays (210/330/90), display (336.5,
#: 422.5) here. The margins, measured: outer edges land at 325 against the
#: wedge band's inner edge at ~370, still 45 clear; inner edges at 145
#: against the tourbillon's ~95. The spoken brief derived home.html's
#: polygon delta from the 307.57/388.9 anchor — two moves stale, the same
#: trap the amendment above records — so those lists translate by
#: (-23.3, -13.5), measured from where the points actually stand.
#: ROOM_PIVOT and MOON_XY take the same radius in this commit; home.html's
#: PR.cx/cy carry the same two numbers. The flange's left edge on the
#: $LEDGER numeral row stays ~272, which the block's left-justify
#: (LEDGER_LEFT_X, this commit) clears.
RES_PIVOT = ((500.0 + (297.4 - 500.0) * DIAL_K) * VB_PX,
             (500.0 + (383.0 - 500.0) * DIAL_K) * VB_PX)
RES_R = 79.6 * DIAL_K * VB_PX          # = REG_TRACK (80) — home PR.r moves too
RES_RIM = 89.6 * DIAL_K * VB_PX        # = REG_RIM (90) — home PR.rim moves too
#: 90 -> 130, 2026-08-06 night: see THE FAN HAD TO TURN above. home.html's
#: PR.a0 carries the same number and the two must move in one commit.
RES_A0, RES_SWEEP, RES_ZONE = 130.0, 120.0, 24.0
#: home.html's PR_DAY_CREDITS. Stated twice, in two languages, so it moves in
#: one commit — the same contract SLEEP_XY/POWER_XY have with that file. It
#: is one DAY's allowance, measured on this machine 2026-08-06.
RES_DAY_CREDITS = 150000.0
#: "AS THE NEEDLE APPROACHES E ... AND GO AMBER UNDER A DAY." The amber
#: threshold is the ZONE THE DIAL ALREADY PAINTS (the last 24 of 120 degrees,
#: i.e. a fifth of the tank) and NOT a literal day, and that is a deliberate
#: reading of the ask rather than a liberty. The full scale IS one day's
#: allowance — so "under a day of range" is true at every reading this gauge
#: can ever give, and a lamp that is always lit is decoration, which is the
#: silent half of §1 wearing an amber bulb. The throb starts a third of the
#: way up and ramps in, so approaching the zone is visible before entering it.
RES_AMBER_FRAC = RES_ZONE / RES_SWEEP
RES_THROB_FRAC = 0.35
#: The range plate, under the gauge. MEASURED clearances: the E index's ink
#: ends at y=777, the POWER disc is centred (180,790) with a 70px tap radius
#: and the nearest ink here is 92 from it, and the furthest corner of the
#: block sits at r=297 from the dial centre against the wedge ring's inner
#: edge at 362.9 — so no wedge, button or label is touched.
#: (396,745) -> (330,570), 2026-08-06 night: the plate follows its gauge to
#: ten o'clock, and where it lands is the tightest corner of the new layout.
#: It sits under the E terminal rather than under the pivot, because under
#: the pivot puts its right edge 78 from the middle of the glass and the
#: owner's own instruction is that the centre stays quiet. MEASURED against
#: the four things that box it in: SLEEP's disc 17.0, the moonphase
#: register's flange 20.8, the E letter 34.1, and its own outermost corner at
#: r=293.1 — inside the ring's padded band, as it has been since DIAL_K (that
#: corner was at r=333), but at 167.4 deg, where no wedge's arc reaches.
#: The first cut of this had it at y=570 and the flange was 7.9 away; 556 is
#: the answer to a measurement, not a second opinion.
#: (330,556) -> (348,640), 2026-08-07: the plate follows its gauge to nine
#: o'clock and goes back UNDER THE PIVOT, which the note above rejected for a
#: reason that has expired — at ten o'clock, under the pivot put the plate's
#: right edge 78 from the middle of the glass, and the pivot is now 192 out
#: instead of 172 and 12 degrees further round, so the same placement leaves
#: 116. It is also what makes this plate and the ROOM dial's name plate read
#: as the same part on two registers, which is "equal treatment".
#: MEASURED off the drawn rows rather than derived: draw_centred sets from
#: the TOP, so the figure inks y 640..668 and the caption 672..685 — the
#: figure's top is 100 below the pivot, i.e. 12 clear of an 88 flange, and
#: the caption's widest case ("NOTHING BURNING", ~130px) reaches x=283 at
#: y=685, which is 18.3 from the POWER disc's edge. The furthest corner of
#: the block sits at r=186 from the dial centre, nowhere near any wedge.
#: (348,640) -> (348,560), 2026-08-07 later: the gauge went up to 210 deg
#: (see the note at REG_R) and the plate goes with it — but NOT to 100
#: straight below the new pivot, which is the placement the paragraph above
#: argued for. At nine o'clock "straight down" ran along the dial's edge;
#: from 210 deg it runs INTO the middle of the glass, and a plate centred
#: (374, 544) reaches x=450 on its figure row against the tourbillon's
#: furthest ink at 97.3 from the centre, which is x=442.8 on that row.
#: SO IT KEEPS ITS OWN x — the one number in this plate's history that has
#: never had to move — and follows the pivot up by 80. MEASURED there: the
#: flange's bottom edge is y=528 at x=348, so 32px of air above the figure;
#: the widest figure's outer corner is r=272.3 from the dial centre, 15.6
#: inside the wedge ring's padded band at 287.9; the block's nearest ink to
#: the centre is 117.7 out, 20.4 clear of that 97.3; SLEEP's disc is 37.6
#: away and POWER's 91.7.
#: (348,560) -> (312,628), 2026-08-07: THE TOURBILLON GREW (TOURB_R 95 ->
#: 130) and 560 sat inside the new well twice over — the widest figure
#: ("47 HOURS", 140px) inked to 123.6 from the dial centre against ink now
#: reaching ~132.6, and its right edge at x=418 sat inside the aperture's
#: grown damage rect (x 402..678), where every rect repaint would rub it
#: out (see _tourb_rect_paint). So back DOWN into the nine-o'clock pocket
#: the (348,640) era used, and LEFT until even RANGE_W's worst case stops
#: at x=400.4, outside the rect. MEASURED there: nearest figure ink to the
#: centre 165+, SLEEP's disc 17.5 clear (the (330,556) era accepted 17.0),
#: POWER's 25+, the moonphase flange 50+.
RANGE_XY = (312, 628)                  # was (348, 560), (348, 640),
                                       # (330, 556), (396, 745), (360, 796)
RANGE_W = 190.0 * DIAL_K
RES_AMBER = (255, 176, 64)
#: 2026-08-07: the throb ring's rim (RES_PIVOT + 90) reaches x=426.5, inside
#: the tourbillon's grown damage rect (x 402..678) — a rect repaint would
#: erase that arc mid-breath. Rather than teach the rect path about it, the
#: fast path stands down while the ring is up, which is the `plain` gate's
#: own policy for everything else painted after the movement.
_RES_THROB = {"up": False}
RES_METAL = _THEME["res_metal"]        # the colourway's metal, applied
                                       # AFTER desertify (see below), so it
                                       # rides the theme table (2026-08-08):
                                       # rose gold (232,168,128) L=182.6 on
                                       # patek, brushed steel (176,184,196)
                                       # L=182.9 on royal-oak — the plate
                                       # keeps its weight beside the amber
                                       # lamp on either row.


def _range_text(led) -> tuple:
    """(figure, caption) for the range plate — what a fuel gauge is for.

    "I cannot tell" gets its own answer (§2): with nothing burning there is
    no projection to make, and the plate says so rather than showing the
    infinity that division would produce.
    """
    rem = max(0.0, RES_DAY_CREDITS - led["real"])
    rate = led["rate_real"]
    if rate <= 0.0:
        return ("—", "NOTHING BURNING")
    mins = rem / rate
    if mins < 90.0:
        n = int(round(mins))
        return (f"{n} MIN", "LEFT AT THIS RATE")
    hours = mins / 60.0
    if hours < 48.0:
        n = int(round(hours))
        return (f"{n} HOUR" + ("" if n == 1 else "S"), "LEFT AT THIS RATE")
    n = int(round(hours / 24.0))
    return (f"{n} DAY" + ("" if n == 1 else "S"), "LEFT AT THIS RATE")


def draw_reserve(frame: "Image.Image", now: float) -> None:
    """The range plate and the reserve light.

    DRAWN AFTER desertify(), unlike the counter, and that is the file's own
    policy rather than an inconsistency: everything above the colourway is
    ambient and wears it, everything below carries MEANING in its colour. A
    reserve light that had been duotoned into rose gold would be a warning
    lamp in the colour of the thing it is warning about.
    """
    led = _ledger_now(now)
    if led is None:
        _RES_THROB["up"] = False        # nothing painted, nothing to protect
        return
    frac = max(0.0, min(1.0, 1.0 - led["real"] / RES_DAY_CREDITS))
    low = frac <= RES_AMBER_FRAC
    col = RES_AMBER if low else RES_METAL
    # The throb this face already has — the enrolment ring's 1.15 Hz breath,
    # same rate, so the two never beat against each other on one screen.
    k = 0.0
    if frac <= RES_THROB_FRAC:
        k = min(1.0, (RES_THROB_FRAC - frac)
                / max(1e-6, RES_THROB_FRAC - RES_AMBER_FRAC))
    _RES_THROB["up"] = k > 0.0          # stands the tourbillon's rect path
    if k > 0.0:                         # down; see the note at _RES_THROB
        ph = 0.5 + 0.5 * math.sin(now * math.tau * 1.15)
        a = int(235 * k * (0.35 + 0.65 * ph))
        r = int(RES_RIM) + 8
        lay = Image.new("RGBA", (2 * r, 2 * r), (0, 0, 0, 0))
        dl = ImageDraw.Draw(lay)
        dl.arc([r - RES_R, r - RES_R, r + RES_R, r + RES_R],
               RES_A0, RES_A0 + RES_ZONE, fill=col + (a,), width=7)
        dl.ellipse([r - RES_RIM, r - RES_RIM, r + RES_RIM, r + RES_RIM],
                   outline=col + (a // 2,), width=2)
        frame.paste(lay, (int(RES_PIVOT[0]) - r, int(RES_PIVOT[1]) - r), lay)
    d = ImageDraw.Draw(frame)
    fig, cap = _range_text(led)
    f_fig = face_for(fig, "bold", 28)
    f_cap = face_for(cap, "label", 13)
    draw_centred(d, RANGE_XY[0], RANGE_XY[1], fig, f_fig, col, 1.0,
                 limit=RANGE_W)
    draw_centred(d, RANGE_XY[0], RANGE_XY[1] + 32, cap, f_cap,
                 tuple(int(c * 0.72) for c in col), 1.6, limit=RANGE_W)


#: ── MORE GOLD, SPRINKLED — 2026-08-07, amendment 2 ────────────────────────
#:
#: Owner: "the colors are still too uniformly drab ... extend the accent in
#: small doses: the counterweight tails of the three subdial hands, the
#: reserve's F and E letters, the moonphase's 24h hand tip. Sprinkled means
#: sprinkled — half a dozen small strikes, not a gold wash."
#:
#: WHY THESE TWO REGISTERS ARE RE-STRUCK AFTER desertify() RATHER THAN
#: COLOURED AT THE SOURCE: the ROOM hand is drawn before the duotone and
#: the RESERVE hand and its letters are BAKED (home.html) — and desertify()
#: opens with convert("L"), so gold laid on that side arrives as the dial's
#: blue. The moonphase hand is the one of the three already drawn on this
#: side, so it alone takes tail/tip directly (see _moon_register).
#:
#: THE RESERVE'S ANGLE IS RECOMPUTED, NOT SAMPLED: the baked hand stands at
#: a0 + sweep*left (home.html setReserve) and `left` is the same
#: 1 - real/RES_DAY_CREDITS draw_reserve derives from the same stamp — so
#: the lobe lands on the baked counterpoise to within the still's ~20s of
#: burn, on a gauge that moves in hours. The hand's own K is home's stated
#: 1.2861 viewBox units, through the same #dial transform as everything
#: baked.
#:
#: THE LETTERS ARE A MASK, NOT A REDRAW: PIL's glyphs would never land on
#: the browser's, so the F and E are re-inked through their own measured
#: ink — the ledger cover's technique, pointed at two letters. The
#: threshold is a measured separation (§3): the letters read ~193 in the
#: bake, the rim ring that crosses their boxes ~150, so 175 splits them.
GOLD_FE_INK_L = 175
#: 14 -> 18, 2026-08-09: the letters went 21 -> 28px and moved 4 viewBox
#: units further out with the growth (home.html, "21 -> 28px" beside the
#: F/E builder — the two constants are the SAME number and move together or
#: this window samples the flange where the letter used to be). The box
#: stays +-14 x +-15: the glyph's half-cap goes 8 -> 10.5 and the widest
#: half-glyph 5 -> 7.5, so it still fits with margin, and the window
#: travelling outward with the letter takes it FURTHER from the rim arc
#: rather than nearer — measured on the re-bake, the arc no longer reaches
#: inside either box, where at 21px it clipped the F's by two rows.
GOLD_FE_R = 18.0
#: THE WINDOW IS CUT TO THE LETTER, 2026-08-09, and that is a FIX rather
#: than bookkeeping. It was (+-14, +-15) around a glyph that measured
#: (+-5, +-8), and the spare 9px of window on the inboard side had been
#: sampling the RIM ARC all along: on the 21px bake the F's window clipped
#: the arc two rows deep and the E's took a run of it, so a few px of flange
#: were being struck gold every bake. At 28px the letters measure (+-7,
#: +-11) and the same slack put the arc ON the window edge, which is where
#: it showed. (+-10, +-12) holds either letter with 3px of margin for a
#: browser that hints a pixel differently, and the nearest arc ink is then
#: outside the window in every direction — asserted on the re-bake, both
#: windows report their sampled ink clear of all four edges.
GOLD_FE_BOX = (10, 12)
_GOLD_FE: list = []


def _gold_fe_sync(base) -> None:
    """Per bake: mask the reserve's F and E out of base.png for the gold
    strike draw_gold_strikes lays after the duotone."""
    out = []
    try:
        r_let = RES_RIM + GOLD_FE_R * DIAL_K * VB_PX
        for a in (RES_A0, RES_A0 + RES_SWEEP):
            t = math.radians(a)
            cx = RES_PIVOT[0] + r_let * math.cos(t)
            cy = RES_PIVOT[1] + r_let * math.sin(t)
            bw, bh = GOLD_FE_BOX
            box = (int(cx) - bw, int(cy) - bh, int(cx) + bw, int(cy) + bh)
            m = base.crop(box).convert("L").point(
                lambda p: 255 if p > GOLD_FE_INK_L else 0)
            if m.getbbox() is None:
                print(f"gold: no letter ink in {box} — that end stays "
                      "steel this bake", flush=True)
                continue
            out.append((box, m))
    except Exception as e:                      # noqa: BLE001
        out = []
        print(f"gold: F/E masks not sampled {e!r}", flush=True)
    _GOLD_FE[:] = out


#: ── 2026-08-09: THE INDEX MARKS GO RED, AND THE TRACK GETS NUMBERS ────────
#: Owner, the two asks that land on the same geometry: "the subdial rings'
#: index marks" among the places Rosso must go, and "give the subdials
#: tachymeter-style numerals instead of the AP's plain tracks."
#:
#: A PLAIN TRACK IS A TRACK WITH NO NUMBERS ON IT, which is precisely what
#: both registers wear: thirteen graduations at three weights and not one
#: figure. A car gauge numbers its scale — that is the difference the owner
#: is naming, and it is the one mark of the four that a glance can read from
#: across the room.
#:
#: WHY THIS IS A SEPARATE OVERLAY AND NOT A COLOUR IN THE TILES, and it is
#: the same trap draw_gold_strikes exists for: the ROOM tile is composited
#: BEFORE desertify() and the RESERVE's scale is BAKED into base.png, so a
#: red drawn at either source arrives through convert("L") as a grey. Both
#: therefore get their red on this side of the duotone, from one baked tile
#: each, pasted once per frame. (The day/night register is already drawn
#: after the colourway and takes its red directly, at its own ticks.)
#:
#: THE RESERVE'S GEOMETRY IS THE ROOM'S, and that is not an assumption: the
#: ROOM was built as "the RESERVE, mirrored ... same track, same rim, same
#: 120 degrees of scale, same thirteen graduations with the same three
#: weights" (the note at THE ROOM), so the same k/weight/radius arithmetic
#: draws both and the two overlays cannot drift apart.
#:
#: 0 / 50 / 100 ON BOTH, because on both it is literally what the needle
#: reads: the RESERVE runs 0 at RES_A0 (nothing left) to 100 a sweep later,
#: and the ROOM runs 0 at ROOM_A0 (silence) to 100 at the top of its energy
#: scale. Numbering them the same is also what keeps them a set.
#: Fraction of the track the numerals stand on. The binding neighbour is the
#: RESERVE's own baked caption, and it is MEASURED on the shipped ferrari
#: bake (aura-shared/face-profiles/ferrari/base.png) rather than derived: the
#: word RESERVE's first ink row is at pivot+54, and at 0.52 the 0 — the
#: lowest of the three numerals, at RES_A0 — has its bottom at pivot+36.8,
#: so 17.2 px of air. (0.62 would also have cleared, at 11.5; 0.52 is chosen
#: for the ROOM's side, where a numeral further out starts crowding the tick
#: band it is labelling.) On the ROOM the same three land at (36,-21),
#: (36,21) and (0,42) about a pivot whose label is 64 above and whose name
#: row is 96 below — clear of both by more than a line.
INSTR_NUM_R = 0.52
INSTR_NUM_SIZE = 12
_INSTR_SCALE: dict = {}


def _instr_scale(tag: str, a0: float, sweep: float, track: float,
                 rim: float) -> "Image.Image":
    """One register's instrument scale — red index marks and three numerals
    on the track — baked once and held for the life of the process."""
    if tag in _INSTR_SCALE:
        return _INSTR_SCALE[tag]
    n = int(math.ceil(rim)) * 2 + 4
    c = n / 2.0
    lay = Image.new("RGBA", (n, n), (0, 0, 0, 0))
    d = ImageDraw.Draw(lay)

    def pt(a: float, r: float) -> tuple:
        t = math.radians(a)
        return c + r * math.cos(t), c + r * math.sin(t)

    # The thirteen graduations, at _room_tile's own radii and weights, so the
    # red lands exactly on the steel it is replacing rather than beside it.
    for k in range(13):
        a = a0 + sweep * k / 12.0
        end, major = k in (0, 12), k % 6 == 0
        r0 = rim if end else track
        r1 = track * (0.750 if end else (0.792 if major else 0.875))
        d.line([pt(a, r0), pt(a, r1)], fill=INSTR_RED + (255,),
               width=3 if end else (2 if major else 1))
    # ── 2026-08-09: MORE RED ON THE THREE COMPLICATIONS ──────────────────
    # Owner, at the glass: "add more red to the 3 complications." The index
    # marks and numerals were already the accent, so the registers were red
    # LINES on a steel gauge — correct, and not enough mass to register as
    # red from a step back. Two additions, both car-gauge idiom rather than
    # decoration, and both drawn HERE on purpose: this tile is composited
    # after desertify(), so its colour is real rather than a luminance the
    # duotone will re-tint. The bezel bands cannot carry red for exactly
    # that reason — they are metal drawn on the other side of the ramp.
    #
    #   * THE GAUGE RING, at the inner edge of the machined bezel, where the
    #     metal stops and the face begins. That edge is not a free choice:
    #     the bezel's chamfer lands ON the track by construction (see
    #     INSTR_BEZEL_LAND), so a ring at track+1 sits in the seam and reads
    #     as the painted lip of the instrument rather than a stripe across
    #     it. A full circle of accent on each register, which is also the
    #     "red all the way round" the ring-motif brief asked for.
    #   * THE REDLINE, the top sixth of the sweep, heavier and at the track.
    #     Every rev counter has one and it is the single most recognisable
    #     mark on a car instrument; on the ROOM and RESERVE it reads as the
    #     top of the scale, which is what it actually is.
    d.arc([c - (track + 1), c - (track + 1), c + (track + 1), c + (track + 1)],
          a0, a0 + sweep, fill=INSTR_RED + (208,), width=2)
    _rl = a0 + sweep * (5.0 / 6.0)
    d.arc([c - track, c - track, c + track, c + track],
          _rl, a0 + sweep, fill=INSTR_RED + (255,), width=4)
    f = face("label-b", INSTR_NUM_SIZE)
    for k, lab in ((0, "0"), (6, "50"), (12, "100")):
        nx, ny = pt(a0 + sweep * k / 12.0, track * INSTR_NUM_R)
        bb = f.getbbox(lab)
        draw_centred(d, nx, ny - (bb[1] + bb[3]) / 2.0, lab, f,
                     INSTR_RED + (255,))
    _INSTR_SCALE[tag] = lay
    print(f"instrument: {tag} scale baked {n}x{n} — red index marks and "
          "0/50/100 on the track", flush=True)
    return lay


def _instr_paste(frame: "Image.Image", tile: "Image.Image",
                 pivot: tuple) -> None:
    c = tile.width / 2.0
    frame.paste(tile, (int(round(pivot[0] - c)), int(round(pivot[1] - c))),
                tile)


def _strike_tip(d: "ImageDraw.ImageDraw", pivot: tuple, ang: float,
                K: float, needle: bool) -> None:
    """The red point, re-struck on the far side of the duotone over a hand
    that was laid in steel on the near side of it.

    The (r, w) arithmetic is _draw_hand's verbatim — same 72-unit track, same
    K contract — so the strike cannot land off the hand it is painting. Both
    callers draw at s=1.0, which is why `s` is not a parameter here."""
    t = math.radians(ang)
    ux, uy = math.cos(t), math.sin(t)

    def at(r: float, w: float) -> tuple:
        return (pivot[0] + r * K * ux - w * K * uy,
                pivot[1] + r * K * uy + w * K * ux)

    nose = ([(r, w) for r, w in NEEDLE_SHAFT if r >= NEEDLE_TIP_R] if needle
            else [(58.0, 1.7), (68.0, 0.0)])
    d.polygon([at(r, w) for r, w in nose]
              + [at(r, -w) for r, w in reversed(nose[:-1])],
              fill=HAND_TIP_INK)


def draw_gold_strikes(frame: "Image.Image", now: float) -> None:
    """The sprinkled gold that cannot ride its own draw call — the ROOM and
    RESERVE counterpoises and the reserve's two letters. AFTER desertify()
    and before the dial rotate, or it is not gold and does not turn.

    2026-08-09: on an INSTR row it also lays the two registers' red scales
    and the needles' red tips, for the same reason and at the same moment —
    everything here is a colour the duotone would eat."""
    d = ImageDraw.Draw(frame)
    if INSTR:
        # The scales go down FIRST, under the hands that read on them.
        _instr_paste(frame, _instr_scale("room", ROOM_A0, ROOM_SWEEP,
                                         ROOM_R, ROOM_RIM), ROOM_PIVOT)
        _instr_paste(frame, _instr_scale("reserve", RES_A0, RES_SWEEP,
                                         RES_R, RES_RIM), RES_PIVOT)
    ang = _ROOM.get("ang")
    if ang is not None:
        K = ROOM_R / 72.0
        t = math.radians(ang)
        tx = ROOM_PIVOT[0] + HAND_TAIL_R * K * math.cos(t)
        ty = ROOM_PIVOT[1] + HAND_TAIL_R * K * math.sin(t)
        tr = HAND_TAIL_W * K + 0.6
        d.ellipse([tx - tr, ty - tr, tx + tr, ty + tr], fill=HAND_TAIL_INK)
        if INSTR:
            _strike_tip(d, ROOM_PIVOT, ang, K, needle=True)
    led = _ledger_now(now)
    if led is not None:
        frac = max(0.0, min(1.0, 1.0 - led["real"] / RES_DAY_CREDITS))
        t = math.radians(RES_A0 + RES_SWEEP * frac)
        K = 1.2861 * DIAL_K * VB_PX
        tx = RES_PIVOT[0] - 20.0 * K * math.cos(t)
        ty = RES_PIVOT[1] - 20.0 * K * math.sin(t)
        tr = 8.2 * DIAL_K * VB_PX + 0.6
        d.ellipse([tx - tr, ty - tr, tx + tr, ty + tr], fill=HAND_TAIL_INK)
        if INSTR:
            # THE LEAF, NOT THE NEEDLE, and this is the one place the family
            # is knowingly split. This register's hand is drawn by home.html
            # (#res-hand) and baked into base.png, which is rendered ONCE for
            # the whole fleet and has no idea which theme the device wears —
            # the same argument that put the carbon weave in this file rather
            # than on that page (_carbon_weave_sync). A needle there would
            # arrive on the patek and royal-oak pucks too. So the ferrari's
            # reserve keeps the baked leaf and takes the red tip and the white
            # counterweight over it; the leaf's own tip triangle is struck,
            # because a needle-width strike would leave steel showing either
            # side of it. Re-baking that page per theme is the move that
            # closes this, and it is not a colour change.
            _strike_tip(d, RES_PIVOT, RES_A0 + RES_SWEEP * frac, K,
                        needle=False)
    for box, m in _GOLD_FE:
        frame.paste(TOURB_GOLD, box, m)
    # The $LEDGER brand line, same strike (see LEDGER_CAP_SEARCH). The steel
    # bezel overlay pastes after this, so the ring hairline crosses the gold
    # exactly as it crosses every other baked row on this rim.
    cap_gold = TOURB_GOLD
    if _LED["throb"]:
        # The step's throb (see LEDGER_STEP_MIN_S): a table lookup only
        # while the window is open; a frame outside it pays the falsy
        # check above and nothing else.
        u = (now - _LED["throb"]) / LEDGER_THROB_S
        if 0.0 <= u < 1.0:
            cap_gold = _LEDGER_THROB_TABLE[int(u * len(_LEDGER_THROB_TABLE))]
        else:
            _LED["throb"] = 0.0
    # Face first, then the relief pair over it (2026-08-08 premium pass):
    # the rim in the tourbillon's lit gold, the under edge in the
    # wordmark's own occlusion crack — one overhead light. UNDER BEFORE
    # RIM, the reverse of _aura_embossed's order, and measured before it
    # shipped: at this 17px the caption's bars are 1-2 mask rows tall, so
    # the two edge masks overlap and whichever pastes last owns the thin
    # strokes — occlusion-last read 1.77x top/under on the composite
    # (under the standard's 2x floor) where rim-last reads 3.3x on the
    # disjoint edge pixels, and a thin mark lit from above is what says
    # RAISED at all.
    for box, m, m_top, m_under in _GOLD_CAP:
        frame.paste(cap_gold, box, m)
        frame.paste(GOLD_UNDER, box, m_under)
        frame.paste(TOURB_GOLD_LIT, box, m_top)


#: The one new tap target on this face, and it is on the instrument itself:
#: the sub-dial and the block above it (owner: "A tap on it opens a card
#: offering more $LEDGER"). Hit-tested in the LOGICAL frame, after every
#: wedge and after both buttons, so no existing target changes shape,
#: position or meaning — the closest of them, POWER, is 192px away against a
#: combined 170.
#:
#: THE ONE PLACE THE TWO OVERLAP, stated rather than discovered later: the
#: $LEDGER block sits at r 375..425 from the dial centre, which is inside the
#: wedge ring's padded hit band, and its top-right CORNER touches -145 deg —
#: exactly where the REQUESTS/CLINIC arc's 8 deg of finger padding ends. That
#: corner therefore belongs to whichever of those two is LIVE, because they
#: are tested first and this is tested last. Nothing that was tappable
#: yesterday answers differently; the counter itself sits at -153 deg, well
#: clear, and the sub-dial's circle does not touch any wedge's box at all
#: (checked over the whole disc, not at its centre).
#: x DIAL_K, 2026-08-06 night, AND THIS IS THE ONE THAT MUST NOT BE MISSED:
#: it is a hit-test, so getting it wrong costs a tap target that answers
#: where nothing is drawn — invisible until somebody reaches for it. The
#: radius follows RES_PIVOT, which moved; the box was (84, 300, 252, 442).
LEDGER_HIT_R = 100.0 * DIAL_K
# x0 175 -> 66, 2026-08-07 amendment 2: the block is left-justified at
# LEDGER_LEFT_X=73 (its old left edge was ~86 and drifting with the figure),
# so the box follows the ink it is a target for. Nothing else answers on
# this rim — SLEEP's disc starts at y≈520, below the box.
# y (348, 462) -> (302, 417), 2026-08-07 ledger amendment: the block rose 45
# display px (see LEDGER_BAND) and the box follows the ink, same rule as
# amendment 2 above — top 2 over the figure's measured 304, bottom still
# under the bracket, which moved the same 45 (home.html PR_ANCHOR 410->365).
# (66, 302, 310, 417) -> (114, 337, 358, 457), 2026-08-07 amendment 4: the
# block moved 48 right / 40 down clear of the ring (see LEDGER_SEARCH) and
# the box follows the ink — top 2 over the figure's measured 339, bottom
# under the bracket (home.html PR_ANCHOR 365->405). SLEEP's disc still
# starts below the new bottom.
# (114, 337, 358, 457) -> (119, 339, 358, 457), 2026-08-08 premium pass:
# the right-anchored block's worst LEFT edge is the live figure's floor at
# LEDGER_LEFT_X=121 (measured baked left edges 143/157/121/184), so the
# box's left follows the ink in — a 20px strip that answered where nothing
# is drawn any more is the invisible-target trap this constant's own note
# warns about. Top 4 over the figure's measured 343; right and bottom
# unmoved.
LEDGER_TAP_BOX = (119, 339, 358, 457)


def _ledger_hit(x: float, y: float) -> bool:
    if math.hypot(x - RES_PIVOT[0], y - RES_PIVOT[1]) <= LEDGER_HIT_R:
        return True
    x0, y0, x1, y1 = LEDGER_TAP_BOX
    return x0 <= x <= x1 and y0 <= y <= y1


#: ── THE ROOM: THE THIRD COMPLICATION, 2026-08-06 late night ───────────────
#:
#: Owner, at the glass: "the centre is empty now that the wordmark is small,
#: and it wants THREE complications of similar size rather than two. You have
#: RESERVE and the MOONPHASE. For the third, use what no watch can have: this
#: device HEARS. Give it a ROOM complication — a small subdial reading the
#: live sound level of the room, with a needle that moves as people speak, and
#: the name of the last person it recognised beneath it. It is a real
#: instrument reading a real quantity, and it is the one dial on this face
#: that no watchmaker could put there."
#:
#: IT IS THE RESERVE, MIRRORED, and that is the whole of "they read as a set
#: rather than as three separate ideas". Every number below is RES_* reflected
#: about the panel's vertical axis or copied outright — same pivot radius from
#: the centre, same track, same rim, same 120 degrees of scale, same thirteen
#: graduations with the same three weights, the same broad flat baton hand.
#: Written as the RESERVE's constants rather than as fresh ones for the reason
#: DIAL_K states: if that sub-dial is ever re-cut, this one has to move in the
#: same commit or the pair stops being a pair.
#:
#: THE LAYOUT, and it is the only thing here that is new geometry. The three
#: now sit on ONE circle about the dial centre, 60 degrees apart:
#:
#:     RESERVE   r=198.5 at 150 deg   (unmoved — it is baked in home.html)
#:     MOONPHASE r=199   at  90 deg   (MOON_XY 758 -> 739; see that note)
#:     ROOM      r=198.5 at  30 deg   (here)
#:
#: EVERY CLEARANCE ON THIS SIDE IS THE RESERVE'S OWN, BY REFLECTION — the disc
#: reaches r=267.5 from the dial centre against the wedge ring's inner edge at
#: 317.9, so no wedge, hit-test or label is touched. The one thing that is NOT
#: a reflection is the name plate, which is set tighter than the RANGE plate
#: it mirrors. MEASURED off the rendered layer rather than derived, with the
#: longest name the limit allows: the whole complication inks x 642..781,
#: y 570..727, furthest point r=288.0 — 29.9 clear of the ring. (The RANGE
#: plate's own corner is at 333 and has been since DIAL_K, which is inside the
#: ring's padded band; that is recorded here rather than copied.) The moon
#: sits 56px off the name's left edge and 50 off the disc.
#:
#: THE LAST TENTH OF A PIXEL OF THAT, STATED: handle_tap pads the ring inward
#: to WEDGE_R0 - 30 = 287.9, so the outermost corner of the LONGEST name the
#: 128px limit allows is 0.1 inside the padded band — a press exactly there
#: would reach the LOCK wedge. Nothing new becomes tappable and nothing that
#: was tappable stops being so; what changes is that ink now sits under 0.1px
#: of a target it does not own, which is worth knowing before somebody
#: reports a wedge firing "on the name".
#:
#: IT ADDS NO TAP TARGET. handle_tap is untouched, _ledger_hit still tests one
#: circle at RES_PIVOT and this pivot is not it — "change no wedge's function,
#: position or tap target" (owner, same breath).
#:
#: NO E AND F, and that is a decision rather than an omission. home.html's
#: RESERVE names its ends because "how far round is the needle is not a
#: reading unless the ends are named" — true of a quantity you have to
#: interpret, and the reason that gauge carries two letters. This one is read
#: by MOTION: the owner asked for "a needle that MOVES as people speak", so
#: the scale's meaning arrives from the room rather than from its ends, and
#: the two heavy end graduations (the only ones that cross the track — that
#: sub-dial's own device for saying "this is the end") carry what is left.
#: The one place a letter could physically go on this flank is the radius
#: straight below the pivot, which is where the NAME goes, and the name is
#: the half of this complication the owner asked for by name.
#:
#: DRAWN BEFORE desertify(), like the moonphase and unlike the RANGE plate, so
#: it wears the colourway's steel rather than a colour chosen here. That is
#: what makes "same metal treatment" true by construction instead of by eye:
#: the RESERVE's sub-dial is baked into base.png and duotoned, the moon's
#: frame is drawn here and duotoned, and so is this. Nothing on it carries
#: meaning in its colour — there is no reserve LIGHT on a sound meter — so
#: nothing needs the exemption draw_reserve takes.
#:
#: ── 2026-08-06, night: SUPERSEDED IN ITS LAYOUT, NOT IN ITS IDEA ─────────
#: Owner, correcting the paragraph above by voice and saying so: "do NOT
#: space the three complications evenly ... the 5712 arrangement, adapted:
#: a POWER RESERVE ... upper-left, around ten o'clock; the MOONPHASE as the
#: largest of the three, lower-left around seven ... and a SMALL THIRD
#: subdial low-right around five. The upper right stays clean ... Same metal
#: treatment on all three so they read as a set, but NOT the same size — the
#: moonphase is the largest, the room dial the smallest."
#:
#: So the one-circle-60-degrees-apart layout above is dead, and this is what
#: replaced it (display px, from the dial centre):
#:
#:     RESERVE   r=172.0 at 207.9 deg   rim 69.1   (ten o'clock)
#:     MOONPHASE r=192.0 at 120.0 deg   rim 88     (seven o'clock, largest)
#:     ROOM      r=189.5 at  59.9 deg   rim 50     (five o'clock, smallest)
#:
#: THIS DIAL IS NO LONGER THE RESERVE MIRRORED, and that is the correction
#: rather than a drift: the owner asked for three sizes, so ROOM_R/ROOM_RIM
#: become numbers of their own instead of RES_R/RES_RIM. What is still
#: copied outright is everything that makes them read as a SET — the same
#: flange, the same track, the same thirteen graduations at the same three
#: weights, the same broad flat baton, the same steel drawn before
#: desertify(). "Same metal treatment ... but NOT the same size" is exactly
#: that split, and it is why the hand's K below is now derived from ROOM_R
#: instead of from DIAL_K: the baton is written in the RESERVE's own 72-unit
#: track, so dividing by 72 keeps its proportions when the track shrinks.
#:
#: WHERE IT SITS, MEASURED: pivot (635, 704), so the flange reaches r=239.5
#: from the dial centre against the wedge ring's padded inner edge at 287.9,
#: and it clears the moonphase register by 53. The NAME PLATE is the thing
#: that approaches the ring, as it was before: at 104px it inks to a corner
#: at r=277.9, 10 clear of that band — where the previous cut had 0.1, which
#: the note above records as a thing worth knowing. It is now ten times that
#: and no longer worth reporting.
#:
#: ── 2026-08-07: IT GOES TO THREE O'CLOCK AND BACK TO THE COMMON SIZE ─────
#: The owner's Royal Oak note (at REG_R) puts one register at nine and one at
#: three, both on the horizontal centreline, and makes all three the same
#: diameter — so "the room dial the smallest" above is superseded and this is
#: the RESERVE mirrored again, which is what the first cut of this dial was.
#: ROOM_R/ROOM_RIM therefore stop being numbers of their own and become the
#: shared pair; the hand's K goes on being derived from ROOM_R, so the baton
#: written in the RESERVE's 72-unit track grows with the track rather than
#: overhanging it. Pivot (635,704) -> (732,540).
#: Pivot (732,540) -> (706.28,444), 2026-08-07 later: three o'clock was not
#: evenly spaced from the other two, so this register goes UP 30 degrees to
#: 330 — see the note at REG_R for the arithmetic and every clearance it was
#: measured against. The radius is unchanged, so is ROOM_R/ROOM_RIM, and so
#: is every number inside this instrument.
#: (706.28, 444) -> (720.13, 436), 2026-08-07 amendment: OUT to r=208 on
#: the same 330-degree ray — all three subdials equidistant at r=208 (see
#: the note at RES_PIVOT). The owner: "they have plenty of margin" — the
#: flange's outer edge goes 280 -> 298 against the wedge band's inner edge
#: at ~370, and the inner edge to 118 where it crowded the tourbillon's
#: ~95 at 99. Every number inside the instrument is unchanged.
#: (720.13, 436.0) -> (743.52, 422.5), 2026-08-07 amendment 2: FURTHER OUT
#: to r=235 display on the same 330-degree ray — all three subdials again
#: (see the note at RES_PIVOT). The flange's outer edge goes 298 -> 325
#: against the wedge band's inner edge at ~370, the inner edge to 145
#: against the tourbillon's ~95. Every number inside the instrument is
#: unchanged.
ROOM_FEED = Path("/tmp/aura_face/room.json")
ROOM_PIVOT = (743.52, 422.5)
ROOM_R, ROOM_RIM = REG_TRACK, REG_RIM
#: The scale, reflected: 90 deg is straight down and QUIET, -30 is up-right
#: and LOUD, so the needle rises toward twelve as the room does. RES_A0/
#: RES_SWEEP run 90 -> 210, which is the same arc on the other flank.
ROOM_A0, ROOM_SWEEP = -30.0, 120.0
#: OFF-SCALE, and it is the whole of §1/§2 on this complication. A meter with
#: no feed must not read the same as a silent room — that is precisely the
#: silent success, and it would be the easiest one on this face to ship, since
#: a quiet house and a dead microphone both produce zero. So "I cannot tell"
#: gets its own answer: the needle parks 14 degrees BELOW the quiet end, where
#: no reading can put it, and the name row says so in words.
ROOM_PARK = 104.0
ROOM_NO_FEED = "NO EARS"
#: Older than this and the feed is not a reading, it is a memory. puck_ears
#: republishes every DOA_PERIOD_S (0.6 s), so six seconds is ten missed ticks
#: — long enough to survive a busy frame, short enough that a stopped ears
#: process shows up while somebody is still standing there.
ROOM_FRESH_S = 6.0
#: THE SCALE'S TWO ENDS, MEASURED ON THE ARRAY AND NOT CHOSEN. puck_ears
#: publishes the XVF3800's own speech energy, max across beams, which is the
#: quantity its DOA gate already reads every 0.6 s — so this costs the ears
#: nothing and it is a real instrument on a real quantity, which is the ask.
#: The numbers are that file's own measurements: a quiet room reads exactly 0
#: on every beam, DOA_SPEECH_MIN is 5000 (a floor with three orders of
#: magnitude of headroom, not a tuned threshold), one word read ~216,000 and
#: the owner speaking read 1,190,534. So the scale runs from the floor to
#: 1.2M and it is LOGARITHMIC, because that span is 240x and a linear needle
#: would sit on the stop for ordinary speech — the failure the RESERVE's own
#: full scale had to be re-measured to fix. One word lands at 0.69 of scale.
#: Expressed against the floor rather than in dBFS, which is the house rule.
ROOM_E0, ROOM_E1 = 5000.0, 1.2e6
#: Needle ballistics, in SECONDS rather than per-frame, because this face
#: runs at 8 fps idle and 40 while a finger is down and a per-frame constant
#: would make the needle twice as lively under a fingertip. Fast up, slow
#: down: a VU meter's asymmetry, and the reason a needle reads as a room
#: rather than as a flicker.
ROOM_RISE_S, ROOM_FALL_S = 0.12, 0.9
_ROOM: dict = {"mtime": None, "data": None, "n": 0.0, "t": 0.0}


def _room_now(now: float):
    """The feed, or None. None is drawn as a decline, never swallowed."""
    try:
        m = ROOM_FEED.stat().st_mtime
    except (FileNotFoundError, NotADirectoryError):
        _ROOM["mtime"] = _ROOM["data"] = None
        return None
    if _ROOM["mtime"] != m:
        _ROOM["mtime"] = m
        try:
            _ROOM["data"] = json.loads(ROOM_FEED.read_text())
        except Exception:
            _ROOM["data"] = None          # half-written; next tick
    d = _ROOM["data"]
    if not d or now - float(d.get("at", 0.0)) > ROOM_FRESH_S:
        return None
    return d


def _room_frac(energy):
    """Speech energy -> 0..1 of scale, or None for 'no reading'.

    None rather than 0.0 when the array answered nothing at all: a HID read
    that comes back empty is not a silent room, and the two must not arrive
    here as the same float (§2).
    """
    if energy is None:
        return None
    e = max(float(energy), 0.0)
    if e <= ROOM_E0:
        return 0.0
    return min(1.0, math.log10(e / ROOM_E0) / math.log10(ROOM_E1 / ROOM_E0))


def _room_needle(now: float, frac) -> float:
    """The needle's own position, in degrees. Ballistics live here."""
    dt = max(0.0, min(1.0, now - _ROOM["t"])) if _ROOM["t"] else 0.0
    _ROOM["t"] = now
    if frac is None:
        _ROOM["n"] = 0.0
        return ROOM_PARK
    tau = ROOM_RISE_S if frac > _ROOM["n"] else ROOM_FALL_S
    _ROOM["n"] += (frac - _ROOM["n"]) * (1.0 - math.exp(-dt / tau)) if dt \
        else 0.0
    return ROOM_A0 + ROOM_SWEEP * (1.0 - _ROOM["n"])


#: The instrument's STATIC half — flange, track, thirteen graduations, the
#: word ROOM — built once and copied per frame. Measured on the dev box:
#: drawing all of it every frame is 0.57 ms against 0.33 for a copy plus the
#: hand and the name, on a puck whose composite already measures 64.5 ms of a
#: 71.4 ms budget and which idles at 84C with nothing wrong (see IDLE_FPS).
#: Only the hand moves; a scale that is redrawn every frame to arrive at the
#: same pixels is the kind of work this face cannot afford twice.
#: (176,264) pivot (88,88) -> (128,152) pivot (64,64), 2026-08-06 night: the
#: layer follows the dial down to the smallest of the three. It has to hold
#: the flange (50), the word ROOM above it and the NAME below it, and nothing
#: else — a box sized to the old rim would paste 40px of transparent margin
#: over the tapisserie on every frame for no picture.
#: (128,152) pivot (64,64) -> (232,240) pivot (116,116), 2026-08-07: the
#: flange is the common 88 again, so the layer has to hold 88 either side of
#: the pivot and the name row's ink to 109 below it. 232x240 is that plus a
#: few px of antialiased fringe and nothing more — the note above is still
#: the rule, only the rim it is measured against changed.
ROOM_BOX = (232, 240)               # the layer; pivot sits at (116, 116)
ROOM_PX = 116.0                     # the pivot inside that box, both axes
#: The two rows, as fractions of the rim rather than as the old absolute 50
#: and 78 — the dial shrank by 0.72 and type that did not shrink with it
#: would have crowded a flange 19px closer in. 10pt/13pt is where the ramp
#: stops being readable from a shelf, so they stop there and the NAME's limit
#: comes down to 104 to keep its corner out of the ring's padded band.
#: -36 -> -64 and 56 -> 96, 2026-08-07, and the two are the SAME fractions
#: they were: the label's ink sat at 0.58..0.8 of a 45px track and now sits
#: at 0.675..0.8 of an 80px one, and the name still starts just outside the
#: flange (8px, where it was 6). draw_centred sets from the TOP, so the name
#: inks to 109 below the pivot; its widest corner is r=267 from the dial
#: centre, 20.7 clear of the wedge ring's padded band. The type sizes do NOT
#: grow with the register — 10pt/13pt is the readability floor this note
#: settled, and the RESERVE's own baked label is 10.4px beside it.
#: ── 2026-08-09: SIZE FIRST, AND THIS POCKET ACTUALLY HAS THE AIR ─────────
#: Owner at the glass: "RESERVE, its F and E, ROOM, PAUL ... make them
#: BIGGER — meaningfully, not a point — and heavier in weight, using the air
#: that exists inside each pocket ... if a caption cannot be read at arm's
#: length it is decoration, and decoration inside an instrument is clutter."
#:
#: THIS SUPERSEDES "the type sizes do NOT grow with the register — 10pt/13pt
#: is the readability floor" directly above. That note fixed a FLOOR and then
#: sat on it; the owner's complaint is that the floor is also where the type
#: stopped, and 8px of cap on a 1080 dial is under the floor at arm's length
#: whatever the ramp says. The floor stands; the type no longer stops there.
#:
#: MEASURED, not chosen — the ROOM layer rendered against the real bake with
#: the needle stepped through its whole travel (a caption's neighbour on this
#: register is a moving hand, so one frame is not the measurement), then the
#: nearest ink to each candidate row:
#:
#:     ROOM   10px cap 8  air 23.2   ->  18px cap 13  air 19.6
#:     NAME   13px cap 10 air  6.5   ->  20px cap 15  air  6.5
#:
#: Both rows keep their tops where the note above put them, so they grow into
#: the empty half of the pocket and every clearance that note measured about
#: the flange is untouched: the label's air is to the RIM (the hand sweeps
#: -30..90, the label sits at north, and the counterpoise's highest reach is
#: 29.3 below it), and the name's 6.5 is the fixed gap up to the flange,
#: which no font size can close. Layer slack under the name's ink: 12.5px of
#: ROOM_BOX's 240, so the box does not have to grow.
#:
#: WHY THE ROOM WORD STOPS AT 18 WITH 19.6px STILL FREE, which is the one
#: place this pass does NOT fill the air: the RESERVE's own word is walled in
#: at cap 11 by its hand at EMPTY (home.html, "SIZE FIRST"), and these two
#: are the same caption on two registers of one watch. 13 against 11 still
#: reads as a set; 17 against 11 reads as two watches.
#:
#: Tracking scales with the size — 1.4 and 1.6 were tuned as a fraction of a
#: 10px and a 13px em, and a fixed gap on a 1.8x glyph is tight tracking, not
#: the same tracking. The NAME's limit goes 104 -> 120 for the same reason:
#: at 13px "NO EARS" set 58 in a 104 box and at 20px it sets 90, and a limit
#: that does not move turns a size increase into an ellipsis (§1 — a caption
#: that quietly loses its last letters looks like a name we got wrong).
ROOM_LABEL_DY = -64.0
ROOM_LABEL_SIZE = 18                # was 10; see the note above
ROOM_LABEL_TRACK = 2.5              # was 1.4, the same fraction of the em
ROOM_NAME_DY = 96.0
ROOM_NAME_SIZE = 20                 # was 13
ROOM_NAME_TRACK = 2.5               # was 1.6
ROOM_NAME_W = 120.0
_ROOM_TILE = None


#: ── THEY ARE RECESSED POCKETS, NOT PRINTED CIRCLES, 2026-08-07 ────────────
#:
#: Owner, in the same breath as the layout above: "give each one a thin
#: border ring, a snailed interior of fine concentric grooves, and set them
#: slightly darker than the dial ground so they read as recessed pockets
#: rather than as printed circles."
#:
#: THE DARKENING IS THE HALF THAT DOES THE WORK, and it is set against the
#: ground it sits on rather than chosen — the house rule about expressing a
#: level relative to the floor it competes with, in the one place on this
#: face where the floor is ink rather than room tone. The tapisserie's raised
#: tops land at luminance 40 through the duotone and its grooves at 10 (the
#: same measured pair MOON_SKY_TOP is set by). Black at alpha 56 takes the
#: tops to 31: under the machining at every point, and not so far under that
#: the register stops being a floor and becomes a hole.
#:
#: THE GROOVES ARE A SNAIL — concentric and fine. 3.5px of pitch on an 88px
#: flange is 24 rings, which from a shelf reads as a turned surface rather
#: than as 24 circles. One pixel at alpha 26, which is below the border ring
#: and well below the graduations: a groove that competes with a graduation
#: is a scale nobody can read.
#:
#: TWO OF THE THREE ARE DRAWN HERE AND THE THIRD IS BAKED, which is the
#: standing arrangement on this face rather than a slip. The RESERVE's
#: flange, track and ticks live in home.html's #reserve, so its pocket has to
#: be baked with them or this file would paint over that gauge's own scale.
#: The four numbers below are stated on that page too (SNAIL_PITCH there, and
#: the fill/stroke opacities on #res-pocket, #res-snail and #res-rim) and
#: they move in one commit, exactly as DIAL_K and SLEEP_XY do.
#:
#: IT IS COMPOSITED, NOT DRAWN. PIL's ImageDraw does not blend into an RGBA
#: image — it REPLACES the pixel — so a groove at alpha 26 drawn straight
#: onto the alpha-56 wash would punch a hole in the wash instead of sitting
#: on it, and the register would read as a dark ring with 24 bright ones cut
#: through it. The grooves and the border go on their own layer and the two
#: are alpha_composited. Paid once per tile: the ROOM's is built once for the
#: process and the moonphase's about every 1.8h behind its own cache.
#: 56 -> 44, 2026-08-08 (the depth pass below): the owner's verify band for
#: this pass is "pocket floor 10-20% darker than adjacent dial", and 56/255
#: is 22% — the tops went 40 -> 31, just past the band. 44/255 is 17.3%
#: (tops 40 -> 33.1), mid-band and still under the machining. home.html's
#: #res-pocket carries the same move (0.22 -> 0.17) in this commit, exactly
#: as the note above demands.
SNAIL_GROUND = 44                   # alpha of the black wash: the floor
SNAIL_PITCH = 3.5                   # display px between grooves
SNAIL_LUM, SNAIL_A = 226, 26        # the groove itself
SNAIL_RING_LUM, SNAIL_RING_A = 236, 150      # the thin border ring
SNAIL_RING_W = 2
#: ── 2026-08-08: THE POCKETS GET DEPTH ─────────────────────────────────────
#: Owner, premium pass: the three registers still wore printed circles. Each
#: flange is now a recessed pocket under the ONE upper-left sky the bezel and
#: the numerals share: the border ring becomes the standard relief pair (top
#: edge lit, under edge occluded), an inner WALL lit backwards — bright
#: lower-right, dark upper-left, the tourbillon bore's own arithmetic
#: (TOURB_WALL_W), because an interior catches the key light on the far side
#: — and a soft contact shadow inside the upper-left where the dial
#: overhangs the hole. All of it is baked with the tiles it belongs to (the
#: ROOM's once per process, the moon's behind its ~1.8h cache, the RESERVE's
#: stamped onto each fresh base.png in _pocket_depth_sync); the frame loop
#: keeps exactly the pastes it had.
POCKET_KEY = (-0.7071, -0.7071)     # the sky, upper-left — TOURB_KEY's own
                                    # vector, stated here because that
                                    # constant is defined further down file
POCKET_WALL_W = 7                   # px of visible wall below the dial edge
POCKET_WALL_LIT, POCKET_WALL_DARK = 72, 4    # lower-right flank / overhung one
POCKET_RIM_DARK = 8                 # the under edge; the lit one is
POCKET_RIM_A = 220                  # SNAIL_RING_LUM, where the ring has
                                    # always kept it
POCKET_SHADOW_A = 150               # the overhang's contact shadow, and its
POCKET_SHADOW_BLUR = 4.0            # softness — hard would read as a 2nd rim
#: ── 2026-08-09: THE GAUGE BEZEL (INSTR rows only) ─────────────────────────
#: Six px of flat land and four of chamfer, inward from the rim: on all three
#: registers that is 90 -> 79, and the track those registers read on is at
#: 80, so the bezel's inner edge lands ON the track and the scale begins
#: exactly where the metal stops. That is not a coincidence to preserve by
#: luck — REG_RIM and REG_TRACK are 10 apart by construction (see REG_TRACK)
#: and these two constants sum to that gap on purpose.
#: The land is lit at the rim pair's full swing and the chamfer at HALF it,
#: which is what makes the step between them visible: two bands lit
#: identically are one wide band, and the section is the whole point of
#: calling it a bezel rather than a flange.
INSTR_BEZEL_LAND = 6
INSTR_BEZEL_CHAMF = 4
INSTR_BEZEL_DARK, INSTR_BEZEL_LIT = 26, 208


def _plain_metal(lum: float, alpha: int = 255) -> tuple:
    """A source luminance as a plain grey, for anything drawn BEFORE
    desertify() and therefore getting the colourway for free. The moonphase
    passes _dial_metal instead — same luminances, ramped by hand, because it
    is composited on the other side of the duotone."""
    return (int(lum), int(lum), int(lum), int(alpha))


def _snail_pocket(lay: "Image.Image", px: float, py: float, rim: float,
                  metal=None) -> None:
    """The recessed floor every register stands in, and its depth.

    2026-08-08: the uniform border ring moved into _pocket_relief, which
    re-lights it as the standard relief pair and adds the wall and the
    overhang's shadow — see THE POCKETS GET DEPTH at POCKET_KEY."""
    m = metal or _plain_metal
    n = int(math.ceil(rim)) * 2 + 4
    c = n / 2.0
    ground = Image.new("RGBA", (n, n), (0, 0, 0, 0))
    ImageDraw.Draw(ground).ellipse([c - rim, c - rim, c + rim, c + rim],
                                   fill=(0, 0, 0, SNAIL_GROUND))
    cut = Image.new("RGBA", (n, n), (0, 0, 0, 0))
    dc = ImageDraw.Draw(cut)
    rr = rim - SNAIL_PITCH
    while rr > SNAIL_PITCH:
        dc.ellipse([c - rr, c - rr, c + rr, c + rr],
                   outline=m(SNAIL_LUM, SNAIL_A), width=1)
        rr -= SNAIL_PITCH
    lay.alpha_composite(Image.alpha_composite(ground, cut),
                        (int(round(px - c)), int(round(py - c))))
    _pocket_relief(lay, px, py, rim, metal)


def _pocket_relief(lay: "Image.Image", px: float, py: float, rim: float,
                   metal=None, ring_pad: float = 0.0) -> None:
    """The depth half of a pocket: wall, contact shadow, rim relief pair.

    The wall is the tourbillon bore's arithmetic verbatim (see TOURB_WALL_W):
    5-degree arc segments, colour set by the dot of each segment's bearing
    with -POCKET_KEY, so an interior is brightest at lower-right — exactly
    opposite every raised edge on the dial. The border ring is the same
    segments dotted with +POCKET_KEY, which is the relief pair: lit where the
    sky strikes the lip, occluded where the lip turns away. The shadow is the
    dial overhanging the hole, so it falls INSIDE the upper-left, on its own
    layer and blurred — ImageDraw replaces rather than composites, and a
    blur cannot be drawn at all. Every caller bakes this once per tile; the
    frame loop never runs it.

    ring_pad: how far OUTSIDE the rim the relief pair also reaches. The two
    tile registers draw their pair on virgin ground and take 0; the RESERVE's
    stamp lands OVER home.html's baked #res-rim, whose centred 2.5px stroke
    stands ~1.25px proud of the rim — measured: an inward-only pair left that
    outer half shining on the occluded side and the top/under ratio read 1.5x
    against the 2x the pass demands, so its pair widens to bury it."""
    m = metal or _plain_metal
    d = ImageDraw.Draw(lay)
    box = [px - rim, py - rim, px + rim, py + rim]
    for seg in range(72):
        a0 = seg * 5.0
        t = math.radians(a0 + 2.5)
        f = 0.5 + 0.5 * (math.cos(t) * -POCKET_KEY[0]
                         + math.sin(t) * -POCKET_KEY[1])
        d.arc(box, a0 - 0.6, a0 + 5.6,
              fill=m(POCKET_WALL_DARK
                     + (POCKET_WALL_LIT - POCKET_WALL_DARK) * f),
              width=POCKET_WALL_W)
    sh = Image.new("RGBA", lay.size, (0, 0, 0, 0))
    rr = rim - POCKET_WALL_W + 1
    ImageDraw.Draw(sh).arc([px - rr, py - rr, px + rr, py + rr],
                           150.0, 300.0, fill=(0, 0, 0, POCKET_SHADOW_A),
                           width=14)
    lay.alpha_composite(sh.filter(ImageFilter.GaussianBlur(
        POCKET_SHADOW_BLUR)))
    rbox = [px - rim - ring_pad, py - rim - ring_pad,
            px + rim + ring_pad, py + rim + ring_pad]
    for seg in range(72):
        a0 = seg * 5.0
        t = math.radians(a0 + 2.5)
        f = 0.5 + 0.5 * (math.cos(t) * POCKET_KEY[0]
                         + math.sin(t) * POCKET_KEY[1])
        d.arc(rbox, a0 - 0.6, a0 + 5.6,
              fill=m(POCKET_RIM_DARK
                     + (SNAIL_RING_LUM - POCKET_RIM_DARK) * f, POCKET_RIM_A),
              width=SNAIL_RING_W + int(round(ring_pad)))
    # THE GAUGE BEZEL (2026-08-09, INSTR): a car gauge has a machined bezel,
    # not a jewelled flange, and the difference is that a bezel has a
    # SECTION — a flat land you can see the width of, then a chamfer falling
    # to the glass. The relief pair above is one 2px hairline and reads as a
    # printed circle at arm's length whatever it is lit like. So on an
    # instrument row the same rim gets two more concentric bands INSIDE it,
    # both lit off the one sky: a wide flat land, and a chamfer under it
    # struck at HALF the land's swing so the step between them is visible
    # rather than a second copy of the same gradient.
    if INSTR:
        # PIL's arc width runs INWARD from the radius given, so each band is
        # named by its OUTER edge and the next one starts where it ended.
        for band_r, band_w, swing in (
                (rim - 1.0, INSTR_BEZEL_LAND, 1.0),
                (rim - 1.0 - INSTR_BEZEL_LAND, INSTR_BEZEL_CHAMF, 0.5)):
            bbox = [px - band_r, py - band_r, px + band_r, py + band_r]
            for seg in range(72):
                a0 = seg * 5.0
                t = math.radians(a0 + 2.5)
                f = 0.5 + 0.5 * (math.cos(t) * POCKET_KEY[0]
                                 + math.sin(t) * POCKET_KEY[1])
                f = 0.5 + (f - 0.5) * swing
                d.arc(bbox, a0 - 0.6, a0 + 5.6,
                      fill=m(INSTR_BEZEL_DARK
                             + (INSTR_BEZEL_LIT - INSTR_BEZEL_DARK) * f,
                             POCKET_RIM_A),
                      width=int(round(band_w)))


#: The RESERVE's pocket depth. The floor, snail and scale of that register
#: are BAKED (home.html's #reserve — see TWO OF THE THREE ARE DRAWN HERE
#: above), so its depth cannot ride a tile this file composites per frame
#: without repainting the gauge; instead the SAME relief is stamped straight
#: into each freshly landed base.png, once per bake, and the frame loop pays
#: nothing new. Stamped AFTER _ledger_sync on purpose: every mask that
#: function samples (the numeral's cover, the F/E gold, the caption) is read
#: off the pristine bake before this inks an annulus near the reserve.
_RES_DEPTH = {"tile": None, "mtime": None}


def _pocket_depth_sync(layers) -> None:
    #: ── 2026-08-12: MINIMAL SUPPRESSED THE SUBDIAL AND LEFT ITS HOLE ──────
    #: Every other half of the RESERVE complication is gated on MINIMAL
    #: (draw_reserve, draw_gold_strikes, the figure) — but those gates all sit
    #: in the FRAME path, and this one is a BAKE STAMP. So the chopard dial
    #: suppressed the instrument and went on cutting the pocket it used to sit
    #: in: a 188px dark ring with nothing inside it, landing across the
    #: numeral X. Measured on his glass at (376,440), 2,421 px of near-black
    #: on an opaline ground.
    #:
    #: This is the MINIMAL note's own lesson one layer down — a dial is only
    #: as good as the last thing painted on it, and half the things painted on
    #: it are stamped into the bake, not drawn per frame. When a row asks for
    #: less, check BOTH chains.
    if MINIMAL:
        return
    m = layers.mtimes.get("base") or layers.mtimes.get("legacy")
    if layers.base is None or m is None or _RES_DEPTH["mtime"] == m:
        return
    _RES_DEPTH["mtime"] = m
    if _RES_DEPTH["tile"] is None:
        n = int(math.ceil(RES_RIM)) * 2 + 8
        lay = Image.new("RGBA", (n, n), (0, 0, 0, 0))
        c = n / 2.0
        _pocket_relief(lay, c, c, RES_RIM, ring_pad=2.0)
        # The two END indexes are the one part of the baked scale that
        # reaches the rim (the rest stops at the r=80 track, inside the
        # wall), so their outer reach is re-struck OVER the wall — the tile
        # z-order the ROOM and moon get for free by drawing their scales
        # after their pockets. Pre-composited by hand (ImageDraw replaces):
        # home.html's #res-ticks ink at .62 over the wall's grey at each
        # end's own bearing.
        d = ImageDraw.Draw(lay)
        for a in (RES_A0, RES_A0 + RES_SWEEP):
            t = math.radians(a)
            f = 0.5 + 0.5 * (math.cos(t) * -POCKET_KEY[0]
                             + math.sin(t) * -POCKET_KEY[1])
            w = POCKET_WALL_DARK + (POCKET_WALL_LIT - POCKET_WALL_DARK) * f
            ink = tuple(int(round(0.62 * v + 0.38 * w))
                        for v in (218, 225, 234)) + (255,)
            d.line([(c + RES_RIM * math.cos(t), c + RES_RIM * math.sin(t)),
                    (c + (RES_RIM - POCKET_WALL_W - 1) * math.cos(t),
                     c + (RES_RIM - POCKET_WALL_W - 1) * math.sin(t))],
                   fill=ink, width=3)
        _RES_DEPTH["tile"] = lay
        print("pocket: reserve depth tile baked "
              f"({n}x{n} at {RES_PIVOT[0]:.0f},{RES_PIVOT[1]:.0f})",
              flush=True)
    tile = _RES_DEPTH["tile"]
    layers.base.paste(tile, (int(round(RES_PIVOT[0] - tile.width / 2.0)),
                             int(round(RES_PIVOT[1] - tile.height / 2.0))),
                      tile)


#: ── 2026-08-09: THE GROUND BECOMES A CARBON-FIBRE WEAVE (ferrari) ─────────
#:
#: Owner, commissioning the ferrari theme: "the tapisserie becomes a
#: CARBON-FIBRE WEAVE: fine 2x2 twill, the diagonal sheen alternating cell to
#: cell so it flashes as the eye moves. Same baked-ground machinery as the
#: tapisserie, different pattern."
#:
#: WHY IT IS STAMPED HERE AND NOT DRAWN IN home.html, which is where the
#: tapisserie itself lives and would be the obvious place. Three reasons, and
#: the first one is the one that decides it:
#:   * ONE BAKE SERVES THE WHOLE FLEET. base.png is rendered off that page and
#:     lands in /tmp/aura_face on every puck; the page has no idea which theme
#:     the device it is feeding is wearing. A weave drawn there would arrive on
#:     the patek and royal-oak pucks too, which is a regression on two
#:     shipping faces to add a third.
#:   * THE THEME IS A DEVICE FACT (~/aura_face/THEME, see _theme_name), and
#:     dj_face is the only half of the pair that reads it.
#:   * THE PATTERN IS ALREADY ESTABLISHED. _pocket_depth_sync and
#:     _btn_machine_sync both stamp treatments home.html cannot make onto each
#:     fresh bake, once, mtime-guarded; this is that machinery pointed at the
#:     ground instead of at a pocket. The frame loop pays nothing new.
#:
#: IT MODULATES, IT DOES NOT OVERPAINT, and that is the whole design. A
#: blanket fill of weave over the dial would take the tapisserie's texture out
#: AND every piece of large-scale shading with it — the wedges' contact
#: shadows, the panel washes, the vignette under the ledger block. So the
#: stamp is: LOW-PASS the bake to recover the shading alone (the blur's sigma
#: is over a cell pitch, so the tapisserie's own 14px texture is what it
#: removes), then ADD the weave's deviation from its own mean back onto it.
#: Shading survives; the pattern is replaced. The clamp before the blur is
#: what stops a bright letter bleeding a halo of lifted weave around itself —
#: ink is pinned to the field ceiling first, so it cannot contribute.
#:
#: WHERE IT MAY WRITE, and this is a MEASURED separation, not a chosen one
#: (§3). home.html's own tapisserie note states the field's range: "the field
#: now runs L 8.5..68 against the chapter ring's minute hairline at 88 and a
#: baton at 204". So everything at or under 68 is ground and everything at or
#: over 88 is a mark, with 20 counts of documented gap between them — the
#: stamp ramps its own alpha across exactly that gap rather than picking a
#: number inside it, so an antialiased letter edge fades out instead of
#: acquiring a hard collar.
#:
#: IT WRITES GREY, and that is safe rather than sloppy: desertify() opens with
#: convert("L"), so the dial ground's colour in base.png has never reached the
#: panel — only its luminance has. The one consumer that reads base as RGB is
#: _stamp_rgb, at y=6, and WEAVE_R stops 34px short of it. (2026-08-09: the
#: "34px" is superseded — WEAVE_R is 527 now and the clearance is no longer a
#: subtraction but a geometric impossibility. The argument is unchanged and
#: the new number is at WEAVE_R.)
#: COST STATED: the $LEDGER cover patch (_ledger_sync) is built by stretching
#: ONE donor column sideways, so over a weave it reads as horizontal banding
#: rather than as weave — the same artefact it already had over the
#: tapisserie's grid, in a 145x30 window that lives behind the live figure.
WEAVE_CELL = 14                 # px. The tapisserie's own pitch on this panel
                                # (14 viewBox x VB_PX x DIAL_K = 14.06), kept
                                # because that number is a legibility argument
                                # — home.html: at 45 degrees the short axis
                                # foreshortens to ~0.7, so a cell is never
                                # under ~10px on the glass.
WEAVE_SS = 4                    # supersample for the tile: a 45-degree line
                                # on the integer grid is a staircase
WEAVE_TOW = 3.5                 # px between tows within one cell
WEAVE_FIELD_LIT = 44            # the cell whose tows face the key light...
WEAVE_FIELD_DARK = 28           # ...and the cell whose tows turn away. THIS
                                # PAIR IS THE SHEEN: a 2x2 twill alternates
                                # tow direction cell to cell, so half the
                                # cells catch the room and half do not, which
                                # is what makes carbon flash as the eye moves.
WEAVE_VALLEY = 10               # cut into the field between two tows
WEAVE_RIDGE_LIT = 18            # the lit crest, up-left of every valley...
WEAVE_RIDGE_DARK = 12           # ...smaller on the cell that faces away
WEAVE_GUTTER = 8                # the crossing between cells — the tapisserie
                                # groove's own floor, so the two grounds sit
                                # in the same measured band
WEAVE_CLAMP = 72                # ink is pinned here before the blur
WEAVE_BLUR = 16.0               # sigma, over a cell pitch: what survives is
                                # shading, what dies is the old texture
WEAVE_INK_LO, WEAVE_INK_HI = 68, 88   # the documented gap; see the note above
WEAVE_R = 527                   # the dial disc. See below — this was 500.

#: ── 2026-08-09: THE CARBON GOES DARKER, TO MATCH THE PHYSICAL BEZEL ──────
#: Owner, holding the puck against the screen: "maybe make the carbon fiber
#: even darker to match the natural black rim of the touch display."
#:
#: That is a real target and not a taste: the WaveShare panel's moulded rim
#: sits a few counts off black, and the dial ground was landing at a median
#: of (39,37,37) — visibly a dark GREY beside it, so the glass read as a
#: window set into the bezel instead of continuous with it.
#:
#: WHERE THE DARKENING GOES, and this is the part worth getting right. The
#: obvious levers are both wrong:
#:   * THE WEAVE'S OWN LEVELS DO NOTHING. The stamp adds the tile's
#:     deviation FROM ITS OWN MEAN (`ImageChops.add(shade, field, 1.0,
#:     -mean)`), so sliding WEAVE_FIELD_* down shifts the mean with them and
#:     cancels exactly. Anyone who "darkens the carbon" there will measure no
#:     change and conclude the stamp is not running.
#:   * DESERT_BLACK / DESERT_MID are the whole duotone ramp, so moving them
#:     darkens the aluminium and the marks along with the ground.
#: What is wanted is the FIELD only, which is precisely what WEAVE_INK_LO
#: already separates — the documented ground/mark gap (field <= 68, marks
#: >= 88, 20 counts of daylight between). So the shading is scaled before
#: the weave rides on it, and the same ramp that protects letter edges from
#: acquiring a collar protects them from acquiring a shadow.
#:
#: 0.62 is chosen against the panel, not picked: it takes the measured
#: ground median from (39,37,37) to about (24,23,23), which is the rim's
#: own neighbourhood, while leaving the weave's peak-to-trough deviation
#: untouched — the twill flashes exactly as much as it did, on a darker
#: ground, which is what carbon actually does.
#:
#: 2026-08-09, LATER — 0.62 WAS NOT DARK ENOUGH. Owner, after seeing it:
#: "just make them as dark as possible while preserving the carbon look."
#: 0.62 measured (34,32,32) on the live panel, still a visible grey beside
#: the moulding. 0.30 takes it to roughly (19,18,18).
#:
#: AND THE TOW GAIN IS WHY THIS IS TWO NUMBERS AND NOT ONE. The stamp is
#: `shade * K + (tile - mean)`, so the shading and the twill are separable —
#: which is the whole reason a dark carbon is possible at all. Scaling the
#: COMBINED result would darken the weave in exact proportion and the fabric
#: would fade out with the ground; scaling only the shading drives the field
#: toward black while the tows keep their full swing, and at some point the
#: deep gutters clip at zero and the pattern loses its dark half. So the
#: deviation is given its own gain, set just under 1 to buy headroom against
#: that clip: dark enough that the ground is nearly black, with the tows
#: still carrying ~±13 counts of swing, which is what the eye reads as weave.
WEAVE_GROUND_K = 0.30
WEAVE_TOW_K = 0.78

#: ── 2026-08-09: RED TOWS IN THE WEAVE — BUILT, SHIPPED, AND REJECTED ─────
#: Recorded because it was on the glass and the answer was no, and the next
#: session will otherwise have the same idea for the same good reasons.
#:
#: THE ASK, and the reasoning behind it was sound: "any way we can sprinkle
#: in random red tiles in that charcoal black background, tastefully? the
#: theme has to be red, even subtly, throughout. literally the puck plastic
#: casing color overpowers the screen with its beautiful red." The
#: diagnosis was about MASS and it was correct — every red on this dial is
#: a line, lines have no area, and the ground is the only surface big
#: enough to answer a red shell.
#:
#: WHAT WAS BUILT: carbon-kevlar hybrid, which is a real material and what a
#: Ferrari cabin is actually trimmed in. ~1 cell in 23 dyed, placement from
#: an LCG over the cell index so the fabric is reproducible across restarts,
#: modulated by the weave's own tows so a dyed cell showed thread rather
#: than a flat square, masked by the same ground ramp the grey uses, and
#: tinted after the duotone (a red stamped into base.png arrives grey —
#: desertify() opens with convert("L")).
#:
#: WHY IT CAME OUT, one look later: "get rid of the random red points on the
#: carbon grid. just make them as dark as possible while preserving the
#: carbon look." At 14px the cells read as confetti rather than as thread —
#: the modulation was not enough to overcome the fact that a CELL is a
#: square, and a scatter of red squares on black is pixel noise however it
#: is shaded. The lesson worth keeping: putting red into the ground fights
#: the ground's job. The dial reads premium BECAUSE the field is quiet, and
#: the answer to "not enough red" is more red on the OBJECTS — rings,
#: strokes, instrument marks — not a busier floor.
#:
#: The one number worth keeping from it: at 1-in-23 and alpha 150 the cells
#: were worth about 0.2 points of red coverage. They cost the field's calm
#: for almost nothing on the instrument that was supposed to justify them.
#: ── 2026-08-09, MEASURED ON THE FIRST FERRARI RENDER: 500 LEFT A RING OF
#: TAPISSERIE ON THE GLASS, and the old comment ("inside the bezel's foot,
#: R_VERT - RING - CHAPTER = 504.4") stands with its date as the reason it
#: was wrong. That number is the foot of the bezel's CONTACT SHADOW, not of
#: its metal: bezel_steel.png is TRANSPARENT from 504.4 out to 526.4 —
#: everything but its ticks and its two hairlines — because the chapter ring
#: is a window onto the dial, deliberately. So the annulus 500..526.4 was
#: dial the weave never reached and the bezel never covered, and it showed
#: through the minute track as the old square tapisserie beside the new
#: diagonal twill: a 26px texture seam, visible at 1:1 on the right flank
#: between STERLING's border and the chapter ring.
#: 527 puts the disc mask's own hard edge 0.6px UNDER the metal, which is the
#: only place a hard edge can hide. The ledger stamp row is still clear by
#: construction and by more than before: a disc of radius 527 about y=540
#: does not reach y=6 at all (534 > 527), where the 34px of the old note was
#: a clearance that had to be checked.

_WEAVE = {"tile": None, "field": None, "mask": None, "mtime": None}


def _weave_tile() -> "Image.Image":
    """One period of 2x2 twill: four cells, two tow directions, baked once.

    Drawn in CELL-LOCAL coordinates so the tile repeats seamlessly — the
    discontinuity at a cell boundary is not a seam, it is the crossing, and
    the gutter is drawn over it.

    ONE SKY, like everything else on this dial: whichever way a tow runs, its
    lit crest is laid UP-LEFT of its own valley. That is the tapisserie's own
    rule ("one offset for both families, because one light source") applied to
    a pattern with two directions instead of two axes.
    """
    if _WEAVE["tile"] is None:
        n, s = WEAVE_CELL * 2, WEAVE_SS
        lay = Image.new("L", (n * s, n * s), WEAVE_GUTTER)
        c = WEAVE_CELL * s
        span = c * 2.0                       # long enough to cross a cell
        for cy in range(2):
            for cx in range(2):
                lit = (cx + cy) % 2 == 0
                field = WEAVE_FIELD_LIT if lit else WEAVE_FIELD_DARK
                crest = field + (WEAVE_RIDGE_LIT if lit else WEAVE_RIDGE_DARK)
                # Each cell is drawn into its OWN canvas and pasted, which is
                # what clips one cell's tows to one cell. Drawing all four
                # into the tile directly is the trap here: a striation is
                # longer than the cell it belongs to, so the last cell drawn
                # wins the whole tile and the checkerboard vanishes — which
                # is exactly what the first render of this tile did.
                cell = Image.new("L", (c, c), field)
                dc = ImageDraw.Draw(cell)
                # The tow direction: up-right on a lit cell, down-right on a
                # dark one. ux,uy is along the tow; the perpendicular step is
                # what the striations are spaced along.
                ux, uy = (0.7071, -0.7071) if lit else (0.7071, 0.7071)
                px, py = -uy, ux
                k = WEAVE_TOW * s
                steps = int(span / k) + 2
                for i in range(-steps, steps + 1):
                    ox, oy = c * 0.5 + px * i * k, c * 0.5 + py * i * k
                    seg = [(ox - ux * span, oy - uy * span),
                           (ox + ux * span, oy + uy * span)]
                    dc.line(seg, fill=WEAVE_VALLEY, width=max(1, int(1.1 * s)))
                    # the crest, one step UP-LEFT of the valley it lights
                    off = 0.95 * s
                    dc.line([(x - off, y - off) for x, y in seg],
                            fill=crest, width=max(1, int(0.9 * s)))
                # Inset by half an output pixel each side: what is left of the
                # gutter fill between two cells is the crossing, one panel px
                # wide, which is the tapisserie groove's weight.
                g = s // 2
                lay.paste(cell.crop((g, g, c - g, c - g)),
                          (cx * c + g, cy * c + g))
        _WEAVE["tile"] = lay.resize((n, n), Image.BOX)
    return _WEAVE["tile"]


def _weave_field() -> tuple:
    """(the tiled weave over the whole panel, its mean, the dial-disc mask).

    Full-panel and cached for the life of the process — this is COMPOSE-LOOP
    RULE 2 (bake the static thing once), not rule 1's forbidden per-frame
    allocation: nothing here runs inside the frame loop at all.
    """
    if _WEAVE["field"] is None:
        tile = _weave_tile()
        field = Image.new("L", (SIZE, SIZE), 0)
        for y in range(0, SIZE, tile.height):
            for x in range(0, SIZE, tile.width):
                field.paste(tile, (x, y))
        mask = Image.new("L", (SIZE, SIZE), 0)
        ImageDraw.Draw(mask).ellipse(
            [SIZE / 2 - WEAVE_R, SIZE / 2 - WEAVE_R,
             SIZE / 2 + WEAVE_R, SIZE / 2 + WEAVE_R], fill=255)
        _WEAVE["field"] = field
        _WEAVE["mask"] = mask
        h = tile.histogram()
        _WEAVE["mean"] = int(round(sum(i * n for i, n in enumerate(h))
                                   / float(max(1, sum(h)))))
        print(f"weave: 2x2 twill baked, cell {WEAVE_CELL}px, "
              f"mean L {_WEAVE['mean']}", flush=True)
    return _WEAVE["field"], _WEAVE["mean"], _WEAVE["mask"]


#: ── THE RM GEAR TRAIN, 2026-08-09 ────────────────────────────────────────
#:
#: Spec, filed 2026-08-08 and never built until now (PREMIUM.md): "the Patek
#: move is ABSENCE — an unbroken guilloched centre where the eye rests —
#: plus the RM whisper underneath: a faint GEAR TRAIN rendered across the
#: dial background, interlocking wheels in copper linework at very low
#: contrast (single-digit percent above the ground), BEHIND every functional
#: element ... It must never fight a caption or a hand; if any legibility
#: number drops, the gears dim until it recovers." Owner tonight: "we had
#: this idea to do a subtle gear setup richard millie style in the
#: background ... but subtle in the background."
#:
#: SUBTLE IS THE WHOLE SPEC, so it is expressed as a measured ceiling rather
#: than a taste: GEAR_LIFT is the luminance added to the GROUND, and the
#: verification is the median lift over the untouched ground, which must
#: stay under 8 counts. A gear train you can read the time through is the
#: design; one you notice is a failure of it.
#:
#: WHY IT IS STAMPED INTO base.png AND NOT DRAWN PER FRAME. Three reasons,
#: all of which the carbon weave already established:
#:   * IT IS STATIC. Compose-loop rule 2 — bake the static thing once. The
#:     frame loop pays nothing at all for this.
#:   * IT GETS ITS COLOUR FREE. desertify() opens with convert("L"), so a
#:     grey lift stamped here comes out of the duotone in the theme's own
#:     metal — rose gold on patek — with no colour code anywhere. "Copper
#:     linework" is what the patek ramp DOES to a light grey line.
#:   * IT CANNOT TOUCH A MARK. The same ground/mark ramp the weave uses
#:     (WEAVE_INK_LO/HI, the documented 68..88 gap) masks this, so the
#:     train passes BEHIND every caption, hand and index by construction
#:     rather than by careful placement. That is the brief's "must never
#:     fight a caption", answered structurally: it is not that the gears
#:     avoid the captions, it is that they cannot reach them.
#:
#: THE WHEELS ACTUALLY MESH. Centre distance is r1 + r2 with one shared
#: module, so a chain walked across the dial engages tooth-to-tooth. It
#: would have been easier to scatter circles, and it would have looked
#: like scattered circles: the thing the eye reads as "movement" is teeth
#: that line up, even at 6% contrast.
GEAR_MODULE = 7.4               # px of pitch diameter per tooth
#: 18/255 = 7.1% — inside the brief's "under 8%" and inside its "single-
#: digit percent above the ground". The first cut was 26 (10.2%) and
#: measured over the ceiling, which is exactly the kind of thing that gets
#: shipped as "looks subtle to me" when nobody puts a number on it.
#: ── 31, AND THE CEILING MOVED TO 12% (2026-08-11) ───────────────────────
#: Owner: "move the ceiling up to 12%, let's just try it out there is no harm
#: in me testing it."
#:
#: The 8% came from his own 2026-08-08 identity spec, and it was written for
#: a train that did not move. Once it turned, the spec ate itself: 7.1% is
#: at the edge of visible standing still, so the motion had nothing to be
#: seen ON. Speed was spent first (see GEAR_TOOTH_S) because it costs no
#: contrast; this is the second lever and it is his to spend.
#:
#: 31/255 = 12.2%. The measurement in _gear_train_sync still prints the
#: median lift against the ceiling, so the number stays honest and this can
#: be walked back in one constant.
#: ── AND BACK TO 20 (2026-08-12) ─────────────────────────────────────────
#: The 12% experiment was his ("let's just try it out there is no harm in me
#: testing it") and it produced the complaint it was always going to: at
#: 12.2% the wheels stop being a ghost and become CIRCLES ON A WATCH DIAL —
#: "why did that inner circle pop up again", the fifth time he had said it
#: today about four different objects.
#:
#: Masking them out of the wedge panes was necessary and not sufficient: the
#: 31-tooth wheel is 230px across and reads as a drawn circle wherever it
#: lands. 20 counts is 7.8%, inside his own 2026-08-08 spec, and the motion
#: added for #17 survives it — a moving line at 7.8% is far easier to see
#: than a still one, which is the whole reason speed was spent first.
GEAR_LIFT = 20                  # peak luminance added, BEFORE the ramp
#: a theme may ask for more — the patek's idealface pass wants the train
#: "a slightly bit brighter" (owner, 2026-08-13)
def _gear_lift() -> int:
    return int(_THEME.get("gear_lift") or GEAR_LIFT)
#: ── 2 PX, NOT 1 (2026-08-10) ─────────────────────────────────────────────
#: At GEAR_LINE=1 and 7.1% lift the train measured inside spec and was
#: INVISIBLE on the glass. The ceiling is not wrong — it was written
#: assuming a plain ground, and the patek's ground is a tapisserie whose
#: own texture runs at a similar amplitude, so hairlines at 7% sit under
#: the noise floor of the surface they are drawn on.
#:
#: The fix is AREA, not contrast — the same lesson the SLEEP/POWER labels
#: taught twice: a mark too thin to hold ink cannot be rescued by more ink.
#: Doubling the stroke doubles the visible mass while every pixel stays at
#: the same 7.1% lift, so the contrast ceiling holds by construction and
#: the median lift measurement is unchanged.
GEAR_LINE = 2                   # linework, never fill — but readable
GEAR_TEETH = (23, 14, 31, 17, 26, 12)   # the chain, in order
GEAR_START = (232.0, 690.0)     # first centre, lower-left quadrant
GEAR_WALK = (-38.0, 26.0, -14.0, 34.0, -30.0)   # degrees, centre to centre
#: ── AND THEN IT TURNS (2026-08-11) ───────────────────────────────────────
#: A going train that does not go is a picture of a movement. The whole
#: point of the RM ghost is that the dial has a MECHANISM behind it, and a
#: still one says the opposite of that.
#:
#: WHY IT IS NOT A STATE TABLE, which is this file's usual idiom (the
#: shimmer's 56 states, the sterling glow's 64) and was the first design:
#: a cyclic table has to CLOSE, and this train cannot. Meshing wheels all
#: advance the same arc, so one tooth pitch of travel returns every wheel's
#: TEETH to an identical position — but each wheel also carries 5 spokes,
#: and 360/23 degrees is not a symmetry of a 5-spoke pattern. The table
#: would wrap with the spokes visibly jumping back, once per loop, forever
#: — the same hitch scripts/render_centre.py chose its tooth counts to
#: avoid. Closing it properly needs every wheel at a whole revolution
#: together, which is hundreds of states of a 1080px ground.
#:
#: A CONTINUOUS PHASE HAS NO SEAM TO CLOSE. The cost of drawing live is
#: what made it static in the first place, and the answer is the same one
#: the tourbillon aperture uses: do the work in a BOX, not on the dial.
#: Measured on the puck's own panel, and these are the numbers that decide
#: the design:
#:     full 1080x1080 frame     17.99 ms   (and compose already burns 54 ms
#:                                          of the 125 ms budget)
#:     the six wheel rects      153k px against the dial's 1.17M — 13%
#: Re-stamping the whole ground per frame is ~18 ms, which would eat both
#: 33 ms slots the aperture spends its 30 Hz on and drop the carriage from
#: 24 updates a second. Six small rects is ~2 ms and leaves that alone.
#:
#: THE GATE AND THE GROUND UNDER EACH WHEEL ARE STATIC, so both are cached
#: per bake: the frame does one small draw, one multiply and one add per
#: wheel, over ground it never has to re-derive.
#:
#: SPEED: one tooth pitch every GEAR_TOOTH_S. Stated in TEETH rather than
#: rpm because that is the quantity meshing wheels share — the 12-tooth
#: wheel turns once every 24 s and the 31 once every 62, from one number,
#: and they stay in mesh by construction. Slow on purpose: a dial is
#: glanced at, and background motion the eye cannot ignore is motion in the
#: way.
#: ── 0.85, NOT 2.0: SUBTLE MOTION IS THE SAME AS NONE (2026-08-11) ───────
#: Owner, once it was live: "oh i see the subtle movement, but yes it's not
#: obviously visible."
#:
#: He is right, and the contradiction is worth naming because it is built
#: into the brief. The train's whole spec is SUB-VISIBLE — 7.1% lift, under
#: an 8% ceiling he set himself — and a thing you can barely see standing
#: still is a thing you cannot see moving. §1, in the ground: an animation
#: nobody perceives is indistinguishable from the static bake it replaced.
#:
#: Contrast is not available; the ceiling is the design. SPEED IS FREE, and
#: it is the term the eye is actually sensitive to. At 2.0 s/tooth every
#: wheel's rim travelled 11.5 px/s (the arc per tooth is 23px and it is the
#: SAME for all six — that is what meshing means). At 0.85 that is 27 px/s,
#: which crosses from "did that move?" to obviously turning without touching
#: a single pixel's brightness.
GEAR_TOOTH_S = 0.85             # seconds per tooth of travel
#: ── AND IT TICKS AT 4 Hz, NOT EVERY FULL FRAME (2026-08-11) ──────────────
#: MEASURED ON THE PUCK'S OWN CPU, not on the dev box, because the two
#: disagree by 2.3x: the tick is 1.50 ms here and 3.38 ms (p95 3.44) there.
#:
#: Why that number needs a decision rather than a shrug. The full-frame
#: budget is 125 ms at 8 fps, the compose already spends ~54 ms of it, and
#: the two 33 ms slots the tourbillon aperture uses for its 30 Hz repaints
#: need 66 ms of what is left. 71 - 3.4 = 67.6 against 66 required: it fits,
#: with 1.6 ms of margin, which is not margin. Paying for a background
#: texture with the carriage's own cadence is the wrong trade — that motion
#: is the subject and this is the ground.
#:
#: 4 Hz halves the average and costs nothing visible: at one tooth per 2 s a
#: 12-tooth wheel advances 3.75 degrees between ticks, on linework at 7.1%
#: contrast. There is no eye that resolves that as steps.
#: 6 Hz, up from 4. The cadence has to rise WITH the speed or the gain is
#: spent on stepping: at 0.85 s/tooth and 4 Hz each tick jumps 6.8px of rim,
#: which reads as a stutter rather than as rotation. At 6 Hz it is 4.5px.
#: Costs 3.38 ms on the puck (measured there, not here — the dev box is
#: 2.3x optimistic) six times a second instead of four.
GEAR_TICK_S = 1.0 / 6.0         # seconds between turns of the ghost train
_GEARS = {"layer": None, "mtime": None, "rects": None, "ground": None,
          "gate": None, "wheels": None, "at": 0.0, "pristine": None}


#: ── THE WEDGE TYPE STANDS UP, 2026-08-10 ─────────────────────────────────
#: Owner: "i would like some more differentiation or depth to the fonts on
#: the wedges for the patek, can it pop out while it's sitting in these
#: recessed wedges?"
#:
#: WHY THE THEME WORK NEVER REACHED THEM. BRIEFING, STERLING, LOCK, VOLUME
#: and SETTINGS are BAKED INTO base.png by home.html as flat type. Nothing
#: in this file draws them, so every pass that gave the panes a chamfer, a
#: wash and a sweep left the words themselves untouched — flat letters on a
#: newly three-dimensional pane, which is exactly the mismatch he is
#: pointing at. The pane got a section; the type never did.
#:
#: So the treatment is STAMPED onto the bake, the same answer as the
#: machined caps: sample the ink that is already there, build the relief
#: pair from it, composite it back. No new type is drawn, so the localised
#: labels keep whatever script home.html set them in — this file never
#: learns what the words say.
#:
#: APPLIED, NOT ENGRAVED — the opposite of the cap labels, and deliberately.
#: A cap label is cut INTO metal so it lights backwards; a wedge caption
#: sits ON a recessed pane and should read as raised type catching the same
#: upper-left sky as every other proud edge on this dial. Lit rim LAST:
#: draw_micro's own note records that at these sizes the two edge masks
#: overlap on thin stems and whichever pastes last owns them, and lit-last
#: is what reads raised.
#:
#: The contact shadow is what actually sells it. Relief alone makes a
#: letter look embossed; a shadow thrown down-right onto the pane floor is
#: what makes it look like it is STANDING on something.
WTYPE_INK_MIN = 150             # what counts as caption ink on the bake
WTYPE_LIT = 252                 # the lit upper-left rim
WTYPE_OCC = 14                  # the occluded lower-right flank
WTYPE_SHADOW_A = 120            # contact shadow onto the pane floor
WTYPE_SHADOW_DXY = 2
WTYPE_SHADOW_BLUR = 1.7
_WTYPE = {"mtime": None}


def _wedge_type_sync(layers) -> None:
    """Per bake: raise the five wedge captions off their panes."""
    m = layers.mtimes.get("base") or layers.mtimes.get("legacy")
    if layers.base is None or m is None or _WTYPE["mtime"] == m:
        return
    _WTYPE["mtime"] = m
    try:
        t0 = time.time()
        src = layers.base.convert("L")
        # WHERE it may write: inside the five sectors and nowhere else, so
        # a bright mark anywhere else on the dial is untouched. Padded in
        # slightly so the pane's own bright border is not mistaken for type.
        region = Image.new("L", (SIZE, SIZE), 0)
        dr = ImageDraw.Draw(region)
        for a0, a1, _c in WEDGES:
            dr.polygon(_wedge_sector_poly(a0 + 1.6, a1 - 1.6,
                                          WEDGE_R0 + 9.0, WEDGE_R1 - 9.0,
                                          pad=0.0), fill=255)
        ink = ImageChops.multiply(
            src.point(lambda v: 255 if v >= WTYPE_INK_MIN else 0), region)
        if sum(ink.histogram()[64:]) < 200:
            # §1: no ink found means home.html moved the captions, and a
            # silent no-op here would look exactly like "the pass ran and
            # did nothing", which is how the wedges stayed flat for a week.
            print("wedge type: NO caption ink under the sectors — did "
                  "home.html move the labels?", flush=True)
            return
        out = layers.base.copy()
        # 1. the contact shadow, on the pane, down-right away from the key
        sh = ImageChops.offset(ink, WTYPE_SHADOW_DXY, WTYPE_SHADOW_DXY)
        sh = ImageChops.subtract(sh, ink).filter(
            ImageFilter.GaussianBlur(WTYPE_SHADOW_BLUR))
        lay = Image.new("RGBA", (SIZE, SIZE), (0, 0, 0, 0))
        lay.putalpha(sh.point(lambda v: v * WTYPE_SHADOW_A // 255))
        out.paste((0, 0, 0), (0, 0), lay.getchannel("A"))
        # 2. THE LIT RIM, on the TOP-LEFT, and the direction was inverted
        # in the first cut. subtract(ink, offset(ink, +1, +1)) leaves the
        # part of the mark the down-right copy does NOT cover — which is
        # the UPPER-LEFT edge, the one facing the sky. The first pass
        # painted that edge dark and the lower-right bright, so the type
        # lit backwards and read as engraved outlines rather than raised
        # letters. Exactly the same shape of error as a negated up-vector:
        # every pixel correct, the whole thing inside out.
        #
        # AND ONLY THE ONE RIM. These captions are ~2px strokes; a bright
        # edge plus a dark edge is 2px of treatment on a 2px letter, so the
        # body gets consumed and the word turns hollow. The lit rim raises
        # it, the contact shadow below grounds it, and the letter itself is
        # left alone — which is what "pop out" actually needs.
        edge = ImageChops.subtract(ink, ImageChops.offset(ink, 1, 1))
        lay = Image.new("RGBA", (SIZE, SIZE), (0, 0, 0, 0))
        lay.putalpha(edge.point(lambda v: v * 210 // 255))
        out.paste((WTYPE_LIT,) * 3, (0, 0), lay.getchannel("A"))
        layers.base.paste(out, (0, 0))
        print(f"wedge type: {len(WEDGES)} captions raised in "
              f"{(time.time() - t0) * 1000:.0f} ms — applied relief pair "
              f"+ contact shadow", flush=True)
    except Exception as e:                      # noqa: BLE001
        print(f"wedge type: NOT stamped {e!r} — captions stay flat",
              flush=True)


def _gear_wheels() -> list:
    """Where the six wheels are, once. (teeth, cx, cy, r, spin_sign, box).

    The chain walk was inline in the drawing code, which meant the only way
    to know where a wheel WAS involved drawing it. The tick needs the
    geometry every frame and the pixels only inside one box, so the walk is
    its own function now — one definition, three readers.
    """
    if _GEARS["wheels"] is not None:
        return _GEARS["wheels"]
    out = []
    cx, cy = GEAR_START
    prev_r = None
    ang = 0.0
    for i, teeth in enumerate(GEAR_TEETH):
        r = teeth * GEAR_MODULE / 2.0
        if prev_r is not None:
            # MESHING: centres exactly r1 + r2 apart, walking by the angle.
            ang += GEAR_WALK[i - 1]
            step = prev_r + r
            cx += step * math.cos(math.radians(ang))
            cy += step * math.sin(math.radians(ang))
        # A MESHED PAIR TURNS IN OPPOSITE DIRECTIONS. Getting this wrong is
        # the one error in a gear animation that everybody sees and nobody
        # can name — the teeth pass through each other.
        pad = GEAR_LINE + 2
        box = (max(0, int(cx - r) - pad), max(0, int(cy - r) - pad),
               min(SIZE, int(cx + r) + pad + 1),
               min(SIZE, int(cy + r) + pad + 1))
        out.append((teeth, cx, cy, r, 1.0 if i % 2 == 0 else -1.0, box))
        prev_r = r
    _GEARS["wheels"] = out
    return out


def _draw_wheel(d, teeth, cx, cy, r, phase, ox=0.0, oy=0.0) -> None:
    """One wheel at `phase` radians, into an already-open ImageDraw.

    `ox/oy` shift it into a crop's own coordinates, so the tick can draw a
    170px wheel into a 174px box instead of onto a 1080px canvas.
    """
    cx, cy = cx - ox, cy - oy
    # the wheel: pitch circle, root circle, hub, spokes, teeth. The three
    # circles are rotationally symmetric, so the phase never touches them.
    d.ellipse([cx - r, cy - r, cx + r, cy + r], outline=_gear_lift(),
              width=GEAR_LINE)
    rr = r - GEAR_MODULE * 0.62
    d.ellipse([cx - rr, cy - rr, cx + rr, cy + rr], outline=_gear_lift(),
              width=GEAR_LINE)
    hub = max(6.0, r * 0.20)
    d.ellipse([cx - hub, cy - hub, cx + hub, cy + hub],
              outline=_gear_lift(), width=GEAR_LINE)
    # A TOOTH IS A SHAPE, NOT A TICK. Two flanks and a crest, so the
    # rim reads as engagement rather than as a dotted circle — which
    # is the whole difference between a gear and a decorative ring.
    for k in range(teeth):
        a0 = 2.0 * math.pi * (k + 0.16) / teeth + phase
        a1 = 2.0 * math.pi * (k + 0.84) / teeth + phase
        d.line([(cx + rr * math.cos(a0), cy + rr * math.sin(a0)),
                (cx + r * math.cos(a0), cy + r * math.sin(a0)),
                (cx + r * math.cos(a1), cy + r * math.sin(a1)),
                (cx + rr * math.cos(a1), cy + rr * math.sin(a1))],
               fill=_gear_lift(), width=GEAR_LINE)
    # spokes — an odd count, so the wheel never reads as a cross
    for k in range(5):
        a = 2.0 * math.pi * k / 5.0 + phase
        d.line([(cx + hub * math.cos(a), cy + hub * math.sin(a)),
                (cx + rr * 0.94 * math.cos(a), cy + rr * 0.94 * math.sin(a))],
               fill=_gear_lift(), width=GEAR_LINE)


def _gear_layer() -> "Image.Image":
    """The whole train at phase 0, as an L mask. Bake-time only."""
    if _GEARS["layer"] is not None:
        return _GEARS["layer"]
    lay = Image.new("L", (SIZE, SIZE), 0)
    d = ImageDraw.Draw(lay)
    for teeth, cx, cy, r, _sign, _box in _gear_wheels():
        _draw_wheel(d, teeth, cx, cy, r, 0.0)
    _GEARS["layer"] = lay
    return lay


def _gear_train_sync(layers) -> None:
    """Per bake: lay the ghost train into the dial ground. patek only."""
    if _THEME.get("ghost") != "gears":
        return
    m = layers.mtimes.get("base") or layers.mtimes.get("legacy")
    if layers.base is None or m is None or _GEARS["mtime"] == m:
        return
    _GEARS["mtime"] = m
    try:
        t0 = time.time()
        src = layers.base.convert("L")
        train = _gear_layer()
        # THE GROUND/MARK RAMP, and the disc, exactly as the weave uses
        # them: full strength on open ground, fading to nothing across the
        # documented 68..88 gap, and clipped to the dial.
        lo, hi = WEAVE_INK_LO, WEAVE_INK_HI
        ramp = src.point(lambda v: 255 if v <= lo else
                         (0 if v >= hi else int(255 * (hi - v) / (hi - lo))))
        disc = Image.new("L", (SIZE, SIZE), 0)
        ImageDraw.Draw(disc).ellipse(
            [SIZE / 2 - WEAVE_R, SIZE / 2 - WEAVE_R,
             SIZE / 2 + WEAVE_R, SIZE / 2 + WEAVE_R], fill=255)
        gate = ImageChops.multiply(ramp, disc)
        add = ImageChops.multiply(train, gate)
        before = src.copy()
        # WHAT THE TICK NEEDS, CACHED WHILE THE GROUND IS STILL PRISTINE.
        # Both of these are static for the life of a bake: the dial under
        # each wheel, and the gate that decides where a line may show. The
        # frame loop then owns exactly one variable — the phase — and never
        # re-derives a ramp or re-reads the ground.
        # ── THE TICK CANNOT CACHE FROM HERE, AND IT TRIED (2026-08-11) ──
        # Owner, minutes after the animation went live: "whoah now the power
        # and sleep buttons are clipped in their backgrounds."
        #
        # This function runs FIRST of the stamps, which is right for a ground
        # pass and fatal as a cache point. The tick repaints each wheel's box
        # as `cached ground + gears`, so whatever it caches is what that box
        # REVERTS TO four times a second — and _wedge_type_sync,
        # _ledger_sync, _pocket_depth_sync and _btn_machine_sync all stamp
        # after this line. The 23-tooth wheel's box is 180px at (232,690),
        # which is exactly where the machined SLEEP and POWER caps live, so
        # the tick spent every tick rubbing them out.
        #
        # A cache is only pristine with respect to a POINT IN THE PIPELINE,
        # and "pristine" here meant "before four passes that had not run yet".
        # The tick takes its own copy at the end of the chain instead.
        _GEARS["ground"] = _GEARS["gate"] = None
        # ...and keep the dial as it was BEFORE any of them, because the
        # tick needs to know which pixels are still open dial. See the
        # unchanged-mask in the tick: "dark" is not the same question as
        # "nothing has been stamped here", and the ramp only answers the
        # first one.
        _GEARS["pristine"] = src.copy()
        out = ImageChops.add(src, add)
        layers.base.paste(Image.merge("RGB", (out, out, out)), (0, 0))
        # MEASURED, NOT ASSERTED (§6, and the brief set the number). The
        # median lift over the pixels the train actually touched — the
        # figure the spec caps at single digits.
        import statistics
        px_b, px_a = before.load(), out.load()
        px_g = add.load()
        lifts = [px_a[x, y] - px_b[x, y]
                 for y in range(120, SIZE - 120, 7)
                 for x in range(120, SIZE - 120, 7)
                 if px_g[x, y] > 0]
        med = statistics.median(lifts) if lifts else 0
        print(f"gears: RM ghost train stamped in "
              f"{(time.time() - t0) * 1000:.0f} ms — "
              f"{len(GEAR_TEETH)} meshing wheels, median lift {med} "
              f"counts ({100.0 * med / 255.0:.1f}% of range, ceiling 8%) "
              f"over ground", flush=True)
    except Exception as e:                      # noqa: BLE001
        # §1: a ghost that quietly did not arrive looks exactly like a
        # ghost that was never built, which is how this went unnoticed
        # from 08-08 to tonight.
        print(f"gears: NOT stamped {e!r} — the dial keeps its plain ground",
              flush=True)


def _gear_train_tick(layers, now: float) -> None:
    """Per frame: turn the six wheels, inside their own boxes and nowhere
    else. See GEAR_TOOTH_S for why this is a live draw and not a table.

    Costs one small draw, one multiply and one add per wheel over ground
    that was cached when the bake landed. Everything outside the six boxes
    is untouched, which is what keeps this off the full-frame budget.
    """
    if _THEME.get("ghost") != "gears" or layers.base is None:
        return
    if _GEARS.get("mtime") is None or _GEARS.get("pristine") is None:
        return                       # no bake has landed yet
    if not _GEARS.get("ground"):
        # FIRST TICK OF THIS BAKE: take the ground and the gate from a base
        # every other stamp has already finished with. The gate falls out of
        # that same ink, so a machined cap or a raised caption inside a box
        # now MASKS the train exactly as a caption on open dial does — the
        # ghost passes behind them by construction rather than by placement,
        # which is the property the ground/mark ramp was chosen for.
        _src = layers.base.convert("L")
        _ramp = _src.point(lambda v: 255 if v <= WEAVE_INK_LO else
                           (0 if v >= WEAVE_INK_HI else
                            int(255 * (WEAVE_INK_HI - v)
                                / (WEAVE_INK_HI - WEAVE_INK_LO))))
        _disc = Image.new("L", (SIZE, SIZE), 0)
        ImageDraw.Draw(_disc).ellipse(
            [SIZE / 2 - WEAVE_R, SIZE / 2 - WEAVE_R,
             SIZE / 2 + WEAVE_R, SIZE / 2 + WEAVE_R], fill=255)
        # ══ AND THE TRAIN MUST STAY OUT OF THE WEDGE PANES ══════════════
        # 2026-08-11, after the ceiling went to 12%: "why did that inner
        # circle pop up again! ... this thing keeps coming up over and over
        # and over." He is looking at gear wheels, and he is right that it
        # is the same complaint he has made all day about circles crossing
        # his wedges — it just arrived by a new route.
        #
        # The ramp gate stops the train reaching a MARK, and it does that
        # correctly. A wedge pane is not a mark: it is a dark translucent
        # FILL with a bright border, so the ramp reads its interior as open
        # ground and the 31-tooth wheel draws a 230px circle straight
        # through STERLING. At 7.1% that sat under the tapisserie's own
        # noise and nobody saw it. At 12.2% it is a circle on his dial.
        #
        # Raising the contrast was his call and it looks right on open
        # ground. What was wrong was WHERE, so the fix is the mask and not
        # the ceiling: the five sectors come out of the gate, padded, and
        # the train runs behind the dial rather than through the menu.
        _pane = Image.new("L", (SIZE, SIZE), 255)
        _pd = ImageDraw.Draw(_pane)
        for _a0, _a1, _c in WEDGES:
            _pd.polygon(_wedge_sector_poly(_a0 - 1.0, _a1 + 1.0,
                                           WEDGE_R0, WEDGE_R1, pad=8.0),
                        fill=0)
        _gate = ImageChops.multiply(ImageChops.multiply(_ramp, _disc), _pane)
        # ── AND "OPEN GROUND" IS NOT "DARK" ──────────────────────────────
        # The ramp calls a pixel ground when it is DARK, which is right for
        # the dial and wrong for everything stamped onto it: the engraved
        # lettering inside a machined SLEEP cap is dark too, so the ramp
        # alone hands the train the inside of the cap's own letters. Caught
        # by the regression test at 4 px of 10,545, each lifted by exactly
        # GEAR_LIFT — small, and the wrong kind of small, because it is a
        # ghost train showing through solid metal.
        #
        # The honest test is not "is this dark" but "has anything been put
        # here", and that is a comparison against the dial as it stood
        # before the stamps ran. Where they wrote, the train stays out.
        _diff = ImageChops.difference(_src, _GEARS["pristine"])
        # EXACTLY zero, AND GROWN BY A PIXEL. A tolerance of 2 still let the
        # antialiased edge of an engraved letter read as untouched; tightening
        # it to 0 left exactly one pixel, where a letter's soft edge happened
        # to cross the ground's own value and matched it by coincidence.
        # Chasing that with a finer threshold is the shape this project has a
        # rule about — no threshold separates "a stamp that lands on the
        # ground's value" from "the ground".
        #
        # So it is not a threshold question: dilate the TOUCHED mask by one
        # pixel and every antialiased skirt is covered whatever value it
        # took. One MaxFilter on a 1080 image, once per bake.
        _touched = _diff.point(lambda v: 255 if v else 0).filter(
            ImageFilter.MaxFilter(3))
        _untouched = _touched.point(lambda v: 0 if v else 255)
        _gate = ImageChops.multiply(_gate, _untouched)
        _GEARS["rects"] = [w[5] for w in _gear_wheels()]
        _GEARS["ground"] = [_src.crop(b) for b in _GEARS["rects"]]
        _GEARS["gate"] = [_gate.crop(b) for b in _GEARS["rects"]]
        print(f"gears: ground cached for {len(_GEARS['rects'])} boxes AFTER "
              f"the stamps — the train turns behind the caps, not over them",
              flush=True)
    # THE CADENCE, and the skip has to be FIRST — see GEAR_TICK_S. A skipped
    # tick leaves the last state pasted in the ground, so nothing flickers
    # and nothing needs redrawing to hold still.
    if now - _GEARS["at"] < GEAR_TICK_S:
        return
    _GEARS["at"] = now
    try:
        wheels = _gear_wheels()
        for i, (teeth, cx, cy, r, sign, box) in enumerate(wheels):
            # One tooth of travel every GEAR_TOOTH_S, so a wheel's own
            # period falls out of its tooth count and the mesh holds.
            ph = sign * (now / GEAR_TOOTH_S) * (2.0 * math.pi / teeth)
            mask = Image.new("L", (box[2] - box[0], box[3] - box[1]), 0)
            d = ImageDraw.Draw(mask)
            # EVERY WHEEL THAT REACHES INTO THIS BOX, not just this one.
            # The boxes are squares around wheels that MESH, so neighbours
            # always overlap — drawing only the owner would erase the arc
            # of its neighbour that falls inside, and the two boxes would
            # then take turns rubbing each other out, once per frame.
            for j, (t2, x2, y2, r2, s2, b2) in enumerate(wheels):
                if b2[0] >= box[2] or b2[2] <= box[0] \
                        or b2[1] >= box[3] or b2[3] <= box[1]:
                    continue
                p2 = s2 * (now / GEAR_TOOTH_S) * (2.0 * math.pi / t2)
                _draw_wheel(d, t2, x2, y2, r2, p2, box[0], box[1])
            out = ImageChops.add(
                _GEARS["ground"][i],
                ImageChops.multiply(mask, _GEARS["gate"][i]))
            layers.base.paste(Image.merge("RGB", (out, out, out)),
                              (box[0], box[1]))
    except Exception as e:                      # noqa: BLE001
        # §1 — and turn it OFF rather than raising per frame at 8 fps,
        # which would fill the journal faster than anyone could read it.
        _GEARS["ground"] = None
        print(f"gears: the train STOPPED {e!r} — the stamped phase-0 "
              f"ground stands", flush=True)


def _carbon_weave_sync(layers) -> None:
    """Per bake: re-surface the dial ground as carbon. ferrari only.

    FIRST of the base stamps, before _ledger_sync — the pocket tile and the
    machined caps are opaque things that sit ON the dial, so they must land on
    top of the weave, and both of them sample ink far above WEAVE_INK_HI,
    which this pass never touches.
    """
    if _THEME.get("ground") != "carbon":
        return
    m = layers.mtimes.get("base") or layers.mtimes.get("legacy")
    if layers.base is None or m is None or _WEAVE["mtime"] == m:
        return
    _WEAVE["mtime"] = m
    try:
        t0 = time.time()
        field, mean, disc = _weave_field()
        src = layers.base.convert("L")
        shade = src.point(lambda v: min(v, WEAVE_CLAMP)).filter(
            ImageFilter.GaussianBlur(WEAVE_BLUR))
        # THE GROUND GOES DOWN, THE WEAVE DOES NOT (see WEAVE_GROUND_K).
        # Scaling the SHADING before the tile rides on it darkens the field
        # and leaves the twill's deviation — its whole visible character —
        # at full strength. Doing it the other way round would flatten the
        # pattern by exactly the same factor and read as "the carbon went
        # away", which is the opposite of the ask.
        if WEAVE_GROUND_K != 1.0:
            shade = shade.point(lambda v: int(v * WEAVE_GROUND_K))
        # The tows keep their own gain (see WEAVE_TOW_K): the ground goes
        # nearly black while the twill keeps enough swing to be read as a
        # weave rather than as noise on a black disc.
        #
        # NOT `ImageChops.add(shade, field, WEAVE_TOW_K, ...)`. That third
        # argument is a DIVISOR — add() computes (a + b) / scale + offset —
        # so passing a gain below one there AMPLIFIES the pair by its
        # reciprocal. Tried on the glass, 2026-08-09: it lifted the ground
        # 1.28x and turned the carbon into a bright grey mesh, i.e. exactly
        # the opposite of the ask, while reading as a plausible edit.
        # The deviation is therefore scaled about a 128 midpoint FIRST and
        # added at unit scale, which says what it means.
        dev = field.point(
            lambda v: max(0, min(255, int(round((v - mean) * WEAVE_TOW_K))
                                 + 128)))
        out = ImageChops.add(shade, dev, 1.0, -128)
        # The ground/mark ramp across the documented gap, times the disc.
        lo, hi = WEAVE_INK_LO, WEAVE_INK_HI
        a = ImageChops.multiply(
            src.point(lambda v: 255 if v <= lo else
                      (0 if v >= hi else int(255 * (hi - v) / (hi - lo)))),
            disc)
        layers.base.paste(Image.merge("RGB", (out, out, out)), (0, 0), a)
        print(f"weave: dial re-surfaced as carbon in "
              f"{(time.time() - t0) * 1000:.0f} ms", flush=True)
    except Exception as e:                      # noqa: BLE001
        # PRINCIPLES §1: a ground that quietly stayed a tapisserie on a
        # ferrari is a face wearing another theme's texture with nothing in
        # the log to say so.
        print(f"weave: NOT stamped {e!r} — the dial keeps the tapisserie",
              flush=True)


#: ── 2026-08-08: SLEEP AND POWER BECOME MACHINED BUTTONS ──────────────────
#: Owner, premium pass: the two controls were line icons in flat discs. Each
#: is now a raised polished button under the ONE upper-left sky (POCKET_KEY):
#: a domed steel cap, the relief pair on its rim (top edge lit, under edge
#: occluded — a RAISED element, so the opposite lighting to the pockets'
#: interiors), a soft drop shadow onto the dial down-right away from the key
#: light, a specular arc on the cap's upper-left, and the glyph + label
#: ENGRAVED — darker floor, occluded upper flank, lit lower flank, the
#: inverse of applied relief. ONE cap for both, so they read as two buttons
#: from one case; only the engraving keeps each control's ink — icy for
#: SLEEP, the warning salmon for POWER (§8's colour, not decoration).
#:
#: home.html still draws the disc, glyph and (localised, size-fitted) label;
#: the stamp samples that ink off the pristine bake as its engraving
#: stencil, so a translated label engraves without this file knowing the
#: script. Like the RESERVE's pocket the discs' geometry is baked in
#: home.html, so the treatment is stamped onto each fresh base.png, once per
#: bake (_pocket_depth_sync's pattern) — the frame loop pays nothing new.
#:
#: THE CENTRES JOIN THE SLEEP_XY TWO-FILE CONTRACT: these are home.html's
#: #btn-sleep / #btn-power circles (viewBox 96.3,540.7 and 166.7,731.5,
#: r=51.85) through #dial's scale and the panel factor — verified on a live
#: base.png: bright-ink centroids (133.9,578.4) / (204.8,769.8) against the
#: 134.5 / 205.2 computed here. If those circles move, these move in the
#: same commit — and if the sampled window holds no ink the stamp declines
#: LOUDLY and leaves the bake alone rather than paint a button where none
#: is drawn (§1).
#:
#: 2026-08-08, later: the engraving above was corrected for contrast — the
#: label now leaves the cap for the dial and only the glyph engraves. See
#: BTN_LABEL_SPLIT below and PREMIUM.md.
#: 2026-08-08, later still — THAT MOVE IS REVERSED, at the glass: "the label
#: belongs ENGRAVED IN THE CAP". Both bands engrave again; the split survives
#: only as the seam between two renormalisations. The paragraph above stands
#: with its date.
BTN_DISC_R = 51.85 * DIAL_K * VB_PX
BTN_DISC_XY = (
    ((500.0 + (96.3 - 500.0) * DIAL_K) * VB_PX,
     (500.0 + (540.7 - 500.0) * DIAL_K) * VB_PX),      # SLEEP
    ((500.0 + (166.7 - 500.0) * DIAL_K) * VB_PX,
     (500.0 + (731.5 - 500.0) * DIAL_K) * VB_PX),      # POWER
)
#: The engraving fills per button: (floor lacquer, lit lower flank).
#: 2026-08-08 correction: POWER's floor darkened (66,17,13)->(26,8,6) — its
#: salmon glyph bakes at L~175, so the stencil cuts at ~87% depth and the
#: old floor landed 2.45:1 against the cap face where >=3:1 is the floor
#: (measured, see PREMIUM.md). Identity keeps riding the lit salmon flank.
#:
#: 2026-08-08, LATER — THE CONTRAST IS INVERTED. Owner at the glass: "it just
#: has to be a brighter colour to stand out against the background, it's hard
#: to read." The paragraph above stands with its date, and it optimised the
#: WRONG HALF: an engraved mark in real metal reads because its LIT LOWER EDGE
#: catches the sky, not because its floor is dark. So the floors come UP off
#: pure shadow (they were landing at L~14/18, inside the cap's own dark rim at
#: L~12 — the glyph vanished into the shadow side rather than sitting in it),
#: and the lit edges go substantially brighter, keeping the identity tints
#: where they are actually seen. THE FLOOR IS THE SHADOW, THE EDGE IS THE
#: LETTER — and the edge is what gets measured from now on (see the docstring
#: of _btn_machine_sync).
#:
#: 2026-08-08, WITH THE HALO — POWER's floor goes back down, (54,28,24) ->
#: (30,15,12). The paragraph above stands with its date and its reason was
#: sound WHILE the floor's neighbour was the dome's own dark rim; the halo
#: makes the floor's neighbour a lit pool instead, so a floor lifted "off pure
#: shadow" is now just a letter with less contrast against the light it sits
#: in. Measured on this bake: it moved POWER's label from 4.51:1 to 4.92:1
#: against its immediate surround. SLEEP's icy floor is already dark enough
#: and is untouched. The salmon identity was never in the floor — it rides
#: the lit flank, which is unchanged.
BTN_ENGRAVE_INK = (((30, 38, 52), (235, 246, 255)),    # SLEEP — icy
                   ((30, 15, 12), (255, 196, 186)))    # POWER — salmon
#: +2.5: the baked stroke's proud outer half. home.html's 2.6-unit stroke
#: is centred ON r=51.85, so ~1.3px (+AA) stands outside the disc — the
#: exact trap the RESERVE stamp paid for (#res-rim, ring_pad=2 in
#: _pocket_depth_sync); measured here as a salmon halo on POWER's occluded
#: side until the cap grew to bury it.
BTN_CAP_R = BTN_DISC_R + 2.5
BTN_CAP_LO, BTN_CAP_HI = 58.0, 120.0   # dome face: rim-ward -> highlight
BTN_RIM_DARK, BTN_RIM_LIT = 12, 185    # the relief pair's two ends
BTN_SHADOW_DX, BTN_SHADOW_DY = 5, 6    # down-right, away from the key
BTN_SHADOW_A, BTN_SHADOW_BLUR = 130, 4.0
#: 2026-08-08, correction at the glass: "the sleep and power font and icons
#: are lost in that gradient" — the engraving sat tone-on-tone on the domed
#: blue. Fixed by CONTRAST, not size: only the GLYPH engraves (dark floor,
#: its pair at full strength), and the label leaves the cap for the dial
#: beneath the button — applied steel type with the standard relief pair. A
#: label on a curved gradient can never win; watches put the text on the
#: dial, not on the crown. The split row is home.html's own geometry: glyph
#: ink ends <=6px below the disc centre, label ink (baseline centre+36,
#: fitted <=16px tall) starts >=+20, so +15 parts them with margin even for
#: a grown localised label.
#:
#: 2026-08-08, THE MOVE TO THE DIAL IS REVERSED — owner at the glass: "the
#: machined cap is drawn and the word sits BELOW it on bare dial ... resolve
#: it ONE way: the label belongs ENGRAVED IN THE CAP." The paragraph above
#: stands with its date, and its diagnosis was right — a HALF-DEPTH cut on a
#: curved gradient can never win. What was wrong was the remedy: the label
#: bakes at 0.55 alpha where the glyph bakes solid, so one stencil
#: renormalisation could only ever bring one of them to full depth. The
#: split row survives for exactly that: the two bands are renormalised
#: SEPARATELY (glyph x8/7, label x2) and merged back into one stencil, so
#: both cut at full depth and both stay in the cap. BTN_LABEL_DROP /
#: BTN_LABEL_STEEL / BTN_LABEL_LIT are retired with this pass — the label is
#: no longer applied type on the dial, so it has no body colour and nowhere
#: to drop to.
BTN_LABEL_SPLIT = 15         # tile rows below centre: glyph above, label below
#: 2026-08-08, FOURTH ATTEMPT — THE LETTERS GET THEIR OWN LIGHT. Owner, third
#: time of asking: "put a glow or something around it, i have no idea but i
#: can't read it." Every pass above tried to make the CUT better — deeper
#: floor, brighter lit edge — and each one measured well and still could not
#: be read, because a 1.5px stroke has no area no matter what its edge scores.
#: The mark competes against the cap's dark side for the eye, and it always
#: loses on mass.
#:
#: So the ground changes instead of the mark: the stencil is dilated ~2px,
#: blurred, and laid down in the cap's own metal lit to near-white BEFORE the
#: three engraving passes, so every letter sits in a pool of light and the
#: dark cut reads against THAT, not against the dome. This is what a
#: lume-filled engraving does on a real watch. The floor stays dark, the lit
#: edge stays, the halo is a new layer under both — nothing above is removed.
BTN_HALO_INK = (255, 244, 226)   # warm near-white — lume, not screen-white
#: 2026-08-08, the owner at the glass: "sleep and power are a bit too
#: blurry to the human eye, it's fine for the icons but the FONTS have to
#: be sharper." The icons survived because they are thick strokes; the
#: labels are ~1.5px and a 5-box dilation blurred at 2.0 doubled their
#: apparent width into a smear. The pool has to be TIGHT ENOUGH TO SIT
#: UNDER THE LETTER rather than around it: +1px each side, blurred just
#: enough to read as light rather than as a second outline.
BTN_HALO_GROW = 3                # MaxFilter box: +1px of glow each side
BTN_HALO_BLUR = 1.0              # tight — the letter's edge stays an edge
BTN_HALO_A = 0.98              # peak alpha of the pool

#: ── 2026-08-09, THE FIFTH ATTEMPT, AND THE FIRST ONE WITH A MEASUREMENT ──
#: Owner, at the glass again: "sleep and power are still illegible / blurry."
#: That is the THIRD time of asking on this one object, so PRINCIPLES §3
#: applies — stop tuning and measure the separation. Measured on the live
#: panel, both caps, sampling the label band:
#:
#:     SLEEP  engraved floor (53,51,51)  lit flank (197,193,193)   7.04:1
#:            cap surface    (120,116,116)   ->  label vs cap      2.72:1
#:     POWER  engraved floor (60,57,57)  lit flank (192,188,188)   6.08:1
#:            cap surface    (118,114,114)   ->  label vs cap      2.41:1
#:
#: THE RELIEF WAS NEVER THE PROBLEM. It measures 6–7:1, comfortably over the
#: 4.5 floor, and all four previous passes moved that number — a deeper
#: floor, a brighter flank, an eroded flank, then a lume pool. The number
#: that decides legibility is the other one: the letters are read against
#: THE CAP, and that is 2.4:1.
#:
#: AND IT CANNOT BE FIXED BY MAKING THE CUT BETTER, for a reason worth
#: writing down: an engraved mark's mean IS the surface it is cut into. A
#: groove has a dark flank and a lit flank that average back to the metal —
#: that is what engraving is. So a purely engraved label can only ever be
#: read by its EDGES, and at a ~1.5px stroke there is no room for three
#: relief passes plus a 1px halo each side. Every treatment is wider than
#: the stroke it is treating, which is precisely why it reads as a smear:
#: the owner's word both times was "blurry", and blurry is what you get when
#: a letter is 1.5px wide and its decorations are 4px.
#:
#: SO THE LABEL STOPS BEING AN ENGRAVING AND BECOMES AN ETCH-AND-FILL, which
#: is what real switchgear actually is: the groove is cut and then PAINTED,
#: so the mark carries its own colour instead of borrowing the metal's. That
#: gives figure-ground contrast a cut cannot, and it is not a cheat — it is
#: the more common manufacturing process of the two.
#:
#: Three changes, and the halo goes with them:
#:   * THE LABEL IS SCALED UP about its own centroid. At 1.5px no treatment
#:     survives; at ~2px the letterform holds. The glyph is untouched — it
#:     was never the complaint ("it's fine for the icons").
#:   * IT IS FILLED SOLID in near-black. Against the measured cap face of
#:     ~119 that is 6.9:1, up from 2.4:1, on the axis that actually decides.
#:   * THE HALO IS WITHDRAWN FROM THE LABEL and kept for the GLYPH. Its own
#:     note says it exists so a dark cut reads against light rather than
#:     against the dome — a filled mark does not need that, and on a thin
#:     stroke the pool is what was doubling the apparent width.
#: The lit lower flank stays, at low alpha and eroded, so the fill still
#: reads as sunk into metal under the one upper-left sky rather than printed
#: on top of it.
#: 1.45 was a hair too wide — owner, reading it at last: "i see now which is
#: good but the font is just a very very tiny bit too big, it is hitting the
#: circle." The letterform comes back to 1.30 and the BOLD below keeps the
#: mass, which is the right division of labour anyway: scale sets how much
#: of the cap the word occupies, the pen sets whether it can hold ink.
#:
#: ── AND THEN SCALING CAME OUT ALTOGETHER, 2026-08-09 (patek) ─────────────
#: Owner, on the new Patek: "the mute/sleep button has regressed where the
#: circle and the interior don't line up." It had, badly — a magnified arc
#: cutting across the cap and SLEEP sitting outside its own disc.
#:
#: THE BUG IS AN ASSUMPTION, not a number: the scale was applied to the
#: whole lower band of the sampled stencil, centred on that band's ink
#: BOUNDING BOX, on the belief that the band contains nothing but the label.
#: On the ferrari bake it did. On the patek bake the lower band ALSO catches
#: part of the disc's own baked ring, so the bbox centre was pulled off the
#: word, the arc was magnified along with the letters, and both landed in
#: the wrong place. It measured fine on one theme and was broken on another,
#: which is why it shipped.
#:
#: The mass was never coming from the scale anyway — it comes from the pen
#: and the fill (see BTN_LABEL_BOLD, and the 11px -> 300px measurement
#: there). So the geometry is left exactly as home.html baked it, the label
#: is CLIPPED to the cap's interior so no baked rim can ever be mistaken for
#: type again, and the boldening does the reading. 1.0 means no transform at
#: all — the branch is skipped, not run with an identity matrix.
BTN_LABEL_SCALE = 1.0        # the glyph is untouched — it was never the ask
#: How far inside the cap the label must sit. The baked disc ring lives at
#: the rim; anything this far in is type or nothing.
BTN_LABEL_CLIP_IN = 10
BTN_LABEL_FILL = (14, 13, 13)    # the paint in the groove
BTN_LABEL_FILL_A = 0.96          # solid, but not a hole in the cap
BTN_LABEL_SHEEN_A = 0.34         # the lit lower lip of the cut, kept subtle
#: ── AND THE STROKE HAS TO HAVE MASS TO HOLD THE PAINT ────────────────────
#: The fill above landed correctly on the first try and the owner still
#: could not read it — "really cannot read the sleep/power at all now."
#: Measured on that render, and this is the number that explains it: the
#: label ink reached (17,16,16), exactly the near-black specified, but only
#: 11 PIXELS OUT OF 2080 in the label band got under L40. The letters were
#: one-pixel cores with antialiased shoulders, so the paint had almost
#: nothing to sit in and the band averaged out to grey.
#:
#: Contrast was never the missing ingredient after the fill went in; AREA
#: was. A 1.5px stroke scaled to 2px is still mostly edge. So the stencil is
#: DILATED as well as scaled — a real etched label on a control cap is a
#: bold condensed face precisely because thin strokes do not survive being
#: cut into metal, and this is the same constraint arriving from the same
#: physics. Scale widens the letterform, dilation widens the pen.
BTN_LABEL_BOLD = 3           # MaxFilter box: +1px of pen on every side

_BTN_MACH = {"mtime": None}

#: ── 2026-08-09: THE CAPS GO ANODISED RED (ferrari only) ──────────────────
#: Owner: "can we give some 'red love' to the ferrari version? the left side
#: of the face is still too dark. perhaps SLEEP / POWER their icons / font /
#: circle are red or some combination that is gradient and tasteful?"
#:
#: He is pointing at the one place the instrument agrees with him. Measured
#: by 45-degree sector outside r=300, the west sector reads 2.24% against a
#: 3% floor and is the LAST bare one on the dial — and the two caps are what
#: lives there. This is the same object the ring-motif brief named ("tint
#: the mute and sleep ... red as well to get this motif of red around the
#: full circle"), so it closes that too.
#:
#: WHY A POST-DUOTONE PASTE AND NOT A TINT IN THE STAMP. The caps are
#: stamped into base.png, which is upstream of desertify(), and desertify
#: opens with convert("L") — so a red painted into the stamp arrives on the
#: glass as a grey. That is exactly why these caps are graphite on ferrari
#: while they are rose gold on patek: they are not coloured at all, they
#: take whatever the colourway makes of their luminance, and the ferrari
#: ramp is neutral by design.
#:
#: So the cap is built ONCE per bake exactly as it always was — dome,
#: relief pair, specular, engraved glyph, etched label, all in grey — and a
#: COLOURISED COPY is kept beside it. The frame loop pastes that copy after
#: the duotone. Two ~110px pastes per frame, no allocation, and the whole
#: gradient comes free: the dome's own luminance ramp is what colorize maps,
#: so the anodising is dark at the rim and hot toward the upper-left key,
#: which is what anodised aluminium actually does.
#:
#: BEFORE THE DIAL ROTATE, with the moonphase and the bezel — the caps turn
#: with the face, and a fixed-coordinate paste after the rotate would slide
#: off them the moment the wordmark steers.
#:
#: The three stops are an anodising ramp, not a hue slide: near-black with
#: red in it, the accent's own body, and a hot highlight that keeps some
#: white so the dome still reads as METAL rather than as a red balloon.
#: MEASURED AND CORRECTED ON THE FIRST RENDER. The mid started at
#: (168,26,46) and two numbers came back wrong:
#:   * the etched label fell to 2.08:1 / 1.93:1 against its own cap. The
#:     near-black fill that rescued these labels an hour ago is the WRONG
#:     ink on a red cap — dark-on-mid-red has almost no luminance gap. Real
#:     red anodised switchgear is laser-filled in WHITE for exactly this
#:     reason, so on an anodised row the fill inverts (BTN_LABEL_FILL_LIT).
#:   * the west sector jumped 2.24% -> 20.97% of red against a 12% ceiling —
#:     the caps are large discs and a saturated fill made them a blob in one
#:     sector rather than red around the circle. The mid comes down, which
#:     both settles the sector and deepens the anodising.
BTN_ANODISE = ((18, 3, 7), (132, 20, 36), (255, 176, 172))
#: The etched label on an anodised cap: light, not dark. Written as a GREY
#: because it is laid into the tile BEFORE the colorize, so this luminance
#: is what the anodising ramp turns into a pale rose fill — in family with
#: the cap instead of a white sticker on it.
BTN_LABEL_FILL_LIT = (228, 226, 226)
_BTN_RED: list = []


#: ── 2026-08-12: THE CAP METAL WAS THE ONE THING A THEME COULD NOT CHANGE ──
#: Every other metal on this face comes out of the theme row. This one was
#: three literals, so a pusher on a rose-gold ladies' watch came out the same
#: blue steel as the Royal Oak's — the fifth thing tonight that assumed one
#: dial (see the polarity table in FAILURES 2026-08-12).
#:
#: A KEY WITH THE OLD LITERALS AS ITS DEFAULT, not a derivation. Deriving the
#: tint from each theme's res_metal was the tempting version and it moves the
#: patek: its (176,184,196) gives (0.947, 0.990, 1.054) against the
#: (0.94, 0.97, 1.06) that has always been here — close, not equal, and
#: "close" repaints a cap the owner has already signed off.
#:
#: VERIFIED, and verified at the right level. _btn_steel's two forms were run
#: against each other over 2,600 luminances covering the whole range the caps
#: use: ZERO mismatches, so every row without the key is byte-identical
#: through this function. Note what that does NOT claim — the patek's caps on
#: the glass moved by a mean of +3.9 levels across the same restart, and so
#: did the whole dial (+3.5), because the colourway drifts with the ledger.
#: A global shift measured at one spot will happily be read as a local
#: regression; check the field around it before believing that.
BTN_TINT = _THEME.get("btn_tint", (0.94, 0.97, 1.06))


def _btn_steel(lum: float, alpha: int = 255) -> tuple:
    """The structure metal — a tint on a plain grey. Blue-steel by default;
    see BTN_TINT for the row that asks for something else."""
    return (int(min(255.0, lum * BTN_TINT[0])),
            int(min(255.0, lum * BTN_TINT[1])),
            int(min(255.0, lum * BTN_TINT[2])), int(alpha))


def _btn_machine_sync(layers) -> None:
    """Stamp the machined SLEEP/POWER caps onto a freshly landed base.png.

    ── 2026-08-13, THE IDEALFACE CRITIQUE: NOT ON THE PATEK ────────────────
    "SLEEP and POWER are the weakest elements ... filled copper discs on a
    dial where everything else is line-drawn instrument." The stamp is what
    fills them: home.html's own discs are dark ground + engraved ring +
    glyph — line-art that matches the wedges — and the cap paints copper
    over that. A theme may now decline the cap (btn_flat) and keep the
    bake's engraving. Hit zones untouched; the true case-pusher redesign is
    its own pass.

    Verified by measurement on a live bake, 2026-08-08 (the numbers are in
    PREMIUM.md): shadow centroid (+29.6,+32.3) / (+26.4,+34.9) px, rim
    top/under 5.11x / 5.67x (need >=2), glyph floors 31.7 / 46.1 against a
    cap face of 85.8. Build cost ~15 ms once per bake; per-frame zero.
    Contrast correction, same day (see BTN_LABEL_SPLIT), re-measured on the
    same bake: glyph floors 20.1 / 17.5 against a 76 face = 3.79x / 4.34x
    (>=3 required), engraved pair 20.6x / 16.9x, label moved to the dial at
    8.4:1 / 8.2:1 to its local ground (>=4.5), applied pair 4.3x / 2.9x
    (>=2). Still ~16 ms once per bake.
    2026-08-08, the label returns to the cap ENGRAVED (see BTN_LABEL_SPLIT);
    re-measured on the same bake: label floors 20.4 / 18.4 against cap faces
    of 76.2 / 76.0 = 3.73x / 4.13x (>=3), and every label pixel now lands
    inside the cap radius.

    2026-08-08, later — THE CHECK ITSELF WAS WRONG, and that is the finding.
    Every line above verifies the FLOOR against the cap face; all of them
    passed, and the owner still could not read the words. Measuring the LIT
    EDGE instead, on a live bake, said why in one number: the label had ZERO
    lit-edge pixels under either cap (the erosion at `lab` had removed the
    whole flank on strokes that thin), so the brightest thing in the label
    band was the bare dome at L 87, and the "label" was a dark cut at L 14 /
    18 on a 69 face. A floor contrast can be perfect on a mark nobody can
    see. So: THE MEASUREMENT THAT COUNTS IS LIT EDGE vs CAP FACE, >= 4.5:1
    (WCAG AA for text; the plain L ratios quoted above cannot express a mark
    BRIGHTER than its ground, which is what an engraved edge is).
    Measured after the fix, patek-premium base.png, masks taken from this
    function's own composite passes:
      SLEEP  glyph edge L 242.5 vs face 82.3 = 7.02:1
             label edge L 235.5 vs face 69.3 = 8.10:1
      POWER  glyph edge L 210.2 vs face 82.4 = 5.01:1
             label edge L 207.2 vs face 69.3 = 5.98:1
    Floors lifted off pure shadow at the same time (L 14/18 -> 22/38 in the
    label band) so the cut sits in the cap's dark side instead of vanishing
    into it. Still ~16 ms once per bake.

    2026-08-08, FOURTH ATTEMPT — THE HALO SHIPS (see BTN_HALO_INK). Every
    entry above is a better CUT and the owner asked three times, so the fourth
    pass changed the GROUND instead: a warm near-white pool under each letter.
    All of the above stands with its date; nothing was removed, and the labels
    stayed in the cap (the dial fallback was not needed).
    Measured on the live patek-premium bake, stamped through this function,
    letter core vs the cap face IMMEDIATELY around it (the 1-4px annulus,
    which is now the pool) — the number the owner's complaint is about:
      SLEEP  glyph 6.43:1   label 6.96:1
      POWER  glyph 5.65:1   label 4.92:1
    all >= 4.5:1, and the label ink is now DARKER than its surround rather
    than brighter (letter L 0.008 / 0.024 in a pool of L 0.353 / 0.312) — an
    engraved word read as a mark in light, not as a hairline in shadow. Taken
    the other way, band vs the cap face BEYOND the halo: 7.33 / 8.29 / 6.03 /
    8.21:1. Halo containment: it is clipped at R-3 and blurred 2.0, so the
    only lightened pixels outside the cap radius are the same 34 the cap's
    resampled rim always contributed. ~18 ms once per bake; per-frame zero."""
    if _THEME.get("btn_flat"):
        return
    m = layers.mtimes.get("base") or layers.mtimes.get("legacy")
    if layers.base is None or m is None or _BTN_MACH["mtime"] == m:
        return
    _BTN_MACH["mtime"] = m
    # A fresh bake means fresh caps: drop the anodised copies from the last
    # one or they accumulate, and the frame loop pastes two stale discs over
    # the two new ones for the life of the process.
    _BTN_RED.clear()
    t0 = time.time()
    R = BTN_CAP_R
    pad = int(math.ceil(BTN_SHADOW_BLUR * 2
                        + max(BTN_SHADOW_DX, BTN_SHADOW_DY))) + 2
    n = (int(math.ceil(R)) + pad) * 2
    c = n / 2.0
    done = []
    for (bx, by), (floor_ink, edge_ink), tag in zip(
            BTN_DISC_XY, BTN_ENGRAVE_INK, ("sleep", "power")):
        ox, oy = int(round(bx - c)), int(round(by - c))
        # The engraving stencil: home.html's baked glyph and fitted label,
        # read off the pristine bake and clipped inside the rim stroke.
        # (Both bands engrave — they are split below only to be brought to
        # full depth separately, then merged back into one stencil.)
        sten = layers.base.crop((ox, oy, ox + n, oy + n)).convert("L").point(
            lambda v: max(0, min(255, (v - 70) * 255 // 120)))
        clip = Image.new("L", (n, n), 0)
        ImageDraw.Draw(clip).ellipse(
            [c - R + 7, c - R + 7, c + R - 7, c + R - 7], fill=255)
        sten = ImageChops.multiply(sten, clip)
        #: ── 2026-08-12: THE DECLINE THAT COULD NOT DETECT A MISSING BUTTON ─
        #: The contract at BTN_DISC_XY promises this stamp "declines LOUDLY
        #: and leaves the bake alone rather than paint a button where none is
        #: drawn (§1)". It could not keep it. The only test was "are there
        #: bright pixels here", and bright pixels are exactly what a bake with
        #: NO button on a LIGHT dial is made of — so on the chopard face
        #: (home_chopard.html, 250 lines, no #btn-sleep or #btn-power at all)
        #: it took the whole opaline ground as its engraving stencil, cut the
        #: cap to full depth everywhere, and stamped two near-black discs onto
        #: her dial at L 54 and L 78. They were on his glass all night.
        #:
        #: THE STENCIL'S OWN COVERAGE SAYS IT, and the separation is total —
        #: measured on the two live bakes, this function's own crop and clip:
        #:      patek base.png    sleep 3.88%   power 3.25%
        #:      chopard base.png  sleep 100.00% power 100.00%
        #: Ink is a glyph and a word; it covers a few per cent of a cap. Half
        #: a cap of "ink" is not ink, it is the ground, and this is the third
        #: THEME-POLARITY bug in this file — every treatment here assumes
        #: bright marks on a dark dial, and hers is dark marks on a bright
        #: one. 40% is an order of magnitude above the real case and 60 points
        #: below the failure; nothing lives in between (§3).
        area = sum(clip.histogram()[128:])
        inked = sum(sten.histogram()[128:])
        if inked < 40:
            print(f"button: {tag} cap DECLINED — no baked ink under the "
                  "stamp; did home.html's disc move alone?", flush=True)
            continue
        if inked > 0.40 * area:
            print(f"button: {tag} cap DECLINED — the stamp window is "
                  f"{100.0 * inked / area:.1f}% 'ink', which is ground and "
                  f"not a button (a real cap runs 3-4%). This bake draws no "
                  f"{tag} disc; SLEEP/POWER still tap, they are just not "
                  f"painted here.", flush=True)
            continue
        # The two bands, split at home.html's own geometry (see
        # BTN_LABEL_SPLIT): glyph above the row, label below it. Both are
        # engraved; they are kept apart only because they need DIFFERENT
        # arithmetic to reach the same depth, and because the lit flank
        # below has to treat them differently.
        split = int(round(c + BTN_LABEL_SPLIT))
        lab = sten.copy()
        lab.paste(0, (0, 0, n, split))
        sten.paste(0, (0, split, n, n))
        # A cap with no label band is a cap whose word went missing: say so
        # (§1) and cut the glyph anyway rather than leave the button blank.
        if sum(lab.histogram()[64:]) < 40:
            print(f"button: {tag} label NOT engraved — no label ink under "
                  "the stamp; did home.html's label move alone?", flush=True)
        # Full-depth cut: POWER's salmon bakes at L~175 so its stencil tops
        # out near 223, and an 87% floor is where tone-on-tone came from.
        # The label bakes at 0.55 alpha, so its band takes x2 — the same
        # renormalisation the applied pass measured for this same ink.
        sten = sten.point(lambda v: min(255, v * 8 // 7))
        lab = lab.point(lambda v: min(255, v * 2))
        # THE LIT FLANK IS WHAT KILLED THE LABEL THE FIRST TIME, and depth
        # was only half of it. A 1px lit edge inside a 3px glyph stroke
        # leaves 2px of floor; inside the label's ~1.5px strokes it leaves
        # NONE, and the word came back as a bright smear on a bright dome —
        # which is what "lost in that gradient" was. Measured on this bake
        # before the erosion: label floor 221.4 / 135.2 against cap faces of
        # 73.8 / 74.8, i.e. the "floor" was BRIGHTER than the face it was
        # supposed to be cut into.
        # So the label's lit flank was struck from an ERODED stencil: it
        # appeared only where a stroke was wide enough to keep its floor and
        # vanished on the thin ones instead of eating them.
        #
        # 2026-08-08, later — THAT EROSION IS REMOVED. The paragraph above
        # stands with its date; measured on a live bake it erased the label's
        # lit flank ENTIRELY (zero lit-edge pixels under either cap; the
        # brightest thing in the label band was the dome at L 87), leaving the
        # word as a dark floor at L 14 / 18 on a 69 face — a cut nobody could
        # read, which is exactly what the owner reported. Keeping the floor of
        # a 1.5px stroke was never worth the letterform: on strokes that thin
        # the lit edge IS the letter, so the label's flank now comes off the
        # full stencil like the glyph's does.

        def _band(a, b, dx, dy):
            """One flank of the cut, over both bands at once."""
            return ImageChops.lighter(
                ImageChops.subtract(a, ImageChops.offset(a, dx, dy)),
                ImageChops.subtract(b, ImageChops.offset(b, dx, dy)))
        # The cap, built 2x and LANCZOS'd down for clean edges: a dome lit
        # from POCKET_KEY (circles shrinking toward the highlight), the
        # relief pair on the rim, a specular arc upper-left.
        N, C, R2 = n * 2, float(n), R * 2.0
        cap = Image.new("RGBA", (N, N), (0, 0, 0, 0))
        d = ImageDraw.Draw(cap)
        d.ellipse([C - R2, C - R2, C + R2, C + R2],
                  fill=_btn_steel(BTN_CAP_LO))
        hx, hy = C + 0.34 * R2 * POCKET_KEY[0], C + 0.34 * R2 * POCKET_KEY[1]
        for i in range(1, 29):
            t = i / 28.0
            ri = R2 * (1.0 - 0.90 * t)
            lum = BTN_CAP_LO + (BTN_CAP_HI - BTN_CAP_LO) * (t ** 1.3)
            d.ellipse([C + (hx - C) * t - ri, C + (hy - C) * t - ri,
                       C + (hx - C) * t + ri, C + (hy - C) * t + ri],
                      fill=_btn_steel(lum))
        for seg in range(72):
            a0 = seg * 5.0
            t = math.radians(a0 + 2.5)
            f = 0.5 + 0.5 * (math.cos(t) * POCKET_KEY[0]
                             + math.sin(t) * POCKET_KEY[1])
            d.arc([C - R2, C - R2, C + R2, C + R2], a0 - 0.6, a0 + 5.6,
                  fill=_btn_steel(BTN_RIM_DARK
                                  + (BTN_RIM_LIT - BTN_RIM_DARK) * f),
                  width=7)
        spec = Image.new("RGBA", (N, N), (0, 0, 0, 0))
        sr = 0.60 * R2
        ImageDraw.Draw(spec).arc([C - sr, C - sr, C + sr, C + sr],
                                 196.0, 244.0,
                                 fill=(240, 248, 255, 115), width=6)
        cap.alpha_composite(spec.filter(ImageFilter.GaussianBlur(2.5)))
        disc = Image.new("L", (N, N), 0)
        ImageDraw.Draw(disc).ellipse([C - R2, C - R2, C + R2, C + R2],
                                     fill=255)
        cap.putalpha(ImageChops.multiply(cap.getchannel("A"), disc))
        cap = cap.resize((n, n), Image.LANCZOS)
        # The engraving: dark floor, occluded top-left flank, lit
        # lower-right flank — the inverse of every applied edge above, the
        # pair at full strength. The lit flank is 1px, not the shipped 2:
        # the moon is a 3px stroke, and a 2px full-strength edge floods the
        # floor the correction was for.
        # (ImageChops.offset wraps, and the stencil's clip keeps its ink
        # >=7px off the tile edge, so nothing wraps into anything.)
        # THE HALO, UNDER THE LETTERFORM (see BTN_HALO_INK). The dilated,
        # blurred stencil in warm near-white metal, clipped well inside the
        # rim so no glow escapes onto the dial. It goes down FIRST: the three
        # engraving passes below then cut into a lit pool instead of into the
        # dome's dark side, which is the whole point — the letter is read as
        # a dark mark on light, and its lit edge still catches the sky.
        # THE LABEL IS SCALED ABOUT ITS OWN INK before anything is cut, so
        # the letterform has strokes wide enough to survive being treated
        # (see BTN_LABEL_SCALE). Scaled about the ink's BOUNDING BOX centre
        # rather than the tile's: the word is not centred in the tile and
        # scaling about the tile would walk it sideways off the cap.
        # CLIP THE LABEL TO THE CAP'S INTERIOR FIRST (see BTN_LABEL_CLIP_IN).
        # The band is sampled off the bake by row, so on some themes it also
        # catches the lower arc of the disc's own baked ring. That is not
        # type and must never be treated as type — it is what put a
        # magnified arc across the patek's caps.
        _lc = Image.new("L", (n, n), 0)
        ImageDraw.Draw(_lc).ellipse(
            [c - R + BTN_LABEL_CLIP_IN, c - R + BTN_LABEL_CLIP_IN,
             c + R - BTN_LABEL_CLIP_IN, c + R - BTN_LABEL_CLIP_IN], fill=255)
        lab = ImageChops.multiply(lab, _lc)
        _bb = lab.getbbox()
        if _bb and BTN_LABEL_SCALE != 1.0:
            _bx = (_bb[0] + _bb[2]) / 2.0
            _by = (_bb[1] + _bb[3]) / 2.0
            _s = BTN_LABEL_SCALE
            lab = lab.transform(
                (n, n), Image.AFFINE,
                (1.0 / _s, 0, _bx - _bx / _s, 0, 1.0 / _s, _by - _by / _s),
                resample=Image.BICUBIC)
        # ...and then given a heavier pen (see BTN_LABEL_BOLD). Dilate before
        # the fill, so the paint has a stroke to sit in rather than a core.
        if BTN_LABEL_BOLD > 1:
            lab = lab.filter(ImageFilter.MaxFilter(BTN_LABEL_BOLD))
        # THE HALO IS THE GLYPH'S ALONE NOW (see BTN_LABEL_SCALE's note). On
        # the label it was adding a bright pool either side of a 1.5px
        # stroke, which is the "blurry" the owner reported twice.
        pool = sten.filter(
            ImageFilter.MaxFilter(BTN_HALO_GROW)).filter(
            ImageFilter.GaussianBlur(BTN_HALO_BLUR))
        hclip = Image.new("L", (n, n), 0)
        ImageDraw.Draw(hclip).ellipse(
            [c - R + 3, c - R + 3, c + R - 3, c + R - 3], fill=255)
        pool = ImageChops.multiply(pool, hclip)
        glow = Image.new("RGBA", (n, n), BTN_HALO_INK + (0,))
        glow.putalpha(pool.point(lambda v: int(v * BTN_HALO_A)))
        cap.alpha_composite(glow)
        # Both bands cut together now, all three passes: floor, occluded
        # flank, lit flank — the label is treated exactly like the glyph.
        #
        # 2026-08-08, WITH THE HALO — the label's lit flank comes off an
        # ERODED stencil again. That erosion was removed earlier today (see
        # the paragraph above, which stands with its date) and removing it was
        # right AT THE TIME: the ground was the dome's dark side, so on a
        # 1.5px stroke the near-white flank was the only part of the word the
        # eye could find. The ground is now a lit pool, and against a pool a
        # near-white letter is invisible — measured on this bake before the
        # erosion came back: SLEEP's label ink 0.90 vs its own surround 0.87,
        # i.e. 1.02:1, a word painted in the same light it sits in. Eroding
        # gives the flank back only where a stroke can spare it (the glyphs
        # keep theirs), so the thin label strokes stay the DARK cut the halo
        # is there to show off. No threshold: the ink's own width decides.
        # THE GLYPH KEEPS ALL THREE ENGRAVING PASSES. It is a thick stroke,
        # it has the room, and it was never what could not be read.
        sten_edge = sten.filter(ImageFilter.MinFilter(3))
        for mask, ink, k in (
                (sten, floor_ink, 1.0),
                (_band(sten, sten, 1, 1), (0, 0, 0), 0.60),
                (_band(sten, sten_edge, -1, -1), edge_ink, 1.0)):
            lay = Image.new("RGBA", (n, n), ink + (0,))
            lay.putalpha(mask.point(lambda v, k=k: int(v * k)))
            cap.alpha_composite(lay)
        # THE LABEL IS ETCHED AND FILLED. One solid pass of paint, then a
        # single lit lower lip so it still reads as sunk into the metal
        # rather than printed on it. No floor pass and no halo: the fill IS
        # the floor, and it carries its own colour, which is the whole
        # difference between 2.4:1 and something a person can read.
        _fill = BTN_LABEL_FILL_LIT if INSTR else BTN_LABEL_FILL
        lay = Image.new("RGBA", (n, n), _fill + (0,))
        lay.putalpha(lab.point(lambda v: int(v * BTN_LABEL_FILL_A)))
        cap.alpha_composite(lay)
        # The cut's lip runs the OTHER way when the fill is light: a pale
        # mark needs a dark lower lip to sit in the metal, exactly as a dark
        # one needs a bright one. Same geometry, opposite ink.
        sheen = ImageChops.subtract(lab, ImageChops.offset(lab, -1, -1))
        lay = Image.new("RGBA", (n, n),
                        ((0, 0, 0) if INSTR else edge_ink) + (0,))
        lay.putalpha(sheen.point(lambda v: int(v * BTN_LABEL_SHEEN_A)))
        cap.alpha_composite(lay)
        # Shadow first — down-right, away from the key light — then the cap
        # over its upper-left half.
        tile = Image.new("RGBA", (n, n), (0, 0, 0, 0))
        ImageDraw.Draw(tile).ellipse(
            [c - R + BTN_SHADOW_DX, c - R + BTN_SHADOW_DY,
             c + R + BTN_SHADOW_DX, c + R + BTN_SHADOW_DY],
            fill=(0, 0, 0, BTN_SHADOW_A))
        tile = tile.filter(ImageFilter.GaussianBlur(BTN_SHADOW_BLUR))
        tile.alpha_composite(cap)
        layers.base.paste(tile, (ox, oy), tile)
        # THE ANODISED COPY (see BTN_ANODISE), kept for the frame loop to lay
        # down after the duotone. Built from the grey tile's own luminance,
        # so every bit of modelling already in it — dome ramp, rim pair,
        # specular, engraved glyph, etched label — survives the recolour
        # instead of being redrawn in another metal.
        if INSTR:
            _lum = tile.convert("L")
            _red = ImageOps.colorize(_lum, BTN_ANODISE[0], BTN_ANODISE[2],
                                     mid=BTN_ANODISE[1]).convert("RGBA")
            _red.putalpha(tile.getchannel("A"))
            _BTN_RED.append(((ox, oy), _red))
        done.append(tag)
    print(f"button: machined caps stamped ({'+'.join(done) or 'none'}) "
          f"in {(time.time() - t0) * 1e3:.1f} ms", flush=True)


def _room_tile() -> "Image.Image":
    global _ROOM_TILE
    if _ROOM_TILE is not None:
        return _ROOM_TILE
    lay = Image.new("RGBA", ROOM_BOX, (0, 0, 0, 0))
    px = py = ROOM_PX
    # THE POCKET FIRST, under its own scale — the recessed floor, the snail
    # and the thin border ring that replaced this register's hairline flange
    # (see SNAIL_GROUND).
    _snail_pocket(lay, px, py, ROOM_RIM)
    d = ImageDraw.Draw(lay)

    def pt(a: float, r: float):
        t = math.radians(a)
        return px + r * math.cos(t), py + r * math.sin(t)

    # The track, and thirteen graduations at three weights — home.html's own
    # figures for the RESERVE, in display px. The two ENDS cross the track
    # (rim -> 0.75 R) rather than stopping on it: an end index that ends
    # where every other index ends does not say "this is the end", which is
    # that sub-dial's note and the same rule here.
    d.arc([px - ROOM_R, py - ROOM_R, px + ROOM_R, py + ROOM_R],
          ROOM_A0, ROOM_A0 + ROOM_SWEEP, fill=(226, 234, 244, 41), width=3)
    for k in range(13):
        a = ROOM_A0 + ROOM_SWEEP * k / 12.0
        end, major = k in (0, 12), k % 6 == 0
        r0 = ROOM_RIM if end else ROOM_R
        r1 = ROOM_R * (0.750 if end else (0.792 if major else 0.875))
        d.line([pt(a, r0), pt(a, r1)], fill=(218, 225, 234, 158),
               width=3 if end else (2 if major else 1))
    # ROOM where the RESERVE has RESERVE: straight up from the pivot at the
    # same fraction of the flange, in the same ink at the same opacity.
    draw_tracked(d, px, py + ROOM_LABEL_DY, "ROOM",
                 face("label-b", ROOM_LABEL_SIZE),
                 (203, 211, 222, 204), ROOM_LABEL_TRACK)
    _ROOM_TILE = lay
    return _ROOM_TILE


#: ── 2026-08-07: A HAND, NOT A BAR ─────────────────────────────────────────
#:
#: Owner, by voice, on all three registers at once: "the hands for the
#: reserve, moon phase and volume have to be way way more elegant ... What is
#: there now is a plain tapered bar, and a plain bar is what a gauge has, not
#: what a watch has. Give them a real hand profile: a slim polished shaft
#: that tapers along its length, a counterweight tail on the far side of the
#: pivot so the hand looks BALANCED on its arbor rather than stuck to it, and
#: a fine point that actually reaches its scale ... On a subdial the
#: counterweight is most of the elegance — it is the detail the eye reads as
#: watchmaking ... keep them all the same family: reserve, moonphase and
#: volume are three hands on one watch, not three widgets."
#:
#: ONE PROFILE, ONE FUNCTION, and that is the "same family" clause taken
#: literally: the ROOM and MOONPHASE hands were two copies of the same six
#: numbers and are now one call each. The RESERVE's is drawn by home.html
#: (#res-hand) and cannot share code across the language boundary, so it is
#: the same (r, w) pairs re-solved about its own pivot there, in a comment
#: that names this one. They move in one commit or the family breaks.
#:
#: WRITTEN IN THE RESERVE'S 72-UNIT TRACK, exactly as the flat baton it
#: replaces was, so every caller goes on passing K = its own track / 72 and
#: the profile scales with the register instead of overhanging it.
#:
#: WHAT DELIBERATELY SURVIVES THE BATON, because the clearances measured in
#: the notes above were measured against them: the tip is still r=68 — into
#: the tick band, 4 short of the track — and the pivot cap is still 5.2,
#: which is the number the moonphase note relies on to cover the aperture's
#: foot. Every OUTWARD reach is therefore the one the old measurements used.
#:
#: THE SHAFT IS NARROWER THAN THE BATON, 4.6 half-units at the shoulder
#: against a flat 5.5 the whole way, and that is the brief's word "slim"
#: taken as a measurement. It is also what makes the counterpoise read: a
#: lobe the same width as the bar it hangs off is a bar with a rounded end.
#:
#: THE TAIL IS THE ONE THING THAT REACHES FURTHER than the baton did, so it
#: is the one thing to re-measure: -12 becomes -20 at the counterpoise's
#: centre and -26.4 at its far edge, i.e. 29.3 display px about a pivot with
#: an 88px flange. The two things that sit near a pivot on this face both
#: clear it — the word ROOM is 64 above its own pivot, and the closest the
#: lobe comes to it is 29.3 (the needle at rest, pointing down), so 34.7 of
#: air; and the moonphase aperture already lies OVER its pivot, which that
#: register's pointer has always crossed on the days its travel takes it
#: there. See THE POINTER there.
#:
#: THE COUNTERPOISE IS A CIRCLE, not more polygon, and not because it is
#: easier: a round counterweight on a thin neck is the shape the eye reads as
#: an applied hand rather than as a wider end of the same bar, which is the
#: half of the brief that says "balanced on its arbor rather than stuck to
#: it". It is drawn at the SAME size on both registers — like the cap and
#: unlike the shaft — because `s` exists only to keep the moonphase pointer
#: narrow over its busy aperture, and a counterpoise thinner than the cap it
#: balances reads as a mistake.
#:
#: (r along the hand, half-width across it), tail first, so the mirror image
#: of the list is the other flank and the two close into one polygon.
HAND_SHAFT = ((-20.0, 2.0), (-8.0, 1.7), (4.0, 4.2), (14.0, 4.6),
              (38.0, 3.2), (58.0, 1.7), (68.0, 0.0))
#: THE LIT FLANK IS A RIDGE, and a ridge needs two sides. The first cut of
#: this was a bright hairline down one edge of a flat shaft and it did not
#: survive the render: a 10px-wide hand in 243/248/254 against a body of
#: 212/218/226 is 30 levels apart across two pixels, which at arm's length is
#: no highlight at all. So the OTHER half of the shaft is filled darker
#: first, the hairline goes on the lit edge, and the ridge falls where the
#: two meet — which is what the tourbillon's arms already do (_tourb_cage
#: draws GOLD_LIT down one edge and GOLD_DARK down the other) and is the
#: comparison the owner made. The light on this dial comes from one side; a
#: polished hand has to say so on both.
#:
#: HAND_GLINT is inset ~0.8 off the flank so the hairline sits ON the metal
#: rather than beyond its edge, and stops at 64 so it runs out before the
#: point instead of blunting it.
HAND_GLINT = ((4.0, 3.4), (14.0, 3.8), (38.0, 2.4), (58.0, 1.0), (64.0, 0.4))
HAND_TAIL_R, HAND_TAIL_W = -20.0, 6.4    # the counterpoise, unscaled
HAND_CAP = 5.2                           # the arbor cap, unscaled — see above

#: ── 2026-08-09: THE NEEDLE, for INSTR rows ────────────────────────────────
#: Owner: "swap the leaf hands for straight needle pointers with red tips and
#: white counterweights."
#:
#: WHAT MAKES IT A NEEDLE IS THE ABSENCE OF THE SHOULDER. The leaf above
#: swells to 4.6 half-units at r=14 and tapers back — that belly is the whole
#: reason it reads as a watch hand, and it is exactly what a rev-counter
#: needle does not have. So this profile leaves the arbor at 2.4 and runs
#: STRAIGHT to the point: every intermediate half-width is on the line
#: between (2, 2.4) and (68, 0), which is what "straight" has to mean if the
#: silhouette is to be a triangle rather than a thinner leaf.
#:
#: EVERY OUTWARD REACH IS THE LEAF'S, deliberately, and this is the clause
#: that keeps the clearances in the notes above valid: the tip is still 68,
#: the tail still -20, the cap still HAND_CAP. Only the WIDTHS move, so no
#: measurement taken against the leaf has to be taken again.
#: 40.0 is a KNOT rather than a spare point: it is where the red tip starts
#: (NEEDLE_TIP_R below), and having the profile already carry a vertex there
#: is what lets the tip be a slice of this same list instead of a second
#: piece of geometry that can drift off it. Every half-width is on the line
#: 2.8 - 0.042424*(r - 2), which is where 1.87 and 1.19 come from.
#: 2.4 -> 2.8 AT THE SHOULDER, AND THE TIP MOVES 54 -> 40, both measured off
#: the first render rather than chosen: on the ROOM register K is
#: ROOM_R/72 = 1.111, so a 0.51 half-width is 0.57 px and the "red tip" was
#: SUB-PIXEL — struck, present in the geometry, and invisible on the glass,
#: which is §1's silent success wearing a different hat. From 40 the tip is
#: 31 px long and 2.6 px wide where it starts, which reads across a room.
NEEDLE_SHAFT = ((-20.0, 2.0), (-8.0, 1.8), (2.0, 2.8), (24.0, 1.87),
                (40.0, 1.19), (68.0, 0.0))
#: The glint is one straight hairline down the lit flank, inset the same ~0.8
#: the leaf's is and stopping at 62 so it runs out before the point.
NEEDLE_GLINT = ((2.0, 2.0), (24.0, 1.2), (46.0, 0.5), (62.0, 0.2))
#: Where the red tip starts, in the same 72-unit track. 28 of 68 is the
#: outer 40% of the needle — a painted point, which is what a rev counter
#: has, and short of the "red hand" a full-length one would be. See the
#: sub-pixel measurement in the NEEDLE_SHAFT note for why it is not 54.
NEEDLE_TIP_R = 40.0
#: THE TWO STRIKES, as one name each, because they are laid at four sites
#: (the moon hand direct, the ROOM and RESERVE counterpoises and the two tips
#: re-struck in draw_gold_strikes) and a fifth site would otherwise mean a
#: fifth conditional. On a row without INSTR both are the accent, which is
#: what all four sites carried before this pass — those rows are unmoved.
HAND_TAIL_INK = INSTR_WHITE if INSTR else _THEME["accent"]
HAND_TIP_INK = INSTR_RED if INSTR else _THEME["accent"]


def _draw_hand(d: "ImageDraw.ImageDraw", px: float, py: float, ang: float,
               K: float, steel, s: float = 1.0, tail=None, tip=None) -> None:
    """One hand, pointing at `ang` degrees about (px, py).

    `K` is the caller's own track / 72. `s` scales the WIDTHS only: the
    lengths are shared so the registers read as one family however their
    scales differ. `steel` is (shaft, shade, glint, cap) — four colours
    rather than one so each register can supply them in its OWN space: the
    ROOM dial is drawn before desertify() and passes raw greys, the moonphase
    is drawn after it and passes the same luminances through _dial_metal.

    `tail` and `tip` are the amendment-2 gold strikes ("more gold,
    sprinkled"): the counterpoise's fill, and a small cap over the last ten
    units of the point. ONLY a caller on the far side of desertify() may
    pass them — before it, convert("L") hands the gold back as grey. The
    ROOM hand and the baked RESERVE hand get theirs re-struck after the
    duotone instead (see draw_gold_tails).
    """
    shaft, shade, glint, cap = steel
    t = math.radians(ang)
    ux, uy = math.cos(t), math.sin(t)

    def at(r: float, w: float) -> tuple:
        return (px + r * K * ux - w * s * K * uy,
                py + r * K * uy + w * s * K * ux)

    # THE PROFILE IS THE THEME'S (2026-08-09, INSTR): leaf on a dress row,
    # straight needle on an instrument one. Same lengths, same tail, same
    # cap — see the note at NEEDLE_SHAFT for why only the widths move.
    prof = NEEDLE_SHAFT if INSTR else HAND_SHAFT
    glints = NEEDLE_GLINT if INSTR else HAND_GLINT
    d.polygon([at(r, w) for r, w in prof]
              + [at(r, -w) for r, w in reversed(prof[:-1])], fill=shaft)
    d.polygon([at(r, 0.0) for r, _w in prof]
              + [at(r, -w) for r, w in reversed(prof[:-1])], fill=shade)
    tr = HAND_TAIL_W * K
    tx, ty = at(HAND_TAIL_R, 0.0)
    d.ellipse([tx - tr, ty - tr, tx + tr, ty + tr], fill=tail or shaft)
    d.line([at(r, w) for r, w in glints], fill=glint, width=2,
           joint="curve")
    if tip is not None:
        # A needle's tip is PAINTED, so it is the last stretch of the whole
        # profile in red rather than the leaf's little cap over the last ten
        # units — the same polygon arithmetic, from NEEDLE_TIP_R out.
        if INSTR:
            nose = [(r, w) for r, w in prof if r >= NEEDLE_TIP_R]
            d.polygon([at(r, w) for r, w in nose]
                      + [at(r, -w) for r, w in reversed(nose[:-1])], fill=tip)
        else:
            d.polygon([at(58.0, 1.7), at(68.0, 0.0), at(58.0, -1.7)], fill=tip)
    cr = HAND_CAP * K
    d.ellipse([px - cr, py - cr, px + cr, py + cr], fill=cap)


def draw_room(frame: "Image.Image", now: float) -> None:
    """The sound-level sub-dial at three o'clock, and who was last heard.

    Composited through an alpha layer rather than drawn onto the frame,
    because the RESERVE it takes its treatment from is a set of translucent
    strokes over the tapisserie (home.html's #reserve: the rim at 0.18, the
    track at 0.16, the graduations at 0.62). Painting the same greys opaquely
    would put a heavier instrument on the right of the dial than on the left,
    which is the one thing "so they read as a set" cannot survive — and it is
    now the ONLY thing keeping them a set, since the sizes differ on purpose.
    """
    d0 = _room_now(now)
    frac = _room_frac(d0.get("energy") if d0 else None)
    ang = _room_needle(now, frac)
    # Stashed for draw_gold_strikes: the counterpoise is re-struck in gold
    # on the far side of desertify(), at this same frame's angle.
    _ROOM["ang"] = ang
    cx, cy = ROOM_PIVOT
    x0, y0 = int(cx - ROOM_PX), int(cy - ROOM_PX)
    lay = _room_tile().copy()
    d = ImageDraw.Draw(lay)
    px, py = cx - x0, cy - y0
    # THE HAND, the shared profile at A HAND, NOT A BAR — tapered shaft,
    # counterpoise, lit flank, tip at r=68 of a 72 track. It points INTO the
    # tick band; a hand that stops short of its own scale cannot indicate on
    # it. (It was a broad flat baton, 11 units wide the whole way to a
    # squared end; the owner's word for that was "a plain tapered bar".)
    # K WAS DIAL_K x VB_PX, WHICH IS WHAT ROOM_R/72 USED TO EQUAL. Now that
    # this is the smallest of the three the two have parted, and the hand
    # has to follow its OWN track or a full-size one overhangs a 45px scale.
    _draw_hand(d, px, py, ang, ROOM_R / 72.0,
               ((212, 218, 226, 255), (162, 170, 182, 255),
                (246, 250, 255, 255), (224, 231, 239, 255)))
    # ...AND THE NAME UNDER IT, which is the half of this complication no
    # watch has. "—" is a live meter that has not recognised anybody yet;
    # NO EARS is no meter at all, and the needle is off-scale beside it.
    who = (d0 or {}).get("who")
    name = ROOM_NO_FEED if d0 is None else (str(who).upper() if who else "—")
    ink = (203, 211, 222, 204) if d0 is not None else (196, 154, 140, 210)
    draw_centred(d, px, py + ROOM_NAME_DY, name,
                 face_for(name, "label-b", ROOM_NAME_SIZE),
                 ink, ROOM_NAME_TRACK, limit=ROOM_NAME_W)
    frame.paste(lay, (x0, y0), lay)


#: COMPOSE-LOOP RULE 1 BITES HERE (2026-08-07 touch pass; the full rules
#: stand at "-- compose --" in main): this call allocated a fresh
#: full-canvas RGBA EVERY FRAME. The scratch layer is allocated ONCE and
#: reused; each frame erases only last frame's ink box and, when the dial
#: is not turned to a talker, composites only this frame's.
_WM_LAYER: dict = {"im": None, "box": None}


def draw_wordmark(frame: "Image.Image", now: float,
                  brand: bool = False) -> None:
    """AURA in applied gold, VISION in applied blue-steel, set as ONE word.

    (VISION breathed flat blue until 2026-08-08, refile three — see the
    note at STEEL_RIM. Both words are embossed sprites now, one light.)

    Drawn onto its own transparent layer and rotated to the talker's bearing,
    then composited — so the TEXT turns and the sky underneath does not.

    `brand` is the DIAL layout: small, under twelve, the centre left to the
    complications (see WORDMARK_BRAND_K). The home face passes it; the lock
    screen does not, and must not — see that note for why the two differ.
    """
    layer = _WM_LAYER["im"]
    if layer is None or layer.size != frame.size:
        layer = Image.new("RGBA", frame.size, (0, 0, 0, 0))
        _WM_LAYER["im"] = layer
    elif _WM_LAYER["box"] is not None:
        layer.paste((0, 0, 0, 0), _WM_LAYER["box"])
    _draw_wordmark_flat(layer, now, brand)
    box = _WM_LAYER["box"] = layer.getbbox()
    #: ── FITTED TO THE CIRCLE, NOT PLACED IN IT (2026-08-17) ─────────────
    #: Owner: "center AURAVISION in the middle of the circle it's
    #: overlapping outwards."
    #:
    #: The wordmark is set at a typed point size and centred, so whether it
    #: FITS the iris has always been a coincidence — and once the iris got
    #: its own rim at 270 px the coincidence stopped holding. Measured
    #: rather than re-typed: the rendered block is scaled down until its
    #: ink sits inside the circle with a margin, which means it survives
    #: every future change to the rim, the type size or the string.
    #:
    #: Only ever DOWN. Scaling type up is how you get a soft, swollen
    #: wordmark; if it already fits, nothing happens at all.
    if box is not None and not brand and AURORA_BLOB:
        _bw = box[2] - box[0]
        _bh = box[3] - box[1]
        #: 0.86 of the chord at the block's own height, so the corners
        #: clear the curve rather than the midline touching it
        #: 0.86 -> 0.76: at 0.86 it fitted arithmetically and still
        #: read as crowded, because the eye judges a word inside a circle
        #: against the CURVE beside it, not against the widest chord. A
        #: word that ends 20 px from the rim looks like it is escaping.
        _fit = (AUR_RIM_R1 * 2.0) * 0.76
        if _bw > _fit and _bw > 0:
            _k = _fit / float(_bw)
            _nw, _nh = max(1, int(_bw * _k)), max(1, int(_bh * _k))
            _crop = layer.crop(box).resize((_nw, _nh), Image.LANCZOS)
            layer.paste((0, 0, 0, 0), box)
            _nx = int(WORDMARK_XY[0] - _nw / 2)
            _ny = int(box[1] + (_bh - _nh) / 2)
            layer.paste(_crop, (_nx, _ny), _crop)
            box = _WM_LAYER["box"] = layer.getbbox()
    ang = _doa_angle(now)
    if abs(ang) > 0.5:
        # About the block's OWN centre either way, or the brand turns on a
        # pivot 280px below it and swings off the top of the dial.
        pivot = (WORDMARK_XY[0], float(WORDMARK_BRAND_Y)) if brand \
            else WORDMARK_XY
        turned = layer.rotate(-ang, resample=Image.BICUBIC, center=pivot)
        frame.paste(turned, (0, 0), turned)
    elif box is not None:
        cut = layer.crop(box)
        frame.paste(cut, box[:2], cut)


AWAITING_NAME = Path("/tmp/aura_face/awaiting_name")
#: ── A MODE FLAG ON DISK OUTLIVES WHATEVER RAISED IT ──────────────────────
#: `aura.speakerid.enrollment.asked_recently` owns this window and its
#: docstring owns the argument: the conductor's bow-out runs only after
#: REASK_SILENCE_S of quiet, and a television never hands a room ten quiet
#: seconds, so a flag meant to cover one question stayed open all evening
#: on the owner's puck and a line of film narration walked through it.
#: mtime is the end condition the room cannot veto.
#:
#: NOT IMPORTED, and that is a deliberate exception to §15 rather than an
#: oversight: `enrollment` pulls numpy and the speaker registry, and this is
#: the COMPOSITOR — a module that must come up on a puck with nothing else
#: alive and must not carry the identity stack to read one float. So it is
#: mirrored with its owner NAMED on the line below — and if the two ever
#: disagree, enrollment.py is right and this is wrong. The consequence of
#: drift here is bounded and cosmetic in the safe direction: too small and
#: the ring stops early on a ceremony still running, too large and it
#: lingers on a dead one. It can never admit a name that is not one.
CEREMONY_WINDOW_S = 90.0        # == aura.speakerid.enrollment.NAME_WINDOW_S


def _ceremony_live(now: float) -> bool:
    """Has she ACTUALLY just asked this room for a name?

    The bounded read of AWAITING_NAME, in the compositor. `.exists()` alone
    is what the enrolment module's own docstring forbids: the conductor
    raises this flag and its clear can be blocked by a noisy room, so a
    stale flag is the normal case rather than the exotic one.
    """
    try:
        return (now - AWAITING_NAME.stat().st_mtime) <= CEREMONY_WINDOW_S
    except OSError:
        return False


def _ceremony_running(now: float) -> bool:
    """Is an enrolment under way right now? Cheap enough for every frame:
    two stats and a cached read."""
    try:
        if _ceremony_live(now) or ENROLL_CATS.exists():
            return True
    except Exception:
        pass
    return _enroll_state(now) is not None


#: ── 2026-08-07, amendment 4: EMBOSSED UPWARD ──────────────────────────────
#: Owner: "more textured, 3d... where it seems almost embossed upward."
#: Raised relief, not printed gold — so the light source moves OVERHEAD.
#: The amendment-3 bevel lit the up-LEFT inner rim and shaded the down-right
#: one; a diagonal light reads as tilted type, and it left the under-edges
#: bare. Three optical facts make relief read as UP, and each is drawn in
#: _draw_wordmark_flat:
#:   * every upper edge of every stroke carries a bright rim, every LOWER
#:     edge a dark occlusion line — the under-edge shadow is the facet the
#:     old bevel was short of, and it is what pins the letter to the ground
#:     instead of letting it float;
#:   * the letter face takes a vertical gradient, brighter at the top of a
#:     stroke falling toward its foot, because a raised face tips toward an
#:     overhead light;
#:   * a whisper of horizontal brushed grain in the face, so it reads as
#:     metal rather than moulded plastic.
#: DRAWN HERE, NOT BAKED the bake_bezel.py way, though that route was on the
#: table: the wordmark cannot hold still for a bake — VISION breathes per
#: frame, x and the word gap fall out of live font metrics, and the size
#: constants have moved three times today alone. The footprint stays the
#: light face's own ink (third-pass rule above); only the fill and the rims
#: change, so every stem still measures what the face measures.
#: MEASURED ON THE RENDER (this box's URW faces; interior stem columns —
#: an AA edge column wobbles with per-row hinting and is not the face):
#: the A's crossbar top edge peaks at luma 226 against an under edge of 75
#: — 3.0x, over the 2x floor the brief set (dial layout 226/80, 2.8x) —
#: and the U's stem face falls 196 -> 147 monotonically, every row,
#: through the grain (dial 188 -> 156).
#: 2026-08-09, themes: these three were the halfway triples WRITTEN OUT;
#: now the brand metal moves per row (the fourth-pass note at _THEMES) they
#: are COMPUTED from it, exactly as STEEL_FACE_TOP/BOT below are computed
#: from VISION's — so the halfway clause in the note above holds on every
#: row instead of on the one it was measured for. ROUND-HALF-UP, not the
#: steel pair's floor division, and that is not a taste: on the gold the
#: floor loses a level (212+247)//2 = 229 against the literal's 230, and
#: this pass has to leave patek and royal-oak byte-identical. Both existing
#: rows land on (230,201,131) and (168,136,68) exactly.
GOLD_FACE_TOP = tuple((a + b + 1) // 2
                      for a, b in zip(_THEME["brand_ink"],
                                      _THEME["brand_lit"]))
GOLD_FACE_BOT = tuple((a + b + 1) // 2
                      for a, b in zip(_THEME["brand_ink"],
                                      _THEME["brand_dark"]))
GOLD_UNDER = _THEME["brand_under"]  # under-edge occlusion: DARKER than the
                                  # shaded flank, because the crack where a
                                  # ledge meets the ground sees ambient only
#: ── 2026-08-08, refile three: THE FULL WORDMARK IN RELIEF ─────────────────
#: Owner: VISION gets the same upward emboss as the gold AURA, in its own
#: blue-steel — top-edge highlight, under-edge occlusion, vertical face
#: gradient, ONE light shared with the bezel. Shared light means shared
#: GEOMETRY: the same overhead source, the same vertical offsets, the same
#: grain — only the metal changes. Both layouts get the pair for free
#: because lock and dial share _draw_wordmark_flat.
#: THE BREATH RETIRES WITH THIS (VISION_HZ and its note stand, dated). A
#: sprite stamped once cannot change colour per frame, and _vision_ink's
#: per-frame blue was the one input that kept VISION off the r73 bake;
#: "zero per-frame work" was this brief's own words. The steel is derived
#: the way the gold was: face-top is VISION_LO halfway to VISION_HI,
#: face-bot VISION_LO halfway to the under-edge, ink stays VISION_LO — so
#: B-R stays positive at every pixel, the blue answer to the gold's
#: everywhere-negative.
STEEL_RIM = VISION_HI             # the specular top edge — peak short of
                                  # white, see the note at VISION_HI
STEEL_UNDER = _THEME["steel_under"]  # under-edge occlusion: ambient only,
                                  # the crack where the ledge meets ground.
                                  # Blue (24,46,66) on royal-oak, warm on
                                  # patek — it is the metal's own ambient,
                                  # so it rides the theme table (2026-08-08)
#: 2026-08-08, themes: these two were the halfway triples WRITTEN OUT; now
#: the metal moves per theme they are COMPUTED, so the halfway clause in the
#: note above holds on every row. On royal-oak the arithmetic lands
#: byte-identical to the old literals, (105,205,255) and (42,123,160).
STEEL_FACE_TOP = tuple((a + b) // 2 for a, b in zip(VISION_LO, VISION_HI))
STEEL_FACE_BOT = tuple((a + b) // 2 for a, b in zip(VISION_LO, STEEL_UNDER))
_GOLD_FACE_CACHE: dict = {}


def _gold_face(w: int, h: int, top=GOLD_FACE_TOP,
               bot=GOLD_FACE_BOT) -> Image.Image:
    """The embossed face for one applied word: vertical gradient x grain.

    Cached per size — the fill is static and only the mask it is pasted
    through moves. The grain is hash-noise, not random(): the same size
    must render the same face every frame, or the metal shimmers like
    water. Streaks run ~5 rows tall and 9 counts deep so the row-to-row
    swing stays under the gradient's own step — the gradient must stay
    monotonic top to bottom THROUGH the grain, or the relief read
    collapses into texture.

    `top`/`bot` are the metal (refile three, note at STEEL_RIM): gold by
    default, blue-steel for VISION. Same gradient, same grain — one light.
    """
    got = _GOLD_FACE_CACHE.get((w, h, top, bot))
    if got is not None:
        return got
    col = Image.new("RGB", (1, h))
    col.putdata([tuple(t + round((b - t) * i / max(1, h - 1))
                       for t, b in zip(top, bot))
                 for i in range(h)])
    fill = col.resize((w, h), Image.NEAREST)
    gw, gh = max(2, w // 16), max(2, h // 5)
    g = Image.new("L", (gw, gh))
    g.putdata([255 - round((math.sin(j * 12.9898 + i * 0.37 + 78.233)
                            * 43758.5453) % 1.0 * 9)
               for j in range(gh) for i in range(gw)])
    grain = g.resize((w, h), Image.BILINEAR)
    got = ImageChops.multiply(fill, Image.merge("RGB", (grain,) * 3))
    _GOLD_FACE_CACHE[(w, h, top, bot)] = got
    return got


#: COMPOSE-LOOP RULE 2 BITES HERE (2026-08-07 touch pass; the full rules
#: stand at "-- compose --" in main): ANYTHING STATIC GETS BAKED ONCE. The
#: DRAWN-NOT-BAKED note at GOLD_FACE_TOP is about the WORDMARK — VISION
#: breathes and the layout falls out of live font metrics — but every input
#: the emboss itself takes is STILL at runtime: constants and cached font
#: metrics. So the embossed word is rendered once into a small RGBA sprite,
#: keyed on all of them, and pasted per frame; in practice it builds once
#: per layout (lock / dial) per process.
_AURA_EMBOSS: dict = {}


def _aura_embossed(d, word, wf, wtrack, ink, spec, wx, wy, relief):
    """The applied word, embossed once into a small cached sprite.

    Returns (sprite, paste_x, paste_y). The same three draws as the live
    version — the ink, the metal face through the ink mask, the bright top
    rim and the dark under-edge — at the caller's own subpixel offset, so
    the pixels match the per-frame rendering exactly; only WHEN they are
    computed changed.

    `relief` is (face_top, face_bot, rim, under) — the metal only (refile
    three): gold for AURA, blue-steel for VISION. The geometry — overhead
    light, vertical offsets, grain — is identical for both, which is what
    makes the two words read as struck by the one bezel light.
    """
    face_top, face_bot, rim, under = relief
    o = max(1, round(spec / 2.0))
    pad = o + 2
    ix, iy = int(math.floor(wx)), int(math.floor(wy))
    fx, fy = wx - ix, wy - iy
    # `relief` IS PART OF THE KEY (2026-08-08, the aperture below). It was
    # not, and that was safe only while one process had one metal per word.
    # The patek now sets the SAME word in the SAME face two ways — applied on
    # the lock screen, engraved in the dial's window — so a key without the
    # metal serves whichever was stamped first the moment the two sizes ever
    # coincide. That is a silent wrong-colour, not a crash (§1).
    key = (word, wf.size, round(wtrack, 2), o, round(fx, 2), round(fy, 2),
           relief)
    spr = _AURA_EMBOSS.get(key)
    if spr is None:
        w = int(math.ceil(track_len(d, word, wf, wtrack))) + 2 * pad + 2
        h = int(math.ceil(wf.getbbox(word)[3])) + 2 * pad + 2
        m = Image.new("L", (w, h), 0)
        track_text(ImageDraw.Draw(m), (pad + fx, pad + fy), word, wf, 255,
                   wtrack)
        spr = Image.new("RGBA", (w, h), (0, 0, 0, 0))
        track_text(ImageDraw.Draw(spr), (pad + fx, pad + fy), word, wf,
                   ink, wtrack)
        bb = m.getbbox()
        if bb:
            spr.paste(_gold_face(bb[2] - bb[0], bb[3] - bb[1],
                                 face_top, face_bot),
                      (bb[0], bb[1]), m.crop(bb))
        down = m.transform(m.size, Image.AFFINE, (1, 0, 0, 0, 1, -o))
        up = m.transform(m.size, Image.AFFINE, (1, 0, 0, 0, 1, o))
        spr.paste(rim + (255,), (0, 0),
                  ImageChops.subtract(m, down))
        spr.paste(under + (255,), (0, 0), ImageChops.subtract(m, up))
        _AURA_EMBOSS[key] = spr
    return spr, ix - pad, iy - pad


#: ── 2026-08-08: ON THE PATEK THE WORDMARK IS AN APERTURE ──────────────────
#: The owner, with his own reference open — a Patek 5271P Grand
#: Complications, whose day and month are RECESSED WINDOWS cut into the dial
#: behind polished frames: "let's make aura vision on the patek recessed
#: similar to the style here with the day/month windows... it needs to feel
#: more special, this is a premium product offering."
#:
#: So on THIS THEME ONLY the brand stops being type laid on the dial and
#: becomes a hole in it. Four parts, and every one is a treatment this file
#: already owns, borrowed rather than invented:
#:   * the FLOOR is a black wash, not a colour — SNAIL_GROUND's own
#:     arithmetic, and its own alpha. A wash is a FRACTION of whatever dial
#:     lands under it, so "10-20% darker than the adjacent dial" holds over
#:     the tapisserie's raised tops AND its grooves, and would still hold if
#:     the colourway moved under it (§6: relative to the floor it competes
#:     with, never an absolute). 44/255 = 17.3%, mid-band — the same number
#:     and the same reasoning the register pockets settled on today.
#:   * the WALL is lit BACKWARDS, the pockets' rule at _pocket_relief: an
#:     interior catches the key light on the FAR side, so with this face's
#:     overhead light (amendment 4 at GOLD_FACE_TOP) the top of the opening
#:     is the occluded overhang and the bottom is the lit far wall. Vertical
#:     only, because that is where the wordmark's light has been since
#:     amendment 4 and two lights on one dial is the tell of a fake.
#:   * the FRAME is the relief pair every raised edge here wears — top edge
#:     lit, under edge occluded — in the theme's own rose gold (RES_METAL),
#:     with the metal's face gradient between them. Its rim and its crack are
#:     the halfway triples the gold and the steel are built from, so the
#:     arithmetic at STEEL_FACE_TOP holds on this row too.
#:   * the LETTERS invert. See _engraved.
#:
#: WHY THE LOCK SCREEN DOES NOT GET IT, and this is the one place the brief
#: is read narrowly on purpose: he asked for a window CUT INTO THE DIAL, and
#: measured it against "the adjacent dial". The lock screen is deep space
#: with a starfield — there is no dial there to cut, and a rose-gold frame
#: floating in a star field is a sticker, which is the exact read this pass
#: exists to kill. Dial layout only (`brand`), and the lock screen keeps the
#: applied pair it has had since refile three.
#:
#: SIZED SO THE AIR IS THE POINT: "on the 5271P the window is mostly frame
#: and space, which is what makes it read as jewellery rather than a label."
#: MEASURED on the render, patek, dial layout: the type inks 356 x 26 px and
#: the opening it sits in is 416 x 62, so the type covers 40% of the window's
#: height and 86% of its width — air on every side, most of it above and
#: below, which is how a day aperture is proportioned.
#: THE TWO CLEARANCES THAT BIND, both measured, not estimated: the outer
#: frame's lower corners land at y=328 against the RESERVE and ROOM flange
#: tops at y=332.5 (4.5px, and the corner radius buys a little more), and its
#: upper corners at r=354.2 from the dial centre against the wedge ring's
#: inner edge at WEDGE_R0 = 369.6 (15.4px). Both are the numbers that move if
#: the pads below move — the block cannot grow without taking one of them
#: negative.
#:
#: VERIFIED ON THE RENDER, patek, dial layout, over home.html's own source
#: greys through desertify() — the owner's four bars, in his order:
#:   floor     adjacent dial L 39.5 -> window floor L 32.5 = 17.7% darker,
#:             mid of the 10-20% band (936 sampled floor pixels)
#:   frame     top edge L 218.3 against the under edge's L 39.9 = 5.48x,
#:             against a floor of 2x. The wall runs the other way, as it
#:             must: upper L 39.9, lower L 218.3
#:   letters   worst face row 5.74:1 against the window floor, mean 7.51:1,
#:             floor 4.5:1 — see ENGRAVE_LIFT, which exists for that row
#:   cost      draw_wordmark(brand) 0.819 -> 1.081 ms, +0.261 ms, which is
#:             0.37 points of the 71.4 ms idle-frame budget against a bar of
#:             2. ONE aperture sprite is built per process. Measured on the
#:             dev box and NOT on the puck (§6 — the honest half of this
#:             line): it is a paste of a cached sprite either way, so what
#:             carries across is the shape of the cost, not the millisecond.
#: ── 2026-08-09: THE WINDOW IS OFF. THIRD ASK ON THE SAME OBJECT ──────────
#: Owner, on the new patek: "get rid of that stupid lower remnant of a box
#: in the AURA VISION part of the dial." That is the THIRD complaint about
#: this one rectangle — "the aura vision framing is still gaudy, the
#: rectangle is not pleasing look wise", then "get rid of, again, that
#: awkward border around AURA VISION", and now this. PRINCIPLES §3 applies
#: to taste as well as to thresholds: after the second failure, stop
#: refining and change the approach.
#:
#: WHAT HE IS SEEING, and why removing the frame did not remove the box. The
#: 2026-08-08 pass took away the drawn outline and left "the floor wash and
#: the wall's relief pair", believing that a recess defined by light alone
#: could not read as a rectangle. But the wall pair is built by shifting the
#: floor mask up and down and subtracting — which paints a lit band along
#: the TOP edge of the box and another along the BOTTOM. With the sides
#: gone, what survives is exactly two horizontal rules bracketing the
#: wordmark: a box with its sides rubbed out, which is a more distracting
#: object than the box was, because the eye completes it anyway.
#:
#: Verified where it comes from before touching it: the region is CLEAN in
#: base.png, so nothing is baked — it is composited live here, on the patek
#: row only, which is why it appeared the instant the owner switched to the
#: new Patek and was never on the ferrari.
#:
#: The letters keep their own applied relief, which was always doing the
#: work. Nothing else reads this flag, so the builder and its constants stay
#: put with their notes: this is one line, and it is reversible in one line.
APERTURE_ON = False
APERTURE_PAD_X = 30            # air between the type and the frame, each side
APERTURE_PAD_Y = 18            # ...and above/below. The binding one — see the
                               # 4.5px to the flange tops in the note above
# 5 -> 1, 2026-08-08: there is no lip any more (see the note in the
# builder). The value survives only as the inset between the sprite's edge
# and the recessed floor, which wants to be hairline now — the whole
# treatment is the floor and its wall.
APERTURE_FRAME_W = 1           # the hairline inset; the lip is retired
APERTURE_WALL_W = 3            # visible interior wall below the dial surface
APERTURE_RADIUS = 16           # a day window is a rounded rectangle
APERTURE_FLOOR_A = SNAIL_GROUND   # the wash — 44/255, 17.3% darker. Written
                                  # as that constant, not as 44, because the
                                  # two answer the SAME verify band and must
                                  # not drift apart
APERTURE_RIM = tuple((c + 255) // 2 for c in RES_METAL)      # the lit lip
APERTURE_UNDER = _THEME["steel_under"]     # the crack: ambient only, warm
APERTURE_FACE_TOP = tuple((a + b) // 2 for a, b in zip(RES_METAL, APERTURE_RIM))
APERTURE_FACE_BOT = tuple((a + b) // 2
                          for a, b in zip(RES_METAL, APERTURE_UNDER))
_APERTURE: dict = {}


#: How far the incision's dark end sits back up toward its lit one, and it
#: is a LEGIBILITY FLOOR wearing a taste's clothing. The pure swap (0.0) is
#: the physically honest incision and it was the first thing rendered here;
#: measured on it, the top three face rows of every stroke came out 4.21,
#: 4.34 and 4.39:1 against the window floor — three rows under the 4.5:1 the
#: brief sets, because STEEL_FACE_BOT and GOLD_FACE_BOT were chosen as the
#: SHADED FLANK of a letter standing ON the dial, where nothing was reading
#: them against a floor 17% down. A third of the way back clears it with
#: room — worst face row 5.74:1, mean 7.51:1 — and the face still falls from
#: luma 152.5 at the top of a stroke to 200.7 at its foot, monotonically,
#: every row, which is the read that says "cut".
ENGRAVE_LIFT = 1.0 / 3.0


def _engraved(relief):
    """The same metal, CUT INTO the dial instead of applied to it.

    The owner's own two cues — "darker floor, lit lower edge" — are the
    applied rendering read backwards, so this is a swap rather than a second
    palette: the face gradient inverts (a stroke's floor is dark at the top,
    where the dial overhangs it, and bright at its foot, where the overhead
    light reaches the far wall) and the relief pair swaps ends (top edge
    occluded, LOWER edge lit).

    NOTHING IS DIMMED, which is deliberate rather than lazy. GOLD_FACE_BOT
    measures 4.44:1 against this window's floor unmodified, so a letter
    darkened to say "sunk" would buy the engraving read with the one thing
    the brief will not trade. The inversion spends the contrast the applied
    version was putting into a highlight instead, and ENGRAVE_LIFT pays for
    the last three rows.
    """
    face_top, face_bot, rim, under = relief
    sunk = tuple(int(round(b + (t - b) * ENGRAVE_LIFT))
                 for b, t in zip(face_bot, face_top))
    return (sunk, face_top, under, rim)


def _aperture(w: int, h: int) -> "Image.Image":
    """The recessed window, baked once per size and pasted thereafter.

    COMPOSE-LOOP RULE 2 (the worked example is _AURA_EMBOSS above): every
    input here is a constant or a cached font metric, so this builds once
    per process and the frame loop pays a paste. It is drawn onto the
    wordmark's own layer, under the letters, so it turns to the talker with
    them — a window the words slide out of would be worse than no window.
    """
    got = _APERTURE.get((w, h))
    if got is not None:
        return got
    fw, wl = APERTURE_FRAME_W, APERTURE_WALL_W
    out = Image.new("L", (w, h), 0)
    ImageDraw.Draw(out).rounded_rectangle([0, 0, w - 1, h - 1],
                                          APERTURE_RADIUS, fill=255)
    inn = Image.new("L", (w, h), 0)
    ImageDraw.Draw(inn).rounded_rectangle(
        [fw, fw, w - 1 - fw, h - 1 - fw],
        max(1, APERTURE_RADIUS - fw), fill=255)
    spr = Image.new("RGBA", (w, h), (0, 0, 0, 0))
    # THE FLOOR IS A WASH, NOT A FILL. Black at alpha 44 leaves the dial
    # under it visible and a fixed 17.3% down — see the note above.
    spr.paste((0, 0, 0, APERTURE_FLOOR_A), (0, 0), inn)
    # The wall, lit backwards: the same shift-and-subtract the letters use
    # for their relief pair, with the two ends exchanged.
    dn = inn.transform(inn.size, Image.AFFINE, (1, 0, 0, 0, 1, -wl))
    up = inn.transform(inn.size, Image.AFFINE, (1, 0, 0, 0, 1, wl))
    spr.paste(APERTURE_UNDER + (255,), (0, 0), ImageChops.subtract(inn, dn))
    spr.paste(APERTURE_RIM + (255,), (0, 0), ImageChops.subtract(inn, up))
    # ── NO LIP, 2026-08-08: THE RECESS IS THE WHOLE TREATMENT ──────────
    # The band used to carry a gold face plus its own outer relief pair —
    # a drawn frame around the wordmark. The owner, twice: "the aura vision
    # framing is still gaudy, the rectangle is not pleasing look wise...
    # let's do more elegant/subtle", then "get rid of, again, that awkward
    # border around AURA VISION it does not look premium at all and worse
    # it overlaps with the sterling spawned AI tile."
    #
    # An aperture in a real dial is defined by LIGHT, not by an outline: a
    # chamfer catching the sky on one edge and shadow on the other, meeting
    # the dial with nothing but a change of value. So the frame is gone —
    # what remains is the floor wash and the wall's relief pair above, which
    # IS the recess. It also stops the treatment colliding with anything
    # beside it: no band, no footprint beyond the letters' own air.
    _APERTURE[(w, h)] = spr
    return spr


def _draw_wordmark_flat(frame: "Image.Image", now: float,
                        brand: bool = False) -> None:
    d = ImageDraw.Draw(frame)
    size = WORDMARK_BRAND_SIZE if brand else WORDMARK_SIZE
    track = WORDMARK_BRAND_TRACK if brand else WORDMARK_TRACK
    gap = WORDMARK_BRAND_GAP if brand else WORDMARK_GAP
    # Bold on the dial lasted one pass — see WORDMARK_BRAND_TRACK_K,
    # 2026-08-07: the light face is back on both variants, presence bought
    # with tracking instead of weight.
    f = face("text", size)
    # 2026-08-07, third pass on the weight: AURA GOES THINNER STILL. Owner,
    # third time today: "change AURA VISION so the AURA is more elegant,
    # perhaps not bold, it looks declasse." The regular face above was pass
    # two and did not go far enough — gold plus heavy is the exact read he
    # is naming; gold plus thin is Cartier. The device carries no Light cut
    # of Nimbus Sans, but the URW narrow face (the "label" role's own
    # primary, verified on the puck) has the thin stroke: measured on the
    # render its stem is 0.82 of the regular's. AURA ONLY — VISION stays
    # the regular face and is the yardstick (the A's stem must set no wider
    # than the V's). Sized up until the CAP HEIGHTS LEVEL (narrow runs ~4%
    # short at like size), and TRACKED so the word keeps its set width: the
    # gaps absorb exactly what the glyphs gave back, so every clearance
    # measured beside WORDMARK_BRAND_Y stands unmoved. Thin strokes, wide
    # tracking, the same footprint.
    fa_size = size
    fa = face("label", fa_size)
    while (fa.getbbox("AURA")[3] - fa.getbbox("AURA")[1]) < \
          (f.getbbox("AURA")[3] - f.getbbox("AURA")[1]):
        fa_size += 1
        fa = face("label", fa_size)
    track_a = track + (sum(d.textlength(c, font=f) for c in "AURA")
                       - sum(d.textlength(c, font=fa) for c in "AURA")) / 3.0
    a_w = track_len(d, "AURA", fa, track_a)
    v_w = track_len(d, "VISION", f, track)
    x = WORDMARK_XY[0] - (a_w + gap + v_w) / 2
    # CENTRE THE GROUP, NOT THE WORDMARK.
    #
    # WORDMARK_XY[1] was tuned by eye with the hint underneath it, so the
    # wordmark alone sat above centre and the PAIR sat below it — the hint
    # hangs HINT_DY (125px) down, and nothing accounted for that weight.
    # The owner: "AURA VISION and the line below is still skewed south...
    # it's designed for when 'just say hi' disappears. but it should both
    # disappear and the remaining AURAVISION should re-orient to be centre
    # mass on the screen."
    #
    # Exactly right, and it is two layouts rather than one offset. So the
    # block's own extent is measured and centred on the face, and when the
    # hint retires (the ceremony starts) the wordmark re-centres alone in
    # the same breath. Nothing is tuned by eye; both cases fall out of the
    # font metrics.
    # INK, NOT THE FONT BOX. Centring ascent+descent put the letters
    # visibly high: this is all-caps, so the descender space is empty and
    # half of it is counted as weight that is not there. getbbox measures
    # where the ink actually falls relative to the draw origin, which is
    # the only thing the eye is judging.
    # ── THE DOOR ONLY NEEDS ONE SIGN (2026-08-18) ────────────────────────
    # Owner: "it says 'just say hi aura to get started' twice, one time
    # within the circle and one time outside of it. get rid of the one in
    # the circle."
    #
    # He is right and this is the older of the two. HINT_TEXT under the
    # wordmark predates the lock hints entirely; when LOCK_HINT_BOT was
    # added below the circle yesterday it said the same sentence in better
    # words, and nobody retired the one it replaced. Two signs saying the
    # same thing read as a mistake even when each is well set, and it is
    # the reason the circle looked crowded.
    #
    # The condition was:
    #     (not brand) and LOCKED.exists() and not _ceremony_running(now)
    # and it is kept above rather than deleted because it encodes three
    # separate lessons about WHEN a sign on a door stops being true — see
    # the long note at the draw site. If the copy ever moves back inside
    # the circle, that is the gate it needs.
    #
    # This also re-centres the wordmark: _bot falls back to the wordmark's
    # own ink, which is what "center AURAVISION in the middle of the
    # circle" asked for and what the hint's descender was displacing.
    _hint_on = False
    _mt, _mb = f.getbbox("AURAVISION")[1], f.getbbox("AURAVISION")[3]
    if _hint_on:
        _hf = face_for(HINT_TEXT, "label", HINT_SIZE)
        _bot = HINT_DY + _hf.getbbox(HINT_TEXT)[3]
    else:
        _bot = _mb
    # The block runs from the wordmark's top ink to the lowest ink below it,
    # both measured from the same origin, so centring is one subtraction.
    #
    # The BRAND layout centres on WORDMARK_BRAND_Y instead of on the glass —
    # same subtraction, a different line to sit on. It is the ink's own
    # centre in both cases, which is why the clearances quoted beside that
    # constant are the ones that actually apply.
    mid = float(WORDMARK_BRAND_Y) if brand else SIZE / 2.0
    y = mid - (_mt + _bot) / 2.0
    # APPLIED, NOT PRINTED (amendment 2): three draws per word — a shadow it
    # stands on, the face, a bright top facet up-left — which is the
    # applied-numeral rendering draw_numerals' headstone keeps, at the
    # wordmark's own scale. The offset grows with the type so the facet
    # stays a facet at 66px and does not vanish at 36.
    # Amendment 3: AURA ONLY. VISION is blue light again (see VISION_LO)
    # and light casts no gold shadow, so it sets in a single flat draw.
    # 2026-08-07, third pass: THE BEVEL MOVES INSIDE THE STROKE. The
    # outward shadow+facet above added ~2*spec to every stem — measured on
    # the render, the A's stem hit 8px against the V's 4 at dial size, a
    # bold rebuilt out of offsets after the bold face itself was retired,
    # and exactly the heaviness the owner kept naming. A real applied
    # letter is bevelled INSIDE its own silhouette: the lit facet is the
    # up-left inner rim, the shade the down-right one, and the letter's
    # footprint is exactly the light face's own ink — so the gold does the
    # talking and the stem measures what the face measures.
    spec = max(1.5, size / 24.0)
    # THE WINDOW GOES DOWN FIRST, under the letters that stand in it — the
    # patek's dial only (note at APERTURE_ON). Its box is the type's own
    # extents plus the pads, so it moves with every size and tracking change
    # this file has made three times a day, rather than being a rectangle
    # somebody will forget to re-measure.
    _cut = brand and APERTURE_ON
    if _cut:
        _ax0 = int(round(x - APERTURE_PAD_X - APERTURE_FRAME_W))
        _ay0 = int(round(y + _mt - APERTURE_PAD_Y - APERTURE_FRAME_W))
        _ax1 = int(round(x + a_w + gap + v_w
                         + APERTURE_PAD_X + APERTURE_FRAME_W))
        _ay1 = int(round(y + _mb + APERTURE_PAD_Y + APERTURE_FRAME_W))
        frame.alpha_composite(_aperture(_ax1 - _ax0, _ay1 - _ay0),
                              (_ax0, _ay0))
    # Baseline pinned by ink bbox: the narrow face's caps sit a shade
    # differently on the em, and two words on two baselines reads broken.
    y_a = y + (f.getbbox("AURA")[3] - fa.getbbox("AURA")[3])
    # 2026-08-08, refile three (note at STEEL_RIM): BOTH words are applied
    # now. VISION's flat breathing draw stood here from amendment 3 until
    # today; it joins the emboss in its own blue-steel, and the breath
    # retires — a once-stamped sprite cannot change colour per frame, and
    # zero per-frame work was the brief. Same overhead light for both.
    for word, wf, wx, wy, wtrack, ink, relief in (
            ("AURA", fa, x, y_a, track_a, AURA_INK,
             (GOLD_FACE_TOP, GOLD_FACE_BOT, TOURB_GOLD_LIT, GOLD_UNDER)),
            ("VISION", f, x + a_w + gap, y, track, VISION_LO,
             (STEEL_FACE_TOP, STEEL_FACE_BOT, STEEL_RIM, STEEL_UNDER))):
        # Amendment 4 (note at GOLD_FACE_TOP): the light is OVERHEAD, so
        # the offsets go purely vertical — top edges take the bright rim,
        # lower edges the occlusion line. The diagonal (-o, -o) bevel
        # this replaces stands in the note. COMPOSE-LOOP RULE 2 (note at
        # _AURA_EMBOSS): the emboss is STATIC, so those draws are baked
        # once into a small sprite — re-embossing live cost a full-canvas
        # mask, two full-canvas shifts and three full-canvas colour
        # pastes EVERY FRAME, the ImagingFill2 the profiler caught
        # eating the touch budget. alpha_composite, not paste-with-
        # mask: the destination here is freshly erased glass, and OVER
        # onto transparent reproduces the sprite's own edge pixels
        # exactly, where a masked paste would square the edge alpha.
        # ...and in the window they are CUT, not applied — the same metal
        # read backwards, see _engraved.
        spr, sx, sy = _aura_embossed(d, word, wf, wtrack, ink, spec,
                                     wx, wy,
                                     _engraved(relief) if _cut else relief)
        frame.alpha_composite(spr, (sx, sy))
    # The hint travels with it — same call, same frame, after the same
    # rotate. See HINT_TEXT for why it is no longer baked.
    #
    # ONLY AT THE LOCKED DOOR. It is the sign ON the door — "just say hi
    # Aura to get started" — and once you are through it is an instruction
    # to do the thing you have already done. It followed the wordmark onto
    # the home face because both are drawn by this one call, and sat there
    # permanently after the unlock. The owner: "the home screen now retains
    # the JUST SAY HI AURA on it, where that should disappear."
    # AND NOT ONCE SHE HAS STARTED TALKING TO YOU.
    #
    # The whole ceremony happens AT the lock screen, so "just say hi Aura to
    # get started" sat under the wordmark through the entire enrolment —
    # while she was asking your name, while the carousel turned, while you
    # answered. The owner: "get rid of the JUST SAY HI AURA after we pass
    # that, in the enrollment it shouldn't keep having SAY HI AURA."
    #
    # It is the sign on a closed door. The moment she opens it, it is an
    # instruction to do the thing you have already done. Three signals mean
    # the ceremony is under way, and any of them retires the sign:
    # awaiting_name (she has asked), enroll.json (the ears are collecting),
    # enroll_cats (the carousel is up).
    if _hint_on:
        # face_for/draw_centred rather than face/track_text: this line is a
        # SENTENCE and is the next thing a translation pass will reach for.
        # Set through the Latin path it would come out unjoined and backwards
        # in Persian, or as notdef boxes in Han — a sign on the door that
        # nobody in the room can read. Latin renders identically to before.
        hf = face_for(HINT_TEXT, "label", HINT_SIZE)
        draw_centred(d, WORDMARK_XY[0], y + HINT_DY, HINT_TEXT, hf,
                     HINT_INK, HINT_TRACK)


def track_len(d: ImageDraw.ImageDraw, text: str,
              font: ImageFont.FreeTypeFont, track: float = 0.0) -> float:
    """Width of `text` set with `track` px of extra letter-spacing."""
    if not track:
        return d.textlength(text, font=font)
    return (sum(d.textlength(c, font=font) for c in text)
            + track * max(0, len(text) - 1))


def track_text(d: ImageDraw.ImageDraw, xy, text: str,
               font: ImageFont.FreeTypeFont, fill, track: float = 0.0) -> None:
    """Letter-spaced text. PIL has no tracking parameter, so a tracked run
    is drawn glyph by glyph — which also throws kerning away. That is only
    acceptable because every caller here is a short ALL-CAPS label, where
    the tracking dwarfs any kern pair anyway. Do not use it for prose."""
    if not track:
        d.text(xy, text, font=font, fill=fill)
        return
    x, y = xy
    for c in text:
        d.text((x, y), c, font=font, fill=fill)
        x += d.textlength(c, font=font) + track


#: ── Farsi ─────────────────────────────────────────────────────────────
#: The home face reads in Persian (owner, by voice, 2026-08-05: "translate
#: everything on the screen, my home screen, to Farsi"). Two rules arrive
#: with the script, and both are the opposite of how the rest of this file
#: sets type:
#:
#:  * NEVER TRACK IT. track_text sets a run glyph by glyph, which for Arabic
#:    script throws away the joining forms AND the right-to-left order — the
#:    word comes out as loose isolated letters, backwards. Persian is also
#:    simply not letter-spaced the way small caps are; the tracking that
#:    makes LOCK look composed makes قفل look broken.
#:  * The run must be SHAPED, which is libraqm's job inside Pillow. This
#:    machine has it; the puck is a different build, so its absence is
#:    checked once and SAID OUT LOUD rather than quietly shipping the
#:    backwards version, which would read as a font bug nobody could name
#:    (PRINCIPLES §1).
FA_DIGITS = str.maketrans("0123456789", "۰۱۲۳۴۵۶۷۸۹")
FA_AM, FA_PM = "ق.ظ", "ب.ظ"
_FA_RTL = None

#: The two wedges THIS file paints onto the ring — REQUESTS and PATIENTS —
#: are home-screen furniture exactly like the five home.html bakes, so they
#: read in the room's language with the rest of it. The five baked labels,
#: SLEEP, POWER and the $LEDGER caption are the other half of this change
#: and live in home.html.
#:
#: CHROME ONLY. The request sentence, the patient names and the percentages
#: are the ROOM'S words and a machine translation of them would be a
#: different sentence claiming to be the one somebody said. Labels are ours;
#: content is not.
#:
#: ── DUTCH, 2026-08-06 (owner, by voice: "change my entire home screen into
#: Dutch") ─────────────────────────────────────────────────────────────────
#: Persian before it, Mandarin before that; only these strings moved, which
#: is the point of the whole arrangement. Nothing above changes: the Arabic
#: shaping rules, the RTL check and the per-script sizing are all decided
#: from a string's own CODEPOINTS, so a Latin script simply takes the Latin
#: path again and the machinery for the other two stays intact for the next
#: time somebody asks.
#:
#: THE FA_ PREFIX IS NOW HISTORICAL and is kept on purpose:
#: tests/test_type_fitting.py substitutes these five names to re-run the
#: layout in Latin, Persian and Han, so renaming them would break the one
#: check that proves a translation still fits its wedges. The name says where
#: the slot came from; the value says what the room asked for last.
#:
#: ── TE REO MĀORI, 2026-08-06 (owner, by voice: "change the homepage to be a
#: New Zealand theme, and then all the text to be Māori") ──────────────────
#: Everything above stands; Dutch was simply the language before this one.
#: Māori is Latin script, so this is the same cheap path Dutch took — no
#: shaping, no RTL, no per-script font — and it costs one thing Dutch did
#: not: MACRONS. Ā Ē Ī Ō Ū are Latin Extended-A, and a face without them
#: draws a notdef box in the middle of a word rather than failing loudly
#: (PRINCIPLES §1). Checked in the fonts' own cmaps before writing these
#: strings rather than after someone photographed them: all five files the
#: Latin ramp can reach — Nimbus Sans Regular, Bold and NARROW (which is the
#: one "label" actually picks, so it is the one that matters) plus both
#: DejaVu fallbacks — carry all ten macron letters. Nothing here can fall
#: through to a box. A language needing a block outside Latin-1 gets the
#: same check FIRST; that is how "farsi" and "cjk" earned their own roles.
#:
#: The vowel length is not decoration: KĀORE and KAORE are different words,
#: so the macrons are part of the spelling and never dropped to fit a wedge.
#: Fitting is the fitter's job and it has room — the longest string here is
#: 20 characters against Dutch's 19.
#:
#: ── BACK TO ENGLISH, 2026-08-06 evening (owner, by voice: "I want the home
#: screen to be reverted back to English") ─────────────────────────────────
#: Everything above stands; te reo was simply the language before this one.
#: This is the one direction that costs NOTHING: English is Latin script and
#: Latin-1, so there is no shaping, no RTL, no CJK face, and not one of the
#: macrons the paragraph above had to check in five cmaps before writing.
#:
#: The trap the Dutch pass recorded — fitText() "ADDS a script class, never
#: removes one it did not put there", so seven elements in home.html had to
#: lose a hand-written class="fa" BY HAND — does not recur here: those seven
#: lost it in that pass and nothing has put one back since. A translation
#: INTO an RTL or CJK script still gets its class back automatically.
#:
#: The FA_ prefixes stay historical for the reason given above: they are
#: substituted BY NAME in tests/test_type_fitting.py to re-run this layout in
#: Latin, Persian and Han. Nothing about the per-script machinery is deleted
#: here, which is what keeps the next translation a string swap.
FA_REQUESTS = "REQUESTS"
FA_REQ_STATE = {"queued": "QUEUED", "working": "WORKING",
                "verifying": "VERIFYING", "deploying": "DEPLOYING",
                "done": "DONE", "failed": "FAILED"}
FA_SOMEONE = "SOMEONE"
FA_PATIENTS = "PATIENTS"
FA_CLINIC_CLEAR = "CLINIC CLEAR"
FA_NONE_LEFT = "NONE LEFT TODAY"
#: "{n} TO SEE TODAY" — how many are still to be seen. Latin digits, with the
#: clock above them; one face carrying two numbering systems reads as a bug
#: rather than as a decision, which is why the Persian pass moved them both
#: and why every pass since has left them Latin.
#:
#: ── NEITHER OF THESE TWO IS ON THE GLASS ANY MORE, 2026-08-06 evening ─────
#: The watch-complications pass put patients-remaining in an APERTURE — a
#: date window in a rose-gold frame, holding ONE NUMERAL — so the count is
#: now `str(total)` and neither this sentence nor FA_NONE_LEFT is set on the
#: wedge. See _pat_tile.
#:
#: SAY IT LOUDLY BECAUSE THE FAILURE MODE IS A SILENT ONE (§1): translating
#: either string now changes NOTHING on the dial, and a translator who edits
#: it and sees no difference will go looking for a broken cache. They are
#: kept, not deleted, for two reasons — tests/test_type_fitting.py substitutes
#: FA_TO_SEE by name to re-run this layout in three scripts, and if the words
#: ever come back beside the aperture this is the slot they come back into.
FA_TO_SEE = "{n} TO SEE TODAY"


def _fa_rtl() -> bool:
    """Can Pillow shape and reorder an RTL run? Asked once, logged once."""
    global _FA_RTL
    if _FA_RTL is None:
        try:
            from PIL import features
            _FA_RTL = bool(features.check("raqm"))
        except Exception:
            _FA_RTL = False
        if not _FA_RTL:
            print("font: Pillow has no libraqm — Farsi renders unshaped and "
                  "left to right on this device", flush=True)
    return _FA_RTL


def fa_len(d: ImageDraw.ImageDraw, text: str,
           font: ImageFont.FreeTypeFont) -> float:
    """Width of a Persian run, measured the way it will be drawn."""
    if _fa_rtl():
        return d.textlength(text, font=font, direction="rtl", language="fa")
    return d.textlength(text, font=font)


def fa_text(d: ImageDraw.ImageDraw, xy, text: str,
            font: ImageFont.FreeTypeFont, fill) -> None:
    """One shaped, right-to-left Persian run. No tracking — see above."""
    if _fa_rtl():
        d.text(xy, text, font=font, fill=fill, direction="rtl", language="fa")
    else:
        d.text(xy, text, font=font, fill=fill)


def fa_centred(d: ImageDraw.ImageDraw, cx: float, y: float, text: str,
               font: ImageFont.FreeTypeFont, fill,
               limit: float = 0.0) -> None:
    """A Persian row, centred on cx and trimmed to `limit` px if given.

    draw_tracked/_ellipsize cannot be reused here even at zero tracking:
    both set and MEASURE glyph by glyph, which for Arabic script is the
    unjoined, backwards version. So this is their Persian twin — measured
    with fa_len, set with fa_text, and trimmed with the same visible
    ellipsis, because a row that quietly stops mid-word is the silent half
    of PRINCIPLES §1.
    """
    if limit and fa_len(d, text, font) > limit:
        cut = text
        while cut and fa_len(d, cut.rstrip() + "…", font) > limit:
            cut = cut[:-1]
        text = (cut.rstrip() + "…") if cut.strip() else "…"
    fa_text(d, (cx - fa_len(d, text, font) / 2.0, y), text, font, fill)


# ── TYPE THAT FITS THE SPACE IT IS GIVEN ───────────────────────────────────
#
# Owner, 2026-08-05 night, looking at the puck: "we need to find a way for
# sterling to maximize the font without overstepping, there are some
# constraints like sleep / power but there is plenty of room for the wedges
# to expand the font size to make it more legible".
#
# WHY THIS IS NOT COSMETIC. This face now translates itself on a spoken
# request — it rendered whole in Mandarin and then in Farsi the same
# evening, correctly, down to the Persian numerals. But every size on it was
# chosen for LATIN CAPS. 休眠 at 13px is two glyphs of ten-plus strokes each
# in a box measured for five wide letterforms; SLEEP at 13px is fine. The
# translation was right and the typography was what failed, which is exactly
# the failure that looks like a bad translation.
#
# The rule below therefore has to hold for ANY string in ANY script, so that
# the same code which makes SETTINGS bigger makes 设置 legible. Three parts:
#
#   1. FIT BY MEASUREMENT. Ask the geometry how much room a row has, then
#      find the largest size whose SET WIDTH fits it. Nothing is a hardcoded
#      point size any more; a point size is only ever the design INTENT that
#      the fit starts from.
#   2. PER-ELEMENT CAPS. The wedge sectors have room to spare. The SLEEP and
#      POWER discs do not — the owner named them as the constraint rather
#      than the target — and the clock pill, the $LEDGER block and the tick
#      fan each have a different bound. There is no global multiplier here on
#      purpose; every call site states its own cap and says where it came
#      from.
#   3. PER-SCRIPT MINIMUMS. A size that is comfortable for Latin caps is not
#      comfortable for Han or for Arabic. The script is read off the string's
#      own CODEPOINTS — never off a language setting, which would be a second
#      detector in series with the thing it is describing (PRINCIPLES §7).
#
# ── WHERE THE RATIOS CAME FROM, honestly (PRINCIPLES §6) ───────────────────
#
# MEASURED, on this machine, 2026-08-06: rasterise a run of real labels at
# each size and take the 10th-percentile COUNTER — the white gap between two
# strokes on one scanline. That is the quantity that decides whether strokes
# merge into a blob, which is the actual complaint. The size at which each
# script first holds a 2px counter:
#
#     Nimbus Sans Narrow, "SLEEP SETTINGS BRIEFING"   14 px
#     DejaVu Sans Bold,   "خواب تنظیمات گزارش"        25 px
#     Noto Sans CJK,      "休眠 设置 简报 电源"          29 px
#
# i.e. ratios of 1.79 (Arabic) and 2.07 (CJK) against Latin. That is a
# WORST-CASE metric — one pinched joint in one glyph moves it — and taking it
# literally would set 设置 at 35px in a slot where SETTINGS sits at 17. So it
# is not what is used.
#
# CHOSEN BY EYE, and stated as a choice rather than dressed as a measurement:
# 1.45 for CJK and 1.30 for Arabic, which is the range the typographic
# convention gives and sits well below what the counter measurement argues
# for. The measurement's contribution is the SHAPE of the answer — CJK worse
# than Arabic, both much worse than Latin, and worst at small sizes — not the
# number. NOT YET SEEN ON THE PANEL at the owner's angle; luminance has been
# wrong twice off-axis (PUCK-STANDALONE §12.2) and optical weight will be
# too. If he says it is still tight, move these two numbers and nothing else.
#
# The FLOORS are absolute rather than relative, for the case the ratio cannot
# reach: 12px of Latin is small but readable, 16px of Arabic and 18px of Han
# are the smallest either has any business being on a panel seen from a shelf.
# latin 12 -> 14.4 (+20%), 2026-08-07: the owner, at arm's length, on the
# baked tile labels — the fitter passes, so the FLOOR was low, not the
# solver wrong. home.html's SCRIPT_FLOOR moves in the same commit, as the
# two halves of this policy always do.
SCRIPT_RATIO = {"latin": 1.0, "arabic": 1.30, "cjk": 1.45}
SCRIPT_FLOOR = {"latin": 14.4, "arabic": 16, "cjk": 18}

#: Han, kana, Hangul, and the full-width/CJK punctuation that travels with
#: them. Hangul and kana are in here because they share the problem (dense
#: features in a square em) even though the owner asked about Mandarin.
_CJK_RANGES = ((0x2E80, 0x2FFF), (0x3000, 0x303F), (0x3040, 0x30FF),
               (0x3190, 0x319F), (0x31F0, 0x31FF), (0x3400, 0x4DBF),
               (0x4E00, 0x9FFF), (0xA000, 0xA4CF), (0xAC00, 0xD7AF),
               (0xF900, 0xFAFF), (0xFE30, 0xFE4F), (0xFF00, 0xFFEF))
#: Arabic script, which is what Persian is written in. The DIGITS are
#: deliberately excluded below: ۰۹:۳۰ is four simple shapes and sizing a
#: whole row up because a clock time is in it would be the tail wagging.
_ARABIC_RANGES = ((0x0600, 0x06FF), (0x0750, 0x077F), (0x08A0, 0x08FF),
                  (0xFB50, 0xFDFF), (0xFE70, 0xFEFF))
_ARABIC_DIGITS = ((0x0660, 0x0669), (0x06F0, 0x06F9))


def _in_ranges(cp: int, ranges) -> bool:
    return any(a <= cp <= b for a, b in ranges)


def script_of(text: str) -> str:
    """'cjk' | 'arabic' | 'latin', decided from the CODEPOINTS.

    From the string and not from a language flag on purpose. The face gets
    translated a piece at a time — the wedge labels are Persian while a
    patient's name beside them is still Latin — so "what language is the
    puck in" is not a question any single row can be sized by.

    A MIXED ROW IS SIZED FOR ITS HEAVIEST SCRIPT — one Han character in a
    row of Latin returns 'cjk', not a majority vote. That asymmetry is
    deliberate (PRINCIPLES §8): setting a Latin word at the CJK size makes
    it slightly large, which nobody has ever reported. Setting a Han word at
    the Latin size makes it unreadable, which is the bug this whole block
    exists to fix. A majority vote would size "设置 SETTINGS" for the eight
    Latin letters and leave the two glyphs somebody actually needed to read
    as a blot.

    Arabic-Indic DIGITS do not count as Arabic. ۰۹:۳۰ is four simple shapes,
    and a clock time sitting beside a patient's Latin name must not drag the
    whole row up to the Arabic size.
    """
    n_ar = 0
    for ch in text:
        cp = ord(ch)
        if _in_ranges(cp, _CJK_RANGES):
            return "cjk"
        if _in_ranges(cp, _ARABIC_RANGES) and not _in_ranges(cp,
                                                             _ARABIC_DIGITS):
            n_ar += 1
    return "arabic" if n_ar else "latin"


def face_for(text: str, role: str, size: int) -> ImageFont.FreeTypeFont:
    """The ramp face for `role` — unless the string is in a script the ramp
    cannot set, in which case the script wins.

    The URW base35 ramp is a Latin family and carries neither Arabic nor
    Han; asking it for either returns zero-width notdefs, which paints an
    EMPTY label rather than a wrong one. An empty label is indistinguishable
    from a deploy that never landed (PRINCIPLES §1), so this is the one place
    a caller's stated role is overruled.
    """
    sc = script_of(text)
    if sc == "cjk":
        return face("cjk", size)
    if sc == "arabic":
        return face("farsi", size)
    return face(role, size)


def text_w(d: ImageDraw.ImageDraw, text: str, font: ImageFont.FreeTypeFont,
           track: float = 0.0) -> float:
    """Set width, MEASURED THE WAY IT WILL BE DRAWN.

    Arabic goes through fa_len, which measures the shaped right-to-left run;
    measuring it any other way gives the width of the unjoined, backwards
    version, which is both wrong and wrong in the flattering direction.
    """
    if script_of(text) == "arabic":
        return fa_len(d, text, font)
    return track_len(d, text, font, track)


def draw_centred(d: ImageDraw.ImageDraw, cx: float, y: float, text: str,
                 font: ImageFont.FreeTypeFont, fill, track: float = 0.0,
                 limit: float = 0.0) -> None:
    """One centred row in whatever script it happens to be in.

    Arabic must be shaped and must NEVER be tracked (see the Farsi block);
    Han must not be tracked either — a letter-spaced 简报 reads as two
    unrelated words. Latin keeps the tracking its caller asked for, because
    that is most of what makes small caps look composed rather than loud.
    """
    sc = script_of(text)
    if sc == "arabic":
        fa_centred(d, cx, y, text, font, fill, limit)
        return
    if sc == "cjk":
        track = 0.0
    if limit:
        text = _ellipsize(d, text, font, limit, track)
    draw_tracked(d, cx, y, text, font, fill, track)


#: ── MICRO-TYPOGRAPHY, 2026-08-08 (premium pass) ───────────────────────────
#: Owner: "even the smaller font like RESERVE, and the time in the moonphase,
#: and the volume complication, those fonts are hard to read but also need
#: the extra love and care refinement of looking 3d as well." LEGIBLE FIRST,
#: THEN JEWELED, in that order: every small caption clears a 4.5:1 WCAG
#: floor against the ground IT SITS ON (pocket floors are darker than the
#: open dial — measured there), and then takes the MICRO relief: a single
#: hairline lit top edge and a hint of under-shadow, from the same
#: upper-left sky as every raised mark on this dial. NO face gradient — at
#: 10–13px a gradient eats the counters, which is why this is not
#: _aura_embossed pointed at a caption. Captions are STEEL family; gold
#: keeps its existing accents only (the F/E letters get the same pair in
#: gold at draw_gold_strikes, the $LEDGER caption already had it).
#: Tiles are cached by (text, font, ink), so the frame loop pays one small
#: paste per caption and the rendering happens once per distinct string
#: (compose rule 2 — "all baked"). The dict is bounded because names are
#: open-ended; a clear costs one re-render of whatever is on screen.
_MICRO_TILES: dict = {}
MICRO_UNDER_A = 150                # the "hint" — full black would be a hole
MICRO_LIT = (240, 246, 255, 235)   # BTN_LABEL_LIT's steel (retired with the
#                                    button labels, 2026-08-08) — one family


def draw_micro(target, cx: float, y: float, text: str, font, body,
               track: float = 0.0, limit: float = 0.0, lit=None) -> None:
    """A centred micro-caption with the applied relief pair, from a cache.

    Same (cx, y=top) semantics as draw_centred so call sites swap 1:1, but
    takes the IMAGE rather than its Draw — the pair is edge masks, and edge
    masks need compositing, not strokes. Occlusion first, lit rim LAST: at
    these sizes the two edge masks overlap on thin bars and whichever
    pastes last owns them — lit-last is what reads raised (the $LEDGER
    caption's measured order).
    """
    probe = ImageDraw.Draw(_MICRO_TILES.setdefault(
        "_probe", Image.new("L", (1, 1))))
    if limit and script_of(text) != "arabic":
        text = _ellipsize(probe, text, font, limit, track)
    key = (text, id(font), tuple(body), track, lit)
    tile = _MICRO_TILES.get(key)
    if tile is None:
        if len(_MICRO_TILES) > 64:
            _MICRO_TILES.clear()
        pad = 2
        w = int(math.ceil(text_w(probe, text, font, track))) + 2 * pad
        bb = font.getbbox(text)
        h = int(math.ceil(bb[3])) + 2 * pad + 1
        m = Image.new("L", (w, h), 0)
        draw_centred(ImageDraw.Draw(m), w / 2.0, pad, text, font, 255,
                     track, limit)
        # The pair, derived from the caption's own ink: the mask shifted
        # down-right, minus/versus itself — on-glyph top-left rows for the
        # lit rim, off-glyph lower-right rows for the shadow it throws.
        # (pad keeps the ink off the tile edge, so offset()'s wrap is air.)
        off = ImageChops.offset(m, 1, 1)
        b4 = tuple(body[:4]) if len(body) > 3 else tuple(body[:3]) + (255,)
        l4 = tuple(lit) if lit else MICRO_LIT
        tile = Image.new("RGBA", (w, h), (0, 0, 0, 0))
        for mask, ink in ((m, b4),
                          (ImageChops.subtract(off, m),
                           (0, 0, 0, MICRO_UNDER_A)),
                          (ImageChops.subtract(m, off), l4)):
            lay = Image.new("RGBA", (w, h), ink[:3] + (0,))
            lay.putalpha(mask.point(lambda v, a=ink[3]: v * a // 255))
            tile.alpha_composite(lay)
        _MICRO_TILES[key] = tile
    target.paste(tile, (int(round(cx - tile.width / 2.0)),
                        int(round(y - 2))), tile)


#: Air either side of a row, inside whatever box it was given. 9px is the
#: value _req_tile arrived at by eye against the sector's own border and is
#: kept as the house default so one number governs every fitted row.
FIT_MARGIN = 9.0
#: Below this nothing on a panel seen from a shelf is readable in any script,
#: so the search stops and the caller's ellipsis takes over. It is the point
#: at which "make it fit" stops being a service.
FIT_ABS_MIN = 10
_LAST_LAYOUT: dict = {}
_FIT_CACHE: dict = {}
_FIT_SQUEEZED: set = set()


def fit_size(d: ImageDraw.ImageDraw, text: str, role: str, box_w: float,
             box_h: float = 0.0, *, want: int, cap: int,
             track: float = 0.0, margin: float = FIT_MARGIN,
             who: str = "", quiet: bool = False) -> int:
    """The LARGEST size at which `text` fits `box_w` × `box_h`, capped.

        want   the size the design intends FOR LATIN. Only the per-script
               floor is derived from it — it is an intent, not a ceiling.
        cap    the real constraint on this element, in display px. Every
               call site states its own and says where it came from; there
               is deliberately no global multiplier (owner: sleep/power are
               a constraint, the wedges are not).
        box_w  the room the row actually has, MEASURED from the geometry
               rather than assumed. For an annulus sector that is
               sector_span(); for a disc or a pill it is the chord.
        box_h  optional; 0 means the height is not a binding constraint.

    Walks DOWN from the cap rather than up from the intent, so the answer is
    "the biggest that fits" and not "the intent, nudged". Cached on the
    inputs: this is only paid when a tile is rebuilt, but the tiles rebuild
    on every state change and the face has 12fps to spend on a Jetson.

    THE PER-SCRIPT FLOOR IS A TARGET, NOT A WALL, and that was a real bug on
    the way here: charging the Persian clock its 1.30 made the floor 31px in
    a pill that measures 142x31, so the fit "succeeded" at 31 and the time
    came out ellipsised — a clock reading ۱۰:۰… is worse in every way than a
    clock two points smaller. So a size that does not fit is not returned;
    the search continues below the floor, and MISSING the floor is said out
    loud, once per element and script. An element that cannot carry its
    script at a comfortable size is a design fact somebody needs (the answer
    is usually a bigger box, or fewer words in the label), and the one thing
    it must not be is a silent shrink (PRINCIPLES §1).

    The growth itself comes from `cap`, which callers build with
    script_size(): a Han label starts its search at 1.45x where the Latin one
    starts at 1.0x, so the translated label grows even where the Latin one
    never needed to.
    """
    sc = script_of(text)
    floor = max(SCRIPT_FLOOR[sc], int(round(want * SCRIPT_RATIO[sc])))
    key = (text, role, sc, round(box_w, 1), round(box_h, 1), want, cap,
           round(track, 2), round(margin, 1))
    got = _FIT_CACHE.get(key)
    if got is not None:
        return got
    avail_w = box_w - 2.0 * margin
    avail_h = (box_h - 2.0) if box_h else 0.0
    def fits(s: int) -> bool:
        f = face_for(text, role, s)
        if text_w(d, text, f, track) > avail_w:
            return False
        if not avail_h:
            return True
        bb = f.getbbox(text)
        return (bb[3] - bb[1]) <= avail_h

    size = max(int(cap), FIT_ABS_MIN)
    while size > FIT_ABS_MIN and not fits(size):
        size -= 1
    if size < floor and not quiet:
        tag = (who or role, sc)
        if tag not in _FIT_SQUEEZED and text.strip():
            _FIT_SQUEEZED.add(tag)
            print(f"type: {who or role!r} cannot give {sc} its {floor}px "
                  f"in {box_w:.0f}x{box_h:.0f} — set at {size}px "
                  f"({text[:24]!r})", flush=True)
    if len(_FIT_CACHE) > 512:               # unbounded only if text is
        _FIT_CACHE.clear()                  # unbounded; it is not
    _FIT_CACHE[key] = size
    return size


#: ── THE LIVE PANELS ARE NOT CIRCULAR SECTORS, 2026-08-07 ─────────────────
#:
#: Owner, by voice at the puck, granting the liberty in those words: the
#: panels "do not have to be circular sectors ... they can be shaped along
#: the straight line hexagonal structure that encloses them", and "we do not
#: expand to the edge of the diagonal" — the content stopped well short of
#: where the glass actually is.
#:
#: WHY IT BUYS ANYTHING. Text is rectangular and an arc wastes the outer
#: corner of every row. MEASURED on the live sector (-137..-103), straight
#: outer edge against the arc at WEDGE_R1, in px of row width:
#:
#:      y=204   130 -> 240      y=222   160 -> 262
#:      y=216   150 -> 254      y=228   168 -> 260
#:
#: which is exactly where the starved rows in tests/test_type_fitting.py
#: were losing their floor. Below y≈270 the two are identical: down there
#: the INNER edge (WEDGE_R0) is the constraint and nothing here touches it.
#:
#: THE EDGE IS THE BEZEL'S OWN OPENING, less PANEL_CLEAR of dark. Same
#: octagon _bezel_mask cuts the aperture with (BEZ_OUT - BEZ_BAND), so no
#: part of the bezel — band, inner bevel, or the hour batons applied to it —
#: can be inside it at any bearing, by construction rather than by a
#: clearance somebody measured once. This sector straddles the mitre at
#: -114.4°, so it gets TWO straight edges meeting at that corner instead of
#: one; both are the octagon's own lines, which is what the liberty asked
#: for.
#:
#: THE PANEL TURNS WITH THE OCTAGON. Both are painted BEFORE the dial
#: rotate — the panel because it belongs to the ring, the bezel because
#: draw_bezel_state lights metal baked into base.png — so an edge aligned to
#: a flat stays aligned at every rot.deg. If either ever moves to the other
#: side of that rotate, this alignment is the first thing that breaks.
PANEL_CLEAR = 6.0
_SPAN_CACHE: dict = {}


def _opening_stand(k: int) -> float:
    """How far flat k of the bezel's INNER OPENING stands from the centre,
    in display px. Read at call time because the bezel's constants are
    declared with the bezel, a long way below this."""
    return (BEZ_OUT_VB - BEZ_BAND_VB[k % 2]) * BEZ_VB


def _in_opening(dx: float, dy: float, clear: float = PANEL_CLEAR) -> bool:
    """Is the offset (dx, dy) from the centre inside that opening?"""
    for k in range(8):
        a = k * math.pi / 4.0
        if dx * math.cos(a) + dy * math.sin(a) > _opening_stand(k) - clear:
            return False
    return True


def _opening_r(deg: float, clear: float = PANEL_CLEAR) -> float:
    """The same eight lines, solved for a radius at bearing `deg` instead of
    tested — for drawing the edge and for sizing what has to cover it."""
    th = math.radians(deg)
    r = float(SIZE)
    for k in range(8):
        c = math.cos(th - k * math.pi / 4.0)
        if c > 1e-6:
            r = min(r, (_opening_stand(k) - clear) / c)
    return r


def sector_span(y: float, a0: float, a1: float, r0: float, r1: float,
                flat: bool = False):
    """[x0, x1] of an annulus sector at row y, in face coordinates, or None.

    The generalisation of _req_span, which was written for the one sector
    that needed it and is now the thing every fitted row is measured
    against. Measured rather than derived for the reason that function
    states: a diagonal annulus slice is a different width at every height
    and the arithmetic for it is three cases.

    `flat` replaces the outer arc at r1 with the bezel's straight-edged
    opening, which is what the two live panels are cut to (PANEL_CLEAR).

    CACHED ON ITS ARGUMENTS, since floors-first added passes: a block that
    starves now re-lays itself up to four more times looking for the growth
    it can afford, and every pass asks the same sector about the same rows.
    The sampler is 540 hypots and — flat — eight dot products each, which is
    cheap once and not cheap seven times over on a Jetson at 12fps.
    """
    key = (round(y, 1), a0, a1, r0, r1, flat)
    got = _SPAN_CACHE.get(key)
    if got is not None:
        return got[0]
    lo = hi = None
    cx = cy = SIZE / 2.0
    for x in range(0, SIZE, 2):
        dx, dy = x - cx, y - cy
        r = math.hypot(dx, dy)
        if r < r0:
            continue
        if not (_in_opening(dx, dy) if flat else r <= r1):
            continue
        if not (a0 <= math.degrees(math.atan2(dy, dx)) <= a1):
            continue
        lo = x if lo is None else lo
        hi = x
    out = (lo, hi) if lo is not None else None
    if len(_SPAN_CACHE) > 4096:             # bounded only if y is; it is not
        _SPAN_CACHE.clear()
    _SPAN_CACHE[key] = (out,)               # None is an answer, not a miss
    return out


def span_across(y: float, h: float, a0: float, a1: float, r0: float,
                r1: float, fallback, flat: bool = False):
    """The room a row of height `h` starting at `y` gets — the INTERSECTION
    of the sector across the row's whole height, never a single sample at
    its middle.

    Both edges of a sector are radial lines, so a row is narrower at its top
    on one side and at its bottom on the other; sampling the middle let
    cap-height glyphs poke through the border (PUCK-SHOW, 2026-08-05).
    """
    got = [sector_span(y + h * f, a0, a1, r0, r1, flat)
           for f in (0.15, 0.5, 0.95)]
    got = [g for g in got if g]
    if not got:
        return fallback
    lo, hi = max(g[0] for g in got), min(g[1] for g in got)
    return (lo, hi) if hi - lo > 40 else fallback


#: Leading, as a multiple of the set size.
#:
#: NOT A NEW GUESS. REQ_ROW_Y — (104, 130, 154, 179, 200) — was MEASURED
#: against the sector and is the one layout on this face nobody should
#: re-derive by eye. Stacking the same five rows at their old Latin sizes
#: (18, 20, 20, 14) with a 1.35 factor reproduces it as (104, 128, 155, 182,
#: 201): within 3px on every row. That agreement is the evidence that the
#: stacking below is the measured layout expressed as a rule, rather than a
#: replacement for it — and it is why the rows can now be allowed to GROW
#: without anybody re-measuring where they sit.
ROW_LEADING = 1.35
#: The floor under that leading, in px of clear air between one row's
#: measured ink and the next row's. Found by rendering the Mandarin face —
#: see the note at the bottom of layout_rows.once().
ROW_GAP_MIN = 4
#: A ceiling on any single row inside a ring sector. The sector's usable y
#: extent is ~234px and five stacked rows at 40px need 270, so this can
#: never bind before the block's own budget does; it is here so that a
#: one-word row landing on the widest part of a sector cannot turn into a
#: headline.
WEDGE_ROW_CAP = 40


def layout_rows(d: ImageDraw.ImageDraw, rows, top: float, bottom: float,
                sector, who: str = "", leading: float = ROW_LEADING,
                fallback=(285.0, 366.0), quiet: bool = False):
    """Lay a stack of rows down a sector, each fitted to the room IT gets.

        rows    (text, role, want, cap, track) per row, in order. An empty
                text still consumes its slot — a blank line in the middle of
                a list is information ("no patient at 11:00"), and letting
                the rows below it slide up would rewrite the list.
        top     where the first row's ink starts.
        bottom  the last row's ink may not pass this. Overflow squeezes the
                WHOLE block rather than clipping the last row: five rows in
                four sizes reads as a bug, and a row that runs off the
                bottom of a wedge is the silent kind of wrong.

    Two passes per row, and the second one is the point: an annulus slice is
    a different width at every height, so the span a row gets depends on how
    tall the row is, which is what we are solving for. Pass one asks with the
    intended height, pass two re-asks with the height that came back.

    THE LEADING GIVES WAY BEFORE THE TYPE DOES, and the squeeze is staged in
    that order for a reason found by rendering: squeezing both at once let a
    grown percentage row take its size out of the REQUEST SENTENCE, which had
    been given a growth allowance of exactly 1.0 precisely so it could never
    lose words. Air between rows is cheap; a word off the end of the one row
    that carries meaning is not.
    """
    # (a0, a1, r0, r1) or (a0, a1, r0, r1, flat). `flat` swaps the outer arc
    # for the bezel's straight opening — see PANEL_CLEAR. r1 is unused while
    # it is set, and stays in the tuple so a sector is one shape everywhere.
    a0, a1, r0, r1 = sector[:4]
    flat = bool(sector[4:]) and bool(sector[4])

    def once(lead_k: float, cap_k: float = 1.0):
        # 1.08 is where consecutive rows' ink starts to touch at CJK's
        # near-full-em height, so the leading stops giving there.
        lead = max(1.08, leading * lead_k)
        out, y, ink_bottom = [], float(top), float(top)
        short = False
        for (txt, role, want, cap, track) in rows:
            # THE SQUEEZE TAKES BACK GROWTH, NEVER THE BASE. `natural` is
            # what this row's script needs to match `want` in Latin, and no
            # amount of overflow may push a row under it — a squeeze that
            # can undercut the base size would undo, one row at a time,
            # exactly the thing this whole change exists to do. Rendered
            # proof this is needed: in Mandarin the wedge's own name grew to
            # 30px and the block overran, and the squeeze paid for it out of
            # the ENGLISH request sentence, which had an allowance of 1.0
            # precisely so it could never lose a word.
            natural = script_size(txt or "x", want)
            slot = natural
            if not txt:
                out.append(None)
                y += round(slot * lead)
                continue
            ceiling = max(natural, int(round(cap * cap_k)))
            size = slot
            for _ in range(2):
                sp = span_across(y, size, a0, a1, r0, r1, fallback, flat)
                size = fit_size(d, txt, role, sp[1] - sp[0], want=want,
                                cap=ceiling, track=track, who=who,
                                quiet=True)
            # TWO PASSES CAN STILL LAND ON A SIZE THE ROW NO LONGER HAS THE
            # ROOM FOR: the span depends on the row's height, so pass two's
            # answer is measured against pass one's span. Take the SMALLER
            # of the two answers and re-measure at it — a shorter row can
            # only be given more room, so that direction always converges.
            # Straight edges are what made this visible (PANEL_CLEAR): the
            # panel's width changes fast either side of the mitre, and a
            # 79px row was being set in 76px of span.
            sp = span_across(y, size, a0, a1, r0, r1, fallback, flat)
            size = min(size, fit_size(d, txt, role, sp[1] - sp[0], want=want,
                                      cap=ceiling, track=track, who=who,
                                      quiet=True))
            short = short or size < natural
            sp = span_across(y, size, a0, a1, r0, r1, fallback, flat)
            cx = (sp[0] + sp[1]) / 2.0
            out.append({"text": txt, "size": size, "y": y, "cx": cx,
                        "track": track, "span": sp,
                        "font": face_for(txt, role, size),
                        "limit": 2.0 * max(0.0, min(cx - sp[0], sp[1] - cx)
                                           - FIT_MARGIN)})
            # THE GAP IS MEASURED, NOT DERIVED FROM THE SIZE. A leading of
            # size x 1.35 assumes the ink starts at y, which is true for
            # Latin caps and false for Han: Noto CJK's ascent is tall, so a
            # 30px 请求 draws its ink from y+9 to y+39 and the next row —
            # placed at y+32 by the multiplier — landed ON it. Rendered, in
            # Mandarin, 7px of overlap. So the next row starts at whichever
            # is lower: the leading, or this row's own measured ink bottom
            # plus ROW_GAP_MIN.
            bb = out[-1]["font"].getbbox(txt)
            ink_bottom = y + bb[3]
            y = max(y + round(size * lead), ink_bottom + ROW_GAP_MIN)
        return out, ink_bottom, short

    # ── FLOORS FIRST, THE SURPLUS AFTERWARDS (2026-08-07) ─────────────────
    #
    # NO ROW MAY EXCEED ITS FLOOR WHILE ANOTHER ROW IN THE SAME BLOCK IS
    # UNDER ITS OWN. Owner, by voice, with the measurement in hand: the
    # Mandarin clinic wedge came out 33/13/13/13/20 against floors of
    # 18/18/18/18/14 — the heading 15px OVER its floor and the three rows
    # under it 15px SHORT of theirs. The room existed; the allocator was
    # handing all of it to the row that asked first, because every row's
    # ceiling was its own grow allowance and nothing looked at the block.
    #
    # So the grow allowances are given back in steps, and only as far as the
    # starvation goes: full growth first, and if any row is under its floor,
    # 0.75 of the surplus, then 0.5, 0.25, and finally none at all — where
    # every ceiling is the row's own floor and the rule above holds by
    # construction. It stops at the FIRST step that feeds everybody, so a
    # block with room to spare keeps its hierarchy and only a block that is
    # actually short flattens.
    #
    # It costs nothing: fit_size is cached on its inputs, so the extra
    # passes re-measure almost nothing, and they run only when a row is
    # already starving.
    grow = 1.0
    got, end, short = once(1.0)
    if short:
        for grow in (0.75, 0.5, 0.25, 0.0):
            got, end, short = once(1.0, grow)
            if not short:
                break
    if bottom > top and end > bottom:
        # STAGE ONE: take it out of the leading only.
        got, end, short = once((bottom - top) / max(1.0, end - top), grow)
    if bottom > top and end > bottom:
        # STAGE TWO: the leading has given all it has, so the type goes.
        # Floored: below ~0.6 the answer is that this content does not
        # belong in this sector, and shrinking further only hides that.
        # min(grow, ...) so a squeeze can never hand back growth the pass
        # above took away to feed a starved row.
        got, end, short = once(
            0.0, min(grow, max(0.60, (bottom - top) / max(1.0, end - top))))
        if end > bottom + 4.0 and who not in _FIT_SQUEEZED and not quiet:
            # The per-script floors are floors — a squeeze cannot go under
            # them, so this block genuinely does not fit and SAYS SO. It is
            # the only outcome here nobody can see on the glass: the last
            # row simply runs into the narrow end of the sector and gets
            # ellipsised, which looks like a long word (PRINCIPLES §1).
            _FIT_SQUEEZED.add(who)
            print(f"type: {who!r} overruns its sector by "
                  f"{end - bottom:.0f}px even squeezed — the floors for "
                  f"this script do not fit five rows here", flush=True)
    if not quiet:
        # ── THE SETTLED BLOCK IS WHAT GETS REPORTED (2026-08-07) ──────────
        #
        # fit_size says "cannot give X its floor" the first time it is
        # ASKED, and it is cached, so the FIRST ask wins. The floors-first
        # search above asks with several allowances and throws most of them
        # away — so left alone, that line describes a layout nobody will
        # ever see: it announced the clinic list starving at 17px in a pass
        # whose 20px answer is what actually shipped. A log that cries wolf
        # is worse than no log (§4, §5), so every fit inside layout_rows is
        # quiet and the BLOCK reports its own settled rows here instead.
        # Still once per block, still out loud — a row under its floor is a
        # design fact somebody needs, and the one thing it must not be is
        # invisible (§1).
        under = [(r["text"], r["size"], script_size(t, w))
                 for r, (t, _rl, w, _c, _tk) in zip(got, rows)
                 if r and r["size"] < script_size(t, w)]
        if under and (who, "floor") not in _FIT_SQUEEZED:
            _FIT_SQUEEZED.add((who, "floor"))
            print(f"type: {who!r} settles {len(under)} row(s) under their "
                  f"floor: " + ", ".join(f"{t[:14]!r} {s}px of {f}"
                                         for t, s, f in under), flush=True)
    if who and not quiet:
        # The last layout each named block produced, kept for inspection.
        # tests/test_type_fitting.py asserts against it rather than
        # re-declaring the call sites' arguments, which would be a second
        # copy of the policy and would drift from the first.
        _LAST_LAYOUT[who] = got
    return got


def _share_centre(a, b) -> None:
    """Give two rows one centre and re-derive both limits from it.

    A sentence broken over two lines that also steps sideways reads as a
    typesetting mistake. Every other row stays on the sector's own midpoint
    at its own row, which is what lets a diagonal wedge use its full width;
    these two give that up on purpose. The limits have to be recomputed FROM
    the shared centre — a row nudged off its own midpoint has less to play
    with on one side, and taking half the span width would let it overhang.
    """
    if not (a and b):
        return
    cx = (a["span"][0] + a["span"][1] + b["span"][0] + b["span"][1]) / 4.0
    for r in (a, b):
        sp = r["span"]
        r["cx"] = cx
        r["limit"] = 2.0 * max(0.0, min(cx - sp[0], sp[1] - cx) - FIT_MARGIN)


def script_size(text: str, want: int, grow: float = 1.0) -> int:
    """The size this row's script needs to match `want` in Latin, times an
    allowance for how much it may grow beyond that.

    `grow` is where a caller says how much of the room it is allowed to
    take. It is NOT a global multiplier — every call site picks its own and
    says why, because the hierarchy between rows is what makes a wedge read
    as one object rather than five unrelated words.
    """
    sc = script_of(text)
    #: ── 2026-08-12: THIS SAID `-> int` AND RETURNED 14.4 ──────────────────
    #: SCRIPT_FLOOR's latin entry is a FLOAT (14.4), so `max(14.4, 14)` is
    #: 14.4 and every latin caller asking for want<=14 at grow=1.0 got a
    #: float out of a function annotated int. Harmless here, fatal two calls
    #: later: the pucks run Pillow 9.0.1, which raises TypeError on a float
    #: font size. It killed the whole live STERLING wedge overlay on the
    #: chopard puck — `sterling: wedge overlay failed ... no face at all for
    #: role 'label'`, a message that blames the fonts for an arithmetic bug.
    #: CEIL, not round: 14.4 is a FLOOR and 14 is under it.
    return max(int(math.ceil(SCRIPT_FLOOR[sc])),
               int(round(want * SCRIPT_RATIO[sc] * grow)))


def draw_rows(d: ImageDraw.ImageDraw, laid, inks) -> None:
    """Paint what layout_rows worked out. Split from it so the layout can be
    asserted in a test without a canvas to paint on."""
    for row, ink in zip(laid, inks):
        if row:
            draw_centred(d, row["cx"], row["y"], row["text"], row["font"],
                         ink, row["track"], row["limit"])


def disc_chord(r: float, dy: float, floor_w: float = 0.0) -> float:
    """Full width of a circle of radius r at `dy` from its centre.

    The SLEEP and POWER labels sit in discs, not sectors, so their bound is
    a chord rather than a span — and it collapses fast near the rim, which
    is precisely why the owner named those two as the constraint.
    """
    if abs(dy) >= r:
        return floor_w
    return max(floor_w, 2.0 * math.sqrt(r * r - dy * dy))


def _fit_bold(d: ImageDraw.ImageDraw, text: str, size: int,
              track: float, budget: float):
    """Shrink a bold display line until it fits `budget` px wide.

    The name comes from whoever the room loop identified — it is not a
    string we control, and a long one is exactly the case nobody tests.
    Returns (font, width)."""
    while size > 44:
        f = face("bold", size)
        w = track_len(d, text, f, track)
        if w <= budget:
            return f, w
        size -= 6
    f = face("bold", size)
    return f, track_len(d, text, f, track)


_LOGIN_FOCUS: dict = {}


def _login_focus_mask(size: tuple) -> "Image.Image":
    """The pool of quiet the confirmation seal is struck onto.

    Opaque at the centre, gone by the radius where the outer orbits live,
    so the world survives at the edges while the middle stops arguing.
    Built once — it is the same mask every frame of every ceremony, and
    the confirmation is the one moment on this device where a stranger is
    watching.
    """
    got = _LOGIN_FOCUS.get(size)
    if got is not None:
        return got
    #: imported here like every other numpy user in this file — the module
    #: is not imported at the top on purpose (see the note at the first
    #: one) and test_undefined_names caught this within a minute of it
    #: being written, which is exactly what that guard is for.
    import numpy as _np
    w, h = size
    cx, cy = w / 2.0, h / 2.0
    y, x = _np.ogrid[0:h, 0:w]
    r = _np.sqrt((x - cx) ** 2 + (y - cy) ** 2)
    #: THE PLATEAU HAS TO CLEAR THE WORDMARK, and the first cut did not.
    #: At full strength to r=210 the pool covered the seal and left
    #: AURAVISION ghosting through the tick at r~250-330 — the exact
    #: collision the 0.88 dim was introduced for on 08-18, back at a
    #: quarter of the brightness. Rendered and looked at, which is the only
    #: way that was ever going to be caught.
    #:
    #: Full strength to 330 (past the wordmark), gone by 415 (inside the
    #: innermost orbit at 418, so no orbit is ever touched). Smoothstep
    #: between — a linear ramp shows a visible edge on a dark field, the
    #: same lesson the pane bloom's rim fade learned.
    k = _np.clip((r - 330.0) / (415.0 - 330.0), 0.0, 1.0)
    k = k * k * (3.0 - 2.0 * k)
    #: 235 -> 255 IN THE PLATEAU. At 235 the pool was 92% opaque and
    #: AURAVISION still read through the tick — the same collision, at 8%
    #: of its old strength, which on a black field is still legible
    #: because the wordmark is the brightest thing under it. "Almost
    #: opaque" is not a design decision, it is a leak; a pool the seal is
    #: struck onto should be a ground, not a veil. The ramp still carries
    #: everything back to the stars, so nothing is cut.
    m = Image.fromarray(((1.0 - k) * 255).astype("uint8"), "L")
    _LOGIN_FOCUS[size] = m
    return m


def render_login(backdrop: Image.Image, spec: dict, now: float) -> Image.Image:
    """Voice-print theatre: scanning rings + label, then the welcome.

    TYPOGRAPHY (2026-08-02). Everything here was one 74/30/64px cut of
    DejaVu Sans Bold. It is now a three-step ramp: wide-tracked NARROW
    small caps for the status labels, Nimbus Sans REGULAR for the
    supporting lines, and BOLD kept for exactly two things — the person's
    name and the match percentage. Those are the only two pieces of
    information on the page; everything else is chrome and now reads like
    chrome. See FACES / face() for the fallback rule.

    LAYOUT LANDMARKS — do not move these back:
      * the scan band (waveform / spectrum) sits ABOVE the wordmark at
        cy-270; the owner reported it over the AURA logo twice.
      * the confirmation seal sits at ccy=300, for the same reason.
    """
    frame = backdrop.copy()
    d = ImageDraw.Draw(frame)
    t = now - float(spec.get("start", now))
    verify_s = float(spec.get("verify_s", 16.0))
    verifying = t < verify_s
    #: ── WHEN THE SCAN DECLARES ITS ANSWER (2026-08-21) ──────────────────
    #: The scan has three captions — capture, match, confirm — and the last
    #: boundary was the fraction 0.86, so the CONFIRMATION occupied the
    #: final 14% of whatever the scan was. Measured on puck-10634 that is
    #: 2.97 s of "IDENTITY CONFIRMED", with a full green tick, playing
    #: while she is still running the beat and three seconds before she
    #: says "welcome back".
    #:
    #: The screen answering the question three seconds before the voice
    #: does is the same defect as the 2.76 s of dead air the conductor just
    #: lost: a duration predicted in one file about audio rendered in
    #: another (the house rule — measure rendered audio, never store a
    #: predicted duration). The conductor measures the clips to work out
    #: the scan, so it is the only thing that can know this instant, and it
    #: now says so in the spec.
    #:
    #: The fraction remains the fallback, for a spec written by an older
    #: conductor — which is what a fleet looks like between two deploys.
    _bloom_at = float(spec.get("bloom_at", verify_s * 0.86))
    cx = cy = SIZE // 2
    if verifying:
        # A scan with STAGES — ceremony reads as security. Capturing the
        # waveform, matching the print with a climbing percentage, then
        # the confirmation flash; a progress ring closes over the whole
        # scan, pulse rings breathe, the dashed ring never stops turning.
        p = t / verify_s
        #: ── THE READOUT TAKES THE CENTRE (2026-08-18) ────────────────────
        #: Owner: "the number / percentage should have a % after it and be
        #: in the center of the circle. And put that pulsing volume thing
        #: within the circle as well right above."
        #:
        #: The landmarks in this function's docstring say the opposite —
        #: scan band at cy-270, everything clear of the wordmark — and they
        #: were right at the time: the wordmark owned the middle and he
        #: objected twice to things being stamped over it. What changed is
        #: that during a scan the wordmark is not the subject. The reading
        #: is. So the iris VEILS while verifying and the readout moves into
        #: the space that frees, rather than everything being pushed out to
        #: the rim to avoid a label that has nothing to say right now.
        #:
        #: A veil rather than removing the wordmark because it arrives baked
        #: into the backdrop (lock_img), and because darkening the eye as it
        #: concentrates is the thing actually happening.
        _veil = _auth_veil()
        frame.paste(_veil, (0, 0), _veil)
        da = ImageDraw.Draw(frame, "RGBA")

        #: ── ETCHED, NOT DRAWN ON ────────────────────────────────────────
        #: Owner: "thin the lines / circles that are around it moving during
        #: auth, they are too thick, and vary the color and give them more
        #: professional treatment as to texture, they look cartoonish."
        #:
        #: Cartoonish here is three specific things, and thickness is only
        #: the first: every stroke was 3-6 px, every stroke was FLAT (one
        #: opaque colour end to end), and every stroke was the same cyan. A
        #: marker pen has those properties. An etched instrument does not.
        #:
        #: So: 1 px, and where a line needs weight it gets a second hairline
        #: beside it at a lower alpha, which is how a real engraved line
        #: reads — a cut and the light catching its lip. Alpha carries the
        #: emphasis instead of width. And the palette varies: cold steel,
        #: ice, a violet, and one warm grey, because a screen of pure cyan
        #: is the other half of why it looked like a cartoon.
        for i in range(3):                                # breathing rings
            ph = (t * 0.7 + i / 3.0) % 1.0
            r = 150 + 250 * ph
            v = 1.0 - ph
            col = AUTH_RINGS[i % len(AUTH_RINGS)]
            #: the pair: the cut, then its lit lower lip 2 px out
            da.ellipse([cx - r, cy - r, cx + r, cy + r],
                       outline=col + (int(96 * v),), width=1)
            da.ellipse([cx - r - 2, cy - r - 2, cx + r + 2, cy + r + 2],
                       outline=col + (int(34 * v),), width=1)

        #: the progress ring gets a TRACK — a full dim circle it fills
        #: against. Without one a partial arc reads as a stray mark rather
        #: than a measurement, which is most of why it looked unfinished.
        da.ellipse([cx - 330, cy - 330, cx + 330, cy + 330],
                   outline=AUTH_STEEL + (40,), width=1)
        _pend = -90 + 360 * min(1.0, p / 0.92)
        #: ── THIN, AND THE COLOUR CARRIES THE VOLUME (2026-08-19) ─────
        #: Owner, for the second time: "the circle is too thick, i told
        #: your predecessor, keep that circle thin and just throb the
        #: color to show the volume detection."
        #:
        #: The note forty lines up already says this — "1 px, and where a
        #: line needs weight it gets a second hairline beside it at a
        #: lower alpha ... Alpha carries the emphasis instead of width" —
        #: and then this arc was left at width=2 with a fixed alpha. The
        #: rule was written and one stroke was not brought under it, which
        #: is why the complaint survived the fix that was supposed to
        #: answer it.
        #:
        #: So: 1 px, and the level does the work. `_room_frac` is the same
        #: real reading the ribbon plots — puck_ears' published energy, not
        #: an animation — so a quiet room leaves a calm hairline and a
        #: voice lifts it. That is the "volume detection" the ceremony is
        #: claiming to perform, actually shown.
        #:
        #: None (no reading at all) holds the resting alpha rather than
        #: dropping to nothing: a scan whose ring goes dark because the
        #: array stopped answering looks like the scan failed, and §2 says
        #: absence of evidence is not evidence of absence.
        _lvl = _room_frac((_room_now(now) or {}).get("energy"))
        _lvl = 0.0 if _lvl is None else float(_lvl)
        _a_main = int(120 + 125 * _lvl)                # 120..245
        _a_halo = int(28 + 62 * _lvl)                  # 28..90
        da.arc([cx - 330, cy - 330, cx + 330, cy + 330],
               start=-90, end=_pend, fill=AUTH_ICE + (_a_main,), width=1)
        #: the lit lower lip, 3 px out — weight without thickness, the
        #: same construction the breathing rings use above
        da.arc([cx - 333, cy - 333, cx + 333, cy + 333],
               start=-90, end=_pend, fill=AUTH_ICE + (_a_halo,), width=1)
        #: a bright head on the leading edge — an instrument that is still
        #: moving, rather than an arc that happens to stop somewhere
        _ha = math.radians(_pend)
        _hx, _hy = cx + 330 * math.cos(_ha), cy + 330 * math.sin(_ha)
        da.ellipse([_hx - 3, _hy - 3, _hx + 3, _hy + 3],
                   fill=AUTH_ICE + (235,))

        #: the turning scale: 48 fine ticks, every sixth longer and brighter,
        #: which is a bearing ring rather than a chase of fat dashes
        for k in range(48):
            a0 = (t * 42.0 + k * 7.5) % 360
            _maj = (k % 6 == 0)
            _r1 = 170.0
            _r0 = _r1 - (11.0 if _maj else 5.0)
            _ra = math.radians(a0)
            _c1, _s1 = math.cos(_ra), math.sin(_ra)
            da.line([cx + _r0 * _c1, cy + _r0 * _s1,
                     cx + _r1 * _c1, cy + _r1 * _s1],
                    fill=(AUTH_ICE if _maj else AUTH_STEEL)
                    + (150 if _maj else 70,), width=1)

        # Outer orbits, counter-rotating (owner: "more of the rotational
        # aspects" during login). Slow and thin — depth, not noise.
        #: now 1 px with a faint twin, and four colours rather than three
        #: shades of one. The eye reads depth from the alpha difference,
        #: which is what "more professional treatment" is asking for.
        for rr, spd, ln, col, al in ((470, 22.0, 80, AUTH_STEEL, 150),
                                     (445, -34.0, 46, AUTH_VIOLET, 130),
                                     (496, 13.0, 120, AUTH_SLATE, 110),
                                     (418, -17.0, 30, AUTH_WARM, 90)):
            a0 = (t * spd) % 360
            for _off in (0, 180):
                da.arc([cx - rr, cy - rr, cx + rr, cy + rr],
                       start=a0 + _off, end=a0 + _off + ln,
                       fill=col + (al,), width=1)
                da.arc([cx - rr - 3, cy - rr - 3, cx + rr + 3, cy + rr + 3],
                       start=a0 + _off, end=a0 + _off + ln,
                       fill=col + (al // 3,), width=1)
        #: ── FOUR STEPS, NOT TWO (2026-08-18) ────────────────────────
        #: Owner: "extend artificially the auth process so it makes it look
        #: more thorough."
        #:
        #: Length alone does not read as thorough, it reads as slow — a
        #: progress bar that takes longer is not more convincing, it is
        #: more annoying. What reads as thorough is VISIBLE STEPS: the
        #: label changing tells you something finished and something else
        #: started, and that is the whole of the effect.
        #:
        #: So the scan is stretched (LOGIN_VERIFY_S 16 -> 24 in the
        #: conductor, which owns it) AND the middle is split, so the
        #: sequence is capture -> isolate -> match -> confirm rather than
        #: one long match. Same machinery, one more caption.
        if p < 0.22:
            label = "CAPTURING WAVEFORM"
            pts = []
            for i in range(90):                           # live waveform
                x = cx - 260 + i * (520 / 89.0)
                a = (math.sin(i * 0.35 + t * 9) * 0.5
                     + math.sin(i * 0.13 + t * 5.2) * 0.3
                     + math.sin(i * 0.71 + t * 13.7) * 0.2)
                env = math.sin(i / 89.0 * math.pi)
                # The band lives ABOVE the wordmark (owner, twice: "the
                # volume animation is still over the AURA logo") — same
                # altitude as the confirmation seal, ccy 300.
                #: INSIDE the circle now, just above where the readout
                #: sits — see the note at the veil. cy-270 put it out on
                #: the rim to clear a wordmark that is veiled while this
                #: runs.
                pts.append((x, cy - AUTH_METER_DY + a * 44 * env))
            da.line(pts, fill=AUTH_ICE + (225,), width=2, joint="curve")
            #: a dim baseline so the capture reads as a trace ON something
            da.line([(cx - 210, cy - AUTH_METER_DY),
                     (cx + 210, cy - AUTH_METER_DY)],
                    fill=AUTH_SLATE + (70,), width=1)
        elif t < _bloom_at:
            #: the meter runs through both middle steps; only the reading
            #: waits, because a percentage that appears before there is
            #: anything to measure against is theatre that contradicts
            #: itself
            label = ("ISOLATING VOICEPRINT" if p < 0.46
                     else "MATCHING VOICE PRINT")
            #: ── THE METER MOVES INSIDE (2026-08-18) ──────────────────
            #: Owner: "put that pulsing volume thing within the circle as
            #: well right above [the number]."
            #:
            #: Narrower and finer as well as relocated: 27 bars of 3 px
            #: across 300 px instead of 21 fat ones across 420. The old
            #: bars were 6 px wide with a 5 px corner radius, which makes
            #: them lozenges — that rounding is most of why this screen
            #: read as a cartoon. A level meter is made of thin hard
            #: rectangles, and the colour rides the HEIGHT so the tall
            #: ones are ice and the quiet ones are slate.
            for i in range(27):                           # spectral bars
                x = cx - 150 + i * 11.2
                _u = abs(math.sin(i * 1.7 + t * 6.0)) \
                    * (0.4 + 0.6 * abs(math.sin(i * 0.4 + t * 1.3)))
                h = 5 + 34 * _u
                _c = tuple(int(AUTH_SLATE[j]
                               + (AUTH_ICE[j] - AUTH_SLATE[j]) * _u)
                           for j in range(3))
                da.rectangle([x, cy - AUTH_METER_DY - h,
                              x + 3, cy - AUTH_METER_DY + h],
                             fill=_c + (int(150 + 90 * _u),))
            # The match percentage is one of the two things on this page
            # that is actually INFORMATION, so it keeps the bold — but
            # the per-cent sign is set small and light beside it. A big
            # bold "%" is the clunk the owner was pointing at.
            # It also moved UP, from cy-110 to cy-186. Rendered and
            # looked at: at the old altitude the digits' descender box
            # ended 22px above the AURA wordmark's cap line, which is the
            # same crowding the owner has objected to twice for the scan
            # band and the seal. At cy-186 the number groups with the
            # spectrum bars it is a readout OF (their lowest ink is
            # y 336, 18px above) and clears the wordmark by ~85px.
            #: ── THE READING SITS IN THE MIDDLE (2026-08-18) ──────────
            #: Owner: "the number / percentage should have a % after it
            #: and be in the center of the circle."
            #:
            #: It was at cy-186, pushed up there in August to clear the
            #: wordmark's cap line. The wordmark is veiled during a scan
            #: now, so the constraint is gone and the number can be where
            #: the only piece of information on the screen belongs.
            #:
            #: Centred on its INK, not on its line box. All-caps digits
            #: have an empty descender, so centring the box would sit the
            #: number visibly high — the same measurement error the lock
            #: hints' note describes, and the reason it is done with
            #: textbbox rather than by subtracting half the point size.
            #: The reading has to reach its top exactly where the caption
            #: changes, so it is scaled to `_bloom_at` rather than to the
            #: old 0.86 boundary it used to share. Fixed at 0.40 it would
            #: hit 99% early and then sit there, which is a progress bar
            #: that has stopped meaning anything — and on a longer scan it
            #: would arrive late and jump.
            _p46 = 0.46 * verify_s
            _span = max(1e-3, _bloom_at - _p46)
            _mp = ((t - _p46) / _span) if verify_s > 0 else 0.0
            pct = int(min(99, max(0.0, _mp) * 100))
            if p < 0.46:
                pct = -1
            f_num, f_pc = face("bold", 76), face("text", 34)
            ptxt = str(pct)
            nw = d.textlength(ptxt, font=f_num)
            pw = d.textlength("%", font=f_pc)
            px0 = (SIZE - (nw + 10 + pw)) / 2
            _nb = d.textbbox((0, 0), ptxt, font=f_num)
            ny = cy - (_nb[1] + _nb[3]) / 2.0
            if pct >= 0:
                d.text((px0, ny), ptxt, font=f_num, fill=AUTH_INK)
            #: the sign sits on the number's BASELINE rather than floating
            #: beside its middle: bottom-align both ink boxes.
            _pb = d.textbbox((0, 0), "%", font=f_pc)
            if pct >= 0:
                d.text((px0 + nw + 10, ny + (_nb[3] - _pb[3])), "%",
                       font=f_pc, fill=AUTH_STEEL)
        else:
            label = "IDENTITY CONFIRMED"
            #: ── THE SEAL LANDS IN THE MIDDLE (2026-08-18) ────────────
            #: Owner: "green checkmark after the auth should land in the
            #: center of the screen."
            #:
            #: It was at ccy=300, and the docstring's landmarks say to
            #: leave it there — "the confirmation seal sits at ccy=300,
            #: for the same reason", the reason being that it was once
            #: stamped straight over the AURA wordmark and he objected.
            #: That constraint died with the veil: there is nothing in the
            #: middle of this screen to collide with any more, and a
            #: confirmation that appears off-centre reads as a badge stuck
            #: on rather than the answer to the question the screen was
            #: asking. Both landmarks in the docstring are now obsolete
            #: for the same reason and both notes stay where they are —
            #: they record why the position was right when it was chosen.
            ccy = cy
            #: ── THE BLOOM IS TOLD WHEN, NOT GIVEN A FRACTION ───────────
            #: (2026-08-21) `verify_s * 0.86` puts the confirmation 14%
            #: before the end of the scan, whatever the scan is — which is
            #: a guess at where the welcome line starts, made in a
            #: different file from the one that plays it. Measured on
            #: puck-10634 the two were 2.97 s apart: the tick bloomed, and
            #: three seconds later she said the words it was illustrating.
            #: Two halves of one beat, played apart, on the screen whose
            #: only job is to look certain.
            #:
            #: The conductor knows exactly when the welcome starts — it
            #: measured the clips to work out the scan — so it now says so.
            #: The fraction stays as the fallback for a spec written by an
            #: older conductor, which is the only way a mixed fleet
            #: survives a deploy in either order.
            #: `_bloom_at` is resolved once at the top of this function —
            #: it decides both WHEN this caption appears and how fast the
            #: seal opens, and those two must not be able to disagree.
            #: CLAMPED AT BOTH ENDS. It was `min(1.0, k)` — a ceiling and no
            #: floor — and that was safe only by accident: with the bloom
            #: pinned to `verify_s * 0.86` and this block reached only past
            #: verify_s, k could not be negative. Moving the bloom later
            #: broke that coincidence and `r` went negative, which PIL
            #: reports as "x1 must be greater than or equal to x0" from
            #: inside ImageDraw — a stack trace three frames from anything
            #: that names a ceremony.
            #:
            #: Caught by rendering it rather than by reasoning about it,
            #: which is the whole argument for the preview harness: the
            #: arithmetic above had already been checked on two devices and
            #: was right, and this still would have taken the face down at
            #: the one moment a stranger is watching it.
            k = max(0.0, min(1.0, (t - _bloom_at) * 3.0))  # confirmation bloom
            throb = 1.0 + 0.06 * math.sin(now * math.tau * 1.15)
            r = (110 + 30 * k) * throb
            #: thinner, for the same reason the rings were thinned — an
            #: 8 px ring and a 12 px tick were the heaviest strokes on the
            #: screen and the most cartoonish thing on it. The weight comes
            #: back as a soft outer halo instead, which is how a lit object
            #: reads against black.
            da.ellipse([cx - r - 5, ccy - r - 5, cx + r + 5, ccy + r + 5],
                       outline=AUTH_OK + (46,), width=3)
            da.ellipse([cx - r, ccy - r, cx + r, ccy + r],
                       outline=AUTH_OK + (235,), width=3)
            da.line([cx - 55, ccy + 5, cx - 12, ccy + 48, cx + 66, ccy - 42],
                    fill=AUTH_OK + (240,), width=7, joint="curve")
        # The stage label: narrow small caps, tracked wide, in the light
        # face. It is a caption on the ceremony, not a headline — and the
        # tracking is what makes a caption read as deliberate rather than
        # small. A 12px hairline rule above it does the rest.
        dots = "." * (1 + int(t * 2) % 3) if p < 0.86 else ""
        f_lbl = face("label", 26)
        ly = cy + 236
        tw = track_len(d, label, f_lbl, 8.0)
        d.line([cx - 46, ly - 22, cx + 46, ly - 22],
               fill=(58, 84, 108), width=1)
        track_text(d, ((SIZE - tw) / 2, ly), label, f_lbl, AUTH_STEEL, 8.0)
        if dots:
            d.text(((SIZE + tw) / 2 + 10, ly), dots,
                   font=f_lbl, fill=AUTH_CYAN)
    else:
        name = str(spec.get("name", "")).upper()
        #: ── THE SEAL IS THE MOMENT (2026-08-18) ──────────────────────────
        #: Owner: "add & to the voice print auth and the green checkmark in
        #: the center of the screen, not on top of the circle."
        #:
        #: THE "&" IS DROPPED (2026-08-20). Nobody built it because nobody
        #: knew what it meant, and inventing a symbol on the one screen a
        #: stranger sees first was not worth the guess. Asked, and the
        #: answer was "get rid of the &". The half-instruction stays quoted
        #: above so the next reader is not left hunting for a feature —
        #: that is what a two-year-old ask looks like when only half of it
        #: was ever actionable.
        #:
        #: It sat at ccy=300, which is inside the iris' upper arc — so the
        #: one image that means "I know who you are" was stamped across the
        #: eye, with the wordmark between it and the greeting. Three things
        #: competing for the middle of a screen whose whole job, for two
        #: seconds, is to say one thing.
        #:
        #: So: the seal takes the true centre, and everything that was
        #: competing with it gets out of the way. The backdrop is dimmed
        #: hard for the confirmation — it is the same iris, still there,
        #: just no longer arguing — and the greeting moves below. Nothing
        #: is removed; the emphasis is simply spent on one element instead
        #: of split across three.
        #: 0.72 -> 0.88. At 0.72 the wordmark still read through the tick,
        #: so the checkmark was crossing the word AURAVISION — which is the
        #: overlap he was pointing at, just relocated. At 0.88 the iris
        #: survives as a ghost (the room is still there, she has not gone
        #: dark) and everything else gets out of the way.
        #: ── 2026-08-20: A DESIGN PASS, NOT ANOTHER CORRECTION ─────────
        #: Owner: "the voice verification screen is still not great." It
        #: has been treated as a list of small fixes — centre the tick, add
        #: the ampersand — and the queue entry is right that it wants a
        #: pass instead. Rendering both stages side by side says why in one
        #: look: THEY ARE NOT THE SAME PRODUCT.
        #:
        #: The scan is the best screen on this device — starfield, four
        #: counter-rotating orbits, a chapter ring of ticks, a live
        #: waveform, light tracked caps. The confirmation threw all of it
        #: away: 0.88 toward near-black kills the stars and the orbits, and
        #: what is left is a spring-green checkmark and a bold name, which
        #: is the notification style of every operating system ever
        #: shipped. The ceremony spends twenty seconds building an
        #: atmosphere and then discards it at the exact moment it pays off.
        #:
        #: THE 0.88 WAS TREATING A SYMPTOM. It exists because the wordmark
        #: read through the tick (08-18) — one collision, fixed by dimming
        #: the entire world. So the focus is composed instead: the frame
        #: settles back a little, and a soft radial pool darkens only where
        #: the seal lands. The stars and the outer orbits survive at full
        #: strength, the middle goes quiet, and the seal is struck onto a
        #: clean ground — which is what the dimming was for, without the
        #: cost it charged.
        _vg = _login_focus_mask(frame.size)
        frame.paste(Image.blend(frame, Image.new("RGB", frame.size,
                                                 (3, 6, 10)), 0.42), (0, 0))
        frame.paste(Image.new("RGB", frame.size, (3, 6, 10)), (0, 0), _vg)
        d = ImageDraw.Draw(frame)
        ccy = cy
        throb = 1.0 + 0.05 * math.sin(now * math.tau * 1.1)
        r = 132 * throb
        #: a soft ring under it, so the seal reads as struck onto the glass
        #: rather than floating: the same trick every other lit element on
        #: this device uses, at a fraction of the strength.
        #: ── AND THE SEAL JOINS THE DEVICE IT LIVES ON (2026-08-20) ────
        #: A 7 px ring with a 12 px tick in spring green is the success
        #: state of every operating system ever shipped, and it was the
        #: largest object on the most important screen. Green STAYS —
        #: semantic colour is not the accent, and "verified" has earned a
        #: hue of its own on a device that is otherwise entirely blue —
        #: but it is drawn the way this device draws things: thinner, and
        #: with concentric rings carrying the weight instead of stroke
        #: width. That is the scan's own language, four counter-rotating
        #: orbits and a chapter ring, resolved into something still.
        #:
        #: THREE RINGS, NOT ONE, and the outer two are the same pair the
        #: scan wears. The confirmation then reads as the ceremony
        #: settling rather than as a different screen replacing it.
        for _g, _w, _c in ((r + 44, 1, (16, 62, 46)),
                           (r + 26, 1, (22, 96, 68)),
                           (r + 12, 2, (30, 132, 90))):
            d.ellipse([cx - _g, ccy - _g, cx + _g, ccy + _g],
                      outline=_c, width=_w)
        d.ellipse([cx - r, ccy - r, cx + r, ccy + r],
                  outline=(53, 208, 127), width=4)
        d.line([cx - 62, ccy + 6, cx - 14, ccy + 54, cx + 74, ccy - 46],
               fill=(53, 208, 127), width=7, joint="curve")
        # "WELCOME BACK, PAUL" used to be ONE 74px bold line, so the
        # greeting shouted as loudly as the person. Split: the greeting
        # becomes a tracked small-caps kicker in the light face, the NAME
        # gets the display weight to itself. Tight leading between them
        # (34px) so they read as one block, not two statements.
        f_kick = face("label", 26)
        kick = "WELCOME BACK"
        kw = track_len(d, kick, f_kick, 10.0)
        if not name:
            # No name to give the display line to — the greeting takes it,
            # bold, where the old single line sat.
            f_n, nw = _fit_bold(d, kick, 78, 5.0, 780)
            track_text(d, ((SIZE - nw) / 2, cy + 196), kick, f_n,
                       AUTH_INK, 5.0)
        else:
            #: below the seal now, not beside the wordmark
            track_text(d, ((SIZE - kw) / 2, cy + 172), kick, f_kick,
                       AUTH_STEEL, 10.0)
            #: ── THE NAME IS LIGHT AND WIDE NOW (2026-08-20) ──────────
            #: 84 px BOLD was the loudest type on the device, and it was
            #: on the one screen whose job is confidence rather than
            #: volume. The whole system moved the other way today: the
            #: briefing title went Ubuntu Medium at 0.16 em to Ubuntu Thin
            #: at 0.304, on his own note that "elegant is LIGHT AND WIDE —
            #: the weight comes off and the space between the letters does
            #: the work", and his verdict at the glass was "a lot a lot
            #: better". This screen was left behind and now reads as
            #: another application's dialog.
            #:
            #: Same face, same axis: the title role, tracked. A name at 92
            #: px of Thin with 0.20 em between the letters occupies MORE
            #: width than 84 px of Bold did and shouts less, which is the
            #: whole trade. `_fit_bold` stays for the no-name case below,
            #: where a greeting genuinely is the only thing on the line.
            _trk = 0.20
            f_n = face("title", 92)
            nw = track_len(d, name, f_n, _trk * 92)
            while nw > 800 and f_n.size > 40:
                f_n = face("title", f_n.size - 4)
                nw = track_len(d, name, f_n, _trk * f_n.size)
            track_text(d, ((SIZE - nw) / 2, cy + 204), name, f_n,
                       AUTH_INK, _trk * f_n.size)
        b_at = float(spec.get("briefing_at", 0))
        if b_at:
            # The clock is the other real number on the page, so it is
            # the other thing allowed to be bold: light label, bold time.
            mm, ss = divmod(max(0, int(b_at - now)), 60)
            f_sub, f_clk = face("label", 26), face("bold", 28)
            lbl, clk = "MORNING BRIEFING IN", f"{mm}:{ss:02d}"
            lw = track_len(d, lbl, f_sub, 7.0)
            cw = d.textlength(clk, font=f_clk)
            x0 = (SIZE - (lw + 14 + cw)) / 2
            #: 318 -> 356. The name is set 92 px of tracked Thin now
            #: rather than 84 px of Bold, so its block is taller and the
            #: countdown was sitting on its baseline. A name and the time
            #: of the next briefing are two different statements and the
            #: gap is what says so.
            track_text(d, (x0, cy + 356), lbl, f_sub, AUTH_STEEL, 7.0)
            d.text((x0 + lw + 14, cy + 354), clk, font=f_clk,
                   fill=AUTH_CYAN)
    return frame


def flash_overlay(t: float) -> Image.Image:
    """A pulsing glow over the BRIEFING wedge — urgency you can see across
    the room. Screen-blended, so black is nothing."""
    im = Image.new("RGB", (SIZE, SIZE), 0)
    d = ImageDraw.Draw(im)
    pulse = 0.5 + 0.5 * math.sin(t * 2 * math.pi * 1.1)
    v = int(120 * pulse) + 18
    col = (int(v * 0.28), int(v * 0.82), v)
    for r, w in ((BRIEFING_R1, 14), (BRIEFING_R0, 8)):
        d.arc([SIZE / 2 - r, SIZE / 2 - r, SIZE / 2 + r, SIZE / 2 + r],
              start=BRIEFING_A0, end=BRIEFING_A1, fill=col, width=w)
    return im.filter(ImageFilter.GaussianBlur(4))


#: The ocean (owner, 2026-08-01: "make the background even more dynamic,
#: but subtle, it should almost feel like a gentle ocean wave kind of
#: thing"). A pre-baked field of broad, soft swells drifts on two
#: incommensurate periods and breathes on a third — nothing repeats on a
#: watchable timescale, nothing moves fast enough to watch. Deep-water
#: blue, screened well beneath the accent so the face stays dark.
def _make_swell() -> Image.Image:
    im = Image.new("L", (SIZE, SIZE), 0)
    d = ImageDraw.Draw(im)
    d.ellipse([-500, 200, 700, 900], fill=26)
    d.ellipse([400, 100, 1600, 800], fill=20)
    d.ellipse([100, 600, 1100, 1500], fill=22)
    return im.filter(ImageFilter.GaussianBlur(120))


_SWELL = _make_swell()
_SWELL_TINT = (46, 110, 178)


#: The swell was rebuilt from nothing on every frame — a paste, three
#: point() passes and a merge at 1080², measured at 8.0 ms on the panel
#: (2026-08-06). It did not need to be: its slowest term has a period of
#: 23 s and its fastest 37 s, so between one frame and the next almost
#: nothing about it has changed.
#:
#: dx and dy are already integers and already hold for several frames. The
#: gain is the only continuous term, so it is quantised — 48 steps across
#: a 0.10..1.00 range, about 0.021 per step, which is finer than the
#: posterize this frame is about to go through anyway. Keyed on all three,
#: a held frame is the frame the maths asked for, not an approximation.
_OCEAN_CACHE: dict = {"key": None, "im": None}


def ocean_overlay(t: float) -> Image.Image:
    dx = int(44 * math.sin(t * math.tau / 37.0))
    dy = int(30 * math.sin(t * math.tau / 53.0 + 1.7))
    gq = round((0.55 + 0.45 * math.sin(t * math.tau / 23.0)) * 48)
    key = (dx, dy, gq)
    if _OCEAN_CACHE["key"] == key:
        return _OCEAN_CACHE["im"]
    field = Image.new("L", (SIZE, SIZE), 0)
    field.paste(_SWELL, (dx, dy))
    g = gq / 48.0
    im = Image.merge("RGB", [
        field.point(lambda p, k=c / 255.0 * g: int(p * k))
        for c in _SWELL_TINT])
    # The caller only ever screens this onto a frame, never draws into it,
    # so one shared instance is safe to hand out repeatedly.
    _OCEAN_CACHE["key"], _OCEAN_CACHE["im"] = key, im
    return im


#: The wedge entrance (owner, 2026-08-01: "make those wedges fade in in
#: sort of a dramatic fashion, starting from the top most edge down. have
#: some throbbing around the borders of each as they appear and then they
#: subside as the next one appears on the screen. make it cool"). Wedges
#: are baked into base.png, so the entrance is subtractive: each sector
#: begins under a black cover that dissolves on its cue, while its border
#: carries a throb that subsides exactly as the next wedge's cue lands.
#: Geometry mirrors home.html's MENU verbatim — same angles, same band.
#: 2026-08-08: THE FIVE COLOURS RIDE THE THEME (_TILES["wedges"], top of
#: file), in this same order. They are drawn on the far side of desertify()
#: — the entrance covers, the tour throb and the tap flare all screen these
#: triples onto a frame the duotone has already finished with — so they are
#: a per-theme decision, not a constant. royal-oak's row is these five
#: verbatim, so nothing about this theme moves.
#:
#: AND THE "must match home.html's MENU" CLAUSE BELOW IS NOW A ROYAL-OAK
#: CLAUSE ONLY, which is the one thing here that supersedes older text. On
#: patek the baked tile reaches the glass THROUGH the duotone and is rose
#: whatever home.html painted; a glow matching home.html's source colour
#: would be the single cool mark left sitting on its own warm tile — the
#: exact defect the r=470 bearing scan found. The angles, which are what
#: the hit-test shares with that page, are untouched.
WEDGES = [  # (a0, a1, color) — degrees from 3 o'clock, y-down; top first
    (-62.0, -28.0, _TILES["wedges"][0]),   # BRIEFING  (cyan on royal-oak)
    # Gold since 2026-08-07 ("make THAT gold ... look special") — must match
    # home.html's MENU or the entrance throb glows the wrong metal.
    (-24.0, 10.0, _TILES["wedges"][1]),    # STERLING  (gold, the concierge)
    (14.0, 48.0, _TILES["wedges"][2]),     # LOCK      (red — the brick)
    # Blue-steel since 2026-08-07 14:49 ("go all in with the blue") — must
    # match home.html's MENU, same rule as STERLING's gold above.
    (52.0, 86.0, _TILES["wedges"][3]),     # SETTINGS  (blue-steel on r-oak)
    (90.0, 124.0, _TILES["wedges"][4]),    # VOLUME    (teal on royal-oak)
]
#: THE RING BAND, IN DISPLAY PX — AND IT WAS IN THE WRONG UNITS.
#:
#: 2026-08-05. These were 336.0/458.0, which are home.html's numbers
#: verbatim: `sector(m.a0, m.a1, 336, 458)`. But home.html draws in a
#: 1000-wide viewBox against a 1080 panel, so its 336..458 lands on the
#: glass at 362.9..494.6. Everything live-drawn against this band — the
#: REQUESTS wedge, the clinic list, the unlock entrance's cover masks, the
#: wedge-tour glow — was therefore ~8% small and sat visibly INSIDE the
#: baked ring it was supposed to be part of.
#:
#: MEASURED ON THE ARTEFACT, not derived (PRINCIPLES §6, and the house rule
#: about verifying the artefact rather than the patch): a radial profile of
#: the current base.png finds every baked wedge's fill running 362 to 494
#: display px. The type in this file was already being scaled by the same
#: 1.08 — see the ("REQUESTS", face("label", 18)…) comment, which converts
#: home.html's 17px label for exactly this reason. Only the radii were left
#: in viewBox units.
#:
#: This is what the owner was looking at when he asked for "that concierge
#: wedge" to be pushed out with the rest of the left column.
#: x DIAL_K, 2026-08-06 night. The ring's outer edge was 458 viewBox = 494.6
#: display; home.html's #dial now carries scale(0.80) over the same 458, so
#: the baked sector lands at 395.7 and the hit-test has to land there too —
#: this line and that transform are one artefact. See DIAL_K.
#:
#: ── 2026-08-06, late night: 336 -> 368 VIEWBOX ON THE INNER EDGE ──────────
#: Owner: "narrow the wedge ring ... pull its INNER edge outward to about 368
#: and let the centre grow", and in the same breath the line this constant
#: exists for: "if the wedge ring moves, the tap hit-test moves with it IN
#: THE SAME COMMIT, or a wedge lights where nobody pressed."
#:
#: 368 viewBox is 397.4 display px, written that way for the reason the note
#: above gives — the measured display figure times DIAL_K, not a fresh
#: number. The band goes 105.4 -> 77.8 display px. handle_tap gates on
#: WEDGE_R0 - 30, so the padded target still starts at 288 and no finger
#: that could reach a wedge yesterday has lost it; what it stops doing is
#: accepting a press 28px inside the paint.
# R1 494.6 -> 503.3 with home.html's 458 -> 466 (x1.08), same commit —
# the two-file band contract.
WEDGE_R0, WEDGE_R1 = 397.4 * DIAL_K, 536.8 * DIAL_K  # 368/497 vb x 1.08

#: ── THE AURORA FACE DRAWS ITS OWN PANES, SO IT SETS ITS OWN ANGLES ──────
#: Owner: "increase the wedge sizes and corresponding icons to fill roughly
#: 66% of the circumference to give room for people to touch empty space."
#:
#: The five above are 34 degrees each with 4 degree gaps — 170 degrees of
#: pane in a 186 degree span, less than half the dial, all of it crowded
#: into one side. They are that size because they are BAKED INTO base.png
#: on the watch faces, and the hit-test has to agree with the paint (the
#: two-file band contract, above).
#:
#: The aurora face has no baked art — draw_aurora_menu renders every pane
#: from these numbers at first use — so it is free of that contract and
#: gets its own set: 44 degrees each, 4 degree gaps, 236 degrees total.
#: That is 66% of the circumference, with 124 degrees of blank glass left
#: for the tap that dismisses them, which is the point of the ask.
#:
#: SEPARATE, not a change to WEDGES, and that is deliberate: puck-bob wears
#: FERRARI, whose panes are painted into its bundle. Widening the shared
#: list would move his hit-test off his artwork and he would be pressing
#: 10 degrees beside every control.
#: 48, not 44: at 44 the panes measured 61% of the dial and he asked for
#: roughly 66. 5 x 48 = 240 degrees = 66.7%, which is the number.
#: ── AND THEIR OWN BAND (2026-08-17) ────────────────────────────────────
#: Owner: "the icons are bleeding beyond the edge of the wedge, that should
#: never, ever happen."
#:
#: He is right, and the cause is arithmetic rather than carelessness. The
#: shared band is 130 px thick. Several glyphs reach about 1.2x their
#: nominal radius (the bell's foot, the padlock's shackle), the stroke adds
#: half its width again, and the pane's chamfer eats ~15 px at each edge —
#: so the largest icon that can possibly fit inside 130 px is r = 34, which
#: is roughly what it was before it was raised to 44 for "bigger icons".
#: Both asks cannot be satisfied inside that band.
#:
#: So the aurora face — which already draws its own panes at its own angles
#: — gets its own RADII too: 170 px of band instead of 130. That is what
#: makes a genuinely bigger icon possible rather than an overflowing one.
#: Watch faces keep the shared numbers, because their panes are painted
#: into their bundles.
#: ── THINNER, AND FURTHER OFF THE EYE (2026-08-17) ───────────────────────
#: Owner: "make the wedges even thinner so there is more margin between the
#: eye and the wedges, they look too cartoonish right now."
#:
#: Both halves of that come from one pair of numbers. The band was 330..500
#: — 170 px thick, starting 60 px outside the steel. It is 364..496 now:
#: 132 px of pane (22% thinner) with 94 px of void between the eye's rim
#: and the first pixel of a wedge. Chunky bevelled tiles crowding a small
#: iris is what read as cartoonish; a slimmer arc held well off it reads as
#: instrumentation.
#:
#: The icon follows automatically — icon_radius() derives from this band —
#: which is the point of deriving it: thinning the pane cannot leave an
#: oversized glyph behind in it.
#: ── AND OUT TO THE RIM (2026-08-17) ─────────────────────────────────────
#: Owner: "get the wedges closer to the edge of the circle, there is plenty
#: of margin left in the display." There was — 44 px of unused glass beyond
#: the outer edge on a panel that is only 540 px of radius in the first
#: place. The band moves out bodily rather than growing: same 132 px of
#: pane, now 396..528, which leaves 12 px to the edge and opens the void
#: between the eye and the ring from 94 px to 126.
#: 528 -> 500 (2026-08-17): the wordmark needs the outer rim, and 12 px
#: was never going to hold 30 px type. The band gives 28 px back and thins
#: to 120 px with it — which is the direction he has moved it twice
#: already — leaving 500..540 for AuraVision to sit in.
#: ── HALF THE MARGIN, TWICE (2026-08-17) ─────────────────────────────────
#: Owner: "make the wedges closer to the diameter in general, half that
#: margin could be closed to give a more sense of expanse", and then again:
#: "the wedges need to be closer to the boundary."
#:
#: 500 left 40 px of dead glass outside the ring. Half of that is given
#: back: the band is 400..520 now, 20 px from the edge, same 120 px thick.
#: Everything downstream is derived from these two numbers — the icon
#: radius, the wordmark's median, the hit-test — so the realignment he
#: asked for happens on its own rather than in four more places.
#: ── 412..532 -> 420..540 (2026-08-20) ──────────────────────────────────
#: Owner: "push the wedges even closer to the rim of the display, we can
#: use the space to make the display look larger."
#:
#: The ring moves out 8 px and keeps its 120 px thickness, so nothing
#: downstream re-tunes — the icon radius, the wordmark median and the
#: hit-test are all derived from this pair, which is why the last move
#: (400..520 -> 412..532) also happened here and nowhere else.
#:
#: MEASURED BEFORE AND AFTER with scripts/check_glass_margin.py, because
#: this ring has two different reaches and only one of them is obvious:
#:
#:     at 412..532   structure r=524.3 (+15.7 spare)  halo r=536.4 (+3.6)
#:     at 420..540   structure r=532.3 (+ 7.7 spare)  halo r=544.4 (clipped)
#:
#: The STRUCTURE had 15.7 px of room. The HALO — the bloom and the glow —
#: reaches roughly 12 px past it and had only 3.6, so the constraint on
#: this move is not where the panes end, it is where their light ends.
#: Moving 8 px trades 4.4 px of soft glow at the extreme outer edge for a
#: visibly larger ring, which is the trade he asked for; the panes
#: themselves still clear the housing by 7.7.
#:
#: If the clipped bloom ever reads as a hard edge rather than as a ring
#: that fills the glass, the number to move is the halo's own reach and
#: not this pair — see AUR_BLOOM_* — because pulling the band back in is
#: the thing he has now asked against twice.
AUR_WEDGE_R0, AUR_WEDGE_R1 = 420.0, 540.0

#: ── HOW FAR INSIDE THE RIM THE HALO IS ALREADY DARK ────────────────────
#: The arrival bloom is blurred at 14 px sigma and its box is clamped at
#: the panel edge, so at the rim it was being sliced rather than fading —
#: worst edge alpha 121/255 with the band at 540. This is the distance
#: over which it ramps to nothing, measured from the glass radius inward.
#:
#: 26 px: comfortably more than the ~14 px the blur needs to look
#: continuous, and small enough that the glow still reads as surrounding
#: the pane rather than as a band painted inside it. Raise it if the
#: bloom looks pinched; lower it if a hard edge comes back.
AUR_BLOOM_RIM_FADE = 26.0

#: ── HOW MUCH OF THE GLOW MAY LIE ON THE PANE ITSELF ────────────────────
#: 0.0 is a pure outer glow — the blur minus the shape, nothing at all in
#: the middle. 1.0 is what shipped until 2026-08-20: the full blurred
#: shape, which measured 26-51x brighter inside the pane than outside and
#: is what "oversized highlights over the wedges" describes.
#:
#: 0.15 keeps a trace of the breath he has asked for three times without
#: the slab. Raise it if the arrival stops reading as light condensing;
#: lower it toward 0 if a pane ever looks washed out again.
AUR_BLOOM_ON_PANE = 0.15

#: ── AND HOW WIDE THE GLOW IS, AS A FRACTION OF THE PANE ────────────────
#: Owner, 2026-08-20: "the highlights are both delayed and too large FOR
#: THE WEDGES." The sigma was a flat 14 px against a ring whose panes run
#: 140 px thick at BRIEFING down to 99 px at POWER — so the same halo was
#: a different SIZE of thing on every pane, and on the thin ones it read
#: as a band down the glass rather than light around an edge.
#:
#: 0.06 of the pane's own band: 8.4 px on the widest, 5.9 px on the
#: narrowest, against the 14 px both used to get. Every pane now wears the
#: same proportion of glow, which is what "for the wedges" means, and the
#: value cannot go stale the next time the radii move — this is the third
#: bug this week caused by a length that was written down instead of
#: derived.
#:
#: Measured at the PEAK of the fade (not at rest — the bloom's strength is
#: sin(pi*e), so a settled pane sits at AUR_BLOOM_FLOOR and the endpoint is
#: the one frame the complaint is not about; scripts/measure_pane_highlight
#: .py gets this right and its first version did not).
AUR_BLOOM_SIG_K = 0.06
#: ── SEVEN PANES: SLEEP AND POWER COME BACK (2026-08-17) ────────────────
#: Owner: "re-introduce the power / sleep buttons with this color scheme
#: and make sure they fade in / fade out just like every other wedge" —
#: and, in the same breath, "decrease the wedges a bit in terms of
#: circumference that they take up".
#:
#: They were two machined caps at fixed points on the glass, drawn by a
#: different mechanism from everything around them and therefore not
#: participating in the reveal at all. On a face whose whole grammar is
#: "the controls are summoned", a pair of buttons that are simply always
#: there is the odd thing out. As panes they inherit the stagger, the
#: dissolve, the relief and the dismissal for free.
#:
#: 7 x 30 = 210 degrees, 58% of the dial, down from 67 with five at 48 —
#: which is the "decrease a bit": two MORE controls in LESS circumference,
#: and 150 degrees of blank glass to dismiss into.
AUR_WEDGE_SPAN, AUR_WEDGE_GAP = 30.0, 4.0
AUR_WEDGE_A0 = -86.0
#: SLEEP is the indigo of the night sky the lock screen wears; POWER is the
#: one amber on this face, because it is the only control that ends things.
#: Both sit in the same smoked-glass treatment as the other five — "with
#: this color scheme" — rather than arriving as a different material.
def _aur_ramp(n: int):
    """`n` colours walking one hue sweep, at constant value and chroma.

    Constant is the point. Seven hand-picked colours differ in lightness as
    well as hue, and lightness differences are what the eye reads as "these
    are different KINDS of thing" -- which is the disarray he is seeing.
    Holding value and saturation fixed and moving only the hue makes the
    ring one material in seven shades, which is what a graduated set looks
    like.
    """
    #: ── AND THE SWEEP OVERCORRECTED INTO ONE COLOUR (2026-08-19) ────────
    #: Owner, at the glass, twice within the hour: "let's make the colors
    #: for the wedges more varied again, lock should be red-ish, they all
    #: look the same. try changing the color of the icons or something
    #: within each background so they make sense" — and then "yeah make the
    #: wedges more distinct, vibrant, etc. they are just too bland looking
    #: right now. try some things out."
    #:
    #: THE DOCSTRING ABOVE STANDS WITH ITS DATE AND IS SUPERSEDED HERE, but
    #: only half of it is wrong and the half that is right is the reason
    #: this file keeps swinging. Read it again: the disarray was blamed on
    #: LIGHTNESS differences, not on hue. That diagnosis was correct. The
    #: remedy then held HSV **value** constant — and HSV value is not
    #: lightness. At V=0.86 a yellow measures L* 88 and a blue measures
    #: L* 42; the "constant value" ramp was carrying a 46-point lightness
    #: spread, which is most of what it was written to remove, while
    #: spending its entire hue budget on 188 degrees of blue-violet-magenta
    #: that all collapse to the same dark tile at a third brightness.
    #:
    #: So the fix that was reached for was never actually applied, and what
    #: shipped instead was the one axis the eye cannot use here.
    #:
    #: WHAT THIS DOES: hold **CIELAB L\* and C\*** constant and let the hue
    #: go wherever the CONTROL's meaning says. That is the family invariant
    #: the 2026-08-17 note was groping for, stated in the units the eye
    #: actually works in — seven pigments fired in the same enamel at the
    #: same depth, which is a set, not a charm bracelet. It is also the one
    #: arrangement nobody has tried: hand-picked hues have only ever been
    #: shipped with hand-picked lightnesses beside them (which read as
    #: disarray), and equal lightness has only ever been shipped with a
    #: single narrow hue sweep (which reads as one colour).
    #:
    #: AND IT IS WHAT MADE THE REORDER POSSIBLE AT ALL. He also asked for
    #: POWER/SLEEP/LOCK grouped at the bottom, which puts red, indigo and
    #: amber in slots 4, 5 and 6. No MONOTONE hue sweep passes through
    #: those three in that order; the graduated-ramp design was arithmetic-
    #: ally dead the moment the menu changed. Anything that restores a
    #: sweep here has to move the controls back too.
    #:
    #: AND THE DOCSTRING ABOVE ALSO MISREPORTED ITS OWN ARITHMETIC, which
    #: is why nobody re-read it: "the short way through cyan/green/gold" is
    #: not what `h0=200, h1=28` did. h1 < h0, so it walked 200 -> 388, i.e.
    #: 188 degrees the LONG way, through violet and magenta — the one
    #: direction that sentence says has no place on a machined face. That
    #: sat unread for two days. Corrected here rather than in place, per
    #: the append rule, so the discrepancy stays visible.
    #:
    #: `n` is honoured for callers that want an arbitrary count (nothing
    #: does today); the seven real panes come from AUR_PANES.
    if n == len(AUR_PANES):
        return [_aur_lch(_L, _C, _h) for (_k, _g, _h, _C, _L, _i) in AUR_PANES]
    return [_aur_lch(AUR_PANE_L, AUR_PANE_C, 360.0 * i / max(1, n))
            for i in range(n)]


#: ── THE FAMILY, IN THE UNITS THE EYE USES ───────────────────────────────
#: L* is perceived lightness and C* is perceived colourfulness. Holding
#: both fixed across the ring is what makes seven different hues read as
#: seven of ONE thing. 66/56 is a jewel tone that survives the pane's own
#: 0.40x dimming with its hue intact, and it is the SAME pair the seven
#: real panes carry in AUR_PANES — stated here once so a generated ramp of
#: any other length lands in the same family (§15). Much above C* 56 and
#: the warm end leaves the sRGB gamut at this lightness, and _aur_lch would
#: quietly give some panes less chroma than others — which is the disarray
#: coming back in through a clamp. It already does this at the COOL end:
#: BRIEFING's 212 tops out at C* 36.7, and that is printed at import
#: rather than absorbed.
AUR_PANE_L, AUR_PANE_C = 66.0, 56.0


def _aur_lch(L: float, C: float, h_deg: float) -> tuple:
    """sRGB for a CIELAB L*C*h colour, chroma reduced ONLY if out of gamut.

    Reduced rather than clipped: clipping a channel changes the hue as well
    as the chroma, and a palette whose members are each bent a different
    direction by the clamp is not a family however tidy the table looks.
    Anything that comes back with less chroma than it asked for is printed
    once at import, because a silent gamut clamp is exactly the kind of
    quiet drift §1 is about.
    """
    import math as _m

    def _lab_rgb(_C):
        _hr = _m.radians(h_deg)
        _a, _b = _C * _m.cos(_hr), _C * _m.sin(_hr)
        fy = (L + 16.0) / 116.0
        fx, fz = fy + _a / 500.0, fy - _b / 200.0
        _e, _k = 216.0 / 24389.0, 24389.0 / 27.0
        def _f(t):
            return t ** 3 if t ** 3 > _e else (116.0 * t - 16.0) / _k
        x, y, z = _f(fx) * 0.95047, _f(fy) * 1.0, _f(fz) * 1.08883
        r = 3.2404542 * x - 1.5371385 * y - 0.4985314 * z
        g = -0.9692660 * x + 1.8760108 * y + 0.0415560 * z
        b = 0.0556434 * x - 0.2040259 * y + 1.0572252 * z
        out = []
        for v in (r, g, b):
            v = 1.055 * (v ** (1 / 2.4)) - 0.055 if v > 0.0031308 else 12.92 * v
            out.append(v)
        return out

    lo, hi = 0.0, float(C)
    if all(-0.001 <= v <= 1.001 for v in _lab_rgb(hi)):
        lo = hi
    else:
        for _ in range(24):
            mid = (lo + hi) / 2.0
            if all(-0.001 <= v <= 1.001 for v in _lab_rgb(mid)):
                lo = mid
            else:
                hi = mid
        print(f"aurora: pane hue {h_deg:.0f} cannot hold C*{C:.0f} at "
              f"L*{L:.0f} in sRGB — served at C*{lo:.1f} (expected for the "
              f"cool hues; see AUR_PANES)", flush=True)
    return tuple(int(round(min(1.0, max(0.0, v)) * 255))
                 for v in _lab_rgb(lo))


AUR_WEDGE_COLS = _aur_ramp(len(AUR_PANES))
#: ── THE RING RECEDES (2026-08-19) ───────────────────────────────────────
#: Owner: "i want the wedges on the perimeter of the puck to gently /
#: subtly start from big to large while still lining up around the
#: circumference, it should give more depth to the screen."
#:
#: WHAT THIS IS NOT. It is not a projective tilt. A flat annulus seen
#: off-axis is symmetric with period 180 degrees — small at the top, large
#: at the bottom, small at the top again — and he asked for a run from one
#: end of the ring to the other. So the depth cue here is SIZE CONSTANCY
#: (a thing that subtends less is read as further away), not perspective,
#: and it is stated that way so nobody later "fixes" the asymmetry.
#:
#: WHY BOTH DIMENSIONS MOVE. A pane that is narrower but the same
#: thickness reads as a narrow tile, not as a distant one — the eye reads
#: depth from a UNIFORM scale. So the same weight drives the angular cell
#: and the radial thickness. The radial half is deliberately weaker
#: (AUR_WEDGE_DEPTH_RAD): the thickness is what `icon_radius()` derives
#: from, and taking the full ramp there costs the smallest pane's glyph
#: 24% — on a face whose icons he has already had shrunk twice and then
#: complained were "lost in that dust". Angular carries the effect; radial
#: corroborates it.
#:
#: AND THE TEXTURE COMES ALONG FOR FREE. The material maps are sampled in
#: PANE SPACE (u across the arc, v out from the inner edge), so one shared
#: weave laid on panes of different sizes is finer on the small ones — a
#: texture gradient, which is the other classic depth cue, and it points
#: the same way as the size ramp without a line of code.
#:
#: 0.15: the ends differ by 1.15/0.85 = 1.35x, which is about what a 40
#: degree tilt would do to a real ring, while ADJACENT panes differ by 5%.
#: "Gently / subtly" is a statement about the rate, not about the range —
#: he wants to see depth, and a ramp nobody can see is not a ramp.
#: ── AND 1.35x WAS A RAMP NOBODY COULD SEE (2026-08-19, third pass) ─────
#: Owner, at the glass, having watched 0.15 on the device: "ok i see the
#: carbon fiber weave but the tiles are still too subtly getting smaller,
#: make the north one larger and the gradient of decreasing size 30% ish
#: whatever so you can really see the gradient."
#:
#: THE PARAGRAPH ABOVE STANDS WITH ITS DATE AND IS SUPERSEDED BY THIS ONE.
#: "Gently / subtly / slightly" is what he asked for three times before he
#: had seen it, and it was quoted back correctly each time. He has now
#: seen it. A person looking at the result outranks the same person
#: describing it in advance, and the two must not be averaged.
#:
#: WHY 1.35x READ AS NOTHING, which is the part worth keeping. It is not
#: that 35% is a small number — it is that the two ends of the ramp are
#: 200 degrees apart on a circle, so nothing on this face ever puts the
#: biggest pane next to the smallest one. What the eye actually gets is
#: the 5% step between NEIGHBOURS, and 5% is under the threshold for a
#: size difference between two shapes at different orientations. The ramp
#: was doing exactly what it was specified to do and the specification was
#: measuring the wrong quantity.
#:
#: 0.22 makes the ends 1.22/0.78 = 1.56x — the smallest pane is 0.64 of
#: the largest, "decreasing size" by 36% — and, the number that matters,
#: adjacent panes now differ by 8-12%. His "30% ish whatever" is honoured
#: on the dimension he can actually check (the RADIAL thickness, below,
#: lands on 1.43x = exactly 30% smaller) and exceeded on the angular one,
#: because the angular difference is the one that has to survive being
#: compared across two hundred degrees of arc.
AUR_WEDGE_DEPTH = 0.22
#: 0.60 -> 0.80. The radial ramp is what reads AT A GLANCE, because every
#: pane shares one outer edge (r=532, a true circle, non-negotiable), so
#: the inner edge sweeping in and out is a difference the eye gets for
#: free with no comparison across the ring at all: 140 px thick at twelve
#: o'clock down to 99 at seven, which is 1.42x — his 30%, on the nose.
#:
#: NOT 1.00, and the reason is written down because it is the constraint
#: that stops this going further, and it is NOT the ratio. Two things run
#: out before the geometry does, both on the SMALLEST pane:
#:
#:   * `icon_radius()` derives from the band thickness, and it falls
#:     faster than the thickness does (there is a fixed chamfer clearance
#:     inside the derivation), so a 10% thinner band is a 16% smaller
#:     glyph: 23.5 px at twelve o'clock down to 13.6 at seven. This is a
#:     face whose icons he has already had shrunk once and then called
#:     "lost in that dust", and 13.6 is the number to watch if anyone
#:     pushes the ramp again.
#:   * the carbon tow lands at 6.2 px on the thinnest pane (100 px band /
#:     16 tows), against the ~6 px floor the soleil dial established. One
#:     more notch of radial ramp puts the weave he just approved under the
#:     resolution where it stops being a weave.
AUR_WEDGE_DEPTH_RAD = 0.80
#: ── AND IT IS ANCHORED TO THE CLOCK (2026-08-19, second pass) ──────────
#: Owner, having seen the first cut: "the tiles should start bigger at 12
#: o clock and get slightly smaller as it reaches 7 o clock."
#:
#: The first cut ramped by INDEX — pane 0 smallest, pane 6 largest — which
#: is a sweep with no anchor, and it happened to run the wrong way round
#: as well. The size is a function of BEARING now, so the effect is nailed
#: to the face rather than to the list, and it survives a pane being added
#: or the ring's start angle moving.
#:
#: These bearings are in the file's own screen convention: 0 is three
#: o'clock and the angle increases CLOCKWISE, because y runs down the
#: panel. So twelve o'clock is 270 and seven o'clock is 120 — which is
#: worth writing out, since 270 "looking like" nine o'clock is exactly the
#: sort of thing that gets silently corrected by the next reader.
#:
#: The two anchors are NOT opposite each other: 12 to 7 clockwise is 210
#: degrees and 7 back round to 12 is 150. A plain cosine of the bearing
#: would therefore put its minimum at six o'clock, not seven. So the two
#: arcs are travelled separately, each with its own smoothstep — and
#: BECAUSE smoothstep has zero slope at both ends, the two halves meet
#: with matching derivatives at 12 AND at 7 even though they cover
#: different amounts of arc. That is the whole reason for the shape: a
#: kink at either anchor reads as a defect rather than as depth, and the
#: 150-degree return arc is mostly the blank gap where nobody can see it
#: doing the work.
AUR_WEDGE_BIG_DEG = 270.0      # twelve o'clock — the largest pane
AUR_WEDGE_SMALL_DEG = 120.0    # seven o'clock — the smallest


def _aur_depth_at(deg: float) -> float:
    """The size weight at a screen bearing. 1+D at 12, 1-D at 7 o'clock."""
    d1 = (AUR_WEDGE_SMALL_DEG - AUR_WEDGE_BIG_DEG) % 360.0
    d2 = 360.0 - d1
    if d1 < 1e-6 or d2 < 1e-6:
        return 1.0
    t = (deg - AUR_WEDGE_BIG_DEG) % 360.0
    s = (t / d1) if t <= d1 else (1.0 - (t - d1) / d2)
    s = min(1.0, max(0.0, s))
    u = s * s * (3.0 - 2.0 * s)
    return 1.0 + AUR_WEDGE_DEPTH * (1.0 - 2.0 * u)


#: the converged per-pane weights, filled in by _aur_wedge_ring below.
AUR_WEDGE_W = [1.0] * 7


def _aur_depth_w(i: int, n: int = 7) -> float:
    """Pane i's size weight — read from the ring, not recomputed.

    One list, so the span the painter draws and the thickness
    `wedge_band(i)` returns cannot come from two different evaluations of
    a fixed point (§15).
    """
    try:
        return AUR_WEDGE_W[i]
    except Exception:                                   # noqa: BLE001
        return 1.0


def _aur_wedge_ring(n: int = 7):
    """The graduated ring, tiling EXACTLY the arc the even one did.

    ── THE RENORMALISATION IS THE WHOLE TRICK ──────────────────────────
    Varying the spans without it moves the last pane's end, which moves
    the blank gap, which moves the ribbon and the dismiss target — three
    things that read this geometry and would each drift by a different
    amount. So every pane's CELL (its span plus the gap that follows it)
    is scaled by its weight and the whole ring is then divided by K, the
    factor that puts the total back on the even ring's 234 degrees.

    A gap is scaled by the MEAN of the two panes it separates, because a
    gap belongs to both of them; scaling it by one neighbour makes the
    ring lopsided at the joins in a way that is visible and has no reason.

    K is computed rather than assumed. It was exactly 1.0 while the
    weights were an index ramp with mean 1; anchoring them to the clock
    makes it a real number, and the ring still closes on 148.000000
    degrees because this line is what puts it there.

    ── AND IT IS A FIXED POINT, SOLVED, NOT ASSUMED ────────────────────
    A pane's weight depends on where its centre is and its centre depends
    on every weight before it. Six passes; it converges to under 1e-9 in
    three, and the loop reports if it ever does not, because a silently
    unconverged ring is one that closes on the wrong degree.
    """
    def _build(ws):
        raw_span = [AUR_WEDGE_SPAN * w for w in ws]
        raw_gap = [AUR_WEDGE_GAP * (ws[i] + ws[i + 1]) / 2.0
                   for i in range(n - 1)]
        want = n * AUR_WEDGE_SPAN + (n - 1) * AUR_WEDGE_GAP
        k = want / max(1e-9, sum(raw_span) + sum(raw_gap))
        out = []
        a = AUR_WEDGE_A0
        for i in range(n):
            s = raw_span[i] * k
            out.append((a, a + s, AUR_WEDGE_COLS[i]))
            a += s + (raw_gap[i] * k if i < n - 1 else 0.0)
        return out

    ws = [1.0] * n
    out = _build(ws)
    #: 24, not 6. It converges geometrically and 6 passes left it at
    #: 2.7e-07 — which is harmless for the geometry and DID trip the
    #: "did not converge" line every import, and a warning that always
    #: fires is a warning nobody reads (§1, from the other end).
    for _ in range(24):
        nxt = [_aur_depth_at((a0 + a1) / 2.0) for a0, a1, _c in out]
        moved = max(abs(nxt[i] - ws[i]) for i in range(n))
        ws, out = nxt, _build(nxt)
        if moved < 1e-9:
            break
    else:
        print(f"aurora: wedge weights did not converge (last move "
              f"{moved:.2e}) — the ring still closes, the sizes are "
              f"approximate", flush=True)
    AUR_WEDGE_W[:] = ws
    return out


AUR_WEDGES = _aur_wedge_ring(len(AUR_PANES))
#: The keys the tap dispatch uses, in the same order. Kept beside the
#: geometry, because an order that disagrees between these two lists lights
#: one control and fires another.
#: ── THE RING IS A GRADIENT, NOT A SET (2026-08-17) ──────────────────────
#: Owner: "the wedges should have a more gradient of colors look. it's just
#: disarrayed right now, it should almost feel like a graduated step by step
#: color gradient yet elegant", and then: "reorder the wedges if, say, the
#: brighter red ones like mute have to be further down the chain of wedges."
#:
#: The panes were coloured one at a time, each for its own reason, and the
#: result reads exactly as he says — a set of seven decisions rather than
#: one object. What makes a row of controls look designed is that the eye
#: can follow it: a ring whose hue walks steadily around it is read as a
#: single thing with parts, and a ring of unrelated hues is read as parts.
#:
#: So two changes, and they only work together:
#:   * the palette is a RAMP, generated from one hue sweep rather than
#:     seven literals, so no pane can be individually "wrong" again
#:   * the order follows the ramp, coolest first, so the two hot panes
#:     (LOCK red, POWER amber) land at the END of the chain instead of
#:     interrupting the middle of it
#:
#: Temperature also carries meaning here, which is why the ramp runs the
#: way it does rather than the other: the panes get warmer as they get more
#: consequential. BRIEFING and VOLUME cost nothing; LOCK and POWER end the
#: session. A person reading the ring left to right is reading it in
#: increasing order of "are you sure".
#: SLEEP moved to position 2 (2026-08-17): the ramp runs blue -> violet ->
#: rose -> amber, so position 4 handed the moon a PINK tint. Colour on this
#: ring is meant to carry temperature, and a warm moon says the opposite of
#: what the pane does. Ordering is now semantic as well as chromatic: the
#: two quiet panes take the cool end, the two consequential ones the warm.
#: DERIVED, not restated (2026-08-19). This list is zipped against
#: `wedges()` slot for slot, so a menu reorder that missed it would send
#: every tap to the wrong control while the ring looked perfect — the
#: quietest possible §1 failure, on the pane that ends things.
AUR_WEDGE_KEYS = [_p[0] for _p in AUR_PANES]


def wedge_band(i: int = None):
    """(inner, outer) radius of the pane ring, for the face on the glass.

    Same contract as `wedges()`: one function, read by the sprite bake AND
    the hit-test, so a band that moves takes its touch target with it.

    ── AND WITH `i`, THE BAND OF ONE PANE (2026-08-19) ──────────────────
    The graduated ring gives each pane its own thickness. THE OUTER EDGE
    DOES NOT MOVE: the ring's silhouette against the black stays a true
    circle, which matters twice over — check_glass_margin already measured
    the furthest ink at r=540.1 against a 540 px glass, and a ring whose
    outer edge undulated would read as a wobble rather than as depth. The
    inner edge is what breathes.

    `i is None` answers for the ring as a whole — the MEAN band, which is
    exactly the pair this face has always used, so the wordmark, the
    ribbon and the hit-test are unchanged by this commit. That is not
    laziness in the hit-test's case: the mean inner radius less its 20-30
    px of finger slop still sits inside the innermost pane, so every pane
    keeps a touch target at least as generous as it had. A per-pane gate
    would make the THIN panes harder to hit, and a near-miss on a wedge is
    the "not responsive" complaint this file has already answered twice.
    """
    if not AURORA_BLOB:
        return (WEDGE_R0, WEDGE_R1)
    if i is None:
        return (AUR_WEDGE_R0, AUR_WEDGE_R1)
    m = 1.0 + AUR_WEDGE_DEPTH_RAD * (_aur_depth_w(i, len(AUR_WEDGES)) - 1.0)
    return (AUR_WEDGE_R1 - (AUR_WEDGE_R1 - AUR_WEDGE_R0) * m, AUR_WEDGE_R1)


def icon_radius(i: int = None):
    """The largest glyph the band can hold, DERIVED and never typed.

    1.22 is the widest reach any glyph in `_aur_icon` makes beyond its
    nominal radius (the bell's foot at 1.15, the padlock's body plus its
    keyhole at ~1.2); the stroke is r*0.17 and contributes half of that
    outward; 15 px is the pane's chamfer and 7 is the margin that keeps the
    arris of the glyph off the arris of the pane.

    Written as a calculation because the alternative — a constant tuned
    against today's band — is exactly how an icon ends up bleeding over an
    edge the next time a radius moves (§15).
    """
    r0, r1 = wedge_band(i)
    #: ── AND THEN 25% OFF (2026-08-17) ───────────────────────────────────
    #: Owner: "shrink the icons by 25% they are too clunky and hit the
    #: borders of the wedges." The derivation below is the largest glyph
    #: that FITS; fitting is not the same as sitting well, and a glyph that
    #: touches its chamfer on every side reads as crammed even when it is
    #: geometrically legal. 0.75 is the breathing room, applied once, here,
    #: so the "never bleed" guarantee and the "not clunky" judgement stay
    #: the same number rather than two that drift.
    usable = (r1 - r0) / 2.0 - 15.0 - 7.0
    #: 0.75 -> 0.64 (2026-08-17, second pass): "shrink the icons by 15%
    #: they are too big and clunky". Compounding his two judgements rather
    #: than replacing one with the other — he looked at 0.75 and asked for
    #: 15% off THAT, so 0.75 x 0.85.
    return max(12.0, usable / (1.22 + 0.085) * 0.64)


def wedges():
    """The pane geometry for the face that is actually on the glass.

    One function, called by both the menu painter and the hit-test, for the
    reason the band contract above spells out: if the ring moves, the tap
    moves with it in the same commit, or a wedge lights where nobody
    pressed.
    """
    return AUR_WEDGES if AURORA_BLOB else WEDGES


#: ── THE NAMES ARE A LIST OF THE SAME LENGTH (2026-08-26) ────────────────
#: draw_aurora_menu iterated `wedges()` and then subscripted `AUR_MENU[i]`
#: — aurora's SEVEN pane names, indexed by whatever ring is actually on the
#: glass. On aurora those are the same list and it was invisible; on any
#: other face it is the 2026-08-17 defect in the compositor with the
#: operands swapped ("SLEEP and POWER were tappable and never drawn,
#: because len(WEDGES) and len(wedges()) disagreed"). A length mismatch
#: here does not raise: it hands one pane another pane's identity, which
#: is a silent success (§1) with a name on it.
#:
#: So the names answer per face exactly the way the geometry does, and the
#: two are checked against each other at the one place that reads them.
WEDGE_NAMES = tuple(_TILES.get("wedge_names") or ())


def pane_names():
    """The name per pane, for the face on the glass — same length as
    `wedges()`, and that is the property, not a coincidence.

    Empty is a legitimate answer: a face that never draws a relief pane
    never needs one, and inventing a default here would be a value that
    agrees with its fallback (§15's corollary) — indistinguishable, on the
    glass, from a theme that stated its names correctly.
    """
    return AUR_MENU if AURORA_BLOB else WEDGE_NAMES


if RELIEF_PANES and len(WEDGE_NAMES) != len(WEDGES):
    print(f"relief: theme {FACE_THEME!r} asks for relief panes but its "
          f"tiles name {len(WEDGE_NAMES)} of {len(WEDGES)} wedges — the "
          f"ring stands down to flat tiles rather than drawing panes under "
          f"the wrong names", flush=True)
    RELIEF_PANES = False
#: The two live PANELS (requests / patients) keep the band's outer edge but
#: reach 34px further inboard. 2026-08-07: going back to arcs (the octagon
#: their straight edges were seated against is retired) cost the patients
#: list ~15px of row height and three type-fitter floors; the height comes
#: back from the inside, where the circular dial actually has room — the
#: wordmark tops out near y=320 and these panels live at the upper left.
PANEL_R0 = WEDGE_R0 - 34.0
#: 2026-08-07 14:49, "go all in with the blue": the two live panels' FILLS
#: pull to the dial's own navy — measured, a slate or gold fill at the
#: 0.14 weight reads as gray glass on the blue ground — while the state
#: colour stays on the border and the type, which is where it is read.
#: home.html's baked wedges take the same fill (#2a3f66) in this commit.
#: 2026-08-08: ON THE THEME (_TILES["panel_fill"]). This wash is composited
#: after desertify() at alpha 36, and the navy screens to (5,8,14) — R-B -9,
#: which is arithmetically the -8 the bearing scan found in the live slot.
#: The duotone cannot reach it, so each theme names its own dial ground here.
PANEL_FILL = _TILES["panel_fill"]
#: The tiles' two row inks, likewise after the colourway: a cool white on a
#: rose ground is the same leftover, one row of type at a time.
ROW_INK_LABEL, ROW_INK_BODY = _TILES["row_ink"]
WEDGE_STAGGER_S = 0.75
WEDGE_FADE_S = 0.9
WEDGE_THROB_S = 1.5
#: home.html MENU keys, same order as WEDGES — the tour handshake names
#: the wedge being described and we throb its border while Olga speaks.
WEDGE_KEYS = ["meetings", "sterling", "lock", "settings", "volume"]
WEDGE_TOUR = Path("/tmp/aura_face/wedge_tour.json")

#: Face-the-speaker (owner, 2026-08-01: "have the screen rotate to the
#: direction of the speaker using our powerful mic for beam direction
#: finding ... that way the text is correctly oriented"). The RTX ferries
#: the mic array's bearing into face_doa.json; we glide the dial toward
#: it — never fighting a finger, never snapping. The mapping from mic
#: bearing to display rotation depends on how both sit in the room:
#: DJ_DOA_OFFSET (degrees) and DJ_DOA_SIGN (1/-1) calibrate it live
#: without a code change.
FACE_DOA = Path("/tmp/aura_face/face_doa.json")
DOA_OFFSET = float(os.environ.get("DJ_DOA_OFFSET", "0"))
DOA_SIGN = float(os.environ.get("DJ_DOA_SIGN", "1"))
DOA_GLIDE_DPS = 26.0        # slow and dignified: a coarse bearing
                            # should look like a considered turn, never a
                            # twitch (2026-08-02, coarse mode)
DOA_FRESH_S = 15.0
def _doa_enabled() -> bool:
    try:
        return bool(json.loads(FACE_DOA.read_text()).get("enabled", True))
    except Exception:
        return True


_DOA_ENABLED = True         # RESURRECTED 2026-08-02: the sensor was
                            # fine, we read the wrong register. Coarse
                            # mode — see the quadrant snap below.
_DOA_STATE = {"at": 0.0, "tgt": None}
#: The ceremony's ONE orientation decision (owner, 2026-08-02 morning):
#: snap to the speaker as login.json appears, then hold absolutely still.
#: The window is wider than DOA_FRESH_S because the bearing that matters
#: was measured when the person spoke their name — several seconds before
#: the conductor finishes deciding who they are and writes the file.
LOGIN_SNAP_FRESH_S = 30.0
_LOGIN_SNAP = {"seen": False}


#: Enrollment interest carousel (owner, 2026-08-01: "do some sort of cool
#: graphics that raise a flash about what they're interested in ...
#: international markets, crypto, medicine"). While the conductor holds
#: the flag, category cards cycle over the lock-screen starfield — they
#: double as conversation fuel for the voice-print chat, since Olga has
#: just asked what the newcomer wants out of their briefing.
ENROLL_CATS = Path("/tmp/aura_face/enroll_cats")
#: Five broad defaults plus OTHER (owner: "at least 5 default ones that
#: are broad in scope ... and other").
CATS = [("MEDICINE", (53, 208, 127)),
        ("INTERNATIONAL AFFAIRS", (56, 200, 255)),
        ("CRYPTO", (255, 176, 46)),
        ("FINANCIAL MARKETS", (143, 163, 192)),
        ("TECH & AI", (123, 92, 255)),
        ("SOMETHING ELSE — JUST SAY IT", (224, 85, 154))]


#: A soft radial glow, built once and tinted per category. Cheap: one
#: L-mode gradient, a point() per channel, screened on.
_CAT_GLOW = None


def _cat_glow() -> Image.Image:
    global _CAT_GLOW
    if _CAT_GLOW is None:
        r = 300
        g = Image.new("L", (r * 2, r * 2), 0)
        d = ImageDraw.Draw(g)
        for i in range(r, 0, -6):
            v = int(150 * (1.0 - i / r) ** 2.2)
            d.ellipse([r - i, r - i, r + i, r + i], fill=v)
        _CAT_GLOW = g.filter(ImageFilter.GaussianBlur(26))
    return _CAT_GLOW


def _cat_icon(d: ImageDraw.ImageDraw, kind: str, cx: float, cy: float,
              r: float, col, a: float) -> None:
    """One bright picture per category, drawn as vector art.

    THE OWNER'S BRIEF, VERBATIM: "more pictures, people are dumb, they like
    bright pictures, they don't like to read." He is right about the room
    this thing lives in — somebody walking past a puck reads a SHAPE at four
    metres and a word at one.

    Vector rather than bitmap on purpose: these have to tint to each
    category's colour, scale with the layout, and survive being drawn at
    10fps on an Orin alongside everything else. Six recipes, a few strokes
    each, no assets to push and nothing to go stale.
    """
    ink = tuple(int(v * (0.35 + 0.65 * a)) for v in col)
    hot = tuple(min(255, int(v * (0.5 + 0.5 * a)) + 60) for v in col)
    w = max(3, int(r * 0.10))
    if kind == "MEDICINE":
        # a heartbeat crossing a soft cross
        d.line([cx - r, cy, cx - r * .35, cy], fill=ink, width=w)
        d.line([(cx - r * .35, cy), (cx - r * .12, cy - r * .62),
                (cx + r * .10, cy + r * .55), (cx + r * .32, cy)],
               fill=hot, width=w, joint="curve")
        d.line([cx + r * .32, cy, cx + r, cy], fill=ink, width=w)
    elif kind.startswith("INTERNATIONAL"):
        # a globe: rim, equator, two meridians
        d.ellipse([cx - r, cy - r, cx + r, cy + r], outline=ink, width=w)
        d.line([cx - r, cy, cx + r, cy], fill=ink, width=max(2, w - 1))
        for f in (0.42, 0.82):
            d.ellipse([cx - r * f, cy - r, cx + r * f, cy + r],
                      outline=hot if f < 0.5 else ink, width=max(2, w - 1))
    elif kind == "CRYPTO":
        # a coin with a bolt through it
        d.ellipse([cx - r, cy - r, cx + r, cy + r], outline=ink, width=w)
        d.line([(cx + r * .18, cy - r * .62), (cx - r * .16, cy + r * .04),
                (cx + r * .10, cy + r * .04), (cx - r * .20, cy + r * .64)],
               fill=hot, width=w, joint="curve")
    elif kind.startswith("FINANCIAL"):
        # candlesticks, rising
        for i, (h, y0) in enumerate(((0.42, 0.30), (0.66, 0.02),
                                     (0.34, -0.24), (0.78, -0.48))):
            x = cx - r * .72 + i * r * .48
            top = cy + r * y0 - r * h / 2
            bot = cy + r * y0 + r * h / 2
            d.line([x, top - r * .16, x, bot + r * .16], fill=ink,
                   width=max(2, w - 2))
            d.rectangle([x - r * .13, top, x + r * .13, bot],
                        fill=hot if i % 2 else None, outline=hot, width=w - 1)
    elif kind.startswith("TECH"):
        # a chip with legs
        s_ = r * .58
        d.rounded_rectangle([cx - s_, cy - s_, cx + s_, cy + s_],
                            radius=r * .16, outline=ink, width=w)
        d.rounded_rectangle([cx - s_ * .42, cy - s_ * .42,
                             cx + s_ * .42, cy + s_ * .42],
                            radius=r * .06, outline=hot, width=max(2, w - 1))
        for i in range(-1, 2):
            o = i * s_ * .62
            d.line([cx + o, cy - s_, cx + o, cy - r], fill=ink, width=w - 1)
            d.line([cx + o, cy + s_, cx + o, cy + r], fill=ink, width=w - 1)
            d.line([cx - s_, cy + o, cx - r, cy + o], fill=ink, width=w - 1)
            d.line([cx + s_, cy + o, cx + r, cy + o], fill=ink, width=w - 1)
    else:
        # SOMETHING ELSE — a spark
        for ang in range(0, 360, 45):
            t = math.radians(ang)
            f = 1.0 if ang % 90 == 0 else 0.60
            d.line([cx + r * .18 * math.cos(t), cy + r * .18 * math.sin(t),
                    cx + r * f * math.cos(t), cy + r * f * math.sin(t)],
                   fill=hot if ang % 90 == 0 else ink, width=w)
        d.ellipse([cx - r * .16, cy - r * .16, cx + r * .16, cy + r * .16],
                  fill=hot)


def _fit_cat(d: ImageDraw.ImageDraw, label: str, track: float,
             budget: float):
    """Largest size from the ramp that keeps the label inside `budget`.

    INTERNATIONAL AFFAIRS at 46px ran 640px wide and straight through the
    POWER and LOCK buttons either side. A carousel whose longest entry
    collides with the furniture is not a carousel, it is a bug with a fade.
    """
    for size in (46, 42, 38, 34, 30):
        f = face("text", size)
        w = track_len(d, label, f, track)
        if w <= budget:
            return f, w
    return f, w


def draw_cats(frame: Image.Image, now: float) -> Image.Image:
    """The briefing categories, turning — a picture, a word, and your place
    in the list.

    WAS: one word fading in and out with an arc behind it. The owner, twice:
    "make the whole carousel sexier, it's just rotating text now, more
    graphics or something" and then "more pictures, people are dumb, they
    like bright pictures, they don't like to read."

    So each category now leads with a SHAPE in its own colour, sitting in a
    glow of that colour; the word rises into place beneath it and sinks out
    rather than blinking; and a row of dots shows there are six of these and
    which one is live — the one thing the voice cannot convey while it asks.
    """
    period = 2.8
    idx = int(now / period) % len(CATS)
    ph = (now % period) / period
    label, col = CATS[idx]
    # Quick in, long hold, quick out. The hold is what makes it readable and
    # the old symmetric fade never had one.
    a = min(1.0, ph * 5.0, (1.0 - ph) * 5.0)
    a = a * a * (3 - 2 * a)                      # smoothstep
    cx = cy = SIZE // 2
    icon_y = cy + 168
    word_y = cy + 268

    # -- the glow, in the category's colour ---------------------------
    gl = _cat_glow()
    k = 0.30 + 0.70 * a
    tint = Image.merge("RGB", [gl.point(lambda p, c=c: int(p * c / 255.0 * k))
                               for c in col])
    box = (cx - 300, icon_y - 300, cx + 300, icon_y + 300)
    frame.paste(ImageChops.screen(frame.crop(box), tint), (box[0], box[1]))

    d = ImageDraw.Draw(frame)
    f_cap = face("label", 26)
    cap = "WHAT SHOULD I WATCH FOR YOU?"
    cw = track_len(d, cap, f_cap, 6.0)
    track_text(d, ((SIZE - cw) / 2, cy + 74), cap, f_cap, (150, 165, 190), 6.0)

    # -- the picture ----------------------------------------------------
    _cat_icon(d, label, cx, icon_y - 6 * (1.0 - a), 62, col, a)

    # -- the word, rising and sinking ------------------------------------
    # Budget: clear of the POWER button (right edge 250) and the LOCK wedge.
    f_cat, lw = _fit_cat(d, label, 3.0, 600.0)
    rise = int(18 * (1.0 - a))
    ink = tuple(int(60 + (v - 60) * a) for v in (238, 246, 255))
    track_text(d, ((SIZE - lw) / 2, word_y + rise), label, f_cat, ink, 3.0)

    # -- where you are in the list --------------------------------------
    # A STRAIGHT ROW, ABOVE THE PICTURE, INSIDE THE WEDGE RING.
    # On the arc at r=400 they landed ON the VOLUME and SETTINGS wedges —
    # the ring starts at r=336 and the bottom of the disc is wedge, so there
    # is no room out there. Between the caption and the icon there is.
    n = len(CATS)
    gap = 26
    x0 = cx - gap * (n - 1) / 2.0
    for i in range(n):
        dx = x0 + i * gap
        # Below the WORD, not above the picture: at cy+118 they landed
        # inside the icon's own box. r=332 here, just inside the wedge
        # ring's 336 inner edge, which is the only clear band left.
        dy = cy + 332
        if i == idx:
            rr = 5 + 4 * a
            fill = tuple(int(v * (0.45 + 0.55 * a)) for v in col)
        else:
            rr, fill = 3.5, (86, 100, 122)
        d.ellipse([dx - rr, dy - rr, dx + rr, dy + rr], fill=fill)
    return frame


#: Enrollment stage captions (owner, 2026-08-02 morning). The conductor
#: writes one bare word here — name / interest / learning — and removes
#: the file when the stage is over; absence means no caption. It says on
#: the glass what Olga is asking for by voice, so a newcomer who missed
#: the question (or is standing across a loud room) can still answer.
#: The file may appear or vanish at any frame, so this is stat-cached by
#: mtime: one stat per frame, a read only when it actually changed.
ENROLL_STAGE = Path("/tmp/aura_face/enroll_stage")
ENROLL_CAPTIONS = {
    "name": "TELL ME YOUR FIRST NAME",
    "interest": "WHAT INTERESTS YOU?",
    "learning": "LEARNING YOUR VOICE — KEEP CHATTING",
}
_ENROLL_STAGE_CACHE = {"mtime": None, "text": None}


def _enroll_stage():
    """The current stage word, or None. Cheap enough for every frame."""
    try:
        m = ENROLL_STAGE.stat().st_mtime
    except (FileNotFoundError, NotADirectoryError):
        _ENROLL_STAGE_CACHE["mtime"] = None
        _ENROLL_STAGE_CACHE["text"] = None
        return None
    if _ENROLL_STAGE_CACHE["mtime"] != m:
        _ENROLL_STAGE_CACHE["mtime"] = m
        try:
            word = ENROLL_STAGE.read_text().strip().lower()
        except Exception:
            word = ""
        # An unknown word is NOT silently dropped (PRINCIPLES §1): the
        # conductor is the only writer, so a value we don't recognise
        # means the two sides disagree and someone needs to see it.
        if word and word not in ENROLL_CAPTIONS:
            print(f"enroll: unknown stage {word!r}", flush=True)
        _ENROLL_STAGE_CACHE["text"] = ENROLL_CAPTIONS.get(word)
    return _ENROLL_STAGE_CACHE["text"]


#: Written by puck_ears.Identity._publish on every sample, refusal and
#: promotion. See that docstring: the ears decide the phase, the face only
#: renders it, so there is never a second opinion about how it is going.
ENROLL_STATE = Path("/tmp/aura_face/enroll.json")
ENROLL_FRESH_S = 25.0
_ENROLL_ST = {"mtime": None, "data": None}
#: Ring geometry. Just inside the glass, clear of the wordmark at y=460.
#: x DIAL_K, 2026-08-06 night: 494 is now 65px UNDER the bezel's metal, so
#: the ring — and the thinking sweep that shares its circle — would have
#: run round behind solid steel. The one thing on this glass whose whole
#: job is to be noticed, invisible (§1).
ENROLL_R = round(494 * DIAL_K)
ENROLL_W = round(9 * DIAL_K)


def _enroll_state(now: float):
    """The ears' view of the enrolment, or None when nothing is running."""
    try:
        m = ENROLL_STATE.stat().st_mtime
    except (FileNotFoundError, NotADirectoryError):
        _ENROLL_ST["mtime"] = _ENROLL_ST["data"] = None
        return None
    if _ENROLL_ST["mtime"] != m:
        _ENROLL_ST["mtime"] = m
        try:
            _ENROLL_ST["data"] = json.loads(ENROLL_STATE.read_text())
        except Exception:
            _ENROLL_ST["data"] = None          # half-written; next tick
    d = _ENROLL_ST["data"]
    if not d or now - float(d.get("at", 0)) > ENROLL_FRESH_S:
        return None
    #: ── 2026-08-12: THE RING HE HAS REPORTED ELEVEN TIMES ────────────────
    #: This is "the inner circle", and it was never a renderer bug. Owner,
    #: this morning, on the eleventh report: "i don't think you have ever
    #: identified the root cause?" He was right. Three sessions measured gear
    #: wheels, bezel arcs, pocket rims and contact shadows — all real objects,
    #: none of them this one.
    #:
    #: WHAT IT IS. ENROLL_R is round(494 * DIAL_K) = 459, and the ring he
    #: photographs measures 440-475 with its mass at 454.6 — a closed copper
    #: circle, because draw_enroll_ring paints the UNFILLED TRACK all the way
    #: round "so the ring reads as a gauge rather than as a stray arc". 459 is
    #: inside the wedge ring (369.6..499.2), so the gauge lands straight
    #: across BRIEFING, STERLING, LOCK, VOLUME and SETTINGS. It is a working
    #: indicator doing exactly what it was built to do.
    #:
    #: WHY IT IS ALWAYS THERE. It fires for PASSIVE GUEST SAMPLING, not just
    #: for a real enrolment. Measured on his puck: 39 enrolment events in 30
    #: minutes, guest18 -> guest21 -> guest22 inside two minutes, every one
    #: with "name": null. Short clips cannot be matched (his own print scores
    #: 0.198-0.279 on a two-word greeting against a 0.30 threshold — the open
    #: item from 08-11), so every unrecognised utterance opens a new guest
    #: session and repaints the gauge over his menu.
    #:
    #: A NAMED ENROLMENT IS A CEREMONY AND HAS A RING. Background print
    #: collection is housekeeping and does not: nobody needs a progress gauge
    #: for a job they did not ask for and cannot finish. `name` is exactly the
    #: discriminator — the ceremony sets it, guest sampling leaves it null.
    #:
    #: This does NOT fix the ears. They are still opening a guest session per
    #: utterance and that is the real defect; it is in FAILURES and it touches
    #: voice unlock, so it is the owner's call. This stops the housekeeping
    #: from drawing on his dial while he decides.
    #:
    #: ── ...AND IT TOOK THE CEREMONY'S FIRST HALF WITH IT (2026-08-20) ────
    #: `name` is set by the ceremony — but only once the ceremony HAS the
    #: name. From "hi Aura" through the question, the answer, the re-ask and
    #: the bow-out, every publish carries "name": null, so this line
    #: suppressed the ring for the entire twenty seconds it was written to
    #: cover. draw_enroll_ring's own docstring is the complaint: "the device
    #: asks, you answer, and then NOTHING happens visibly for twenty seconds
    #: ... a working device and a crashed one must not look the same."
    #:
    #: The discriminator was never `name`, it was WHETHER A CEREMONY IS
    #: HAPPENING, and that fact is already on disk with an end condition the
    #: room cannot veto (`_ceremony_live`). Passive guest sampling raises no
    #: AWAITING_NAME, so the 39-events-in-30-minutes housekeeping that this
    #: gate exists to keep off his dial is still silent; a ceremony somebody
    #: is actually standing in front of gets its gauge back.
    if not d.get("name") and not _ceremony_live(now):
        return None
    return d


def _enroll_ring_state(now: float):
    """What the progress ring should draw, or None.

    The ears' own state when they have published one — and a bare WAITING
    when the ceremony is live but nothing has been collected yet. That gap
    is real and it is the worst part of the twenty seconds: she asks, the
    person draws breath, and until the first sample lands there is no
    enroll.json at all. Drawing nothing there is drawing a crashed device.
    """
    st = _enroll_state(now)
    if st is not None:
        return st
    return {"phase": "waiting"} if _ceremony_live(now) else None


#: Written by puck_ears at the ENDPOINT, before ASR — see _pulse there.
PULSE_STATE = Path("/tmp/aura_face/pulse.json")
#: Belt and braces on top of the explicit "idle": if the ears die mid-thought
#: the sweep must stop by itself rather than spin forever, which is its own
#: kind of lie about what the device is doing.
PULSE_FRESH_S = 12.0
_PULSE = {"mtime": None, "data": None}


def _pulse_phase(now: float):
    """The ears' fresh phase — "hearing" or "thinking" — or None.

    Split out of _pulse_active (2026-08-08) for the bezel's listening
    indicator, which needs the WORD and not just the fact: the bloom and
    the comet are different states, not intensities of one.
    """
    try:
        m = PULSE_STATE.stat().st_mtime
    except (FileNotFoundError, NotADirectoryError):
        _PULSE["mtime"] = _PULSE["data"] = None
        return None
    if _PULSE["mtime"] != m:
        _PULSE["mtime"] = m
        try:
            _PULSE["data"] = json.loads(PULSE_STATE.read_text())
        except Exception:
            _PULSE["data"] = None
    d = _PULSE["data"]
    # "hearing" too, not just "thinking": the sweep should start the moment
    # she detects the voice, not when the person has already stopped. It is
    # the same fact — she is engaged with what you are saying — and showing
    # it live is the difference between a device that listens and one that
    # reacts a beat late.
    if (d and d.get("phase") in ("hearing", "thinking")
            and now - float(d.get("at", 0)) < PULSE_FRESH_S):
        return d.get("phase")
    return None


def _pulse_active(now: float) -> bool:
    """True while the ears are working on something they just heard."""
    return _pulse_phase(now) is not None


def draw_thinking_sweep(frame: Image.Image, now: float) -> None:
    """An indeterminate sweep on the enrolment ring's own circle.

    WHY IT IS NOT A PROGRESS BAR. Nothing here knows how long the ASR will
    take — ~1.7s typically on this puck, longer under load — and a bar that
    guesses is worse than none, because it stalls at 90%. This says only
    "heard you, working", which is the honest claim and the one that stops a
    person repeating themselves into a device that is already busy.

    It shares the ring's radius deliberately: during a ceremony that same
    circle then fills with real progress, so the two read as one object
    doing two things rather than as two indicators competing (§7, in pixels).

    ── 2026-08-06: THE LOCK SCREEN ONLY ──────────────────────────────────
    The home face no longer calls this — see the note at its call site, and
    TOURB_R. It is kept, unchanged, for the lock screen, which has neither a
    bezel to light nor a cage to turn: there the ring is still the only
    thing that says she heard you, and the paragraph above is still why it
    looks the way it does.
    """
    d = ImageDraw.Draw(frame, "RGBA")
    box = [SIZE // 2 - ENROLL_R, SIZE // 2 - ENROLL_R,
           SIZE // 2 + ENROLL_R, SIZE // 2 + ENROLL_R]
    head = (now * 150.0) % 360.0          # 2.4s a lap: unhurried, not frantic
    # A comet-tail arc: bright head fading backwards, so the direction of
    # travel is obvious at a glance and it never reads as a static gap.
    # Brighter and heavier than the gauge on purpose. This is the one thing
    # on the glass whose entire job is to be noticed within a second, by
    # somebody who is not looking for it and is standing off to one side —
    # and the wordmark's three failed sizes are the lesson that a measured
    # luminance is not the same as legible at the owner's angle.
    for i in range(18):
        a1 = head - i * 4.0
        alpha = int(255 * (1.0 - i / 18.0) ** 1.5)
        if alpha <= 3:
            break
        d.arc(box, a1 - 4.4, a1, fill=(90, 190, 255, alpha), width=ENROLL_W + 3)
    # A hot core at the head, the comets' own trick: the brightest thing
    # being a line-end reads as an artefact, a bright point reads as motion.
    a = math.radians(head)
    hx = SIZE / 2 + ENROLL_R * math.cos(a)
    hy = SIZE / 2 + ENROLL_R * math.sin(a)
    d.ellipse([hx - 10, hy - 10, hx + 10, hy + 10], fill=(215, 240, 255, 255))


#: Written by puck_conduct when a briefing starts playing: the topic and the
#: real headlines behind it.
BRIEFING_CARD = Path("/tmp/aura_face/briefing.json")
BRIEFING_FRESH_S = 240.0
_BRIEF = {"mtime": None, "data": None}


def _briefing_card(now: float):
    try:
        m = BRIEFING_CARD.stat().st_mtime
    except (FileNotFoundError, NotADirectoryError):
        _BRIEF["mtime"] = _BRIEF["data"] = None
        return None
    if _BRIEF["mtime"] != m:
        _BRIEF["mtime"] = m
        try:
            _BRIEF["data"] = json.loads(BRIEFING_CARD.read_text())
        except Exception:
            _BRIEF["data"] = None
    d = _BRIEF["data"]
    if not d or now - float(d.get("at", 0)) > BRIEFING_FRESH_S:
        return None
    return d


#: ── The markets strip: the one thing only finance gets ────────────────
#: Owner, live: a widget "exclusive to finance". Every topic draws the same
#: card — icon, word, five headlines — and finance is the topic where the
#: CLOCK changes what the words mean: "the S&P closed at 7,490" is last
#: night's news at 07:00 and a ninety-minute-old session at 11:00. So the
#: finance card, and only the finance card, carries the state of the New
#: York session under its headlines.
#:
#: IT IS A CALENDAR, NOT A FEED. Regular hours and weekends only — it does
#: not know market holidays, so on Thanksgiving it counts down to an open
#: that never comes. Hence it says SESSION, and it never prints a price:
#: a made-up tape on a glass people trust is exactly the silent success
#: §1 exists to prevent. Only the times are claimed, and those are real.
MARKET_TZ = "America/New_York"
MARKET_OPEN_HM = (9, 30)
MARKET_CLOSE_HM = (16, 0)
MARKET_INK = (143, 163, 192)      # the FINANCIAL MARKETS carousel colour
MARKET_OPEN_INK = (120, 240, 170)
MARKET_SHUT_INK = (214, 150, 120)
_MARKET_WARNED: list = []


def _hm_left(mins: float) -> str:
    m = max(0, int(mins))
    return f"{m // 60}H {m % 60:02d}M" if m >= 60 else f"{m}M"


def _market_session(now: float):
    """(state, detail, ink) for the strip, or None if this puck cannot
    resolve New York time. None is DRAWN as a decline by the caller, never
    swallowed — a strip that quietly vanishes is indistinguishable from a
    deploy that never landed."""
    try:
        import datetime as dt
        from zoneinfo import ZoneInfo
        ny = dt.datetime.fromtimestamp(now, ZoneInfo(MARKET_TZ))
    except Exception as e:
        if not _MARKET_WARNED:
            _MARKET_WARNED.append(True)
            print(f"markets strip: no {MARKET_TZ} on this puck: {e!r}",
                  flush=True)
        return None
    op = ny.replace(hour=MARKET_OPEN_HM[0], minute=MARKET_OPEN_HM[1],
                    second=0, microsecond=0)
    cl = ny.replace(hour=MARKET_CLOSE_HM[0], minute=MARKET_CLOSE_HM[1],
                    second=0, microsecond=0)
    if ny.weekday() < 5 and op.timestamp() <= now < cl.timestamp():
        return ("OPEN", f"{_hm_left((cl.timestamp() - now) / 60.0)} "
                        f"TO THE CLOSE", MARKET_OPEN_INK)
    # Next open. Adding days to an aware datetime keeps the WALL clock at
    # 09:30 and .timestamp() resolves the real instant, so this stays
    # correct across a DST weekend (§6 — the units that actually apply).
    nxt = op
    while nxt.timestamp() <= now or nxt.weekday() >= 5:
        nxt += dt.timedelta(days=1)
    when = "" if nxt.date() == ny.date() else nxt.strftime("%a").upper() + " "
    return ("CLOSED", f"OPENS {when}{nxt.strftime('%H:%M')} NY",
            MARKET_SHUT_INK)


def draw_markets_strip(d: ImageDraw.ImageDraw, now: float) -> None:
    """The New York session, under the finance headlines.

    Sits at y≈898..962: below where five two-row headlines can reach
    (y≈872 at worst) and inside the disc's chord down there (~660px of
    usable width at y=966, against ~430px of type at the longest).
    """
    cx = SIZE // 2
    f_lab = face("label", 22)
    lab = "NYSE SESSION"
    lw = track_len(d, lab, f_lab, 7.0)
    track_text(d, (cx - lw / 2, 898), lab, f_lab, MARKET_INK + (200,), 7.0)
    st = _market_session(now)
    if st is None:
        f = face("text", 26)
        draw_tracked(d, cx, 930, "CLOCK UNSET", f, MARKET_INK + (215,), 2.0)
        return
    state, detail, ink = st
    f_st, f_de = face("bold", 28), face("text", 26)
    gap, dot = 14.0, 9.0
    sw = track_len(d, state, f_st, 3.0)
    dw = track_len(d, detail, f_de, 1.0)
    x = cx - (dot * 2 + gap + sw + gap + dw) / 2
    d.ellipse([x, 944 - dot, x + dot * 2, 944 + dot], fill=ink + (235,))
    x += dot * 2 + gap
    track_text(d, (x, 930), state, f_st, ink + (255,), 3.0)
    x += sw + gap
    track_text(d, (x, 932), detail, f_de, (214, 226, 240, 225), 1.0)


def draw_briefing(frame: Image.Image, card: dict, now: float) -> Image.Image:
    """The headlines she is reading, on the glass.

    The owner, on the first briefing: "which has no graphics". A voice
    reading six headlines against a starfield is a radio — and the headlines
    are the one part worth SEEING, because you can skim five of them faster
    than she can say one.

    They arrive one at a time, roughly in step with a spoken sentence, so
    the screen stays a beat ahead of the voice rather than dumping a wall of
    text. Topic colour and icon are the carousel's, so the thing you chose
    and the thing you are being read are visibly the same object.
    """
    topic = card.get("topic") or "SOMETHING ELSE"
    lines = [str(x) for x in (card.get("lines") or [])][:5]
    if not lines:
        return frame
    col = next((c for t, c in CATS if t == topic), (56, 200, 255))
    age = now - float(card.get("at", now))

    # ── THE DIAL GETS OUT OF THE WAY, 2026-08-10 ────────────────────────
    # Owner: "the briefing is now overshadowed by 2 complications, the
    # center turbillion also overlaps the briefing." At 0.30 the dial was
    # dimmed but entirely present — two subdials and a moving centrepiece
    # sitting behind six lines of text, all competing for the same eye. A
    # dim is not an occlusion, and the brighter the dial got tonight (the
    # anodised caps, the raised captions, the RTX centre) the worse this
    # read, because every one of those passes made the thing underneath
    # harder to ignore.
    #
    # So: dimmer still, and then a real scrim disc over the dial. The
    # headlines are the content; everything else is a background.
    frame = frame.point(lambda p: int(p * 0.13))
    _scrim = Image.new("RGBA", (SIZE, SIZE), (0, 0, 0, 0))
    ImageDraw.Draw(_scrim).ellipse(
        [SIZE / 2 - 527, SIZE / 2 - 527, SIZE / 2 + 527, SIZE / 2 + 527],
        fill=(4, 5, 9, 208))
    frame = Image.alpha_composite(frame.convert("RGBA"),
                                  _scrim).convert("RGB")
    # ── THE HEADLINES TURN WITH THE WORDMARK (2026-08-11) ────────────────
    # Owner: "still not orienting the scrolling of topics with auravision."
    # Confirmed off a framebuffer grab — AURAVISION running vertically while
    # the headline block sat horizontal, ninety degrees apart.
    #
    # Both are drawn BEFORE the dial rotate, so both turn with the face.
    # The difference is that draw_wordmark then applies _doa_angle on top,
    # turning the brand to face whoever is speaking, and this card did not —
    # so the moment the room's bearing moved, the two most readable things
    # on the glass pointed different ways.
    #
    # This is the same defect the JUST-SAY-HI-AURA hint had (see HINT_TEXT):
    # "anything that must stay level with the wordmark has to be drawn where
    # the wordmark is drawn". The hint was fixed by moving it INTO
    # draw_wordmark; the headline card is far too big for that, so it takes
    # the other half of the same rule and applies the bearing itself.
    #
    # READ, NEVER ADVANCED — _wheel_bearing's rule, and for the same reason.
    # _doa_angle() integrates its easing on every call, so calling it here
    # as well as in draw_wordmark would ease twice per frame and the text
    # would arrive somewhere the brand is still travelling toward.
    _bearing = _DOA["now"] if _DOA_CAL.get("on") else 0.0
    # Content goes on its own layer so it can turn as one block. The dim and
    # the scrim stay on the frame: a disc is the same disc at every angle,
    # and rotating it would only cost a resample.
    _card_ov = Image.new("RGBA", (SIZE, SIZE), (0, 0, 0, 0))
    d = ImageDraw.Draw(_card_ov, "RGBA")
    cx = SIZE // 2

    # the topic, with its own icon, small and at the top
    _cat_icon(d, topic, cx, 232, 34, col, 1.0)
    f_top = face("label", 24)
    tw = track_len(d, topic, f_top, 6.0)
    track_text(d, (cx - tw / 2, 288), topic, f_top,
               tuple(min(255, v + 40) for v in col), 6.0)

    # the headlines, revealed one every REVEAL_S
    REVEAL_S = 3.2
    f_h = face("text", 30)
    y = 356
    for i, h in enumerate(lines):
        t_in = (age - i * REVEAL_S) / 0.6
        if t_in <= 0:
            break
        a = min(1.0, t_in)
        ink = tuple(int(40 + (v - 40) * a) for v in (232, 240, 250))
        # wrap to the disc: 640px is the widest chord that clears the rim
        words, line, rows = h.split(), "", []
        for w in words:
            probe = (line + " " + w).strip()
            if d.textlength(probe, font=f_h) > 640 and line:
                rows.append(line)
                line = w
            else:
                line = probe
        rows.append(line)
        for r in rows[:2]:
            rw = d.textlength(r, font=f_h)
            d.text((cx - rw / 2, y), r, font=f_h, fill=ink)
            y += 38
        # a rule in the topic colour under each item, drawn as it lands
        d.line([cx - 150 * a, y + 6, cx + 150 * a, y + 6],
               fill=col + (int(120 * a),), width=2)
        y += 26
        if y > 900:
            break
    # The one element no other topic gets. Same test the icon uses, so a
    # card that draws the candlesticks also draws the session.
    if topic.startswith("FINANCIAL"):
        draw_markets_strip(d, now)
    # ── THE WAY OUT, DRAWN (2026-08-10) ─────────────────────────────────
    # Owner: "it's impossible to exit right now." It was not — any tap
    # dismisses this card — but nothing on the glass SAID so, and a screen
    # with no visible exit is a screen you are trapped on whatever the
    # code does. Volume and the settings book both carry a DONE ring for
    # exactly this reason; the briefing was the one full-glass mode
    # without one, which is why it is the one that read as stuck.
    _bx, _by = SIZE // 2, 962
    d.ellipse([_bx - 74, _by - 34, _bx + 74, _by + 34],
              outline=(214, 222, 236, 190), width=2)
    _f = face("label", 21)
    _t = "DONE"
    d.text((_bx - track_len(d, _t, _f, 5.0) / 2, _by - 12), _t, font=_f,
           fill=(226, 234, 248, 226))
    # -bearing and about the dial's centre: the same sign and the same kind
    # of pivot draw_wordmark uses, so the block and the brand stay locked.
    # The DONE ring travels with it, which is correct and also harmless —
    # any tap dismisses this card, so the ring is a sign, not a hit target.
    if abs(_bearing) > 0.5:
        _card_ov = _card_ov.rotate(-_bearing, resample=Image.BICUBIC,
                                   center=(SIZE / 2, SIZE / 2))
    frame = Image.alpha_composite(frame.convert("RGBA"),
                                  _card_ov).convert("RGB")
    return frame


def draw_enroll_ring(frame: Image.Image, st: dict, now: float) -> None:
    """How far the enrolment has got, as an arc. NO WORDS.

    The instructional banner that used to live here was killed on
    2026-08-02 because the owner read it as a form popup, and he was right:
    she asks for your name out loud, and a sign repeating the question is
    not a conversation. But the opposite failure is the one that has cost
    every ceremony since — the device asks, you answer, and then NOTHING
    happens visibly for twenty seconds while it quietly collects. §1: a
    working device and a crashed one must not look the same.

    So this says only "I am hearing you, and this much is done", which is
    the one thing speech cannot convey without nagging. It fills clockwise
    from 12 o'clock in the wordmark's own blue; it goes amber and empties
    when the samples disagree, because that is the case where talking more
    does not help and the voice has to explain; and it completes to a full
    ring on success.

    ── AND THERE IS A FOURTH PHASE NOW (2026-08-20): WAITING ─────────────
    Synthesised by `_enroll_ring_state`, never published by the ears, for
    the seconds between "what should I call you?" and the first sample
    landing. An empty track alone would be a static circle — arithmetically
    a gauge at zero and visually indistinguishable from a stuck one — so the
    whole track breathes in the listening cyan instead. It is the least
    this glass can say and still be saying something, which is the entire
    argument of the paragraph above.
    """
    phase = st.get("phase")
    tgt = max(1.0, float(st.get("target_s") or 20.0))
    frac = min(1.0, float(st.get("seconds") or 0.0) / tgt)
    if phase == "waiting":
        d = ImageDraw.Draw(frame, "RGBA")
        box = [SIZE // 2 - ENROLL_R, SIZE // 2 - ENROLL_R,
               SIZE // 2 + ENROLL_R, SIZE // 2 + ENROLL_R]
        k = 0.35 + 0.65 * (0.5 + 0.5 * math.sin(now * 2 * math.pi * 0.45))
        d.arc(box, 0, 360, fill=LISTEN_COOL + (int(20 + 78 * k),),
              width=ENROLL_W)
        return
    if phase == "enrolled":
        frac, col = 1.0, (120, 240, 170)
    elif phase == "refused":
        # Amber, and drained: the progress it looked like it had was not
        # real, and pretending otherwise is how the last one ended with a
        # person talking at a device that had already given up.
        frac, col = 0.0, (250, 176, 74)
    else:
        col = (26, 140, 245)
    d = ImageDraw.Draw(frame, "RGBA")
    box = [SIZE // 2 - ENROLL_R, SIZE // 2 - ENROLL_R,
           SIZE // 2 + ENROLL_R, SIZE // 2 + ENROLL_R]
    # The unfilled track, so the ring reads as a gauge rather than as a
    # stray arc that happens to be there.
    d.arc(box, 0, 360, fill=(255, 255, 255, 26), width=ENROLL_W)
    if phase == "refused":
        # Nothing to fill: a short amber tick at 12 o'clock, breathing, so
        # the ring is visibly SAYING something rather than absent.
        k = 0.45 + 0.55 * (0.5 + 0.5 * math.sin(now * 2 * math.pi * 0.9))
        d.arc(box, -96, -84, fill=col + (int(255 * k),), width=ENROLL_W + 3)
        return
    if frac > 0.002:
        d.arc(box, -90, -90 + 360.0 * frac, fill=col + (235,),
              width=ENROLL_W + 2)
    # A brighter head on the leading edge — the same reason the comets got
    # a hot core: an even line reads as a drawn shape, a bright tip reads
    # as something in motion.
    if 0.002 < frac < 0.999:
        a = math.radians(-90 + 360.0 * frac)
        hx = SIZE / 2 + ENROLL_R * math.cos(a)
        hy = SIZE / 2 + ENROLL_R * math.sin(a)
        d.ellipse([hx - 9, hy - 9, hx + 9, hy + 9], fill=col + (255,))


def draw_enroll_caption(frame: Image.Image, text: str,
                        now: float) -> Image.Image:
    """A caption band across the face, in the carousel's visual language
    (same DejaVu-Bold, same steel caption grey and pale-white headline as
    draw_cats). It sits ABOVE centre so the interest carousel — which
    draws below centre — keeps its own space when both are up."""
    # KILLED 2026-08-02: the owner asked twice — the banner reads as a
    # form popup ("stop this pop-up, tell me your first and last name,
    # kick that out"). Aura ASKS for the name in her own voice; a sign
    # telling you to answer her is the opposite of a conversation.
    return frame
    d = ImageDraw.Draw(frame)
    f_cap = face("label", 26)
    f_msg = face("text", 40)
    cy = SIZE // 2
    tw = d.textlength(text, font=f_msg)
    band_w = max(tw + 90, 460)
    y0 = cy - 300
    # A dim plate under the words: the starfield and the lit bolt both
    # run right through this band, and white-on-anything is not legible
    # across a room.
    plate = Image.new("RGB", (SIZE, SIZE), 0)
    ImageDraw.Draw(plate).rounded_rectangle(
        [(SIZE - band_w) / 2, y0 - 16, (SIZE + band_w) / 2, y0 + 108],
        radius=22, fill=(16, 26, 34))
    frame = ImageChops.screen(frame, plate)
    d = ImageDraw.Draw(frame)
    d.rounded_rectangle(
        [(SIZE - band_w) / 2, y0 - 16, (SIZE + band_w) / 2, y0 + 108],
        radius=22, outline=(56, 200, 255), width=2)
    cap = "ENROLLING"
    tw2 = d.textlength(cap, font=f_cap)
    d.text(((SIZE - tw2) / 2, y0), cap, font=f_cap, fill=(150, 165, 190))
    # A slow breath on the headline — the same "alive, not a sticker"
    # treatment the login seal gets. Nothing fast: this is text to read.
    k = 0.86 + 0.14 * (0.5 + 0.5 * math.sin(now * math.tau * 0.5))
    col = tuple(int(c * k) for c in (235, 242, 250))
    d.text(((SIZE - tw) / 2, y0 + 42), text, font=f_msg, fill=col)
    return frame


#: Instant chime: the conductor TOUCHES this flag over the warm mux
#: (~150ms) and we play the chime locally within a frame — the old
#: ssh+aplay spool cost 1-3s per chime on flapping wifi, which read as
#: dead air after every answer ("still deadspace after me saying my name
#: is Paul", owner, live, third enrollment run). If another clip holds
#: the device the chime loses quietly — a busy speaker is not dead air.
CHIME_FLAG = Path("/tmp/aura_face/chime")
CHIME_WAV = "/tmp/briefing/wake_chime.wav"

#: Local playback orders. Audio used to ride the conductor's ssh session
#: — and sshd sessions live in a systemd scope that gets TERM-then-KILLed
#: when a dead link finally times out. nohup cannot escape a cgroup;
#: every "mysterious" mid-clip rc=137 was that teardown. WE are a
#: service with our own cgroup, so we play the clips. The conductor
#: writes {"wav": path, "at": ts} to PLAY_FLAG (atomic mv); we spawn
#: the player locally (pw-play — 2026-08-02, this line said "aplay" and
#: no longer does; see _audio_spawn) and publish {"wav","pid","rc","at"}
#: to PLAY_STATE
#: (rc null while playing) so the conductor can verify without guessing.
#: PLAY_STOP kills the current clip.
PLAY_FLAG = Path("/tmp/aura_face/play.json")
PLAY_STOP = Path("/tmp/aura_face/play_stop")
PLAY_STATE = Path("/tmp/aura_face/play_state.json")

#: The THINKING overlay (owner, twice in one morning: "some interesting
#: 'thinking' type graphic ... like at Anthropic, I see stuff like
#: 'gestating...'" and "dynamic text updates that change, like
#: 'thinking...', 'checking several sources...'"). The conductor writes
#: this flag when a question enters the answer path and removes it when
#: the first answer clip plays; we cycle wry status verbs while it lives.
THINKING = Path("/tmp/aura_face/thinking.json")
_THINK_VERBS = (
    "thinking…",
    "checking several sources…",
    "weighing expert views…",
    "consulting the wires…",
    "doing the analysis…",
    "cross-checking the desk notes…",
    "composing a straight answer…",
    "separating signal from noise…",
    "reading between the headlines…",
    "assembling the picture…",
)
_THINK_STATE = {"mtime": 0.0, "started": 0.0, "order": []}

#: THINK_Y stays at 812. It was checked, not assumed (2026-08-02), and
#: the numbers are here so the next session does not re-derive them:
#:
#:   * CIRCLE. Widest verb ("reading between the headlines…") is 557px at
#:     30px DejaVu Bold, so half-width 278. The block's lowest ink is
#:     y 888 (dots, ascent+descent 36 from 852); the chord half-width
#:     there is sqrt(540^2 - 348^2) = 413. Clear by 135px. At the verb's
#:     own baseline the margin is 166px.
#:   * FOOT. Every pack sets `.foot { bottom: 140px; font-size: 24px }`,
#:     so its line box is y 912–940 and its glyph tops are ~917. The
#:     dots end at 888. Clear by 29px.
#:   * CONTENT. `.content { top: 215; bottom: 195 }` in every pack, so
#:     the slide's own content box runs to y 885 — the verbs are INSIDE
#:     it. On the Q&A slide (s7) the centred stack ends around y 678 and
#:     nothing is there, which is the slide this overlay is nearly always
#:     shown over. On a dense slide it is not empty.
#:
#: So the landmark does not move; what was missing was contrast against
#: whatever it lands on. A cyan verb over a lit tile is the invisible
#: case, and an invisible status line is the silent-success shape
#: (PRINCIPLES §1) — the room would read a working answer path as a hang.
#: Hence the scrim below, which occupies y 790–908: under the dots,
#: above the foot.
THINK_Y = 812
THINK_SCRIM_TOP, THINK_SCRIM_H = 790, 118
_THINK_SCRIM: dict = {"mask": None, "ink": None}


def _think_scrim(frame: Image.Image) -> None:
    """Darken a soft band behind the status verbs, in place.

    Built once from a 108x24 falloff scaled up — the same trick the ember
    uses, and for the same reason: a smooth gradient is exactly what
    survives a bilinear upscale, so this costs 2.6k Python iterations
    instead of 127k. Per frame it is one masked paste over 118 rows.
    """
    if _THINK_SCRIM["mask"] is None:
        sw, sh = 108, 24
        m = Image.new("L", (sw, sh), 0)
        px = m.load()
        for yy in range(sh):
            fy = math.sin((yy + 0.5) / sh * math.pi) ** 0.65
            for xx in range(sw):
                fx = math.sin((xx + 0.5) / sw * math.pi) ** 0.45
                px[xx, yy] = int(165 * fy * fx)
        _THINK_SCRIM["mask"] = m.resize((SIZE, THINK_SCRIM_H), Image.BILINEAR)
        _THINK_SCRIM["ink"] = Image.new("RGB", (SIZE, THINK_SCRIM_H), (2, 4, 8))
    frame.paste(_THINK_SCRIM["ink"], (0, THINK_SCRIM_TOP),
                _THINK_SCRIM["mask"])


def draw_thinking(frame, now):
    """Cycling status verbs over whatever screen is up while she thinks.

    Verb order reshuffles per question and never repeats back-to-back
    (the variant-pool rule — "you're recycling too much" applies to
    status lines as much as greetings). Honest elapsed dots under it.

    Placement is documented at THINK_Y above — measured against the
    circle edge, the pack `.foot` and the pack `.content` box.
    """
    try:
        st = THINKING.stat()
    except OSError:
        return frame
    if st.st_mtime != _THINK_STATE["mtime"]:
        import random
        _THINK_STATE["mtime"] = st.st_mtime
        try:
            _THINK_STATE["started"] = float(
                json.loads(THINKING.read_text()).get("started", now))
        except Exception:
            _THINK_STATE["started"] = now
        order = list(_THINK_VERBS)
        random.shuffle(order)
        _THINK_STATE["order"] = order
    t = now - _THINK_STATE["started"]
    order = _THINK_STATE["order"] or list(_THINK_VERBS)
    verb = order[int(t / 2.5) % len(order)]
    _think_scrim(frame)
    d = ImageDraw.Draw(frame)
    f = face("label", 30)
    ph = 0.55 + 0.45 * math.sin(now * math.tau * 0.8)
    col = (int(90 + 60 * ph), int(170 + 50 * ph), 255)
    tw = d.textlength(verb, font=f)
    y = THINK_Y
    d.text(((SIZE - tw) / 2, y), verb, font=f, fill=col)
    dots = "·" * (1 + int(t) % 3)
    d.text(((SIZE - d.textlength(dots, font=f)) / 2, y + 40),
           dots, font=f, fill=(110, 150, 190))
    return frame
_AUDIO = {"proc": None, "wav": None}


def _audio_state(rc=None):
    p = _AUDIO["proc"]
    body = json.dumps({"wav": _AUDIO["wav"],
                       "pid": p.pid if p else None,
                       "rc": rc, "at": time.time()})
    tmp = PLAY_STATE.with_suffix(".part")
    tmp.write_text(body)
    tmp.replace(PLAY_STATE)


_PW_ENV = {**os.environ, "XDG_RUNTIME_DIR": "/run/user/1000"}
#: ── pw-play IS BROKEN ON THIS DEVICE, MEASURED (2026-08-17) ─────────────
#: Owner, three times: "no more sound tactile feedback when i hit the
#: screen", "still don't hear a sound", "yet again doesn't make noise".
#: Twice I looked at everything except the player itself. The process table
#: settles it:
#:
#:     ps -eo pid,etimes,stat,comm | awk '$4 ~ /pw-play/'
#:     7883  309  Sl  pw-play      <- eleven of these, five minutes old,
#:     7885  308  Sl  pw-play         sleeping, holding sink clients open
#:
#: They are not zombies (that was this afternoon's separate bug). They are
#: LIVE and stuck: pw-play connects, never plays, never exits. So sound
#: works for the first few taps after a restart, and once enough stuck
#: clients accumulate the sink stops serving new ones and the glass goes
#: silent. That is exactly the symptom he described each time, including
#: "it worked before" — it did, for about a minute.
#:
#: THE FIX IS THE MECHANISM THE REST OF THIS DEVICE ALREADY USES. The
#: conductor plays every clip it has ever played with
#: `aplay -D plughw:CARD=UACDemoV10,DEV=0` and has never had this problem.
#: The long note under _audio_spawn warns that a raw device grab kills the
#: PipeWire graph — written when pw-play worked and the two were competing.
#: It does not work here, so there is nothing left to protect, and the
#: face is now using the same working path as the voice it sits under.
#:
#: By CARD NAME, not by index: card numbering moves when a USB device is
#: replugged, and a UI sound aimed at a card that has become the microphone
#: is a silent failure of exactly the kind this file keeps collecting.
UI_PLAY_DEV = os.environ.get("AURA_PLAYBACK_DEVICE",
                             "plughw:CARD=UACDemoV10,DEV=0")

#: ── ONE OWNER, PLAYING IN SEQUENCE (2026-08-17, the fourth attempt) ─────
#: Owner: "i just tapped it several times and heard it play once but never
#: after". That sentence is the whole diagnosis and it took four goes to
#: hear it properly. Measured on the device:
#:
#:     three SEQUENTIAL aplay -D plughw:CARD=UACDemoV10   3/3 played
#:     three CONCURRENT aplay -D plughw:CARD=UACDemoV10   1/3 played
#:     three concurrent  -D plug:dmix:CARD=UACDemoV10     0/3
#:     three of anything -D default, or paplay            0/3
#:
#: The card is EXCLUSIVE. PipeWire owns it, pw-play (the client that would
#: mix) hangs on this device, dmix is not configured for it, and `default`
#: resolves to null. So exactly one process may hold the speaker at a time,
#: and every previous version of this code fired a fresh player per tap and
#: let them fight. The first tap after a restart won that fight, which is
#: precisely what he kept reporting: it plays once and then never again.
#:
#: There is no device that fixes this. What fixes it is not asking two
#: players to exist at once: a single worker thread owns the speaker and
#: plays what it is given, one clip after another. UI sounds are 20-700 ms,
#: so a queue is invisible — and it is also more honest as behaviour, since
#: a real object makes one sound at a time.
#:
#: DEPTH 3, dropping the oldest. A queue that grows is a device that ticks
#: for ten seconds after you stop touching it, which is worse than a missed
#: tock. Sounds are feedback, and feedback that arrives late is noise.
_SND_Q: list = []
_SND_LOCK = threading.Lock()
_SND_RUN = {"on": False}


def _snd_worker():
    while True:
        try:
            with _SND_LOCK:
                item = _SND_Q.pop(0) if _SND_Q else None
            if item is None:
                time.sleep(0.02)
                continue
            pr = subprocess.Popen(
                ["aplay", "-q", "-D", UI_PLAY_DEV, str(item)],
                stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            #: WAITED ON, which is the entire point — the next clip does not
            #: start until this one has released the card. Bounded so a hung
            #: player can never wedge the queue the way pw-play wedged the
            #: sink; 4 s is far longer than any UI clip.
            try:
                pr.wait(timeout=4.0)
            except Exception:                           # noqa: BLE001
                try:
                    pr.kill()
                except Exception:                       # noqa: BLE001
                    pass
        except Exception as exc:                        # noqa: BLE001
            print(f"ui sound: worker {exc!r}", flush=True)
            time.sleep(0.2)


def _snd_play(path) -> None:
    """Hand a clip to the speaker's one owner. Never blocks the caller."""
    #: the UI sounds have their own worker and never touch _spawn_player,
    #: so the silence switch has to be honoured here too — two players,
    #: two checks, and a note at each saying why the other exists
    if os.environ.get("AURA_SILENT") == "1":
        return
    with _SND_LOCK:
        if not _SND_RUN["on"]:
            _SND_RUN["on"] = True
            threading.Thread(target=_snd_worker, daemon=True).start()
        _SND_Q.append(path)
        while len(_SND_Q) > 3:
            _SND_Q.pop(0)


#: ── RESTORED, AFTER I DELETED IT WITH ITS CALLERS STILL THERE ─────────
#: 2026-08-18. `def _spawn_player` was removed in 37dcf0f last night — the
#: commit that reworked the UI transition sound — and THREE call sites were
#: left behind:
#:
#:   _audio_spawn()   briefing and message playback
#:   _set_volume()    every volume change, UNGUARDED
#:   the chime flag   the instant chime, on every screen
#:
#: So every one of those raised NameError. Two are wrapped in a bare
#: `except Exception: pass` and went silent without a word, which is why
#: this survived a night: the symptom was "no sound", the most-diagnosed
#: symptom in this project, and it looked like the audio bug we already
#: had rather than a new one twelve hours old.
#:
#: `_set_volume` is the unguarded one, and that is the interesting damage.
#: A NameError there propagates out of whatever handler called it, so the
#: REST of that handler never runs. Owner this morning, on two different
#: screens: "the power down sequence ... ignored my shutdown commands and
#: was treating it like i was touching the normal GUI", and "can't exit the
#: current briefing". Both are handlers that touch volume on their way to
#: doing the thing they were asked to do.
#:
#: The lesson is not "be careful when deleting". It is that a bare
#: `except: pass` around a call turned a NameError — the most obvious class
#: of error there is, one that any import-time check would catch — into a
#: silent behavioural bug that cost a morning. §1, from the other side:
#: silent success is bad, and silent FAILURE around a programming error is
#: worse, because it cannot even be reproduced deliberately.
_PLAYERS: list = []


def _spawn_player(argv, **kw):
    """Popen a player and reap the ones that have finished. Never raises."""
    #: ── OFF-DEVICE, PLAY NOTHING (2026-08-18) ────────────────────────
    #: The previews import this module to render sheets, and every path
    #: that would make a sound on a puck fires on the workstation too. 954
    #: stuck pw-play processes accumulated there over one morning of
    #: rendering — pw-play never returns, which is a documented failure of
    #: this project — and the owner heard his own rig making noise.
    #:
    #: One switch, checked at the single spawn point rather than at each
    #: caller, because the callers are the part that keeps growing.
    if os.environ.get("AURA_SILENT") == "1":
        return None
    try:
        for q in list(_PLAYERS):
            if q.poll() is not None:
                _PLAYERS.remove(q)
        pr = subprocess.Popen(argv, **kw)
        _PLAYERS.append(pr)
        #: bounded, but by FORGETTING rather than by killing. Dropping the
        #: reference costs a handle; killing costs the owner a sound, and
        #: the whole point of this function is that sounds happen.
        if len(_PLAYERS) > 64:
            del _PLAYERS[:32]
        return pr
    except Exception as exc:                            # noqa: BLE001
        print(f"ui: player spawn failed {exc!r}", flush=True)
        return None


def _audio_spawn(wav):
    # pw-play, not aplay-on-plughw: PipeWire owns this card and reclaims
    # it on its own schedule — every raw-device player was living on
    # borrowed time (rc=1 mid-clip, rc=-9, the whole week of "clicks").
    # As pipewire CLIENTS our streams mix (chime over narration, no
    # exclusive-device dance) and nothing steals the hardware from us.
    # NO raw-aplay fallback — that was the graph-killer: one plughw grab
    # makes the pipewire sink node unavailable, every later pw-play hits
    # "no node available", which engages MORE fallbacks (soak run 1:
    # 32/41, all nine deaths downstream of the first fallback). Raw
    # device users and pipewire never mix. stderr to a log, not the void.
    _AUDIO["err"] = open("/tmp/aura_face/aplay_err.log", "ab")
    _AUDIO["proc"] = _spawn_player(
        ["pw-play", wav], env=_PW_ENV,
        stdout=_AUDIO["err"], stderr=_AUDIO["err"])
    _AUDIO["wav"] = wav
    _AUDIO["started"] = time.time()


def audio_tick():
    """Run once per frame: honor orders, reap the player, publish state."""
    try:
        if PLAY_STOP.exists():
            PLAY_STOP.unlink()
            _AUDIO["retry_at"] = None
            if _AUDIO["proc"] and _AUDIO["proc"].poll() is None:
                _AUDIO["proc"].terminate()
        if PLAY_FLAG.exists():
            order = json.loads(PLAY_FLAG.read_text())
            PLAY_FLAG.unlink()
            if _AUDIO["proc"] and _AUDIO["proc"].poll() is None:
                _AUDIO["proc"].terminate()
                try:
                    _AUDIO["proc"].wait(timeout=1.5)
                except Exception:
                    pass
            _AUDIO["retries"] = 0
            _AUDIO["retry_at"] = None
            _audio_spawn(order["wav"])
            _audio_state()
            print(f"audio: local play {order['wav']}", flush=True)
        elif _AUDIO.get("retry_at") and time.time() >= _AUDIO["retry_at"]:
            # A clip that died instantly (device busy — usually a chime
            # holding plughw) gets another go instead of paced silence.
            _AUDIO["retry_at"] = None
            _audio_spawn(_AUDIO["wav"])
            print(f"audio: retry {_AUDIO['retries']} {_AUDIO['wav']}",
                  flush=True)
        elif _AUDIO["proc"] is not None:
            rc = _AUDIO["proc"].poll()
            if rc is not None:
                died_fast = time.time() - _AUDIO.get("started", 0) < 1.0
                if rc not in (0, -15) and died_fast \
                        and _AUDIO.get("retries", 0) < 4:
                    _AUDIO["retries"] = _AUDIO.get("retries", 0) + 1
                    _AUDIO["retry_at"] = time.time() + 0.35
                    _AUDIO["proc"] = None
                    return
                _audio_state(rc=rc)
                if rc not in (0, -15):
                    print(f"audio: {_AUDIO['wav']} died rc={rc} after "
                          f"{time.time() - _AUDIO.get('started', 0):.1f}s",
                          flush=True)
                try:
                    _AUDIO["err"].close()
                except Exception:
                    pass
                _AUDIO["proc"] = None
                _AUDIO["wav"] = None
    except Exception:
        pass                                  # a broken order must not
                                              # take the face down with it


#: THE BRICK. While this exists the puck is red and the room is deaf: the
#: conductor mirrors it to the RTX flag that converse checks before touching
#: any capture. Tap the red face to unbrick — deliberately no voice path
#: out, because a room that stopped listening cannot hear you change your
#: mind. (Owner: the legacy lock "turned the puck red to show it was
#: 'bricked' and not listening".)
BRICKED = Path("/tmp/aura_face/bricked")
#: THE ONE "STOP TALKING" SIGNAL, shared with puck_conduct (which raises it
#: from the ears on an addressed line, and watches it to kill playback).
#: Named here rather than passed, because both files are pinned to the same
#: literal path on the device and always have been.
BARGE_FLAG = Path("/tmp/aura_face/barge")

#: VOICE MUTE (2026-08-16). The spoken "hey aura, mute" (the conductor
#: writes this AFTER confirming out loud) deafens the ears exactly like
#: the brick — so it gets the brick's red frame and tap-wake too. It
#: rendered NOTHING when it shipped: a deaf puck wearing its normal face,
#: which is §1 in visual form — the owner muted her, saw a normal dial,
#: and read the mute as failed. One difference from the brick: waking
#: returns to the CURRENT screen (lock stays lock, home stays home) —
#: a voice mute is not a logout and stores no origin.
MUTED = Path("/tmp/aura_face/muted")

#: ── ONE DEAF STATE, WEARING TWO FILENAMES (2026-08-21) ──────────────────
#: Owner: "what the hell is the difference between bricked/locked and
#: muted? it should just be the same."
#:
#: He is right about two of the three, and the third is worth stating so
#: nobody collapses it as well. LOCKED is a genuinely different thing: it
#: is about ACCESS, and she KEEPS LISTENING behind it — which is the only
#: reason a voice unlock can exist. BRICKED and MUTED were one state
#: carrying two flags. Both deafen the ears, both paint _brick_frame, both
#: wake on a tap, and MUTED's own comment above states the entire
#: difference out loud: whether an origin screen is remembered.
#:
#: So there is ONE state here now — deaf, optionally carrying somewhere to
#: come back to — and nothing below asks WHICH file is on disk. It cost
#: real confusion ("why is one puck bricked and the other muted" is the
#: same question with two answers) and it cost a real bug: the aurora ring
#: hid itself on BRICKED and not on MUTED, so the ring stayed up over a
#: muted face for no reason anyone could have named.
#:
#: THE TWO FILES REMAIN THE INPUTS, deliberately and permanently. They are
#: what everything else on the device writes: puck_conduct raises the mute
#: from an addressed line, puck_ears reads both as MUTE_FLAG/BRICK_FLAG,
#: the ears watchdog mirrors that pair, and the RTX mirrors the brick.
#: Several of those are running on other people's pucks at this moment. A
#: face that stopped reading one of them would go deaf-blind to half the
#: fleet's mutes — so this converges on read and keeps both vocabularies
#: on write (§15: one place states the policy, and this is it).
DEAF_FLAGS = (BRICKED, MUTED)


def deaf_now() -> bool:
    """Is the room deaf? Either flag, one answer.

    Never raises. This is asked from the paint branch, the tap handler and
    the UI-sound path every frame, and a stat that threw would take the
    compositor down with it.
    """
    for _p in DEAF_FLAGS:
        try:
            if _p.exists():
                return True
        except Exception:                                   # noqa: BLE001
            pass
    return False


def deaf_origin() -> str:
    """Where a tap should wake TO, or "" for "stay on this screen".

    THE ONE REAL DIFFERENCE between the two flags, and it is a deliberate
    design rather than an accident of history. A brick is entered FROM a
    screen and returns to it — the owner bricked an authenticated session,
    tapped it awake and landed at the auth page he had cleared minutes
    earlier ("lock and tap to wake bring me back to the auth page",
    2026-08-01 19:26). A voice mute is not a logout, so it has nowhere to
    go and waking leaves the glass where it was.

    A brick file that cannot be READ still means "brick", so it answers
    "lock" — the same conservative destination the tap handler has always
    used when the read failed. Losing the origin must not silently turn a
    logout into a wake-in-place.
    """
    try:
        if BRICKED.exists():
            try:
                return BRICKED.read_text().strip() or "lock"
            except Exception:                               # noqa: BLE001
                return "lock"
    except Exception:                                       # noqa: BLE001
        pass
    return ""


def deaf_enter(origin: str = "") -> None:
    """Go deaf, optionally remembering where from.

    With an origin this writes the brick, without it the mute — because
    those two filenames are the vocabulary every OTHER process on the puck
    reads, and this file does not get to rename them unilaterally.
    """
    (BRICKED if origin else MUTED).write_text(origin)


def deaf_wake() -> str:
    """Hear again, and say where the glass should land ("" = stay put).

    CLEARS BOTH FLAGS whichever one was up. Clearing half of a two-file
    state is the shape of the 2026-08-20 bug recorded in handle_tap: the
    tap worked, the log said "UNMUTED", and the device stayed armed to
    deafen itself again — a silent success with a delayed fuse (§1). One
    state means one clear.
    """
    dest = deaf_origin()
    BRICKED.unlink(missing_ok=True)
    MUTED.unlink(missing_ok=True)
    _unmute_persistent()
    if dest == "lock":
        LOCKED.touch()
    return dest

#: SLEEP. While this exists the screen shows the EMBER: a very dim warm
#: glow, breathing, with the time in it. The puck's only jobs asleep are
#: still (a) noticing a finger (handle_tap removes the file) and (b)
#: noticing the file vanish REMOTELY (the RTX conductor wakes on voice),
#: both within ~0.5s of the 2 fps cadence. Sleep is a screen state, not a
#: logout: LOCKED is deliberately untouched, so waking returns to
#: whatever was current (owner: "the screen goes off and ... it will wake
#: if you touch the screen or talk to aura").
#:
#: 2026-08-02: it used to paint ONE pure-black frame and then sit there.
#: Owner, live: "when I hit sleep it just shows an empty screen, wasn't
#: it supposed to show some low light kind of display?" — a black round
#: puck is indistinguishable from a dead one, which is the silent-success
#: shape in visual form (PRINCIPLES §1). It now glows.
SLEEPING = Path("/tmp/aura_face/sleeping")
#: ── THE SLEEP SCREEN IS A SCREEN, SO IT TURNS (2026-08-11) ──────────────
#: Owner: "sleep screen still does not obey the fundamental rule that you
#: have to be able to rotate all screens. i am in the sleep screen and
#: it's misoriented and i can't do the DJ thing."
#:
#: Every other surface on this glass owns a `view_deg`, feeds `_orient_drag`
#: while a finger is down and paints through `_apply_view` — volume,
#: settings, Sterling, the request card, the patients card. The ember had
#: none of the three. Its branch called `blit(_ember_frame(now))` directly,
#: so it painted at one fixed orientation whatever the rest of the face was
#: doing.
#:
#: AND THE FINGER WAS ALREADY BEING TRACKED. `rot.release()` only returns a
#: tap when the press was a tap, so a DRAG never reaches `handle_tap` and
#: never wakes the screen — it went into the dial's own rotation, which the
#: ember does not read. The gesture worked perfectly and landed nowhere.
#:
#: view_deg is seeded from the dial's current angle when the screen goes
#: dark, so the ember comes up wearing the orientation the owner last set
#: rather than snapping back to zero — which is most of what "misoriented"
#: meant. Dragging then adjusts it exactly like every other mode.
_SLEEP = {"asleep": False, "tap_woke": False,
          "view_deg": 0.0, "view_prev_ang": None}

#: ── The ember ─────────────────────────────────────────────────────────
#: MEASURED, not specified in the abstract (PRINCIPLES §6): a "dim" RGB
#: triple means nothing until you convert it. EMBER_PEAK below renders at
#: a maximum pixel luminance of 11/255 and EMBER_CLOCK at 11/255, both
#: measured on the puck with PIL's own L conversion — so a dark room
#: stays a dark room. Raising either channel set means re-measuring;
#: amber is mostly RED, and red is the channel luminance cares least
#: about, which is exactly why an ember can look warm and stay dark.
#: 2026-08-04, the owner AGAIN: "i hit the sleep button and it shows nothing
#: i thought we were going to have a low light text or something saying
#: Aura's sleeping...tap to turn her on". Twice now, and the second report
#: came at eight in the MORNING.
#:
#: Two separate mistakes, and the first one is mine-by-inheritance:
#:
#:  1. L = 11/255 is 4% luminance. That is genuinely "a dark room stays a
#:     dark room" — and completely invisible in daylight, which is when a
#:     person actually walks up to a puck. The measurement was right and the
#:     CONDITION it was measured in was wrong (§6: measure in the environment
#:     that will actually apply, and a lit room is one of them).
#:
#:  2. He asked for TEXT, twice, and got a glowing dot with a clock in it.
#:     A clock does not tell you the device is asleep or that tapping wakes
#:     it. An ember is atmosphere; the words are the affordance.
#:
#: Raised to L≈34 — three times dimmer than a phone at its lowest setting,
#: still unmistakably ON in a lit room, and the breath keeps the trough at
#: 55% so a dark room gets ~19.
#: RAISED AGAIN, 2026-08-04, and this time for a reason no luminance
#: measurement would ever have caught: VIEWING ANGLE. The owner, after the
#: first raise — "ok i see it now but at an angle i can't see it at all."
#:
#: The puck sits on a shelf and is looked at from above and to one side. A
#: small IPS panel loses a great deal of apparent brightness off-axis, so a
#: value measured head-on with PIL says nothing about what a person standing
#: over the device sees. Two raises were spent learning that the instrument
#: (a luminance calculation) and the instrument that matters (his eye, at his
#: angle, in his light) are not the same instrument.
EMBER_PEAK = (197, 81, 26)       # amber core at full breath -> L = 109
#: THE COOL EDGE. Owner, 2026-08-05: "it's just this drab orange thing right
#: now." One colour falling off to black is a dot; a warm core bleeding into
#: a cool surround is a light source in a room, and it is the temperature
#: CONTRAST that does the work, not brightness — which is the only currency
#: this screen has none of to spend.
#:
#: Deep indigo on purpose. Luminance weights blue at 0.114, the lowest of
#: the three, so this is a saturated colour that costs almost nothing in
#: light: L = 65 against the amber's 109, and it sits UNDER the amber in the
#: falloff so the two never sum anywhere near the panel's floor.
EMBER_RIM = (58, 44, 168)        # indigo surround          -> L = 65
EMBER_CLOCK = (208, 190, 168)    # warm ivory, the hour     -> L = 194
#: The meridiem and zone. Deliberately dimmer than the clock: you read the
#: hour from across the room and the "AM · EDT" only when you are already
#: close enough to be reading the hint under it.
EMBER_META = (156, 142, 130)     # -> L = 145
#: The sentence he asked for. Dimmer than the clock on purpose: it is there
#: to be read once, by someone standing over the device wondering whether it
#: is broken, and then ignored.
EMBER_TEXT = (176, 162, 150)     # -> L = 165
#: TWO LINES, BECAUSE THEY ANSWER TWO DIFFERENT QUESTIONS. He asked for
#: "Aura's sleeping" twice and got a glowing dot both times, so the STATE
#: keeps its own line. The second line is the AFFORDANCE, and it changed on
#: 2026-08-05 when waking became a voice gate: a tap now only raises the
#: lock screen, so telling someone to tap would be telling them to do the
#: thing that no longer opens the device.
#:
#: All caps to match the lock screen's own hint — his standing note that the
#: type wants to be "consistently elegant" across every surface.
EMBER_LINE = "AURA IS IN SLEEP MODE  |  SAY HI AURA TO WAKE HER"
#: Caps want air. Tracking is what separates set capitals from
#: shouting, and it is the whole difference between the two here.
EMBER_TRACK_PX = 3.2
EMBER_HZ = 0.15                  # ~6.7s per breath
#: FRAME TIME WHILE ASLEEP. Was 0.5s, and the sleep loop carried a comment
#: forbidding exactly this change: "do not raise the frame rate to smooth
#: the breath — the breath is 0.15Hz, so 2 fps is already 13 frames per
#: cycle."
#:
#: Thirteen frames per cycle is the ARITHMETIC of the fade, not the look of
#: it. Owner, 2026-08-05, watching the real panel: "the fade in fade out of
#: the amber is halting, it's not smooth." Thirteen brightness steps over
#: seven seconds is a slideshow of a fade and the eye reads every step.
#:
#: The old comment was defending a CPU budget, and that budget was real —
#: this runs all night. 0.08s costs ~10% of one core against ~1.6%, on a
#: four-core device that is otherwise idle while asleep, and it cuts the
#: wake latency from ~0.5s to ~0.08s for nothing extra. That is the trade,
#: made deliberately, with the number written down so the next person can
#: re-open it rather than rediscover it.
EMBER_FRAME_S = 0.15             # ~45 frames per breath
#: MEASURED, after the fact, which is the only number that counts here.
#: 0.08s was estimated at "~10% of a core" and came in at 25%, with the
#: puck at 84.9C and the owner asking why the fan had spun up. The estimate
#: was wrong by 2.5x because it counted the blit and not the LUT build and
#: the per-frame allocation. 0.15s is ~13%, still 45 frames per breath —
#: three and a half times the 13 he called halting, and comfortably past
#: where stepping is visible.
#: Gap between the hour and its meridiem, which share one baseline.
#:
#: Deleted by accident 2026-08-05 while removing the sparks: the patch cut
#: from the spark comment to the `_EMBER` dict, and this constant was living
#: inside that range. The NameError went into a bare `except` and the
#: meridiem simply stopped being drawn — the clock re-centred itself and
#: looked deliberate. The owner asked why the feature had been removed.
#: A scripted deletion by RANGE takes whatever is inside the range.
CLOCK_GAP_PX = 16.0
EMBER_FLOOR = 0.55               # trough as a fraction of peak
#: Built at 200x200 and scaled up: a gaussian is the one thing that
#: survives a bilinear upscale intact, and it turns 1.17M pixels of
#: Python into 40k. Measured on the puck: 46ms to build, once.
_EMBER = {"glow": None, "base": None, "minute": None,
          "warned": False}


def _ember_glow() -> Image.Image:
    """The bare radial bloom, tinted and DITHERED, no clock. Once per
    process.

    The dither is not decoration. A 400px-wide gradient that peaks at red
    22 has 22 levels to spend, so its contour steps are ~20px apart — and
    near black a 1/255 step is a ~14% step in LINEAR light, well above
    the eye's ~2% threshold. Rendered and looked at (amplified 18x, since
    the real thing is too dark to inspect directly), the undithered glow
    is a set of concentric rings, not a bloom.

    So: keep the fractional part of v*ch/255 and turn it into a
    probability of rounding up, against a per-pixel uniform random field.
    Every step is a C-speed PIL pass and the whole thing is paid ONCE, at
    build; the per-frame breath LUT then rides on top of an already-noisy
    base, so the contours stay broken.

    NOT VERIFIED on the physical panel — banding near black depends on
    the display's own gamma and its backlight floor, and this was checked
    in PNGs, not in a dark room.
    """
    n = 200
    core = Image.new("L", (n, n), 0)
    halo = Image.new("L", (n, n), 0)
    pc, ph = core.load(), halo.load()
    c = (n - 1) / 2.0
    for yy in range(n):
        for xx in range(n):
            r = math.hypot(xx - c, yy - c) / c
            if r < 1.0:
                a = math.exp(-(r * 2.45) ** 2)      # the amber, tight
                b = math.exp(-(r * 1.30) ** 2)      # the indigo, broad
                pc[xx, yy] = int(255 * a)
                # The halo is what is LEFT of the broad falloff once the
                # core is taken out, so the indigo lives in the ring the
                # amber has already faded out of rather than muddying it.
                ph[xx, yy] = int(255 * max(0.0, b - a))
    core = core.resize((SIZE, SIZE), Image.BILINEAR)
    halo = halo.resize((SIZE, SIZE), Image.BILINEAR)
    noise = Image.frombytes("L", (SIZE, SIZE), os.urandom(SIZE * SIZE))

    def _tint(mask: Image.Image, ch: int) -> Image.Image:
        """One channel of one layer, dithered. See the docstring: the
        rounding carry is what keeps a 22-level gradient from banding."""
        floor = mask.point(lambda v, c_=ch: (v * c_) // 255)
        frac = mask.point(lambda v, c_=ch: (v * c_) % 255)
        # subtract clamps at 0, so this is 1 exactly where frac > noise
        carry = ImageChops.subtract(frac, noise).point(
            lambda v: 1 if v else 0)
        return ImageChops.add(floor, carry)

    # ImageChops.add clamps at 255, so the two layers can never wrap.
    chans = [ImageChops.add(_tint(core, a), _tint(halo, b))
             for a, b in zip(EMBER_PEAK, EMBER_RIM)]
    return Image.merge("RGB", tuple(chans))


def _ember_frame(now: float) -> Image.Image:
    """One breath-frame of the sleeping face.

    The composed base (glow + clock) is rebuilt only when the MINUTE
    changes; every other frame is a single LUT pass — 8.1ms measured on
    the puck, so at 2 fps the ember costs ~1.6% of one core for however
    many hours it runs.
    """
    if _EMBER["glow"] is None:
        _EMBER["glow"] = _ember_glow()
    lt = time.localtime(now)
    if _EMBER["minute"] != lt.tm_min:
        _EMBER["minute"] = lt.tm_min
        base = _EMBER["glow"].copy()
        d = ImageDraw.Draw(base)
        # TWELVE HOUR, WITH THE MERIDIEM AND THE ZONE.
        #
        # Owner, 2026-08-05: "make sure to have an am / pm with the time
        # zone displayed as well." 24-hour was ambiguous on a device that
        # sleeps through both nine o'clocks, and the zone is not decoration
        # here: this puck shipped on a factory image set to America/Chicago
        # and told him the wrong hour for a day and a half. A clock that
        # names its own zone is a clock you can catch lying.
        txt = time.strftime("%-I:%M", lt)
        meta = f"{time.strftime('%p', lt)} · {time.strftime('%Z', lt)}"
        f = face("text", 136)
        w = d.textlength(txt, font=f)
        # A per-minute wander of a few pixels. The clock is otherwise a
        # static bright-ish shape sitting in one place for eight hours,
        # which is the classic way to burn a panel.
        ox = 8 * math.cos(lt.tm_min * 0.7)
        oy = 8 * math.sin(lt.tm_min * 0.7)
        # THE WORDS. Placed below the clock, wandering with it so the panel
        # ages evenly. Written before the clock is blitted so a short font
        # failure cannot leave the screen wordless AND clockless.
        # ONE LINE, ONE BASELINE.
        #
        # Owner: "AM EST should be on the same line as the time." It was set
        # centred underneath, which reads as a second field rather than as
        # part of the clock — the way a watch face sets it, not the way a
        # clock does.
        #
        # anchor="ls" is left-BASELINE, so the meridiem sits on the same line
        # the numerals stand on regardless of the two fonts' box metrics.
        # Centring the pair by their combined width keeps the group optically
        # centred rather than the numerals alone.
        mf = mw = None
        try:
            mf = face("text", 62)
            mw = d.textlength(meta, font=mf) + CLOCK_GAP_PX
        except Exception as exc:
            # SAY WHY. This swallowed a NameError for one whole round of
            # "you got rid of the AM/PM?" — the meridiem simply vanished and
            # the clock re-centred itself as though nothing were missing,
            # which is indistinguishable from a design decision. Once per
            # process, not once per minute.
            if not _EMBER.get("meta_warned"):
                _EMBER["meta_warned"] = True
                print(f"sleep: meridiem NOT drawn — {exc!r}", flush=True)
            mf, mw = None, 0.0
        x0 = (SIZE - (w + (mw or 0.0))) / 2 + ox
        ybase = SIZE / 2 + 22 + oy
        # The hour is written OUTSIDE the try below: a font failure may cost
        # the words, it may not cost the clock.
        d.text((x0, ybase), txt, font=f, fill=EMBER_CLOCK, anchor="ls")
        if mf is not None:
            d.text((x0 + w + CLOCK_GAP_PX, ybase), meta, font=mf,
                   fill=EMBER_META, anchor="ls")
        try:
            # NARROW CAPS, TRACKED. The narrow face is the one in the ramp
            # that holds its colour at small sizes in caps, and the tracking
            # is what keeps a 49-character line from reading as a warning
            # label. One line, his wording.
            lf = face("label", 27)
            draw_tracked(d, SIZE / 2 + ox, SIZE * 0.700 + oy,
                         EMBER_LINE, lf, EMBER_TEXT, EMBER_TRACK_PX)
        except Exception:
            pass
        _EMBER["base"] = base
    k = EMBER_FLOOR + (1.0 - EMBER_FLOOR) * (
        0.5 + 0.5 * math.sin(now * math.tau * EMBER_HZ))
    # A BREATH THAT CHANGES TEMPERATURE, NOT JUST BRIGHTNESS.
    #
    # One LUT applied to all three channels is a dimmer switch, and a dimmer
    # switch on a single hue is precisely the "drab orange thing" he called
    # it. Real embers go white-hot at the peak and blue-grey at the trough,
    # so red rides the breath straight, green lags it slightly, and blue
    # runs INVERSE — strongest at the trough. The result reads as the glow
    # cooling and reheating rather than as a light being turned down.
    #
    # Still one .point() pass over the composed base: three 256-entry lists
    # cost nothing next to the 8.1ms the blit already takes.
    # ROUND, do not truncate. int() on a dark pixel throws away most of
    # the breath: a background value of 20 scaled from 0.55 to 1.0 lands on
    # eleven distinct integers across the whole cycle, and truncation turns
    # each into a visible step. Rounding halves that error for one add.
    lut = ([int(min(255.0, v * k) + 0.5) for v in range(256)]
           + [int(min(255.0, v * k * (0.88 + 0.12 * k)) + 0.5)
              for v in range(256)]
           + [int(min(255.0, v * k * (0.72 + 0.28 * (1.0 - k))) + 0.5)
              for v in range(256)])
    return _EMBER["base"].point(lut)

#: SLEEP/POWER buttons on the home face, in FACE coordinates. They sit
#: OFF the wedge ring, so the wedge test's logical-angle trick does not
#: cover them. Rather than undo the display rotation on the tap point —
#: a second empirical sign to get wrong (see TAP_ANG_SIGN) — they are
#: only accepted while the dial is at rest (within 5 deg of home). On a
#: spun dial the painted buttons are not where they look anyway.
#: 2026-08-02 round 2: home.html moves the whole left column (ledger +
#: sleep + power) UP 60 viewBox px; these are the matching display
#: coordinates for the relaid stack.
#: MOVED ONTO THE ARC, 2026-08-04, together with home.html's baked icons —
#: see the tap-centers note there. The wordmark grew from AURA to AURAVISION
#: and ran straight through the old SLEEP button at (246,523); the three
#: left-hand controls now sit on a R=330 arc at 210/180/150 degrees, which
#: both matches the wedge ring opposite and clears the centre.
#:
#: These two numbers and that SVG are ONE artefact in two files. A change to
#: either alone gives you a button painted where it cannot be tapped, or
#: tappable where nothing is painted — and the second is invisible until
#: somebody reaches for it.
#: THE OTHER HALF OF A TWO-FILE MOVE. These centres are DISPLAY px and the
#: discs they belong to are BAKED into base.png by home.html, which draws in
#: viewBox units (display px x 0.9259). A button that moves in one file and
#: not the other is a button that stops working where it looks, so the two
#: halves ship in one commit — home.html's own comment says so and this is
#: the second half of it.
#:
#: 2026-08-05, owner by voice: "push the left set of items, ledger, sleep,
#: power, that concierge wedge outwards to the diameter that is closer in
#: look to the wedges on the right side ... a sense of symmetry".
#:
#: MATCHED ON OUTER EXTENT, not centre-to-centre. home.html draws the five
#: baked wedges as sector(a0, a1, 336, 458) in VIEWBOX units, so the ring's
#: outer edge lands at 458 / 0.9259 = 494.6 DISPLAY px — measured on the
#: current base.png at 494 and not assumed (PRINCIPLES §6: the units that
#: actually apply). The discs render at r=56 display, so a centre at
#: 494.6 - 56 = 438.6 puts their outer edge exactly on the ring line.
#: Angles are unchanged (174.2 deg and 145.2 deg); only the radius moved,
#: and both now sit on ONE arc where they used to sit at 402.0 and 421.1.
#: x DIAL_K, 2026-08-06 night — the third time this pair has moved and the
#: same rule every time: the discs are baked by home.html and these are the
#: hit-tests, so the two halves ship in one commit or the button stops
#: working where it looks. Was (104,584) and (180,790), r=438.2.
#: 2026-08-08: DERIVED FROM THE PAINT, NOT COPIED FROM IT. The 0.80 -> 0.93
#: bump moved the discs and left these behind at r=350.6 while the painted
#: caps went to r~407.6 — centres 57 px apart, so BTN_R's fingertip pad was
#: spent entirely on the miss and the OUTBOARD edge of each painted button
#: lay outside its own tap circle. Measured and filed in PREMIUM.md two
#: passes before anyone reached for it, which is exactly how long an
#: invisible half of a two-file move survives.
#: So they stop being a copy: BTN_DISC_XY is home.html's own circle centre
#: through DIAL_K and VB_PX, and these round it to whole display px. The
#: next time the dial compresses, the tap moves with the paint or neither
#: moves. Was (191,575) / (252,740) at DIAL_K 0.80.
SLEEP_XY = (round(BTN_DISC_XY[0][0]),
            round(BTN_DISC_XY[0][1]))    # (135, 581), r = 407.1
POWER_XY = (round(BTN_DISC_XY[1][0]),
            round(BTN_DISC_XY[1][1]))    # (205, 773), r = 408.1
#: THE DISC SCALES; THE PAD DOES NOT. 56 is the drawn radius and follows
#: the dial to 45; the +14 is a fingertip against glass, which is the same
#: width of finger it was yesterday (§6).
BTN_R = round(56 * DIAL_K) + 14
BTN_ROT_MAX = 5.0

#: ── THE CASE PUSHERS, 2026-08-14 — the idealface critique's last open
#: item: "on a real watch, functions live on the case — crowns and
#: pushers, not dial buttons." SLEEP and POWER leave the dial: the patek
#: bake drops its two discs (home.html ?nobtns) and the controls become
#: machined hardware seated in the bezel band, raymarched in the house
#: studio (scripts/render_pushers.py — rest and pressed, real travel).
#: THE BEARINGS DO NOT MOVE: derived below from the disc centres rather
#: than copied, so a hand that knows this face still lands where it
#: always did, and the paint and the hit-test cannot drift apart the way
#: the 2026-08-08 r=350.6/407.6 split did.
#: Radius: the wedge ring's outer edge is at 494.6 display px (measured,
#: see the BTN_DISC_XY note) and the round panel ends at 540; a cap of
#: PUSHER_W/2 = 40 centred at 498 spans 458..538 — seated against the
#: band, nothing clipped by the panel's own circle.
PUSHER_DIR = Path.home() / "aura_face" / "pushers"
#: v4 (2026-08-14): JEWELED CHATONS. v1/v2's end-on studs read as rivets
#: (owner: "just awkward … it looks ugly"); v3's flush corrector in the
#: band was killed by physics — MEASURED, not judged: the live compose
#: clips at ~r528 (a sprite at r531 left zero pixels on the glass; the
#: same sprite at 526 survived), and the champagne band lives beyond the
#: clip, so no live paint can sit flush in that metal. The concept that
#: is native to THIS face: the dial is an open movement, and a movement's
#: hardware is the jewel bearing — a gold chaton holding a cabochon.
#: SLEEP is a blued stone (the hands' metal), POWER a ruby (the cage's
#: stones). Seated at the OLD disc centres — bearings and radius with
#: years of proven clearance — so 408 makes _pusher_xy a no-op move.
PUSHER_RING_R = 408.0
#: 30 -> 64 (2026-08-14, owner: "way way too small for any human to read
#: or understand. we need to bring back the icon but i like the idea of
#: two distinct looking jewels and their color"). The stones stay, grow
#: to a readable size, and carry their FUNCTION carved into them — a
#: gold-inlay moon in the blue stone, a gold power mark in the ruby, the
#: signet-gem idiom. Glyphs are drawn at load (_pusher_glyph) so they
#: scale with this number forever.
PUSHER_W = 128   # 64 -> 128, owner: 'double their size again, still too small'
#: identity — the stones carry their own colour from the render
PUSHER_TINT = (1.00, 1.00, 1.00)
PUSHER_V_CAP = 255
_PUSHER = {"press_until": 0.0, "which": None, "spr": None}


def _pusher_xy(old_xy):
    dx, dy = old_xy[0] - SIZE / 2, old_xy[1] - SIZE / 2
    k = PUSHER_RING_R / math.hypot(dx, dy)
    return (round(SIZE / 2 + dx * k), round(SIZE / 2 + dy * k))


CASE_PUSHERS = bool(_THEME.get("case_pushers")) and \
    (PUSHER_DIR / "pusher_sleep_rest.png").exists()
if CASE_PUSHERS:
    #: the hit-tests move WITH the paint, in one commit — the standing
    #: BTN_DISC_XY rule. BTN_R keeps its fingertip pad (§6: the finger is
    #: the same width it was yesterday).
    SLEEP_XY = _pusher_xy(SLEEP_XY)
    POWER_XY = _pusher_xy(POWER_XY)


def _pusher_glyph(im, tag: str) -> None:
    """The function, carved into the stone — a gold-inlay glyph, the
    signet-gem idiom. Drawn at load so it scales with PUSHER_W, with a
    1-2px dark offset under the gold so the inlay sits IN the cabochon
    rather than floating on it."""
    w = im.size[0]
    cx = cy = w / 2.0
    r = w * 0.27
    stroke = max(3, round(w * 0.07))
    ink = (240, 219, 168, 240)
    dark = (16, 11, 8, 170)
    for off, col in (((1, 2), dark), ((0, 0), ink)):
        layer = Image.new("RGBA", im.size, (0, 0, 0, 0))
        d = ImageDraw.Draw(layer)
        ox, oy = off
        if tag == "sleep":
            #: a crescent: the disc, minus a disc shifted toward 2 o'clock
            mask = Image.new("L", im.size, 0)
            dm = ImageDraw.Draw(mask)
            dm.ellipse([cx - r + ox, cy - r + oy,
                        cx + r + ox, cy + r + oy], fill=255)
            dm.ellipse([cx - r * 0.30 + ox, cy - r * 1.55 + oy,
                        cx + r * 1.70 + ox, cy + r * 0.45 + oy], fill=0)
            layer.paste(Image.new("RGBA", im.size, col), (0, 0), mask)
        else:
            #: the power mark: an open ring with the stem through the gap
            d.arc([cx - r + ox, cy - r + oy, cx + r + ox, cy + r + oy],
                  -55, 235, fill=col, width=stroke)
            d.line([cx + ox, cy - r * 1.30 + oy, cx + ox, cy - r * 0.15 + oy],
                   fill=col, width=stroke)
        im.alpha_composite(layer)


def _pusher_sprites():
    if _PUSHER["spr"] is None:
        out = {}
        for tag in ("sleep", "power"):
            for st in ("rest", "pressed"):
                im = Image.open(
                    PUSHER_DIR / f"pusher_{tag}_{st}.png").convert("RGBA")
                h = round(im.height * PUSHER_W / im.width)
                im = im.resize((PUSHER_W, h), Image.LANCZOS)
                _pusher_glyph(im, tag)
                r, g, b, a = im.split()
                im = Image.merge("RGBA", (
                    r.point(lambda v: min(PUSHER_V_CAP,
                                          int(v * PUSHER_TINT[0]))),
                    g.point(lambda v: min(PUSHER_V_CAP,
                                          int(v * PUSHER_TINT[1]))),
                    b.point(lambda v: min(PUSHER_V_CAP,
                                          int(v * PUSHER_TINT[2]))), a))
                out[(tag, st)] = im
        out["boxes"] = {
            tag: (xy[0] - PUSHER_W // 2,
                  xy[1] - out[(tag, "rest")].height // 2)
            for tag, xy in (("sleep", SLEEP_XY), ("power", POWER_XY))}
        _PUSHER["spr"] = out
        print(f"pushers: jeweled chatons loaded from {PUSHER_DIR}",
              flush=True)
    return _PUSHER["spr"]


def draw_case_pushers(frame, now: float) -> None:
    """Two cached pastes on the colourway side — the duotone would grey
    the gold and flatten the stones, the exact BTN_ANODISE argument —
    and before the rotate, so the jewels turn with the movement they are
    set in. The pressed sprite holds 0.35s: long enough to straddle a
    full-frame paint at ~6 full/s, so the stone is SEEN to seat deeper,
    not only heard (§13 — the instant half of the acknowledgment is the
    click; this is the visible half arriving on the next frame)."""
    spr = _pusher_sprites()
    for tag in ("sleep", "power"):
        st = "pressed" if (_PUSHER["which"] == tag
                           and now < _PUSHER["press_until"]) else "rest"
        frame.paste(spr[(tag, st)], spr["boxes"][tag], spr[(tag, st)])

#: POWER is a FULL power down — recovery is the wall plug (owner:
#: "shutdown is a full power down, which would require them to unplug and
#: replug it back in"). That asymmetry (PRINCIPLES §8) is why it takes a
#: second, distinct tap on the red confirm ring within 5s; any other tap
#: or the expiry cancels, and every outcome is logged.
#: SLIDE TO POWER OFF, 2026-08-04, at the owner's request: "do an iphone
#: style confirmation slide to confirm power off, and inform them they will
#: have to unplug and replug in the puck to start again".
#:
#: The tap-a-red-ring confirm it replaces was already asymmetric on purpose
#: (§8 — the expensive direction gets the narrow gesture), but a tap is a
#: tap: a second accidental one lands as easily as the first. A slide cannot
#: be produced by a knuckle, a sleeve, or a cat. It is the standard gesture
#: for exactly this decision on every phone anyone owns, which means it needs
#: no explaining.
#:
#: AND IT SAYS WHAT HAPPENS NEXT. Power-off on this device is not a restart:
#: recovery is the wall plug. A person who does not know that is one tap away
#: from a puck that appears dead. The warning is part of the control, not a
#: line in a manual.
SLIDE_X0, SLIDE_X1 = 250, 830        # track ends, screen coords
SLIDE_Y = 690                        # track centre line
SLIDE_H = 84                         # track height
SLIDE_KNOB_R = 38
#: How far along counts as "meant it". 0.86 rather than 1.0 because a finger
#: that reaches the end of a track usually lifts a few pixels short of it.
SLIDE_DONE = 0.86
CONFIRM_XY = (540, 800)
CONFIRM_R = 90
_POWER = {"until": 0.0, "error_until": 0.0, "slide": 0.0}

#: Volume mode (the legacy rim slider reborn): drag around the circle,
#: twelve detents, each one clicks.
#:
#: Round 2 (2026-08-02): "until" is GONE. The mode used to live on a
#: timeout — armed ~8s at entry, refreshed by every touch — and its
#: expiry was the screen the owner reported "just disappearing after no
#: action". The prior crew hunted for an explicit timer and believed
#: there was none; the mode's LIFETIME itself was the timer. Now a plain
#: open flag: DONE or a genuine takeover (see the pre-empt block in
#: main) are the only exits. view_deg is the per-mode orientation (drag
#: INSIDE the detent ring to spin the overlay toward you, hit-tests
#: undone by _unrotate_pt); drag_role locks each drag, by where it
#: PRESSED, to either the detent ring (r>=300) or orientation — one
#: finger never does both jobs mid-gesture.
_VOL = {"open": False, "level": 60, "detent": None, "grab_deg": 0.0,
        "view_deg": 0.0, "view_prev_ang": None, "drag_role": None}
#: Perceptual detents (2026-08-02 morning): amixer's PCM % is
#: logarithmic-steep at the top of its range — 78% sounded near-silent,
#: and the linear 0..100/12 ring crammed every audible level into the
#: last few clicks (the owner unknowingly left the room at 41%). These
#: percentages are spaced so each detent is a similar step to the EAR.
#: Index = lit detents 0..12; full ring = 100.
VOL_DETENT_PCT = [0, 25, 34, 41, 47, 52, 57, 61, 65, 68, 71, 74,
                  77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 96, 98, 100]
#: THE RING HAS 13 POSITIONS AND THIS TABLE HAS 25.
#:
#: `_detent_from_angle` returns 0..12 — twelve clicks around the ring, by
#: design. The curve was later refined to 25 finer values and nothing
#: reconciled the two, so the top of the dial indexed entry 12 and the
#: volume maxed out at 77%. The last twelve values were unreachable. The
#: owner, turning it all the way up: "now it maxes out at 77%, i'm sure
#: that's an internal thing but for the consumer it should max at 100%."
#:
#: Mapped rather than truncated: the ring keeps its twelve clicks and each
#: one steps across the curve, so full ring = 100% and every detent is
#: still an even step TO THE EAR, which is what the curve is for.
VOL_DETENTS = 12


def detent_pct(det: int) -> int:
    """Ring position 0..12 -> percentage on the perceptual curve."""
    det = max(0, min(VOL_DETENTS, int(det)))
    i = round(det * (len(VOL_DETENT_PCT) - 1) / VOL_DETENTS)
    return VOL_DETENT_PCT[i]


def pct_detent(pct: float) -> int:
    """The inverse, for showing where an externally-set level sits."""
    i = min(range(len(VOL_DETENT_PCT)),
            key=lambda j: abs(VOL_DETENT_PCT[j] - pct))
    return round(i * VOL_DETENTS / (len(VOL_DETENT_PCT) - 1))
#: The DONE button (2026-08-02): volume mode had no obvious exit — the
#: owner adjusted, waited, and was dumped back by a timeout he never
#: chose. Centered below the big readout; hit radius padded because
#: fingers are round and the glass is glass.
#: ── THE VOLUME RING'S GEOMETRY, IN ONE PLACE (2026-08-17) ───────────────
#: Owner: "decrease the radius of the volume green segments by 20% that way
#: it's easier for people to rotate the outside of that circle with their
#: fingers." So the detents come in from 430 to 344, and the whole point is
#: what that OPENS UP: 344 to the glass edge is now bare rim to grab, and
#: turning the screen is a comfortable outside grip rather than a pinch at
#: the hub.
#:
#: These four move together and are therefore written together — the ring
#: was a literal in the draw function and its bands were two more literals
#: three thousand lines apart, which is how a ring gets moved and its
#: hit-test does not (§15).
#:   VOL_RING_R  where the detent arcs are stroked
#:   VOL_SET_R0  inner edge of the band that SETS the level
#:   VOL_RIM_R   past this a drag ORIENTS instead
#: DONE moved in with them: at r=270 with an 80 px button its outer edge
#: reached 350 and would have collided with the new ring at 344.
#: 344 -> 372: he asked for 20% in, looked at it, and asked for 8% back.
#: The bands scale with the ring because they ARE the ring — the set band
#: still straddles the ink and the orient grip still starts just outside.
#: How far a finger must travel before it is turning the screen rather
#: than pressing something. See the note at drag_role: at TAP_MAX_PX a
#: press that slid rotated the whole overlay out from under him.
VOL_ORIENT_MIN_PX = 90.0
VOL_RING_R = 372.0
#: ── THE VOLUME CARD LEARNS THE THEME (2026-08-25) ──────────────────────
#: Owner, at the gallery face: "the entire volume circle is just crazy
#: looking for some reason." Rendered on the workstation
#: (scripts/render_volume_card.py) it is obvious and it is not subtle: the
#: card is aurora's DARK-DIAL treatment painted onto plaster. It dims the
#: frame to 42% so a bright overlay can sit on it, which on a light face
#: turns the museum wall grey and leaves the wordmark and all five wedges
#: bleeding through the scrim; then it writes cyan on top of a bone and
#: gold skin.
#:
#: Third instance of one bug this week — the comet on opaline, the hearing
#: bloom's ink, and now this. A treatment tuned on a dark ground does not
#: survive a light one, and every one of them shipped because the code
#: carried the colour as a literal instead of asking the theme. So these
#: are keys with the aurora values as defaults: every existing face keeps
#: exactly the pixels it has today, and a light row overrides.
VOL_WASH = tuple(_THEME.get("vol_wash", ()))     # blend TO this, if light
VOL_SCRIM = float(_THEME.get("vol_scrim", 0.42))  # else multiply by this
VOL_ON = tuple(_THEME.get("vol_on", (53, 208, 192)))
VOL_OFF = tuple(_THEME.get("vol_off", (46, 56, 66)))
VOL_LABEL = tuple(_THEME.get("vol_label", (120, 190, 185)))
VOL_BIG = tuple(_THEME.get("vol_big", (232, 246, 250)))
VOL_HINT = tuple(_THEME.get("vol_hint", (86, 138, 134)))
VOL_DONE_FILL = tuple(_THEME.get("vol_done_fill", (8, 26, 30)))
VOL_DONE_EDGE = tuple(_THEME.get("vol_done_edge", (53, 208, 192)))
VOL_DONE_INK = tuple(_THEME.get("vol_done_ink", (232, 246, 250)))
#: ── 259 -> 236: HIS THUMB LANDS AT 258 (2026-08-20) ────────────────────
#: Owner, for the third time: "the volume thing still does not click
#: anymore as you scroll around to change it." The click machinery was
#: fixed and measured — one aplay held open, 0.006 ms per tick, and the
#: device log shows the stream opening and closing on every session. So
#: something upstream was never calling it, and his own log says what:
#:
#:     volume: tap screen=(762,672) view=62.2 -> frame=(527,798)
#:             done_d=40/239 r=258
#:
#: r=258 against a band that starts at 259. One pixel. Below it the drag
#: is not a LEVEL drag at all — it becomes `orient`, which spins the
#: overlay toward the viewer and crosses no detents, so the silence was
#: correct behaviour for a gesture he never meant to make.
#:
#: 236 puts 22 px of margin under where he actually holds it. It overlaps
#: the DONE button's disc, which is fine: handle_tap tests DONE FIRST, so
#: the press still lands, and nobody DRAGS a confirm button.
VOL_SET_R0 = 236.0
VOL_RIM_R = 417.0
VOL_DONE_XY = (540, 760)
VOL_DONE_R = 80
VOL_DONE_HIT_R = VOL_DONE_R + 24


def _detent_from_angle(fa: float) -> int:
    """Finger SCREEN angle → detent count. 12 o'clock is zero, clockwise
    fills the ring, and the lit arc always ends under the finger. SCREEN
    angle deliberately — the volume overlay renders ABOVE the dial
    rotation (see draw_volume), so no rot.deg term belongs here. The old
    path drew beneath the rotate, which displaced every detent by
    rot.deg: "not mapping correctly to my finger... weird offset"
    (owner, 2026-08-02 morning).

    Round 2: the overlay itself may now be view-rotated toward the user
    (_VOL["view_deg"]), so callers pass the angle in the OVERLAY's frame
    — screen angle + view_deg, the same pre = screen + applied relation
    the wedge hit-test uses."""
    return max(0, min(12, round(((fa + 90.0) % 360.0) / 30.0)))


# --- Per-mode view orientation (round 2, 2026-08-02) -----------------------
#: The owner: "i can't do the spin of the volume screen so it's not
#: oriented to me". The prior crew drew overlays AFTER the dial rotate in
#: raw screen coords, on purpose, so paint and hit-tests agree — that
#: stays true. Orientation is a SECOND rotation applied to the finished
#: overlay frame (frame.rotate(view_deg)), and every overlay hit-test
#: undoes it with _unrotate_pt first. So the modes are orientable AND the
#: hit-tests stay honest: one transform in, one transform out.

#: ── AN OVERLAY'S TOTAL ROTATION, STATED ONCE (2026-08-17) ───────────────
#: Owner, at the glass: "the orientation is wrong when you bring up volume
#: like i did just now. it is not matching the rotation of the screen."
#:
#: He is right, and it is fallout from this morning's decision that the
#: aurora ring TURNS WITH THE DIAL. Overlays are composited after the dial
#: rotate and were then given only their own orient gesture (`view_deg`),
#: so on a spun dial the home face was tilted and the volume ring was not:
#: two coordinate systems on one piece of glass.
#:
#: The 2026-08-02 lesson still holds and is not being undone — the detents
#: were once displaced by rot.deg because paint went under the rotate
#: while the hit-test stayed in screen space. What broke it then was PAINT
#: AND TAP DISAGREEING, not the rotation itself. So the total is defined
#: here, once, and both sides call this: _apply_view(frame, _overlay_view(
#: d, rot)) to paint, _unrotate_pt(x, y, _overlay_view(d, rot)) to test.
#: They cannot drift, because there is nothing to keep in sync.
#: AND IT IS `dg`, NOT `rot.deg`. The angle actually applied to the glass
#: is `-rot.deg if INVERT else rot.deg` — the same expression the compositor
#: rotates the home frame by and the same one the wedge hit-test corrects
#: with. Adding the raw `rot.deg` here would be right on one puck and
#: mirrored on the other, which is the hardest kind of wrong to see.
def _overlay_view(view_deg: float, rot) -> float:
    """An overlay's frame: its own orient gesture PLUS the dial's."""
    try:
        deg = float(getattr(rot, "deg", 0.0) or 0.0)
        return float(view_deg) + (-deg if INVERT else deg)
    except Exception:                                   # noqa: BLE001
        return float(view_deg)


#: ── THE TAP READS THE ANGLE THAT WAS PAINTED, NOT ONE IT RECOMPUTES ─────
#: (2026-08-17, round 2) Owner, still stuck: "the volume dialogue i still
#: cannot press done to dismiss it." The log was specific — his presses
#: came out as `volume: tap set 96%`, which is the branch for a finger
#: more than 300 px from the centre, when DONE sits at 270.
#:
#: The geometry was not the problem, and that was worth proving rather than
#: assuming: `_unrotate_pt` was measured to invert `_apply_view` to within
#: a pixel at +30, -30 and +90 degrees. If the transform is exact and the
#: answer is still wrong, the two sides are not using the same ANGLE.
#:
#: They were not. `_overlay_view(...)` was evaluated twice — once in the
#: compositor and once in the tap handler — from a `rot` each read for
#: itself, and while `view_deg` was 0 (as it is until someone uses the
#: orient gesture) that difference was invisible, because 0 + anything
#: wrong is still the identity. Adding the dial made the recomputation
#: matter, and the two answers diverged.
#:
#: So the compositor now PUBLISHES the angle it painted each overlay with,
#: and the hit-test reads that value. One writer, one reader, no second
#: evaluation to disagree with the first (§15). If a frame has not been
#: painted yet the default is 0, which is the screen-pinned behaviour that
#: worked for a year.
_VIEW_PAINTED: dict = {}


def _view_used(name: str) -> float:
    return float(_VIEW_PAINTED.get(name, 0.0))


def _unrotate_pt(x: float, y: float, view: float):
    """Map a SCREEN tap into an overlay's own frame when the finished
    overlay was rotated by frame.rotate(view). Same relation the wedge
    test uses (logical = screen + applied): rotate the point by +view
    about the centre."""
    if abs((view + 180.0) % 360.0 - 180.0) < 0.05:
        return x, y
    a = math.radians(view)
    dx, dy = x - SIZE / 2, y - SIZE / 2
    return (SIZE / 2 + dx * math.cos(a) - dy * math.sin(a),
            SIZE / 2 + dx * math.sin(a) + dy * math.cos(a))


def _rot_vec(dx: float, dy: float, view: float):
    """A swipe VECTOR mapped into a view-rotated overlay's frame, so a
    reader facing the rotated book swipes in their own left/right."""
    a = math.radians(view)
    return (dx * math.cos(a) - dy * math.sin(a),
            dx * math.sin(a) + dy * math.cos(a))


def _apply_view(frame: Image.Image, view: float) -> Image.Image:
    if abs((view + 180.0) % 360.0 - 180.0) < 0.05:
        return frame
    return frame.rotate(view, resample=Image.NEAREST, fillcolor=(0, 0, 0))


def _orient_drag(state: dict, rot: "Rotation") -> None:
    """Per-frame: feed the active drag into a mode's view_deg, 1:1 with
    the finger's angular travel (radial gain rolls off near the hub,
    same as the dial — angle-per-pixel explodes there). Sign: content at
    overlay angle θ shows at screen angle θ - view, so following the
    finger means view -= dθ."""
    prev = state.get("view_prev_ang")
    if prev is not None:
        d_a = (rot.finger_ang - prev + 540.0) % 360.0 - 180.0
        state["view_deg"] = (state["view_deg"]
                             - d_a * Rotation._gain(rot.finger_r)) % 360.0
    state["view_prev_ang"] = rot.finger_ang
#: SETTINGS MODE (2026-08-02) — the placeholder live-facts card is gone;
#: the wedge now opens a paged settings book: WI-FI (real, via nmcli on a
#: background thread) / CONTACT / ALERTS / TIME ZONE / SYSTEM. Chrome
#: follows volume mode's hard-won rules: the mode owns the whole glass
#: (no fall-through to the wedges), the dial is PINNED while it is up,
#: everything is painted AFTER the display rotate in raw screen coords so
#: hit-tests and paint agree, and the one exit is a DONE ring — no
#: timeout that dumps the owner out mid-thought. Pages turn by swipe or
#: by the rim chevrons; the dot rail says where you are.
#:
#: Persistent choices live in settings_store.SettingsStore
#: (/home/ledger/aura_face/settings.json — survives reboot); shelling out
#: for facts (nmcli/amixer/systemctl) happens ONLY on the store's
#: background thread. The draw path reads snapshots and memory, nothing
#: else.
#: CONNECT joins the book at index 1 (2026-08-02, AuraConnect phase 2).
#: A sixth WEDGE was the obvious move and the wrong one: the five sectors
#: are 34deg wide between r=336 and r=458, baked into home.html's MENU and
#: into base.png, and the owner approved that dial. The book is already
#: paged, already modal, already orientable — so the drop box is a page.
#: Sitting next to WI-FI is deliberate: both pages answer "how do things
#: get in here". Page order is free — every dispatch below is BY NAME.
#: WALLET joins the book (2026-08-08, premium program): the LINK WALLET
#: ceremony is a page for the same reason CONNECT is — the book is already
#: paged, modal, orientable, and dispatch below is BY NAME.
SET_PAGES = ["WI-FI", "CONNECT", "CONTACT", "ALERTS", "TIME ZONE", "WALLET",
             "SYSTEM"]
SET_DONE_XY = (540, 920)
SET_DONE_R = 64
SET_DONE_HIT_R = SET_DONE_R + 24     # fingers are round, glass is glass
SET_ARROW_L = (120, 540)
SET_ARROW_R = (960, 540)
SET_ARROW_HIT_R = 78
SET_DOTS_Y = 838
SET_DOT_DX = 46.0                    # dot pitch — paint and hit-test share it
SET_SWIPE_PX = 140                   # min horizontal travel to turn a page
#: Round 2: drags that BEGIN out on the rim — past the chevrons (r≈420)
#: and every page's content — rotate the whole settings book toward the
#: person using it (_SET["view_deg"]); inner drags stay page swipes.
SET_ORIENT_R = 440.0
#: Wi-Fi page geometry — the tap hit-tests index the SAME row list the
#: last frame drew (_SET["wifi_rows"]), so a snapshot refresh between
#: frame and finger can never connect to the wrong network.
SET_WIFI_ROWS = 4
SET_WIFI_ROW_Y0, SET_WIFI_ROW_H = 340, 74
SET_WIFI_ROW_X0, SET_WIFI_ROW_X1 = 235, 845
SET_WIFI_RESCAN = (415, 652, 665, 722)          # x0, y0, x1, y1
SET_FIELD_PHONE = (230, 250, 850, 420)
SET_FIELD_EMAIL = (230, 448, 850, 618)
SET_ALERT_Y0, SET_ALERT_H = 268, 132
SET_TZ_CONFIRM_XY = (540, 738)
SET_TZ_CONFIRM_R = 56
#: Steel is the settings wedge's own color; the rest is the house palette.
SET_STEEL = (143, 163, 192)
SET_TEXT = (226, 233, 244)
SET_DIM = (110, 124, 146)
SET_CYAN = (56, 200, 255)
SET_GREEN = (53, 208, 127)
SET_RED = (255, 94, 94)
SET_AMBER = (255, 176, 46)
#: Phase-2 handshake files. The puck cannot type: editing contact fields
#: and joining secured unknown networks are VOICE jobs, and these flags
#: are the contract with the conductor. edit_field holds "phone"/"email";
#: wifi_assist holds the SSID Sterling should join by voice.
EDIT_FIELD = Path("/tmp/aura_face/edit_field")
WIFI_ASSIST = Path("/tmp/aura_face/wifi_assist")
#: Written by the FIRST tap during a briefing show; the compositor draws
#: "TAP AGAIN TO EXIT" while it is fresh. See the note at the double-tap.
SCENE_EXIT_HINT = Path("/tmp/aura_face/scene_exit_hint")
SCENE_EXIT_HINT_S = 1.2         # the same window the double-tap allows
#: WALLET page (premium program, docs/PREMIUM.md). The nonce file is the
#: contract with the RTX bridge: the QR carries {device, nonce, ts}, the
#: bridge checks the signed payload's nonce against this file (no replay),
#: and writes entitlements.json back when the wallet proves out.
#: SECURITY REDLINE: signature-only proof — nothing on this page ever asks
#: for, stores, or displays a seed phrase or private key. A UI that even
#: LOOKS like it wants one is a defect.
WALLET_NONCE = Path("/tmp/aura_face/wallet_nonce")
ENTITLEMENTS = Path("/tmp/aura_face/entitlements.json")
SET_WALLET_ROW = (235, 340, 845, 414)     # x0, y0, x1, y1 — the wifi rows' band
SET_WALLET_QR_PX = 470                    # QR target side — the central dial area
SET_WALLET_QR_CY = 505                    # QR centre y, between caption and dot rail
_WALLET: dict = {"qr_open": False, "qr_img": None, "nonce": ""}
_SET: dict = {"open": False, "page": 0, "grab_deg": 0.0,
              "wifi_rows": [], "assist_ssid": "", "assist_until": 0.0,
              "err": "", "err_until": 0.0,
              # round 2: orientation + first-open coach
              "view_deg": 0.0, "view_prev_ang": None,
              "hint_until": 0.0, "ever_opened": False}
_STORE = settings_store.SettingsStore()
_BACKEND = settings_store.SettingsBackend(_STORE)
#: The conductor writes settings.json DIRECTLY when a value is dictated
#: by voice (edit_field flow). Our in-memory copy must reload when that
#: flag clears, or the next toggle-save clobbers the dictated contact
#: with stale data (voice-capture crew's gap #1, 2026-08-02).
_EDIT_FIELD_SEEN = [False]


def _settings_reload_if_dictated():
    was = _EDIT_FIELD_SEEN[0]
    now = EDIT_FIELD.exists()
    _EDIT_FIELD_SEEN[0] = now
    if was and not now:
        try:
            _STORE.reload()
        except AttributeError:
            _STORE.__init__()
        print("settings: reloaded after voice dictation", flush=True)


# ---------------------------------------------------------------------------
#: ── THE DEVICE HAS TO BE ABLE TO SAY IT IS UNWELL (2026-08-20) ─────────────
#:
#: The consumer-readiness audit's first finding, on two independent passes:
#: IT DOES NOT FAIL, IT FAILS BEAUTIFULLY. Every failure this fleet has
#: actually suffered leaves a device indistinguishable from a working one —
#: the dial animates, the ring answers a finger, and she cannot hear or
#: think. Both non-Paul pucks have shipped a whole day in that state:
#:
#:   * BOB'S, the night of 2026-08-16: the ears watchdog killed and
#:     restarted the process 403 times chasing a 464 MB model over wifi that
#:     dipped to 30 kB/s (FAILURES 2026-08-17). `systemctl is-active
#:     aura-ears` read ACTIVE for every one of those ~80-second lives, and
#:     the SYSTEM page as it stood would have been entirely green.
#:   * FERRARI'S: no ollama binary on the box at all, so every question hit
#:     a refused connection on 127.0.0.1:11434 — undetected for days.
#:
#: In both cases every instrument on the device said fine and the owner said
#: "it doesn't work". This block is the instrument that would have
#: disagreed. §1 at the scale of a product: a working device and a deaf one
#: must not look the same.
#:
#: FOUR RULES IT IS BUILT TO, every one of them paid for elsewhere:
#:
#: 1. NO SUBPROCESS IN THE DRAW PATH, EVER — settings_store's rule, and this
#:    obeys it on a thread of its own. It is a SECOND gatherer only because
#:    it has a different LIFETIME: `SettingsBackend` runs while the book is
#:    open, and the entire point here is to know while nobody is looking. It
#:    shells out through settings_store's own `_sh`, rather than inventing a
#:    second way to run `systemctl is-active` (§15).
#: 2. "I CANNOT TELL" IS NOT "NO" (§2). Until the first poll lands every row
#:    reads CHECKING and the resting-face mark stays dark. A device must not
#:    accuse itself of being broken during its own boot.
#: 3. THE FAN GOVERNOR OWNS TEMPERATURE. `scripts/thermal_policy.py` exists
#:    because brief_baker independently decided 84C was too hot while the
#:    governor deliberately HOLDS the die at 87 — 771 refusals in three
#:    days, an 18-hour-old briefing, nothing in any log marked wrong. An
#:    alarm at the governor's own setpoint would rebuild that deadlock in
#:    pixels and would light this mark permanently on a healthy puck, so the
#:    alarm is PANIC_C and it is IMPORTED.
#: 4. THE CAPTURE HEARTBEAT IS room.json, NOT pulse.json. pulse.json is
#:    written at an ENDPOINT — it says somebody spoke — so a stale one means
#:    "quiet evening" at least as often as "deaf device", and a mark keyed
#:    to it would cry wolf every night. room.json is republished every
#:    DOA_PERIOD_S (0.6 s) whether or not anybody speaks, which is the
#:    quantity actually wanted: are frames still arriving off the array.
#:    BOTH are shown on the page — the pulse as "LAST HEARD", which is real
#:    information — but only room.json raises a fault.
HEALTH_REFRESH_S = 20.0
#: The two units that make this a device rather than a lamp. Named in
#: deploy/aura-ears.service and deploy/aura-conduct.service; both are SYSTEM
#: units, so plain `systemctl is-active` — no --user and no _USER_ENV, which
#: pipewire needs and these must not have.
#:
#: THE THIRD COLUMN IS THE SYMPTOM, and it is the resting face's whole
#: vocabulary. The page is the diagnosis and names the unit; the mark on the
#: glass is read by whoever is standing in the room, and "aura-conduct
#: failed" tells that person nothing they can act on. "SHE CANNOT REPLY"
#: does — it is the sentence they were about to say themselves.
HEALTH_UNITS = (("EARS", "aura-ears", "SHE CANNOT HEAR"),
                ("CONDUCT", "aura-conduct", "SHE CANNOT REPLY"))
#: Ollama's cheapest honest question: /api/tags answers from the server
#: without loading a model, so it costs no GPU and cannot be confused with a
#: cold-load stall.
HEALTH_OLLAMA_URL = "http://127.0.0.1:11434/api/tags"
HEALTH_OLLAMA_TIMEOUT_S = 3.0
#: ROOM_FRESH_S (6 s, ten missed ticks) is right for a NEEDLE, which should
#: fall off scale the moment the feed hiccups. A fault wants to be sure:
#: 90 s is 150 missed ticks, which nothing transient survives, and a
#: genuinely stopped capture still shows up inside two polls.
HEALTH_DEAF_S = 90.0
#: Under this and the device is living on borrowed time — the journal, the
#: packs and the next briefing bake all want room, and a full disk on this
#: fleet has already taken the logging out with it.
HEALTH_DISK_LOW_GB = 1.0
#: The governor's own reading: MAX over every zone, not one pinned zone.
#: `aura_fan_governor` globs exactly this and takes the max, and the number
#: the alarm is compared against comes from the same file's policy, so the
#: two cannot disagree about what "hot" means.
HEALTH_TZ_GLOB = "/sys/class/thermal/thermal_zone*/temp"
#: ── WHERE scripts/ IS DEPENDS ON HOW THIS FILE WAS DEPLOYED ─────────────
#: (2026-08-21) `parents[2] / "scripts"` is correct in the repo, where this
#: file sits at apps/puck_face/dj_face.py. It is wrong on every puck,
#: because the compositor is deployed FLAT to ~/aura_face/dj_face.py — so
#: parents[2] resolves to `/home` and the import looked for
#: `/home/scripts`. Both devices had been running the fallback constants
#: for as long as the health poller has existed, and saying so at startup
#: is the only reason anybody noticed:
#:
#:   health: ... normal band is 87C, hot at 92C (FALLBACK, thermal_policy
#:   unreadable: ModuleNotFoundError("No module named 'thermal_policy'"))
#:
#: The values agreed, which is exactly why it survived — §15's corollary,
#: already stated below about the FILE vs the module name: a value that
#: agrees with its fallback is not evidence it came from the right place.
#: The moment somebody tuned the governor, the face would have kept
#: alarming on the old numbers and nothing would have said why.
#:
#: `brief_baker` and `aura_fan_governor` both resolve it today — the baker
#: from its own ROOT, the governor from a sibling — so this is the one
#: reader that had to guess, and it should not guess once.
_TP_DIRS = [
    #: the repo layout, and the checkout on the puck
    Path(__file__).resolve().parents[2] / "scripts",
    #: the flat deploy: ~/aura_face/dj_face.py, with the tree beside it
    Path.home() / "aura-next" / "scripts",
    #: a copy dropped next to the compositor, last so a stray one cannot
    #: win over the tree it was copied from
    Path(__file__).resolve().parent,
]
try:
    #: APPENDED, not inserted at 0 as brief_baker does the same import. This
    #: is the compositor: it has to come up on a puck with nothing else
    #: alive, and putting 192 repo scripts AHEAD of the standard library on
    #: its path to read one float is a trade with no upside. Nothing in
    #: scripts/ shadows a stdlib name today; appending means it never can.
    for _tpd in _TP_DIRS:
        if (_tpd / "thermal_policy.py").exists():
            sys.path.append(str(_tpd))
            break
    import thermal_policy                                   # noqa: E402
    HEALTH_HOT_C = thermal_policy.PANIC_C
    HEALTH_TARGET_C = thermal_policy.TARGET_C
    #: The FILE, not the module name: "a value that agrees with its fallback
    #: is not evidence it came from the right place" (§15's corollary), and
    #: on a device with two checkouts the name alone would not settle it.
    _HEALTH_TEMP_SRC = getattr(thermal_policy, "__file__", "thermal_policy")
except Exception as _exc:                                   # noqa: BLE001
    HEALTH_HOT_C, HEALTH_TARGET_C = 92.0, 87.0
    _HEALTH_TEMP_SRC = f"FALLBACK, thermal_policy unreadable: {_exc!r}"

#: THE MUTE THAT COMES BACK (FAILURES 2026-08-17, and its correction the
#: next morning: "THE TEMP FLAG IS A PROJECTION, NOT THE STATE").
#: `deploy/aura-ears.service` carries an ExecStartPre that re-creates
#: /tmp/aura_face/muted from this file at EVERY start. So a person who
#: unmutes at the glass, uses the puck all day and then sees the ears
#: restart is silently re-muted — which is precisely what happened to Bob:
#: eleven hours of a device that had been unmuted by hand and was deaf
#: again three minutes after a restart nobody connected to it.
#:
#: The unit hard-codes /home/ledger/aura_face/mute and cannot import this;
#: Path.home() is the same path on the device and the same idiom
#: puck_conduct's NOLOCK uses for its neighbour file in this directory.
MUTE_PERSIST = Path.home() / "aura_face" / "mute"


def _unmute_persistent() -> str:
    """Clear the mute that survives a restart, and say out loud what
    happened either way.

    RENAMED, NOT DELETED. That is how it was cleared by hand on 08-17
    (`mute.cleared-20260817`) and the reason stands: this file is the only
    artefact showing that a device was ever deliberately silenced, and the
    next person asking "why was this puck quiet on the 20th" wants it.

    A FAILURE HERE IS LOUD, in the log AND on the glass. If the rename and
    the unlink both fail, the device is still armed to re-mute itself and
    the person who just tapped has every reason to believe it will not —
    which is the exact shape of the bug this function exists to end. The
    health poller reads MUTE_PERSIST on its next pass and raises
    "RE-MUTES ON RESTART" on the resting face, so the glass says so within
    HEALTH_REFRESH_S without this path needing its own screen.
    """
    try:
        if not MUTE_PERSIST.exists():
            return "absent"
    except Exception:                                       # noqa: BLE001
        return "absent"
    keep = MUTE_PERSIST.with_name(
        f"mute.cleared-{time.strftime('%Y%m%d-%H%M%S')}")
    try:
        MUTE_PERSIST.replace(keep)
        print(f"tap: persistent mute cleared — kept as {keep.name}",
              flush=True)
        return "cleared"
    except Exception as e:                                  # noqa: BLE001
        try:
            MUTE_PERSIST.unlink()
            print(f"tap: persistent mute deleted (could not keep it: {e!r})",
                  flush=True)
            return "cleared"
        except Exception as e2:                             # noqa: BLE001
            print(f"tap: PERSISTENT MUTE NOT CLEARED {e2!r} — {MUTE_PERSIST} "
                  f"is still there and this device WILL re-mute itself at "
                  f"the next aura-ears restart", flush=True)
            return "failed"


_HEALTH: dict = {"at": 0.0, "faults": []}
#: When this process began watching. The deaf test needs it: "room.json has
#: not been written for 90 s" is only meaningful once we have been LOOKING
#: for 90 s, or every compositor start would accuse the ears of being dead
#: during their own cold init.
#:
#: MEASURED AGAINST THE FAILURE IT HAS TO CATCH, not chosen for comfort.
#: The obvious grace — "wait until the ears unit has been continuously
#: active for two minutes" — would have stayed silent through Bob's entire
#: night: the watchdog killed and restarted that process every ~80 s, so it
#: was NEVER continuously active for two minutes, and the one device this
#: mark exists for would have been the one device it could not report.
#: Keyed to our own start instead, which nothing on the box can flap.
_HEALTH_T0 = [0.0]


def health() -> dict:
    """The last health snapshot. Replaced wholesale and never mutated —
    settings_store's rule for its reason: the render thread may still be
    holding last frame's reference."""
    return _HEALTH


def health_faults() -> list:
    """Short words for what is wrong, worst first. Empty both when
    everything checked out and when nothing has been checked YET — see
    rule 2 above; the two are distinguished on the page, not here."""
    return _HEALTH.get("faults") or []


def _health_unit(unit: str) -> str:
    try:
        p = settings_store._sh(["systemctl", "is-active", unit], timeout=6.0)
        return (p.stdout.strip() or p.stderr.strip() or "unknown").lower()
    except Exception as e:                                  # noqa: BLE001
        print(f"health: {unit} is-active failed {e!r}", flush=True)
        return "unknown"


def _health_ollama() -> str:
    """OK, or WHICH failure. REFUSED and TIMEOUT are different diseases —
    ferrari had no binary at all (a refusal) and a wedged server times out —
    and collapsing them to "down" would throw away the one bit that says
    whether to install something or restart something."""
    import urllib.error
    import urllib.request
    try:
        with urllib.request.urlopen(
                HEALTH_OLLAMA_URL, timeout=HEALTH_OLLAMA_TIMEOUT_S) as r:
            code = getattr(r, "status", None) or r.getcode()
            return "ok" if code == 200 else f"http {code}"
    except urllib.error.HTTPError as e:
        return f"http {e.code}"
    except Exception as e:                                  # noqa: BLE001
        t = repr(e).lower()
        if "refused" in t:
            return "refused"
        if "timed out" in t or "timeout" in t:
            return "timeout"
        return "down"


def _health_age(p: Path):
    """Seconds since a flag file was last written, or None if it is not
    there. None is NOT zero and the callers must not read it as fresh."""
    try:
        return max(0.0, time.time() - p.stat().st_mtime)
    except OSError:
        return None


def _health_temp_c():
    import glob as _glob
    best = None
    for f in _glob.glob(HEALTH_TZ_GLOB):
        try:
            v = int(Path(f).read_text().strip()) / 1000.0
        except Exception:                                   # noqa: BLE001
            continue
        # A zone that reads 0 or 500 is a zone that is not measuring silicon.
        if 0.0 < v < 200.0 and (best is None or v > best):
            best = v
    return best


def _health_disk():
    import shutil
    try:
        u = shutil.disk_usage("/")
        return u.free / 1e9, int(round(100.0 * u.used / max(1, u.total)))
    except Exception:                                       # noqa: BLE001
        return None, None


def _health_refresh() -> None:
    global _HEALTH
    f: dict = {"at": time.time()}
    if not _HEALTH_T0[0]:
        _HEALTH_T0[0] = f["at"]
    for _lbl, unit, _sym in HEALTH_UNITS:
        f[unit] = _health_unit(unit)
    f["room_age"] = _health_age(ROOM_FEED)
    f["pulse_age"] = _health_age(PULSE_STATE)
    f["ollama"] = _health_ollama()
    f["temp_c"] = _health_temp_c()
    f["disk_free_gb"], f["disk_pct"] = _health_disk()
    #: THE HEARING ROW ASKS THE ONE STATE (2026-08-21). It read MUTED
    #: alone, so a BRICKED puck — identically deaf, identically red —
    #: reported HEARING: NO FEED on its own settings page and raised the
    #: deafness fault below. Two names for one state, disagreeing about
    #: what the device was doing.
    f["mute_tmp"] = deaf_now()
    try:
        f["mute_persist"] = MUTE_PERSIST.exists()
    except Exception:                                       # noqa: BLE001
        f["mute_persist"] = False

    #: SYMPTOMS, WORST FIRST, and short on purpose: this list is what the
    #: resting face says in one line on a round glass whose usable chord at
    #: that radius is ~430 px. "SHE CANNOT REPLY +5" is the longest string
    #: this table can produce, and the mark shrinks its own type if a theme
    #: ever makes even that too wide (`_health_fit`).
    #:
    #: "activating" is deliberately NOT a fault — a unit two seconds into
    #: its start is a device booting, and a mark that fires on every boot is
    #: a mark people learn to ignore, which costs more than it buys.
    faults: list = []
    for _lbl, unit, sym in HEALTH_UNITS:
        if f[unit] not in ("active", "activating"):
            faults.append(sym)
    #: Only when the unit itself is up: "aura-ears is dead" already says
    #: everything "no frames" would, and two lines for one fault is how a
    #: quiet mark turns into an alarm.
    #:
    #: AND NOT WHILE SHE IS MUTED ON PURPOSE. A mute is deliberate deafness;
    #: reporting it as a fault is the wolf-crying that makes people stop
    #: reading the mark at all. The mute has its own row, and its own face.
    if f[HEALTH_UNITS[0][1]] == "active" and not f["mute_tmp"] \
            and f["at"] - _HEALTH_T0[0] > HEALTH_DEAF_S and (
                f["room_age"] is None or f["room_age"] > HEALTH_DEAF_S):
        faults.append(HEALTH_UNITS[0][2])       # the same symptom, other cause
    if f["ollama"] != "ok":
        faults.append("SHE CANNOT THINK")
    if f["temp_c"] is not None and f["temp_c"] >= HEALTH_HOT_C:
        faults.append("RUNNING HOT")
    if f["disk_free_gb"] is not None \
            and f["disk_free_gb"] < HEALTH_DISK_LOW_GB:
        faults.append("DISK FULL")
    #: The mute that is not in force but is ARMED to come back at the next
    #: ears restart. This is the fault Bob's puck had for eleven hours with
    #: nothing anywhere to report it, and it is the reader-side half of the
    #: fix: even if the glass tap failed to clear the persistent file, the
    #: device now says so within one poll instead of ambushing him later.
    if f["mute_persist"] and not f["mute_tmp"]:
        faults.append("MUTE COMES BACK")
    f["faults"] = faults

    if faults != (_HEALTH.get("faults") or []):
        print("health: " + ("all clear" if not faults
                            else "UNWELL — " + ", ".join(faults)), flush=True)
    _HEALTH = f


def _health_run() -> None:
    while True:
        try:
            _health_refresh()
        except Exception as e:                              # noqa: BLE001
            # The thread must outlive any one bad gather — settings_store's
            # own reasoning, and doubly so here: the watcher going quiet
            # would itself be a silent failure.
            print(f"health: poll failed {e!r}", flush=True)
        time.sleep(HEALTH_REFRESH_S)


def health_start() -> None:
    threading.Thread(target=_health_run, daemon=True, name="health").start()
    print(f"health: watching "
          f"{', '.join(u for _l, u, _s in HEALTH_UNITS)}, ollama, the room "
          f"feed, "
          f"die temp and disk every {HEALTH_REFRESH_S:.0f}s — normal band is "
          f"{HEALTH_TARGET_C:.0f}C, hot at {HEALTH_HOT_C:.0f}C "
          f"({_HEALTH_TEMP_SRC})", flush=True)


#: Deploy hash is not baked into this file, so BUILD is the honest proxy:
#: when this file landed on disk.
try:
    _BUILD = time.strftime("%Y-%m-%d %H:%M",
                           time.localtime(os.path.getmtime(__file__)))
except Exception:
    _BUILD = "unknown"
_RIPPLE = [0.0, 0, 0]        # (t0, x, y) — tap acknowledgment burst
CLICK_WAV = Path("/tmp/aura_face/click.wav")


def _read_volume() -> int:
    try:
        out = subprocess.run(["amixer", "-c", "0", "sget", "PCM"],
                             capture_output=True, text=True, timeout=2).stdout
        m = re.search(r"\[(\d+)%\]", out)
        return int(m.group(1)) if m else 60
    except Exception:
        return 60


def _set_volume(pct: int) -> None:
    _spawn_player(["amixer", "-q", "-c", "0", "sset", "PCM", f"{pct}%"],
                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def _make_click() -> None:
    """A 12ms tick, generated once — the detent's voice."""
    if CLICK_WAV.exists():
        return
    import wave as _w
    rate, dur = 22050, 0.012
    n = int(rate * dur)
    frames = bytearray()
    for i in range(n):
        env = 1.0 - i / n
        v = int(18000 * env * math.sin(i * 2 * math.pi * 2400 / rate))
        frames += int(v).to_bytes(2, "little", signed=True)
    CLICK_WAV.parent.mkdir(parents=True, exist_ok=True)
    with _w.open(str(CLICK_WAV), "wb") as w:
        w.setnchannels(1); w.setsampwidth(2); w.setframerate(rate)
        w.writeframes(bytes(frames))


#: ── THE GLASS ANSWERS (2026-08-17) ──────────────────────────────────────
#: Owner: "i want more tactile feedback so even just a click sound when you
#: tap the screen to show the user its input was acknowledged, and some cool
#: but tasteful noises when the wedges transition in and out."
#:
#: This is PRINCIPLES §13 in its purest form — the first hundred
#: milliseconds belong to acknowledgment — and on a device with no travel
#: in its glass, sound is the only acknowledgment available at that speed.
#: The wedge ring takes 4.1 s to finish arriving; the tick has to land in
#: 20 ms or the tap reads as ignored, which is exactly what he reported
#: about the panes he could not press.
#:
#: THE SOUNDS ARE SYNTHESISED HERE, not shipped as assets. Three reasons:
#: a puck that is missing an asset is a puck that is silently less
#: responsive (§1); the whole set is under a kilobyte of arithmetic; and
#: keeping the shapes in code means the next person can hear WHY they are
#: what they are rather than opening a wav in an editor.
#:
#: TASTEFUL is a specification, not a mood. Every one of these is: quiet
#: (peak well under the detent tick, which is itself a tick and not a
#: beep), short, band-limited under 2 kHz where the puck's small speaker is
#: not shrill, and given a raised-cosine attack so nothing starts with a
#: transient click of its own. The ring's two are the same gesture in
#: opposite directions — a glide up as the panes condense, the same glide
#: down as they dissolve — because they are one control, and a UI whose
#: open and close are unrelated noises sounds like two different machines.
TAP_WAV = Path("/tmp/aura_face/ui_tap.wav")
RING_UP_WAV = Path("/tmp/aura_face/ui_ring_up.wav")
RING_DN_WAV = Path("/tmp/aura_face/ui_ring_dn.wav")
#: -- THE CACHE HAS TO KNOW WHICH SYNTHESIS MADE IT (2026-08-17) ---------
#: These are generated once and skipped if present, and /tmp survives a
#: service restart. So the whole of a rewritten synthesis can be deployed,
#: md5-verified on the device, restarted cleanly -- and the puck goes on
#: playing the sound it built days ago, because the file is still there.
#: The code changed and the artefact did not. Nothing anywhere would say
#: so; the owner would simply report that the new sound sounds identical
#: to the old one, and he would be right.
#:
#: Bump this whenever the synthesis changes. A mismatch deletes the wavs
#: and rebuilds them, which turns a silent staleness into an automatic
#: correction -- and the log line makes it visible either way (S1).
AUR_UI_SND_VER = 5
UI_SND_VER_FILE = Path("/tmp/aura_face/ui_snd.ver")


def _ui_sound_cache_check() -> None:
    """Drop the cached wavs if they were built by a different synthesis."""
    try:
        was = UI_SND_VER_FILE.read_text().strip()
    except Exception:                                   # noqa: BLE001
        was = ""
    if was == str(AUR_UI_SND_VER):
        return
    gone = []
    for q in (TAP_WAV, RING_UP_WAV, RING_DN_WAV):
        if q.exists():
            q.unlink()
            gone.append(q.name)
    UI_SND_VER_FILE.parent.mkdir(parents=True, exist_ok=True)
    UI_SND_VER_FILE.write_text(str(AUR_UI_SND_VER))
    print(f"ui sounds: cache was v{was or '?'}, code is v{AUR_UI_SND_VER} — "
          f"rebuilt {len(gone)} file(s)", flush=True)


def _write_wav(path: "Path", samples, rate: int = 22050) -> None:
    import wave as _w
    frames = bytearray()
    for v in samples:
        frames += int(max(-32000, min(32000, v))).to_bytes(
            2, "little", signed=True)
    path.parent.mkdir(parents=True, exist_ok=True)
    with _w.open(str(path), "wb") as w:
        w.setnchannels(1)
        w.setsampwidth(2)
        w.setframerate(rate)
        w.writeframes(bytes(frames))


def _make_ui_sounds() -> None:
    """Generate the three UI sounds once. Cheap, and skipped if present."""
    rate = 22050
    _ui_sound_cache_check()
    if not TAP_WAV.exists():
        #: THE TAP: a tock, not a tick. The detent's 2400 Hz tick is right
        #: for a ring crossing a notch twelve times a sweep; a finger
        #: landing on glass wants something lower and rounder or the device
        #: sounds like a mouse. 900 Hz with a 1350 Hz partial at a third
        #: the level, 22 ms, raised-cosine in over the first 3 ms.
        #: -- LOUD ENOUGH TO EXIST (2026-08-17) -------------------------
        #: Owner: "no more sound tactile feedback when i hit the screen, i
        #: have no idea why." Nothing was broken: PipeWire alive, the sink
        #: unmuted at 85%, the wav present, pw-play returning 0, no error in
        #: any log. It was simply INAUDIBLE -- 22 ms at a peak of 0.246,
        #: against a room whose noise floor was measured today rising
        #: tenfold when the fan spins up. A sound quieter than the fan is a
        #: sound that does not exist, and every part of the system reported
        #: success while he heard nothing. Silent success, again, in a new
        #: costume.
        #:
        #: 22 -> 34 ms and roughly twice the amplitude. The ceiling is the
        #: detent tick's 0.534 peak (check_ui_sounds enforces it, because
        #: this fires on every touch and the tick fires twelve times per
        #: sweep), so this sits just under it. A slower decay too: 190 was
        #: a click, 120 is a tock, and the low end survives a fan far
        #: better than the transient does.
        n = int(rate * 0.034)
        out = []
        for i in range(n):
            t = i / rate
            atk = min(1.0, i / max(1.0, rate * 0.003))
            atk = 0.5 - 0.5 * math.cos(math.pi * atk)
            env = atk * math.exp(-t * 120.0)
            v = (math.sin(2 * math.pi * 820.0 * t)
                 + 0.38 * math.sin(2 * math.pi * 1230.0 * t)
                 + 0.16 * math.sin(2 * math.pi * 410.0 * t))
            out.append(16400 * env * v)
        _write_wav(TAP_WAV, out, rate)
    #: THE RING: a glide, 240 ms. Up is 430 -> 720 Hz with a fifth above it
    #: at a quarter level; down is the identical curve reversed and a touch
    #: shorter, because leaving should feel lighter than arriving. Peak is
    #: half the tap's — this fires on a gesture the eye is already watching,
    #: so the sound only has to confirm it, not announce it.
    if not RING_UP_WAV.exists() or not RING_DN_WAV.exists():
        _make_ring_sounds(rate)


def _make_ring_sounds(rate: int = 22050) -> None:
    """The ring arriving and leaving: a mass being damped, not a bell struck.

    ── WHY THIS IS THE FOURTH VERSION (2026-08-17) ────────────────────────
    Owner: "the transition sound is just so clunky, it needs to sound more
    gentle not like a brick falling in a video game sound. devote the RTX to
    develop and render a super high quality transition sound it makes a big
    difference in the user experience."

    One correction to the brief, because it saves the next person a night:
    THE GPU IS NOT THE CONSTRAINT. These are one-second mono clips. What was
    actually limiting them, in order, was the synthesis model, the sample
    rate and the reverb — and only the first of those was really hurting.

    A BELL IS THE WRONG OBJECT. Every previous version built the body from
    four sine partials with exponential decays. That is a struck bar: it has
    a transient, a bright onset and inharmonic ring, which is exactly "a
    brick in a video game" when you play it under a finger. A gentle
    transition is not something being STRUCK at all. It is a mass being
    DAMPED — a heavy drawer meeting a soft-close runner, a magnetic catch
    finding its plate. Almost no attack, energy low, and the RELEASE doing
    all the work.

    So the model changes rather than the parameters:

      * MODES WITH REALISTIC DAMPING RATIOS. Real objects damp faster at
        higher frequencies — that frequency-dependent decay is most of what
        the ear uses to judge mass. Here the top mode dies about six times
        faster than the bottom one, which is why this reads as something
        heavy rather than something small.
      * NO TRANSIENT. The envelope opens over 90 ms on a raised cosine.
        Nothing in it can click.
      * A CONTACT WHISPER, not a strike: a very quiet band of low noise in
        the first 120 ms, the sound of two surfaces meeting rather than
        colliding.
      * 48 kHz. The clips are resampled by the player anyway, but the modes
        and the damping are computed at a rate where nothing folds.

    Arriving, the modes are excited together and settle; leaving, the same
    object is released and the low mode is allowed to ring on alone. Same
    instrument, two gestures — which is what makes them a pair rather than
    two noises.
    """
    import numpy as _np
    #: computed at 48k so nothing aliases; written at 48k, and the player
    #: resamples. The old 22050 put a hard ceiling at 11 kHz, which removed
    #: the air that makes a real object sound like one.
    rate = 48000
    for path, up in ((RING_UP_WAV, True), (RING_DN_WAV, False)):
        if path.exists():
            continue
        dur = 0.62 if up else 0.78
        n = int(rate * dur)
        t = _np.arange(n) / rate
        #: A LOW, SLIGHTLY INHARMONIC SET. Not a harmonic series (that is a
        #: string), not wildly inharmonic (that is a bell) — the ratios a
        #: damped plate gives, which is what a well-made drawer front is.
        modes = ((178.0, 1.00, 2.6), (241.0, 0.62, 4.4),
                 (352.0, 0.34, 8.0), (497.0, 0.16, 15.5))
        body = _np.zeros(n)
        for k, (f0, lvl, dec) in enumerate(modes):
            #: leaving, the fundamental is allowed to ring on: the object
            #: has been let go rather than set down
            d = dec * (1.0 if up else (0.62 if k == 0 else 1.35))
            det = 1.0 + 0.0013 * (k + 1) * (1 if k % 2 else -1)
            body += lvl * _np.exp(-t * d) * _np.sin(
                2.0 * _np.pi * f0 * det * t)
        #: the contact whisper — 120 ms of low noise at the moment of
        #: meeting, two poles so it is breath and not hiss
        rng = _np.random.default_rng(19 if up else 23)
        nz = rng.standard_normal(n)
        z1 = z2 = 0.0
        air = _np.zeros(n)
        for i in range(n):
            z1 += 0.020 * (nz[i] - z1)
            z2 += 0.020 * (z1 - z2)
            air[i] = z2
        air *= 26.0 * _np.exp(-t * 26.0)
        #: NO TRANSIENT. 90 ms of raised cosine in, and a long tail that
        #: lets the low mode finish rather than cutting it.
        atk = _np.clip(t / 0.090, 0.0, 1.0)
        atk = 0.5 - 0.5 * _np.cos(_np.pi * atk)
        u = _np.arange(n) / n
        tail = _np.clip((1.0 - u) / 0.30, 0.0, 1.0)
        tail = 0.5 - 0.5 * _np.cos(_np.pi * tail)
        mix = (0.80 * body + 0.20 * air) * atk * tail
        #: a small room, damped twice — see the note this replaces. Short
        #: (180 ms): a gentle sound in a big room is a gentle sound
        #: somewhere else, and this one happens under the listener's hand.
        _ir_n = int(rate * 0.18)
        _ir = (rng.standard_normal(_ir_n)
               * _np.exp(-_np.arange(_ir_n) / rate * 22.0))
        _zz = 0.0
        for _i in range(_ir_n):
            _zz += 0.035 * (_ir[_i] - _zz)
            _ir[_i] = _zz
        _zz = 0.0
        for _i in range(_ir_n):
            _zz += 0.035 * (_ir[_i] - _zz)
            _ir[_i] = _zz
        wet = _np.convolve(mix, _ir)[:n]
        if _np.abs(wet).max() > 1e-9:
            wet /= _np.abs(wet).max()
        mix = mix * 0.86 + wet * 0.14
        mix /= max(1e-6, float(_np.abs(mix).max()))
        _write_wav(path, (mix * 4800.0).tolist(), rate)


def _ui_sound(which: str) -> None:
    """Play a UI sound, unless the device has been told to be silent.

    MUTE MEANS THE GLASS TOO. A puck that has been muted still ticking
    under a finger is the thing mute exists to stop, and the owner has
    muted this device by tapping it more than once today.
    """
    try:
        if deaf_now() or SLEEPING.exists():
            return
        _make_ui_sounds()
        path = {"tap": TAP_WAV, "up": RING_UP_WAV,
                "down": RING_DN_WAV}.get(which)
        if path is None or not path.exists():
            return
        _snd_play(path)
        pr = True
        #: -- SAY IT ONCE (2026-08-17) ----------------------------------
        #: This was `except Exception: pass`. When the owner reported no
        #: tactile feedback, every channel said everything was fine --
        #: because the one place that could have said otherwise had been
        #: told to say nothing. Diagnosing it took a direct pw-play test on
        #: the device, a mixer read and an env comparison, all of which one
        #: log line would have made unnecessary.
        #:
        #: Once per sound kind, not per tap: this fires on every touch and
        #: a line per touch is its own kind of unusable.
        _AUR.setdefault("snd_said", set())
        if which not in _AUR["snd_said"]:
            _AUR["snd_said"].add(which)
            #: ── AND SAY WHEN IT WAS DELIBERATE (2026-08-18) ──────────
            #: With AURA_SILENT set this printed "(spawned)" while _snd_play
            #: had returned without playing anything. That is the project's
            #: own §1 failure inverted — not silent success but a log
            #: CLAIMING an action it did not take — and it is exactly the
            #: line someone would trust while hunting the next audio bug.
            _st = ("silent (AURA_SILENT)"
                   if os.environ.get("AURA_SILENT") == "1"
                   else "spawned" if pr else "SPAWN FAILED")
            print(f"ui sound: {which} -> {path.name} ({_st})", flush=True)
    except Exception as exc:                            # noqa: BLE001
        _AUR.setdefault("snd_said", set())
        if "err" not in _AUR["snd_said"]:
            _AUR["snd_said"].add("err")
            print(f"ui sound: FAILED {exc!r} — the glass is silent",
                  flush=True)


#: ── THE DETENT TICK CANNOT AFFORD A PROCESS (2026-08-20) ───────────────
#: Owner: "volume dialog still does not have the audible click that it used
#: to have when i change the volume."
#:
#: MEASURED ON THE DEVICE, through the shipped path:
#:
#:     click  12 ms clip -> 164.4 ms per aplay invocation
#:     ui_tap 34 ms clip -> 164.3 ms per aplay invocation
#:
#: The clip length is irrelevant; ~152 ms of that is opening the card. The
#: ring has twelve detents, the UI sound worker plays clips ONE AT A TIME
#: and waits for each, and its queue is capped at three. So a sweep asks
#: for twelve ticks, nine are dropped on the floor by the cap, and the
#: three that survive arrive up to half a second after the finger. He is
#: not hearing "no click" — he is hearing a click that missed its moment.
#:
#: The worker is right for what it was built for. That note is about
#: 620 ms ring sounds where serialising is the fix ("i just tapped it
#: several times and heard it play once but never after"). A 12 ms tick
#: fired twelve times a second is the opposite problem, and it was routed
#: through the same queue because both are "a UI sound".
#:
#: SO: one aplay, held open on stdin, for exactly as long as the volume
#: overlay is up. A tick is then a write() of 528 bytes — microseconds,
#: no spawn, nothing to queue, nothing to drop.
#:
#: SCOPED TO THE OVERLAY, and that is not tidiness. The 2026-08-02 note
#: above is still true: a standing plughw grab makes the pipewire sink
#: unavailable and the next answer cannot play. Holding it forever would
#: buy the tick at the cost of her voice. Holding it while a modal volume
#: dialog owns the glass costs nothing, because nothing else is speaking
#: then — and it is released on DONE, on cancel, and on the timeout.
#: ── AN ALSA STREAM NOBODY FEEDS NEVER STARTS (2026-08-20, same day) ────
#: The note above is half right and shipped silent. Held-open-on-stdin was
#: the correct instinct — the spawn measurement is real and a 12 ms tick
#: cannot afford 164 ms of card-open. What it missed is that writing ONLY
#: at the moment of a tick is not a stream. aplay reads a whole PERIOD from
#: stdin before it touches the PCM, and the default period this card
#: negotiates is 24002 frames — 500 ms. A dial sweep hands it 528 bytes a
#: detent and never reaches one period, so aplay never submits anything.
#:
#: MEASURED AT THE DRIVER on puck-10634, /proc/asound/card0/pcm0p/sub0/status
#: through the shipped code:
#:
#:     tick  1 .. tick 12   written 528B .. 6336B   state=PREPARED
#:     settle 0..3 (a further second)               state=PREPARED
#:
#: The card never left PREPARED. Twelve detents, 144 ms of audio accepted
#: by every write(), and the DAC was never started. Not late, not glued
#: together — nothing played at all, while "volume: click stream open"
#: printed and every write returned success. §1, exactly: a silent success
#: is the worst outcome available, and this one survived three reports.
#:
#: SO: the stream is FED. Three things, and all three are load-bearing.
#:
#:  1. EXPLICIT SIZES. --buffer-size=512 --period-size=128 at 22050. The
#:     card then reports buffer=1116 frames at its native 48000 (23 ms)
#:     and reaches RUNNING within 0.5 s of the open. With the defaults it
#:     reports buffer=24002 and stays PREPARED forever.
#:  2. A FEEDER THREAD writing 128-frame blocks of SILENCE continuously,
#:     self-paced off a wall clock so only ~6 periods (35 ms) are ever
#:     outstanding. Self-paced and not on pipe backpressure: the pipe holds
#:     64 KB, which is 1.5 s of audio at this rate, so backpressure alone
#:     would put every tick a second and a half behind the finger.
#:  3. A TICK REPLACES THE NEXT BLOCK OF SILENCE rather than queueing
#:     behind a buffer of it — _click() appends to a bytearray the feeder
#:     drains. Microseconds, no I/O on the UI thread, nothing to drop.
#:
#: And it says what the card actually did, once per open, half a second in.
#: That one line is what would have caught this a week ago.
CLICK_RATE = 22050          # what we hand aplay; plug converts to 48000
CLICK_PERIOD = 128          # frames per write — 5.8 ms
CLICK_BUFFER = 512          # what the card is asked to hold — 23 ms
CLICK_LEAD = CLICK_PERIOD * 6   # frames kept outstanding — 35 ms
CLICK_QUEUE_CAP = CLICK_RATE // 2   # 500 ms of ticks; past that, drop

#: "p" is read directly by the frame loop to decide whether the card is
#: still held — see the derived close in the main tick. Keep the key.
_CLICK_STREAM: dict = {
    "p": None,       # the aplay process, or None
    "pcm": None,     # the tick's raw frames, cached
    "q": bytearray(),  # frames the feeder owes the card, tail-appended
    "th": None,      # the feeder thread
    "run": False,    # the feeder's stop flag
    "wrote": 0,      # frames handed to aplay since this open
}


def _click_pcm() -> bytes:
    """The tick's raw frames, without the 44-byte WAV header."""
    if _CLICK_STREAM["pcm"] is None:
        try:
            import wave as _w
            with _w.open(str(CLICK_WAV), "rb") as w:
                _CLICK_STREAM["pcm"] = w.readframes(w.getnframes())
        except Exception:                                   # noqa: BLE001
            _CLICK_STREAM["pcm"] = b""
    return _CLICK_STREAM["pcm"]


def _click_status_path():
    """The driver's own account of this card, or None off the puck.

    By CARD NAME first, for the same reason UI_PLAY_DEV is: /proc/asound
    carries a symlink per card name, so this follows the device we are
    actually playing to rather than assuming card0. The workstation has no
    such node and gets None, which every caller treats as "do not report".
    """
    cands = []
    m = re.search(r"CARD=([A-Za-z0-9_]+)", UI_PLAY_DEV)
    if m:
        cands.append(Path("/proc/asound") / m.group(1))
    m = re.search(r"hw:(\d+)", UI_PLAY_DEV)
    if m:
        cands.append(Path(f"/proc/asound/card{m.group(1)}"))
    cands.append(Path("/proc/asound/card0"))
    for c in cands:
        try:
            for sub in sorted(c.glob("pcm*p/sub0/status")):
                return sub
        except Exception:                                   # noqa: BLE001
            continue
    return None


def _click_node(path, key: str) -> str:
    """One `key: value` line out of a /proc/asound node.

    The key is stripped, not matched by prefix: this file writes `state:`
    hard against the colon and `hw_ptr      :` padded, and a prefix match
    reads the padded half as absent — which is a missing measurement
    reported as a fact, the shape of bug this whole block is about.
    """
    try:
        for line in path.read_text().splitlines():
            k, sep, v = line.partition(":")
            if sep and k.strip() == key:
                return v.strip()
    except Exception:                                       # noqa: BLE001
        pass
    return "?"


def _click_feed(p) -> None:
    """Keep the card fed. Silence when idle, the tick when one is queued.

    Paced off the wall clock, never off the pipe: the pipe would happily
    accept 1.5 s of audio and the tick would arrive after the finger had
    stopped moving.
    """
    q = _CLICK_STREAM["q"]
    blk_bytes = CLICK_PERIOD * 2
    sil = b"\0" * blk_bytes
    t0 = time.time()
    stdin = p.stdin
    while _CLICK_STREAM["run"] and p.poll() is None:
        due = int((time.time() - t0) * CLICK_RATE) + CLICK_LEAD
        if _CLICK_STREAM["wrote"] >= due:
            time.sleep(CLICK_PERIOD / CLICK_RATE / 2.0)
            continue
        #: one producer appends at the tail (_click), one consumer removes
        #: at the head (here) — so no lock is needed for either to be
        #: correct, and a lock on the UI thread is what we are avoiding.
        if q:
            blk = bytes(q[:blk_bytes])
            del q[:blk_bytes]
            if len(blk) < blk_bytes:
                blk += b"\0" * (blk_bytes - len(blk))
        else:
            blk = sil
        try:
            stdin.write(blk)
            stdin.flush()
        except Exception:                                   # noqa: BLE001
            #: the far end went away (close, or aplay died). Leave quietly:
            #: a traceback per 5.8 ms frame is its own outage.
            break
        _CLICK_STREAM["wrote"] += CLICK_PERIOD


def _click_report(p) -> None:
    """Half a second after the open, say what the DAC actually did."""
    time.sleep(0.5)
    if _CLICK_STREAM["p"] is not p:
        return
    st = _click_status_path()
    if st is None:
        print("volume: click stream open (no /proc/asound — state unknown)",
              flush=True)
        return
    state = _click_node(st, "state")
    hw = st.parent / "hw_params"
    print(f"volume: click stream state={state} "
          f"rate={_click_node(hw, 'rate')} "
          f"buffer={_click_node(hw, 'buffer_size')} "
          f"fed={_CLICK_STREAM['wrote']} frames", flush=True)
    if state != "RUNNING":
        #: LOUD, and this is the line the whole rewrite exists for.
        print(f"volume: click stream is {state}, not RUNNING — the detent "
              f"will be silent", flush=True)


def _click_open() -> None:
    """Hold the card for the life of the volume dialog, and FEED it.

    Idempotent: a second call while the stream is alive is a no-op.
    """
    if os.environ.get("AURA_SILENT") == "1":
        return
    if _CLICK_STREAM["p"] is not None and _CLICK_STREAM["p"].poll() is None:
        return
    try:
        p = subprocess.Popen(
            ["aplay", "-q", "-D", UI_PLAY_DEV,
             "-f", "S16_LE", "-r", str(CLICK_RATE), "-c", "1",
             f"--buffer-size={CLICK_BUFFER}",
             f"--period-size={CLICK_PERIOD}", "-"],
            stdin=subprocess.PIPE,
            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        _CLICK_STREAM["q"].clear()
        _CLICK_STREAM["wrote"] = 0
        _CLICK_STREAM["run"] = True
        _CLICK_STREAM["p"] = p
        th = threading.Thread(target=_click_feed, args=(p,), daemon=True,
                              name="click-feed")
        th.start()
        _CLICK_STREAM["th"] = th
        threading.Thread(target=_click_report, args=(p,), daemon=True,
                         name="click-state").start()
        print(f"volume: click stream open "
              f"(buffer={CLICK_BUFFER} period={CLICK_PERIOD} "
              f"@{CLICK_RATE}, fed)", flush=True)
    except Exception as exc:                                # noqa: BLE001
        #: LOUD. A silent failure here is exactly the report that started
        #: this: the dialog works, the volume moves, and the one piece of
        #: feedback that says a detent was crossed is missing.
        _CLICK_STREAM["p"] = None
        _CLICK_STREAM["run"] = False
        _CLICK_STREAM["th"] = None
        print(f"volume: click stream FAILED to open {exc!r} — the detent "
              f"will be silent", flush=True)


def _click_close() -> None:
    p = _CLICK_STREAM["p"]
    th = _CLICK_STREAM["th"]
    _CLICK_STREAM["p"] = None
    _CLICK_STREAM["th"] = None
    #: stop the feeder BEFORE the pipe goes, so the ordinary path is a
    #: clean exit from the loop rather than an exception per frame.
    _CLICK_STREAM["run"] = False
    if p is None:
        return
    if th is not None and th is not threading.current_thread():
        #: it may be inside write() this instant; 0.5 s is 85 periods of
        #: slack. If it is still there after that, closing stdin under it
        #: raises inside its own try and it leaves anyway.
        th.join(timeout=0.5)
    try:
        if p.stdin:
            p.stdin.close()
        p.wait(timeout=1.0)
    except Exception:                                       # noqa: BLE001
        try:
            p.kill()
        except Exception:                                   # noqa: BLE001
            pass
    _CLICK_STREAM["q"].clear()
    print("volume: click stream closed", flush=True)


def _click() -> None:
    """One detent tick: an append to a bytearray, not a process, not I/O.

    The feeder is already writing silence to a running card, so this
    REPLACES the next block of it — the tick reaches the DAC ~35 ms later
    rather than queueing behind whatever is buffered.
    """
    p = _CLICK_STREAM["p"]
    if p is not None and p.poll() is None:
        pcm = _click_pcm()
        if pcm:
            q = _CLICK_STREAM["q"]
            #: a runaway queue would drift the tick off the finger; past
            #: half a second of backlog the feeder is not keeping up and
            #: another tick would only make it later.
            if len(q) <= CLICK_QUEUE_CAP * 2:
                q.extend(pcm)
            return
    #: no stream (the dialog is not up, or the open failed): the queued
    #: player is still correct for a one-off tick, e.g. the top-up tiers.
    _snd_play(CLICK_WAV)


def _wedge_sector_poly(a0, a1, r0, r1, pad=6.0, flat=False):
    """The wedge as a closed outline: outer edge first, then the inner arc
    back. With `flat`, the outer edge is the bezel's straight opening rather
    than the arc at r1 (see PANEL_CLEAR) — sampled at half a degree, which
    puts every point ON the flat's own line and lands within 0.02px of the
    mitre where two of them meet."""
    pts = []
    steps = max(4, int((a1 - a0) / (0.5 if flat else 3)))
    for i in range(steps + 1):
        ad = a0 + (a1 - a0) * i / steps
        a = math.radians(ad)
        rr = (_opening_r(ad) + pad) if flat else (r1 + pad)
        pts.append((SIZE / 2 + rr * math.cos(a), SIZE / 2 + rr * math.sin(a)))
    for i in range(steps + 1):
        a = math.radians(a1 - (a1 - a0) * i / steps)
        pts.append((SIZE / 2 + (r0 - pad) * math.cos(a),
                    SIZE / 2 + (r0 - pad) * math.sin(a)))
    return pts


def _make_wedge_assets():
    """Pre-baked per-wedge cover masks and border glows — the intro runs at
    ACTIVE_FPS and can afford zero per-frame drawing beyond composites."""
    covers, glows = [], []
    for a0, a1, col in WEDGES:
        m = Image.new("L", (SIZE, SIZE), 0)
        ImageDraw.Draw(m).polygon(
            _wedge_sector_poly(a0, a1, WEDGE_R0, WEDGE_R1), fill=255)
        covers.append(m.filter(ImageFilter.GaussianBlur(2)))
        g = Image.new("RGB", (SIZE, SIZE), 0)
        d = ImageDraw.Draw(g)
        for r, w in ((WEDGE_R1, 12), (WEDGE_R0, 7)):
            d.arc([SIZE / 2 - r, SIZE / 2 - r, SIZE / 2 + r, SIZE / 2 + r],
                  start=a0, end=a1, fill=col, width=w)
        for a in (a0, a1):
            ar = math.radians(a)
            d.line([(SIZE / 2 + WEDGE_R0 * math.cos(ar),
                     SIZE / 2 + WEDGE_R0 * math.sin(ar)),
                    (SIZE / 2 + WEDGE_R1 * math.cos(ar),
                     SIZE / 2 + WEDGE_R1 * math.sin(ar))], fill=col, width=8)
        glows.append(g.filter(ImageFilter.GaussianBlur(5)))
    return covers, glows


_WEDGE_COVERS, _WEDGE_GLOWS = _make_wedge_assets()
_WEDGE_BLACK = Image.new("RGB", (SIZE, SIZE), 0)

#: ── 2026-08-24: THE ENTRANCE LEARNS POLARITY ──────────────────────────────
#: Owner, on the white shell's face: "it doesn't have the same capabilities
#: as the regular OS right now, no fade in for the wedges".
#:
#: He is right, and the cause is one flag: gallery shipped `no_intro=True`
#: on 2026-08-22 because wedge_intro lifts five BLACK covers with a SCREENED
#: glow. On a dark dial the wedges emerge out of the ground they are already
#: sitting on. On plaster the same code paints five black sectors over the
#: porcelain and fades them out — a dark flash, exactly backwards — and the
#: screen does nothing at all, because screening a glow onto a near-white
#: ground has almost no headroom to brighten into.
#:
#: Switching the flag off would restore the bug the flag was hiding. So the
#: entrance is taught the same lesson LISTEN_INK already taught the
#: listening light (§ the row's own comment: "bright-on-dark treatments
#: invert on a light ground"): the COVER becomes the ground, so the wedge
#: still arrives out of the surface it lives on; and the glow DARKENS
#: instead of brightening, because on porcelain a shadow-bloom is what a
#: highlight is on basalt.
#:
#: Two constants rather than a branch at each call site: one owner for the
#: polarity, per §15.
INTRO_INK = bool(_THEME.get("intro_ink"))
_WEDGE_COVER = Image.new(
    "RGB", (SIZE, SIZE),
    tuple(_THEME.get("white", (250, 248, 241))) if INTRO_INK else (0, 0, 0))

#: ── 2026-08-24: THE WEDGES ANSWER A TAP ON A BAKED FACE ───────────────────
#: Owner: "there is no fade in fade out for the wedges when you press the
#: screen."
#:
#: On aurora the ring is summoned and dismissed by tapping, and fades both
#: ways. On a BAKED face the wedges are painted into the base PNG, so they
#: are simply always there — there was never anything to fade, and the
#: entrance fix earlier today only covered the unlock.
#:
#: Rather than lift the wedges out of the bake (which would mean rebuilding
#: gallery_base.png and re-deriving every stop in it), the covers that
#: already exist for the entrance are held at a persistent alpha: 1.0 hides
#: the sector under the ground colour, 0.0 reveals it. A tap on a hidden
#: ring reveals it and does nothing else; the idle timer puts it back. That
#: is the same grammar aurora has — "one tap does one thing".
#:
#: TAP_WEDGES is opt-in per theme rather than on for every baked face,
#: because chopard, ferrari, tourbillon and royal-oak have shipped with
#: their wedges permanently visible and changing that silently is not a fix,
#: it is a surprise.
TAP_WEDGES = bool(_THEME.get("tap_wedges"))
BAKED_UI_FADE_S = 0.55       # each way; symmetrical on purpose
BAKED_UI_IDLE_S = 14.0       # how long the controls stay up unasked
_BAKED_UI = {"a": 0.0,       # 0 = wedges visible, 1 = hidden under ground
             "goal": 0.0, "t": 0.0, "last": 0.0, "init": False}


def baked_ui_visible() -> bool:
    """True when the wedges are up enough to be pressed."""
    return (not TAP_WEDGES) or _BAKED_UI["a"] < 0.5


def baked_ui_show(now: float) -> None:
    _BAKED_UI.update(goal=0.0, last=now)


def baked_ui_hide(now: float) -> None:
    _BAKED_UI.update(goal=1.0, last=now)


def baked_ui_veil(frame: "Image.Image", now: float) -> "Image.Image":
    """Ease toward the goal and paint the ground over the wedge sectors."""
    if not TAP_WEDGES:
        return frame
    st = _BAKED_UI
    if not st["init"]:
        #: start HIDDEN so the first tap has something to reveal; the
        #: unlock entrance calls baked_ui_show itself.
        st.update(a=1.0, goal=1.0, t=now, last=now, init=True)
    dt = max(0.0, min(0.25, now - st["t"]))
    st["t"] = now
    if st["goal"] == 0.0 and now - st["last"] > BAKED_UI_IDLE_S:
        st["goal"] = 1.0
    step = dt / BAKED_UI_FADE_S
    st["a"] += max(-step, min(step, st["goal"] - st["a"]))
    a = max(0.0, min(1.0, st["a"]))
    if a <= 0.01:
        return frame
    for cover in _WEDGE_COVERS:
        frame = Image.composite(
            _WEDGE_COVER, frame, cover.point(lambda p, k=a: int(p * k)))
    return frame


#: ── 2026-08-09: THE WEDGES BECOME SMOKED GLASS (INSTR rows) ───────────────
#:
#: Owner, at the glass on the ferrari, two asks that are one object: "the
#: wedge tile STROKES (all five, replacing the current pale outlines)" among
#: the places Rosso must go, and "THE WEDGES STILL DO NOT POP — the standing
#: wedge-3D brief applies here too, and on carbon they need more:
#: smoked-glass panels with red strokes, a specular sweep, and a contact
#: shadow so they sit ON the weave rather than in it."
#:
#: WHY IT IS AN OVERLAY IN THIS FILE AND NOT A TILE IN home.html, which is
#: where the five sectors are actually baked. The same three reasons the
#: carbon weave gives at _carbon_weave_sync, and the first one still decides
#: it: base.png is rendered ONCE for the whole fleet off a page that has no
#: idea which theme the device wears, so a red stroke drawn there arrives on
#: the patek and royal-oak pucks too. And it could not be stamped onto the
#: bake either — the stamp path runs BEFORE desertify(), whose convert("L")
#: would hand the Rosso back as a grey. So: after the colourway, before the
#: rotate, like every other mark on this face that means something.
#:
#: FOUR MARKS, IN THE ORDER LIGHT PUTS THEM THERE:
#:   1. the CONTACT SHADOW, offset down-right away from the one upper-left
#:      sky, and masked to OUTSIDE the panel — the whole claim is that these
#:      two surfaces are at different heights, and a shadow that also fell
#:      inside the panel would just be a darker tile;
#:   2. the SMOKED GLASS: the theme's own panel fill, lighter at the top edge
#:      and heavier at the foot, so the pane has a direction;
#:   3. the SPECULAR SWEEP, one broad soft diagonal across the pane at the
#:      key light's own bearing;
#:   4. the RED STROKES, the sector's outline plus an inner hairline — the
#:      outline is 4px against home.html's 2.6px baked one so the pale
#:      original is covered rather than outlined a second time.
#:
#: THE SWEEP IS STATIC, and that is a budget decision rather than a taste
#: one. A travelling highlight is what _conj_shim_states does and it costs a
#: table of 56 states plus a paste per frame; this face already spends 64.5
#: of its 71.4 ms at IDLE_FPS (the note at IDLE_FPS, and FAILURES 2026-08-04
#: on what happens thermally when it overspends). One baked highlight from
#: the one sky is also what the rest of this dial does — every pocket, every
#: cap and every applied letter is lit from POCKET_KEY and none of them move.
#:
#: WHAT IT COSTS: five pastes of 318x318, 505k px of alpha compositing per
#: frame against the 1.16M a full-frame blend touches. Timed over 40 frames
#: on the shipped ferrari bake — 0.85 ms median, 1.03 ms p95 — but ON THE
#: WORKSTATION, not on the puck, and §6 says that number is the wrong units:
#: the SoC is several times slower and the frame budget it has to fit in is
#: 71.4 ms of which 64.5 was already spent. Scaled by the ratio those two
#: boxes show elsewhere it lands around 3-5 ms, which fits; RE-TIME IT THERE
#: before believing that.
#:
#: AND THE CONTACT SHADOW IS NOT BLACK-ON-BLACK, which was the thing to check
#: on a dial this dark (the ambient-bed lesson, §6, in visual form). Measured
#: on the shipped ferrari bake at LOCK's outer edge, dial luminance before
#: and after this call: +2 px out 52 -> 23 (-56%), +4 px 51 -> 26 (-49%),
#: +6 px 53 -> 32 (-40%), +12 px 48 -> 43 (-10%), gone by +20. The pane's own
#: interior goes the other way, 27 -> 53, so the edge carries a real step.
#:
#: ── 2026-08-09, THE LIVERY PASS: THE PANES ARE PAINTED, NOT OUTLINED ──────
#:
#: Owner, at the glass, and it is a diagnosis rather than a defect list: "the
#: chassis is sexier than the engine of the screen. the chassis colour is
#: dramatic and the face is subdued." MEASURED on the live ferrari render
#: (/tmp/ferrari_render.py, redness-weighted coverage — see the note at the
#: bottom of this block): RED COVERED 6.5% OF THE DIAL. A race livery reads
#: red at 8-15%. The theme was a dark grey watch with red trim.
#:
#: THE TILES ARE THE LEVER AND NOTHING ELSE IS CLOSE. The five panes are
#: 21.1% of the dial's area between them — bigger than every other mark on
#: this face put together — and until now they carried the theme's smoked
#: PANEL_FILL, which is a neutral (44,40,41). Every other red on the dial is
#: a line, a numeral or a needle tip: strokes and sprinkles cannot move an
#: area figure, which is why the previous pass put red in five places (the
#: $LEDGER figure, VISION, both registers' index marks, the needle tips, the
#: bezel's ticks) and still landed at 6.5%. Paint on a car body is not trim;
#: a body is mostly paint.
#:
#: WHY A WASH AND NOT A FILL. The pane has to stay GLASS — the smoke, the
#: sweep and the contact shadow above are what make it sit on the weave, and
#: a solid Rosso tile would be a red sticker with a highlight on it. So the
#: Rosso goes on at low alpha OVER the smoke and UNDER the sweep, in the
#: pane's own gradient: the specular still reads as light on glass and the
#: label ink underneath still reads.
#:
#: MEASURED on the live render, pane interiors inset 12px so strokes and
#: labels are out of the sample, against the carbon ground's (43,40,40):
#:   before  head (66,63,64)  foot (64,61,62)   — R over max(G,B): +2, +2
#:   after   head (84,61,62)  foot (86,60,61)   — R over max(G,B): +22, +25
#: The tile is a red tile and the type on it keeps the contrast the smoke
#: gave it.
#:
#: THE COVERAGE FIGURE, AND WHY IT IS WEIGHTED RATHER THAN COUNTED (§3 —
#: when a threshold decides the answer, the threshold is the answer). A
#: binary "is this pixel red" test over the same two renders swings from
#: 3.7% to 10.2% on nothing but the choice of chroma cutoff, because a wash
#: at low alpha sits exactly where such a cutoff lives. So the number quoted
#: here is redness-weighted: for each pixel inside the chapter ring (r<504),
#: w = clip((R - max(G,B)) / 64, 0, 1), summed and divided by the dial's
#: area — a fully saturated Rosso stroke counts 1.0 and a wash counts its
#: fraction, which is what "how much red paint is on this body" means.
#:   before this pass  6.45%
#:   after             13.19%      (the brief asked for 10-14)
#: The harness is /tmp/ferrari_render.py — it replays main()'s compose order
#: over the shipped profile bake off-puck. It is a NUMBER, not an eye:
#: face_review.py's argument stands and the panel is still the artefact.
WGLASS_WASH_A = 18          # the Rosso wash, at the lit top edge...
WGLASS_WASH_LIFT = 30       # ...and how much more of it at the foot
WGLASS_FILL_A = 70          # the smoke, at the lit top edge...
WGLASS_LIFT = 26            # ...and how much more of it at the foot
WGLASS_STROKE_W = 4         # covers home.html's 2.6px pale outline
WGLASS_INNER_A = 96         # the inner hairline of the pair
WGLASS_SPEC_A = 74
WGLASS_SPEC_W = 46
WGLASS_SPEC_BLUR = 9.0
WGLASS_SH_DX, WGLASS_SH_DY = 5, 6    # down-right, away from POCKET_KEY
WGLASS_SH_A = 170
WGLASS_SH_BLUR = 5.0

#: ── 2026-08-09: THE WEDGES FINALLY GET A SECTION ─────────────────────────
#: Owner, and this is the twentieth time of asking in a day: "why is the
#: wedge 3d treatment never being done? i feel like i asked for this 20
#: times over the last 20 hours. make them cooler, they are still 2d."
#:
#: HE IS RIGHT, AND THE REASON IT NEVER LANDED IS STRUCTURAL RATHER THAN
#: NEGLECT — which is worth writing down, because otherwise pass 21 does the
#: same thing pass 20 did. PREMIUM.md states the house standard in one line:
#: "Relief is edges + gradient; DEPTH IS SHADOW between planes." Every pass
#: on this object added a SURFACE: a smoke gradient, then a red wash, then a
#: specular sweep, then a contact shadow, then heavier strokes. Those are
#: all the second half of the standard. Not one of them added the FIRST
#: half — the relief pair — so the pane kept acquiring more finish and no
#: section, and a shape with a uniform outline reads flat no matter how
#: beautifully it is filled. The buttons, the pockets, the bore, the bezel
#: and the tourbillon cage all carry the pair; the wedges were the only
#: raised objects on the dial without it.
#:
#: So: a chamfer, struck the way every other raised edge here is struck. The
#: sky-facing edge takes light, the edge turned away takes shadow, both off
#: the one upper-left source (POCKET_KEY). Offsets are the same arithmetic
#: the machined caps use, with the sign flipped — a cap's LABEL is engraved
#: and lights backwards; a pane is raised and lights forwards.
WGLASS_BEVEL = 3          # px of chamfer on the pane's edge
WGLASS_BEVEL_LIT = 190    # alpha of the lit upper-left lip
WGLASS_BEVEL_OCC = 205    # ...and of the occluded lower-right one
WGLASS_BEVEL_BLUR = 0.8   # a machined chamfer is crisp, not a soft airbrush
_WGLASS: list = []


def _wedge_glass_tiles() -> list:
    """The five panes, baked once as (paste-xy, RGBA tile) and held."""
    if _WGLASS:
        return _WGLASS
    pad = (int(WGLASS_SH_BLUR * 3) + max(WGLASS_SH_DX, WGLASS_SH_DY)
           + WGLASS_STROKE_W)
    for a0, a1, _col in WEDGES:
        # pad=0.0: the pane is the baked sector itself, not the padded
        # outline the entrance covers use — a stroke 6px proud of the tile
        # it borders is a stroke on the dial.
        poly = _wedge_sector_poly(a0, a1, WEDGE_R0, WEDGE_R1, pad=0.0)
        xs = [p[0] for p in poly]
        ys = [p[1] for p in poly]
        x0, y0 = max(0, int(min(xs)) - pad), max(0, int(min(ys)) - pad)
        x1 = min(SIZE, int(max(xs)) + pad + 1)
        y1 = min(SIZE, int(max(ys)) + pad + 1)
        w, h = x1 - x0, y1 - y0
        loc = [(px - x0, py - y0) for px, py in poly]
        panel = Image.new("L", (w, h), 0)
        ImageDraw.Draw(panel).polygon(loc, fill=255)
        # 1. the contact shadow, outside the pane only
        sh = Image.new("L", (w, h), 0)
        ImageDraw.Draw(sh).polygon(
            [(px + WGLASS_SH_DX, py + WGLASS_SH_DY) for px, py in loc],
            fill=WGLASS_SH_A)
        sh = ImageChops.multiply(
            sh.filter(ImageFilter.GaussianBlur(WGLASS_SH_BLUR)),
            ImageChops.invert(panel))
        tile = Image.new("RGBA", (w, h), (0, 0, 0, 0))
        tile.putalpha(sh)
        # 2. the smoke, thinner at the top edge where the sky strikes it
        ramp = Image.linear_gradient("L").resize((w, h)).point(
            lambda v: WGLASS_FILL_A + WGLASS_LIFT * v // 255)
        smoke = Image.new("RGBA", (w, h), PANEL_FILL + (0,))
        smoke.putalpha(ImageChops.multiply(ramp, panel))
        tile.alpha_composite(smoke)
        # 2b. THE PAINT (the livery note at WGLASS_WASH_A). Over the smoke so
        # the pane is a red pane and not a red pane-shaped sticker, under the
        # sweep so the specular is still light on glass, and in the pane's own
        # gradient so the wash has the same direction everything else on the
        # tile has.
        wash = Image.new("RGBA", (w, h), INSTR_RED + (0,))
        wash.putalpha(ImageChops.multiply(
            Image.linear_gradient("L").resize((w, h)).point(
                lambda v: WGLASS_WASH_A + WGLASS_WASH_LIFT * v // 255),
            panel))
        tile.alpha_composite(wash)
        # 3. THE SWEEP, AND IT IS ONE SKY, NOT FIVE. The first cut of this
        # put a fixed screen-diagonal streak at 42% of each TILE, and on the
        # render that is exactly what it looked like: five identical stripes
        # at five unrelated bearings, which reads as a texture rather than as
        # light. A ring of glass panes under one upper-left source catches it
        # differently on every pane, and the two things that vary are WHERE
        # along the pane's width the band sits and HOW BRIGHT it is — both
        # off the same number, this pane's own bearing dotted with POCKET_KEY
        # (f=1 facing the sky, 0 turned away), which is the arithmetic every
        # rim, wall and cap on this dial already uses.
        am = math.radians((a0 + a1) / 2.0)
        f = 0.5 + 0.5 * (math.cos(am) * POCKET_KEY[0]
                         + math.sin(am) * POCKET_KEY[1])
        # facing the light: the band rides near the outer edge; turned away:
        # near the inner one, and dimmer.
        r_spec = WEDGE_R0 + (WEDGE_R1 - WEDGE_R0) * (0.25 + 0.5 * (1.0 - f))
        spec = Image.new("L", (w, h), 0)
        scx, scy = SIZE / 2.0 - x0, SIZE / 2.0 - y0
        ImageDraw.Draw(spec).arc(
            [scx - r_spec, scy - r_spec, scx + r_spec, scy + r_spec],
            a0 - 3.0, a1 + 3.0,
            fill=int(round(WGLASS_SPEC_A * (0.35 + 0.65 * f))),
            width=WGLASS_SPEC_W)
        sweep = Image.new("RGBA", (w, h), INSTR_WHITE + (0,))
        sweep.putalpha(ImageChops.multiply(
            spec.filter(ImageFilter.GaussianBlur(WGLASS_SPEC_BLUR)), panel))
        tile.alpha_composite(sweep)
        # 3b. THE CHAMFER — the half of the house standard this object never
        # got (see WGLASS_BEVEL). A raised pane lights FORWARDS: the lip
        # facing the sky catches it, the lip turned away is occluded. Both
        # come off the pane's own mask by the offset-and-subtract the caps
        # use, so the chamfer follows every curve of the sector exactly and
        # costs one bake rather than a per-frame anything.
        _b = WGLASS_BEVEL
        _kx = int(round(-_b * POCKET_KEY[0]))
        _ky = int(round(-_b * POCKET_KEY[1]))
        for _dx, _dy, _ink, _a in (
                (_kx, _ky, INSTR_WHITE, WGLASS_BEVEL_LIT),
                (-_kx, -_ky, (0, 0, 0), WGLASS_BEVEL_OCC)):
            lip = ImageChops.subtract(
                panel, ImageChops.offset(panel, _dx, _dy))
            lip = ImageChops.multiply(
                lip.filter(ImageFilter.GaussianBlur(WGLASS_BEVEL_BLUR)),
                panel)
            lay = Image.new("RGBA", (w, h), tuple(_ink) + (0,))
            lay.putalpha(lip.point(lambda v, k=_a: v * k // 255))
            tile.alpha_composite(lay)
        # 4. the red pair. joint="curve" or a 4px path leaves a notch at
        # every vertex of a 12-segment arc.
        ink = Image.new("RGBA", (w, h), (0, 0, 0, 0))
        di = ImageDraw.Draw(ink)
        di.line(loc + [loc[0]], fill=INSTR_RED + (255,),
                width=WGLASS_STROKE_W, joint="curve")
        inn = _wedge_sector_poly(a0 + 1.1, a1 - 1.1,
                                 WEDGE_R0 + 7.0, WEDGE_R1 - 7.0, pad=0.0)
        di.line([(px - x0, py - y0) for px, py in inn]
                + [(inn[0][0] - x0, inn[0][1] - y0)],
                fill=INSTR_RED + (WGLASS_INNER_A,), width=1)
        tile.alpha_composite(ink)
        _WGLASS.append(((x0, y0), tile))
    print(f"wedges: {len(_WGLASS)} smoked-glass panes baked "
          f"({'x'.join(str(v) for v in _WGLASS[0][1].size)} each, "
          "red strokes, sweep, contact shadow)", flush=True)
    return _WGLASS


#: ── 2026-08-12: SHE FINALLY TELLS THE TIME ───────────────────────────────
#: Owner's reference is a Happy Sport with BLUE HANDS on pink mother-of-pearl,
#: and "the dial shows no time of its own" has been an open item since the
#: face shipped — a watch that cannot be read is an ornament.
#:
#: BLUED STEEL IS A COLOUR THIS FACE COULD NOT HAVE HAD UNTIL NOW, and that
#: is why they are drawn here rather than baked. desertify() reduces the frame
#: to luminance, so a blue hand painted into home_chopard.html would arrive as
#: rose like everything else (see the note in desertify). Drawn after the
#: colourway, they keep their own metal — the same reason the rubies, the
#: bezel and the anodised caps live on this side of it.
#:
#: THEY SWEEP OVER THE CARTOUCHE, and that is not an oversight. On a Happy
#: Sport the stones run loose under the crystal across the whole dial and the
#: hands pass above them; hands that stopped short of the centre would be a
#: different watch. The cartouche is the chamber, the hands are over it.
#:
#: THE PIVOT IS THE DIAL CENTRE AND THE LENGTHS ARE THE CHAPTER'S. The minute
#: hand reaches the railroad track's inner rail (r=330 viewBox = 331 display)
#: because that is what a minute hand is FOR — pointing at the minute marks —
#: and the hour hand stops at 0.68 of it, which is the classic proportion and
#: keeps it clear of the numerals at r=288.
CH_HAND_BLUE = (44, 62, 138)          # blued steel, the deep end
CH_HAND_LIT = (96, 122, 208)          # its lit flank, upper-left key
CH_HAND_TIP = (196, 212, 246)          # the polished tip catch
CH_HAND_PIN = (232, 206, 172)          # rose-gold centre pin


def _ch_hand_poly(ang_deg: float, length: float, half_w: float,
                  tail: float, off: tuple = (0, 0)) -> list:
    """A leaf hand as a polygon: tail, shoulders, point."""
    a = math.radians(ang_deg - 90.0)
    ca, sa = math.cos(a), math.sin(a)
    cx, cy = SIZE / 2.0 - off[0], SIZE / 2.0 - off[1]

    def at(r, w):
        return (cx + r * ca - w * sa, cy + r * sa + w * ca)
    return [at(-tail, 0.0), at(-tail * 0.35, half_w * 0.55),
            at(length * 0.30, half_w), at(length * 0.72, half_w * 0.62),
            at(length, 0.0), at(length * 0.72, -half_w * 0.62),
            at(length * 0.30, -half_w), at(-tail * 0.35, -half_w * 0.55)]


#: ══ THE PROVERBS, UPPER LEFT (2026-08-13) ════════════════════════════════
#: Her request, in three messages: "in the upper left, put in taiwanese a
#: rotating set of motivating proverbs when the sterling custom tile is not
#: there. it's empty space right now" / "rotate the motivating proverbs every
#: minute and have each character gently transition in with a fade type
#: effect".
#:
#: THESE ARE TÂI-GÍ, NOT MANDARIN, and that distinction is the whole risk —
#: the same trap the wedge labels record in home_chopard_tw.html. A
#: translation engine hands you Mandarin in traditional characters and it
#: looks right. Every line here is a saying that exists in Taiwanese and is
#: quoted in Taiwanese, with its Pe̍h-ōe-jī beside it so she can check the
#: READING rather than only the glyphs. Like the wedge labels, this is a
#: proposal for her to correct, not an answer.
#:
#: SHORT ON PURPOSE. They are set on an arc in an 86px-wide band; a saying
#: longer than seven characters either shrinks below what Han can carry at
#: this size (SCRIPT_FLOOR says 18px and these are 30) or runs out of clear
#: dial. The two longest and best-loved ones — 樹頭徛予在,毋驚樹尾做風颱 and
#: 甘願做牛,毋驚無犁通拖 — are 13 and 11 characters and do not fit; if she
#: wants those, they need two lines and a different slot, which is a real
#: design decision and hers to make.
CH_PROVERBS = (
    ("愛拚才會贏", "ài piànn tsiah ē iânn", "you have to fight to win"),
    ("一枝草一點露", "tsi̍t ki tsháu tsi̍t tiám lōo",
     "every blade of grass gets its drop of dew"),
    ("天公疼戇人", "thinn-kong thiànn gōng-lâng",
     "heaven favours the guileless"),
    ("有量才有福", "ū liōng tsiah ū hok",
     "fortune goes to the big-hearted"),
    ("食緊挵破碗", "tsia̍h kín lòng phuà uánn",
     "eat in haste and you break the bowl"),
    ("好心有好報", "hó sim ū hó pò", "a good heart is repaid"),
)
#: ── WHERE, AND IT WAS MEASURED OFF THE GLASS RATHER THAN CHOSEN ─────────
#: The clear annulus in the upper left, found by distance transform on a
#: photograph of the running face: every direction from 180 to 270 degrees
#: has ~43px of clearance from any ink at r=403, which is an 86px band
#: between the railroad track's outer rail and the bezel's inner edge.
#:
#: r=403 ALSO PUTS IT BEYOND THE HANDS. The minute hand reaches 331 and the
#: hour hand 225 (see the note above), so nothing on this dial ever sweeps
#: across the proverb — the one slot on the face where a line of text is
#: never interrupted. That is worth more than a couple of degrees of
#: composition.
#:
#: 222 degrees is the middle of the run: up and to the left, clear of the
#: wedge ring (which starts at -62 and runs clockwise to 124) by a wide
#: margin at both ends.
CH_PROV_R = 403.0
CH_PROV_MID_DEG = 222.0
CH_PROV_SIZE = 30
CH_PROV_INK = (33, 22, 24)        # the Roman numerals' own ink, sampled
#: Rotate on the minute, as asked. The phase comes off the wall clock and
#: not off a counter, so a restart does not reshuffle the sequence — a
#: proverb that jumps back mid-fade is the kind of thing that reads as a
#: crash (§1).
CH_PROV_PERIOD_S = 60.0
#: Per character: how long one takes to arrive, and how far apart they
#: start. 0.42 * 5 + 1.1 = 3.2s for the longest line, which is a fifth of
#: its minute — it should feel like it is being written, not like a
#: loading bar. AND THE FULL FRAME IS ~6 fps (the aperture's rect path runs
#: at 30, the rest of the dial does not), so a fade shorter than about a
#: second would arrive as three steps and read as a flicker.
CH_PROV_FADE_S = 1.1
CH_PROV_STAGGER_S = 0.42
#: ...and the line leaves together, over the last of its minute. A
#: character-by-character exit would still be exiting when the next line
#: starts arriving.
CH_PROV_OUT_S = 0.9


#: One rotated glyph mask per (character, angle). The angles are fixed by
#: the line's length, so a proverb costs its own six masks ONCE and then
#: nothing — the per-frame work is a point() over a 40px mask, which is what
#: makes a per-character fade affordable on a full frame that already costs
#: 70-105 ms.
_CH_PROV_GLYPH: dict = {}


def _prov_glyph(ch: str, deg: float) -> "Image.Image":
    """The character, rendered white on black and turned to the arc."""
    key = (ch, round(deg, 1))
    msk = _CH_PROV_GLYPH.get(key)
    if msk is None:
        f = face("cjk", CH_PROV_SIZE)
        pad = CH_PROV_SIZE
        m = Image.new("L", (CH_PROV_SIZE + 2 * pad,) * 2, 0)
        ImageDraw.Draw(m).text((m.width / 2, m.height / 2), ch, font=f,
                               fill=255, anchor="mm")
        # PIL turns counter-clockwise for positive angles and the bearing
        # runs clockwise on a screen, so the tangent at `deg` is -(deg+90).
        msk = m.rotate(-(deg + 90.0), resample=Image.BICUBIC)
        _CH_PROV_GLYPH[key] = msk
    return msk


def draw_proverb(frame: "Image.Image", now: float) -> None:
    """One Taiwanese saying on the upper-left dial, a character at a time.

    Drawn AFTER the colourway (this ink is final, not a luminance shelf) and
    BEFORE the dial rotate, so it turns with the dial it is printed on —
    the same side of both as the hands and the wedge glass.
    """
    if not _THEME.get("proverbs"):
        return
    try:
        idx = int(now // CH_PROV_PERIOD_S) % len(CH_PROVERBS)
        t = now % CH_PROV_PERIOD_S
        text = CH_PROVERBS[idx][0]
        n = len(text)
        # advance along the arc, in degrees, from the glyph's own width —
        # Han is square and evenly spaced, so one measurement serves all
        adv = (CH_PROV_SIZE + 7.0) / CH_PROV_R * 180.0 / math.pi
        a0 = CH_PROV_MID_DEG - adv * (n - 1) / 2.0
        out = 1.0
        if t > CH_PROV_PERIOD_S - CH_PROV_OUT_S:
            out = (CH_PROV_PERIOD_S - t) / CH_PROV_OUT_S
        for i, ch in enumerate(text):
            # ── EASE, NOT A RAMP. A linear alpha reads as a wipe; the
            # smoothstep is what makes it a fade you notice only after it
            # has happened, which is the "gently" in her message.
            u = max(0.0, min(1.0, (t - i * CH_PROV_STAGGER_S)
                             / CH_PROV_FADE_S))
            u = u * u * (3.0 - 2.0 * u) * out
            if u <= 0.01:
                continue
            deg = a0 + i * adv
            a = math.radians(deg)
            x = SIZE / 2.0 + CH_PROV_R * math.cos(a)
            y = SIZE / 2.0 + CH_PROV_R * math.sin(a)
            # ── SET ALONG THE ARC, WHICH IS THE ONE PLACE THIS DIAL DOES
            # NOT SET TYPE UPRIGHT. The Roman numerals are upright for the
            # reason home_chopard_tw.html records — a numeral you have to
            # tilt your head for is not elegant — and the first cut of this
            # followed them. On a band this steep, upright characters step
            # diagonally past each other and read as five separate marks
            # rather than one sentence. Every curved caption on a real dial
            # (CHRONOMETRE, AUTOMATIC, SWISS MADE) is set tangentially, and
            # the reason the numerals are the exception is that a numeral at
            # six would be upside down. Nothing here passes 50 degrees.
            msk = _prov_glyph(ch, deg)
            frame.paste(CH_PROV_INK,
                        (int(x - msk.width / 2), int(y - msk.height / 2)),
                        msk.point(lambda v, _u=u: int(v * _u)))
    except Exception as exc:                       # noqa: BLE001
        # §1: a caption that quietly does not paint is indistinguishable
        # from a face that never got the change.
        print(f"proverb: not drawn ({exc!r})", flush=True)


#: ── RAYMARCHED HAND SPRITES (2026-08-13) ─────────────────────────────────
#: Owner: "the blue hands for the patek are not refined enough ... more 3d
#: love and light / steel shine ... too flat and not premium, also lower its
#: prominence by 25%." The polygons are replaced, where sprites exist, by
#: renders from scripts/render_hands.py — a real roof-ridge blade with
#: studio light on its flanks and an inlaid lume stripe, finished with an
#: oxide-film colourise (the body tints, the specular stays white, which is
#: what bluing actually is).
#:
#: ROTATED HERE, RENDERED THERE. The GPU work happened once; the Orin pays
#: a cached rotate. Angles round to 0.5 degrees — the minute hand crosses
#: that in ~5s, so the cache turns over at 0.2 Hz, not 30.
_HAND_SPR = {"loaded": False, "hour": None, "minute": None, "meta": None,
             "rot": {}}
HANDS_DIR = Path.home() / "aura_face" / "hands"
#: 0.49 ≈ the polygons' subtle 165 alpha, lowered a further 25% as asked.
HAND_SPR_ALPHA = 0.60   # 0.49 read as weak once the blades were judged
                        # at the glass; still well under the polygons' 165


def _hand_sprites() -> bool:
    if _HAND_SPR["loaded"]:
        return _HAND_SPR["hour"] is not None
    _HAND_SPR["loaded"] = True
    try:
        _HAND_SPR["meta"] = json.loads((HANDS_DIR / "hands.json").read_text())
        for n in ("hour", "minute"):
            im = Image.open(HANDS_DIR / f"{n}.png").convert("RGBA")
            a = im.getchannel("A").point(
                lambda v: int(v * HAND_SPR_ALPHA))
            im.putalpha(a)
            _HAND_SPR[n] = im
        print(f"hands: raymarched sprites loaded from {HANDS_DIR}",
              flush=True)
        return True
    except Exception as exc:                            # noqa: BLE001
        #: §1: fall back to the polygons AND say so — a face silently
        #: wearing the flat hands looks like the upgrade never shipped.
        print(f"hands: NO sprites ({exc!r}) — polygon hands stay", flush=True)
        return False


def _hand_rotated(name: str, ang: float, length_px: float):
    """(sprite, dx, dy): the rotated hand and its paste offset from pivot."""
    key = (name, round(ang * 2.0) / 2.0, int(length_px))
    hit = _HAND_SPR["rot"].get(key)
    if hit is not None:
        return hit
    spr = _HAND_SPR[name]
    meta = _HAND_SPR["meta"][name]
    k = length_px / (meta["pivot_frac"] * spr.height)
    sm = spr.resize((max(1, int(spr.width * k)),
                     max(1, int(spr.height * k))), Image.LANCZOS)
    pivot = (sm.width / 2.0, meta["pivot_frac"] * sm.height)
    rot = sm.rotate(-key[1], resample=Image.BICUBIC, expand=True)
    #: where the pivot landed after an expand-rotate about the centre
    th = math.radians(-key[1])
    cx0, cy0 = sm.width / 2.0, sm.height / 2.0
    vx, vy = pivot[0] - cx0, pivot[1] - cy0
    #: PIL's rotate is CCW in image coords (y down), i.e. the transform of
    #: content positions uses the CW matrix for +theta
    px = vx * math.cos(th) + vy * math.sin(th) + rot.width / 2.0
    py = -vx * math.sin(th) + vy * math.cos(th) + rot.height / 2.0
    out = (rot, px, py)
    _HAND_SPR["rot"][key] = out
    if len(_HAND_SPR["rot"]) > 24:
        _HAND_SPR["rot"].pop(next(iter(_HAND_SPR["rot"])))
    return out


def draw_chopard_hands(frame: "Image.Image", now: float,
                       off: tuple = (0, 0)) -> None:
    """Blued-steel hour and minute hands. Wrapped whole: new paint in a
    compositor that must never stop.

    `off` shifts the pivot, so the damage-rect path can draw the same hands
    into a 288px crop. IT MUST — the first cut of these came back as two
    disconnected blue slivers with nothing inside r=144, because
    _tourb_rect_paint repaints the aperture from (background + pack sprite)
    at 30 fps and knew nothing about anything drawn over the centre
    afterwards. The `plain` gate's own comment says exactly this would
    happen: "anything drawn over the centre AFTER that would be rubbed out
    by a rect paint." The hands sweep over the cartouche by design, so the
    answer is to teach the rect about them rather than to stand the fast
    path down and give back 8.3 -> 28 fps.
    """
    if not _THEME.get("hands"):
        return
    try:
        lt = time.localtime(now)
        mins = lt.tm_min + lt.tm_sec / 60.0
        hours = (lt.tm_hour % 12) + mins / 60.0
        d = ImageDraw.Draw(frame, "RGBA")
        # Tails trimmed 40/46 -> 15/17. Solid, a counterweight reads as a
        # counterweight; OPEN-WORKED it is two stray lines crossing the
        # other hand's two stray lines, and the middle of the dial became a
        # scribble. The open body is what made the tails wrong, so they came
        # down when it went in — one change, not two.
        #: ── SUBTLE VARIANT (2026-08-13, the patek's idealface pass) ─────
        #: "very very subtly do the hour/minute hands emanating from the
        #: tourbillon in the background." Same blued steel as the reference
        #: (a Theorema skeleton with exactly these hands), 70% width, and
        #: the outline alpha comes down so the dial reads first and the
        #: time second. The chopard keeps its full-strength hands.
        if _THEME.get("hands_sprite") and _hand_sprites():
            lt2 = time.localtime(now)
            _mins = lt2.tm_min + lt2.tm_sec / 60.0
            _hrs = (lt2.tm_hour % 12) + _mins / 60.0
            cx0 = SIZE / 2.0 - off[0]
            cy0 = SIZE / 2.0 - off[1]
            #: 2026-08-13: "not long enough" — the minute hand now reaches
            #: the wedge ring's inner edge (397 display px) as a minute hand
            #: should reach its track; hour at the classic 0.66 of it.
            for _n, _a, _ln in (("hour", _hrs * 30.0, 262.0),
                                ("minute", _mins * 6.0, 392.0)):
                spr, px, py = _hand_rotated(_n, _a, _ln)
                #: ── CAST SHADOW (2026-08-13): a real hand floats above
                #: the dial and shadows it. 2px down-right (the house key
                #: is upper-left), soft, black at ~35% of the blade's own
                #: alpha — depth without prominence.
                _sh = spr.getchannel("A").point(lambda v: int(v * 0.35))
                _shadow = Image.merge("RGBA", (
                    Image.new("L", spr.size, 8), Image.new("L", spr.size, 6),
                    Image.new("L", spr.size, 4), _sh))
                frame.paste(_shadow, (int(cx0 - px) + 2, int(cy0 - py) + 3),
                            _shadow)
                frame.paste(spr, (int(cx0 - px), int(cy0 - py)), spr)
            d2 = ImageDraw.Draw(frame, "RGBA")
            for r, col in ((9.0, (140, 108, 84, 230)),
                           (6.5, CH_HAND_PIN + (255,)),
                           (2.6, (252, 246, 236, 255))):
                d2.ellipse([cx0 - r, cy0 - r, cx0 + r, cy0 + r], fill=col)
            return
        _sub = bool(_THEME.get("hands_subtle"))
        _k = 0.70 if _sub else 1.0
        _a = 165 if _sub else 255
        for ang, ln, hw, tl in ((hours * 30.0, 225.0, 13.0 * _k, 15.0),
                                (mins * 6.0, 331.0, 9.0 * _k, 17.0)):
            poly = _ch_hand_poly(ang, ln, hw, tl, off)
            # ── OPEN-WORKED, AND THE STONES ARE WHY ──────────────────────
            # These were solid, and with the pack live the hour hand lay
            # straight across the cartouche and hid most of the happy
            # stones — the one feature the whole face is built around. Any
            # hand pivoting at the dial centre crosses that window; the
            # cartouche IS the centre. So shortening them or thinning them
            # only trades one loss for another.
            #
            # A SQUELETTE HAND IS THE WATCHMAKING ANSWER and it is not a
            # compromise: open-worked hands exist on jewellery pieces for
            # exactly this reason, so the dial under them stays visible.
            # The outline carries the shape, the tip stays solid so the
            # hand still POINTS, and the stones read straight through the
            # body.
            d.line(poly + [poly[0]], fill=CH_HAND_BLUE + (_a,),
                   width=3 if _sub else 4)
            lit = [(x - 1.3, y - 1.3) for x, y in poly]
            d.line(lit + [lit[0]], fill=CH_HAND_LIT + (170,), width=2)
            # the outer third filled, so the pointing end reads as solid
            # metal against the chapter and only the body is open
            # ...and the solid point runs from the shoulders, not just the
            # last two vertices: a three-point barb reads as an arrowhead
            # stuck on the end, where a watch hand tapers into its tip.
            tipf = [poly[2], poly[3], poly[4], poly[5], poly[6]]
            d.polygon(tipf, fill=CH_HAND_BLUE + (_a,))
            a = math.radians(ang - 90.0)
            tipx = SIZE / 2.0 - off[0] + ln * math.cos(a)
            tipy = SIZE / 2.0 - off[1] + ln * math.sin(a)
            d.ellipse([tipx - 2.4, tipy - 2.4, tipx + 2.4, tipy + 2.4],
                      fill=CH_HAND_TIP + (210,))
        # the centre pin, over both, in the case metal
        pcx, pcy = SIZE / 2.0 - off[0], SIZE / 2.0 - off[1]
        for r, col in ((11.0, (140, 108, 84, 255)), (8.0, CH_HAND_PIN + (255,)),
                       (3.4, (250, 238, 226, 255))):
            d.ellipse([pcx - r, pcy - r, pcx + r, pcy + r], fill=col)
    except Exception as e:                      # noqa: BLE001
        _bez_say(f"chhands:{e!r}",
                 f"chopard hands: draw failed {e!r} — the dial has no time")


def draw_wedge_glass(frame: "Image.Image") -> None:
    """The five panes. AFTER desertify() (the red means something) and BEFORE
    the entrance, so a covered wedge stays covered until its own cue."""
    #: ── 2026-08-27: `relief_panes` WAS VETOED BY A KEY ABOUT GAUGES ─────
    #: `if not INSTR: return` stood alone here, and RELIEF_PANES' own note
    #: says the flag "only decides HOW the pane is drawn, never what or
    #: where it is". Both were true and the pair was not: whether the ring
    #: is drawn AT ALL was decided by `instruments`, a key about numbered
    #: tracks and needle pointers. Nobody could see it because the only two
    #: rows that have ever asked for relief — carbon and the ferrari before
    #: it — both set `instruments` as well, so the gate has never been
    #: exercised in the one direction that fails.
    #:
    #: Found by the lacquer row, which asks for relief and deliberately
    #: does NOT ask for gauge furniture (ferrari owns that language). The
    #: symptom is §7 exactly: two gates on one signal, the second vetoing
    #: silently, and the data had arrived — the sprites bake and re-seat and
    #: print five `relief seat` lines before this function drops them on the
    #: floor. It also showed up as two harnesses disagreeing, which is what
    #: caught it: render_face.py calls draw_aurora_menu DIRECTLY and drew
    #: the panes, render_wedge_ring.py goes through here and drew none.
    #:
    #: Byte-identical for every existing row: carbon and ferrari set INSTR
    #: so the first clause is false either way, and patek, royal-oak,
    #: chopard, gallery and aurora set neither key so both clauses still
    #: refuse. Verified by md5 over the four harnesses' PNGs.
    if not INSTR and not RELIEF_PANES:
        return
    #: ── OR AS A LIT SURFACE, ON A ROW THAT ASKS (2026-08-26) ──────────
    #: Owner: "the wedges are just old school 2-d, where is the depth and
    #: embossing, extrusion, etc." The tiles below are the 08-09 answer to
    #: that same sentence and they are still a DRAWING of an edge: a 3 px
    #: chamfer struck as two strokes at fixed alpha, which cannot know
    #: which way any particular edge faces. `_aur_wedge_sprite` computes
    #: the surface instead. This is the gate, and it is the whole of the
    #: change — see RELIEF_PANES.
    #:
    #: THE SAME FUNCTION, SO THE PANES CANNOT DIVERGE FROM THE TAPS. The
    #: relief ring is drawn from `wedges()` and `wedge_band()`, which is
    #: what handle_tap hit-tests, so the band contract at WEDGE_R0 holds
    #: unchanged and nothing here can light a wedge where nobody pressed.
    #: scripts/test_modal_taps.py is the check.
    #:
    #: alphas all 1.0 and now=0.0: the ring is a pure function of
    #: (alphas, rot_deg) — the 08-18 note above _aur_arris_tile measured
    #: that `now` appears in draw_aurora_menu's signature and nowhere in
    #: its body — and a baked face's panes are always simply THERE. None
    #: of aurora's summon, idle or arrival state is touched.
    if RELIEF_PANES:
        draw_aurora_menu(frame, 0.0, [1.0] * len(wedges()))
        return
    for xy, tile in _wedge_glass_tiles():
        frame.paste(tile, xy, tile)


def wedge_intro(frame: Image.Image, t: float):
    """The entrance, `t` seconds after unlock. Returns (frame, done).

    ── THIS BELONGS TO THE BAKED FACES ONLY (2026-08-20) ─────────────────
    Five covers over the five WEDGES, plus a border glow SCREENED over each
    as it lands. On the aurora face that is another ring's choreography in
    another geometry, laid on top of a seven-pane ring that is already
    arriving — which is what the owner was looking at through six rounds of
    "the wedge fade in is still wrong", while every fix went into
    draw_aurora_menu underneath it.
    The caller already skips this on aurora. The guard is repeated HERE
    because a call site can be added and this function cannot be called
    wrongly if it refuses (§15: one owner for the policy, and it is the
    function that implements it). scripts/test_one_entrance.py asserts it.
    """
    if AURORA_BLOB:
        return frame, True
    done = t >= (len(WEDGES) - 1) * WEDGE_STAGGER_S + WEDGE_THROB_S
    for i, (cover, glow) in enumerate(zip(_WEDGE_COVERS, _WEDGE_GLOWS)):
        tl = t - i * WEDGE_STAGGER_S
        a = 1.0 - max(0.0, min(1.0, tl / WEDGE_FADE_S))
        if a > 0.01:
            #: _WEDGE_COVER is the GROUND, not black — see INTRO_INK. The
            #: timing, stagger and easing are untouched: the owner spent six
            #: rounds getting this pace right and none of that was about
            #: colour.
            frame = Image.composite(
                _WEDGE_COVER, frame, cover.point(lambda p, k=a: int(p * k)))
        if 0.0 <= tl < WEDGE_THROB_S:
            env = 0.5 - 0.5 * math.cos(2 * math.pi * min(1.0, tl / WEDGE_THROB_S))
            pulse = 0.6 + 0.4 * math.sin(tl * 2 * math.pi * 2.6)
            k = env * pulse
            if k > 0.03:
                if INTRO_INK:
                    #: DARKEN, do not screen. Screening onto plaster has no
                    #: headroom, so the throb the owner is meant to see
                    #: simply is not there. A neutral graphite shadow is the
                    #: light-ground equivalent of a highlight — the same
                    #: inversion listen_ink makes, and taken from the glow's
                    #: LUMINANCE so the wedge's own tile colour cannot tint
                    #: the shadow (inverting bone or brass gives a cyan cast
                    #: that reads as a colour fault, not as depth).
                    shade = glow.convert("L").point(
                        lambda p, kk=k: 255 - int(p * kk * 0.72))
                    frame = ImageChops.multiply(
                        frame, Image.merge("RGB", (shade, shade, shade)))
                else:
                    frame = ImageChops.screen(
                        frame, glow.point(lambda p, kk=k: int(p * kk)))
    return frame, done


_BRICK_BG = None


def _brick_sub() -> str:
    """The line under NOT LISTENING — an affordance, so it has to be TRUE.

    This screen has printed exactly one confident lie in its life and it
    cost ninety minutes: `tap to wake`, while the aurora ring ate every
    finger before the handler saw it ("i am still stuck on my lock screen
    no touch will remove it", FAILURES 2026-08-17). That ordering bug is
    fixed. The OTHER way to print the same lie is to say it with no
    touchscreen attached — which is exactly the state this face is most
    likely to be found in when a panel drops: deaf, red and unreachable.

    A function rather than an expression inline so the property can be
    asserted without reading pixels (scripts/test_deaf_state.py).
    """
    if _TOUCH["armed"] and _TOUCH["dev"] is None:
        #: the notice stamped in `blit` already names the missing panel and
        #: dates the outage, so this says the one thing it does not: the
        #: affordance printed here is gone.
        return "a tap cannot reach her"
    return "double tap to wake"


def _brick_frame(k: float) -> Image.Image:
    """The red face: unmistakably OFF, across the room, in the dark."""
    global _BRICK_BG
    if _BRICK_BG is None:
        bg = Image.new("RGB", (SIZE, SIZE), (26, 4, 4))
        d0 = ImageDraw.Draw(bg)
        for rr, v in ((520, 44), (400, 30), (280, 18)):
            d0.ellipse([SIZE/2 - rr, SIZE/2 - rr, SIZE/2 + rr, SIZE/2 + rr],
                       outline=(v + 60, v // 3, v // 3), width=2)
        _BRICK_BG = bg.filter(ImageFilter.GaussianBlur(1))
    frame = _BRICK_BG.copy()
    d = ImageDraw.Draw(frame)
    v = int(120 + 80 * k)
    cx = cy = SIZE // 2
    # padlock, big and centered
    d.rounded_rectangle([cx - 90, cy - 40, cx + 90, cy + 110], radius=18,
                        outline=(v, 40, 40), width=10)
    #: shackle ends buried in the body: a deaf face must not wear an OPEN
    #: lock (it read as "unlocked" to Bob while the text said NOT LISTENING)
    d.arc([cx - 62, cy - 130, cx + 62, cy + 70], start=180, end=360,
          fill=(v, 40, 40), width=10)
    f_lbl = face("text", 40)
    f_sub = face("label", 26)
    msg = "NOT LISTENING"
    tw = d.textlength(msg, font=f_lbl)
    d.text(((SIZE - tw) / 2, cy + 170), msg, font=f_lbl, fill=(255, 120, 110))
    #: ── AND IT ONLY SAYS "TAP" IF A TAP CAN ARRIVE (2026-08-21) ─────────
    #: This screen has printed exactly one confident lie in its life and it
    #: cost ninety minutes: `tap to wake`, while the aurora ring ate every
    #: finger before this handler saw it ("i am still stuck on my lock
    #: screen no touch will remove it", FAILURES 2026-08-17). The ordering
    #: bug is fixed; the OTHER way to print that lie is to say it with no
    #: touchscreen attached, which is the state this face is most likely to
    #: be in when the panel drops — deaf, red, and unreachable.
    sub = _brick_sub()
    tw = d.textlength(sub, font=f_sub)
    d.text(((SIZE - tw) / 2, cy + 240), sub, font=f_sub, fill=(150, 70, 66))
    return frame


def draw_volume(frame: Image.Image, now: float) -> Image.Image:
    """The legacy rim slider reborn: twelve detents around the dial, the
    lit arc is the level, drag anywhere on the glass to set it.

    Drawn in SCREEN coordinates, AFTER the dial rotation — the caller
    composites this overlay last (2026-08-02). The old path drew beneath
    the frame rotate, so on a spun dial every detent displayed rot.deg
    away from the finger that set it: "not mapping correctly to my
    finger... weird offset" (owner, 2026-08-02 morning). The big %
    readout exists because the owner unknowingly left the room at 41%.
    """
    #: A LIGHT FACE IS WASHED, NOT DIMMED. Multiplying a plaster ground by
    #: 0.42 does not remove the dial, it turns it grey and leaves every
    #: wedge and the wordmark legible straight through the card. Blending
    #: TOWARD the theme's own plaster covers them the way the dark scrim
    #: covers aurora's.
    if VOL_WASH:
        frame = Image.blend(
            frame, Image.new("RGB", frame.size, tuple(VOL_WASH)), 0.93)
    else:
        frame = frame.point(lambda p: int(p * VOL_SCRIM))
    d = ImageDraw.Draw(frame)
    steps, rr = 12, int(VOL_RING_R)
    det = _VOL["detent"] or 0
    for i in range(steps):
        a0 = -90 + i * (360.0 / steps) + 3
        a1 = -90 + (i + 1) * (360.0 / steps) - 3
        on = i < det
        col = VOL_ON if on else VOL_OFF
        d.arc([SIZE/2 - rr, SIZE/2 - rr, SIZE/2 + rr, SIZE/2 + rr],
              start=a0, end=a1, fill=col, width=14 if on else 7)
    f_big = face("text", 170)
    f_sub = face("label", 30)
    f_done = face("text", 40)
    cap = "VOLUME"
    tw = d.textlength(cap, font=f_sub)
    d.text(((SIZE - tw) / 2, 262), cap, font=f_sub, fill=VOL_LABEL)
    txt = f"{_VOL['level']}%"
    tw = d.textlength(txt, font=f_big)
    d.text(((SIZE - tw) / 2, SIZE / 2 - 220), txt, font=f_big,
           fill=VOL_BIG)
    sub = "DRAG OR TAP THE RING"
    tw = d.textlength(sub, font=f_sub)
    d.text(((SIZE - tw) / 2, SIZE / 2 + 36), sub, font=f_sub,
           fill=VOL_LABEL)
    #: Round 2 said "drag inside the ring to turn the screen toward you",
    #: which stopped being true when the outer rim became an orient grip
    #: (2026-08-17) — and an instruction that names the one place that no
    #: longer works is worse than none. Raised as well, to clear the DONE
    #: button now that it is pinned to the glass rather than rotating with
    #: everything else.
    sub2 = "drag the outer rim or the middle to turn this screen"
    tw = d.textlength(sub2, font=_font(22))
    d.text(((SIZE - tw) / 2, SIZE / 2 + 78), sub2, font=_font(22),
           fill=VOL_HINT)
    #: ── AND IT TURNS WITH THE SCREEN (2026-08-17, round 5) ──────────────
    #: It was briefly pinned to the glass while the rest of the overlay
    #: rotated, which fixed being trapped and looked wrong doing it —
    #: owner: "the done button does not rotate along when i rotate the
    #: whole volume screen. it's just locked." He is right: a screen that
    #: turns as a unit has to turn as a unit.
    #:
    #: It is safe to turn it again now, and that is not the same claim as
    #: the three times it was already tried. What made it unreachable was
    #: the DIAL's angle being folded in — the button moved when he had not
    #: moved anything — and the hit-test recomputing that angle for itself.
    #: The dial term is gone, `view_deg` changes only when HIS finger
    #: changes it, and the test reads the angle the compositor published.
    #: The button now moves only when he turns the screen, which is exactly
    #: when he is looking at it.
    #:
    #: The escape hatch stays regardless: see the hit-test in handle_tap.
    draw_volume_done(frame)
    _ = f_done
    return frame


#: ── THE ONE EXIT IS PINNED TO THE GLASS (2026-08-17, round 4) ───────────
#: "ugh done still does not work" — the fourth report, and the diagnostic
#: line finally said why without any guessing:
#:
#:   volume: tap screen=(351,124)  view=-135.7 -> frame=(385,969)
#:                                 done_d=222/711 r=457
#:   volume: tap screen=(1042,555) view=259.5  -> frame=(464,43)
#:                                 done_d=770/563 r=503
#:
#: He never came within 222 px of the button. Not because he cannot aim —
#: because DONE was drawn INSIDE the rotating overlay, so every time the
#: screen was turned (by the dial, earlier; by his own orient drag, now)
#: the button moved somewhere else on the glass while he was still looking
#: at where it had been.
#:
#: So it stops rotating. It is drawn after `_apply_view`, at a fixed screen
#: position, and hit-tested in raw screen coordinates. The rest of the
#: overlay can turn however he likes; the way OUT is always in the same
#: place, bottom centre, the way the button on a lift always is.
#:
#: §8, and it is the whole reason this is worth a special case: everything
#: else on this screen adjusts something and costs a tap to undo. This one
#: is the only control whose failure leaves him stuck inside a modal.
def draw_volume_done(frame: "Image.Image") -> None:
    d = ImageDraw.Draw(frame)
    bx, by = VOL_DONE_XY
    f_done = face("text", 40)
    #: a filled disc, not an outline: it has to read as a BUTTON at a
    #: glance, over whatever the rotated overlay happens to be showing
    d.ellipse([bx - VOL_DONE_R, by - VOL_DONE_R,
               bx + VOL_DONE_R, by + VOL_DONE_R], fill=VOL_DONE_FILL)
    d.ellipse([bx - VOL_DONE_R, by - VOL_DONE_R,
               bx + VOL_DONE_R, by + VOL_DONE_R],
              outline=VOL_DONE_EDGE, width=5)
    lbl = "DONE"
    tw = d.textlength(lbl, font=f_done)
    d.text((bx - tw / 2, by - 24), lbl, font=f_done, fill=VOL_DONE_INK)


# ---------------------------------------------------------------------------
# Settings mode
# ---------------------------------------------------------------------------

_FONTS: dict = {}


def _font(sz: int) -> ImageFont.FreeTypeFont:
    """One truetype load per size, ever — the settings book draws a dozen
    sizes per frame and re-opening the font file each time is a paper cut
    the frame budget does not owe anyone."""
    f = _FONTS.get(sz)
    if f is None:
        # FONT_PATH is DejaVuSans-BOLD. Every raw truetype() call in this
        # file was therefore rendering heavy DejaVu instead of the light
        # Nimbus ramp — which is exactly what the owner kept describing
        # as "huge, bold and obnoxious". Use the ramp.
        f = _FONTS[sz] = face("text", sz)
    return f


def _flag_write(path: Path, text: str) -> bool:
    """Handshake flags get the same part+rename dance as every other file
    the conductor might read mid-write."""
    try:
        path.parent.mkdir(parents=True, exist_ok=True)
        tmp = path.with_suffix(".part")
        tmp.write_text(text)
        tmp.replace(path)
        return True
    except Exception as e:
        print(f"settings: flag {path.name} write failed {e!r}", flush=True)
        return False


def _settings_err(msg: str) -> None:
    """A write that failed gets a red line on the glass, not a shrug."""
    _SET["err"] = msg
    _SET["err_until"] = time.time() + 6.0


def _settings_open(rot: "Rotation") -> None:
    _SET["open"] = True
    _SET["page"] = 0
    _SET["grab_deg"] = rot.deg       # pin the dial where the finger left it
    _SET["view_deg"] = 0.0
    _SET["view_prev_ang"] = None
    _SET["wifi_rows"] = []
    _WALLET["qr_open"] = False       # a stale QR must not survive a re-open —
    _WALLET["qr_img"] = None         # each showing gets a fresh nonce
    if not _SET["ever_opened"]:
        # First-open coach (round 2, owner: the chevrons were "not that
        # intuitive at first") — once per process, then the dot rail and
        # the neighbour-page labels carry the message on their own.
        _SET["ever_opened"] = True
        _SET["hint_until"] = time.time() + 5.0
    _BACKEND.open()
    print("settings: open", flush=True)


def _settings_close(reason: str) -> None:
    if not _SET["open"]:
        return
    _SET["open"] = False
    _BACKEND.close()
    print(f"settings: closed ({reason})", flush=True)


def _settings_page(delta: int) -> None:
    _SET["page"] = (_SET["page"] + delta) % len(SET_PAGES)
    print(f"settings: page -> {SET_PAGES[_SET['page']]}", flush=True)


def _settings_swipe(dx: float, dy: float) -> None:
    """A released drag while the book is open: mostly-horizontal travel
    turns the page. Anything else was the finger thinking — ignored, but
    the dial never spins (it is pinned for the whole mode)."""
    if abs(dx) >= SET_SWIPE_PX and abs(dx) > 1.4 * abs(dy):
        _settings_page(1 if dx < 0 else -1)     # swipe left = next page


def _settings_dot_at(x: float, y: float, tol_y: float, tol_x=None):
    """Which page dot is under (x, y), or None. `tol_x=None` means "the
    nearest dot on the rail", which is the generous near-miss pass."""
    if abs(y - SET_DOTS_Y) > tol_y:
        return None
    n = len(SET_PAGES)
    i = int(round((x - SIZE / 2) / SET_DOT_DX + (n - 1) / 2.0))
    if not (0 <= i < n):
        return None
    if tol_x is not None:
        dot_x = SIZE / 2 + (i - (n - 1) / 2.0) * SET_DOT_DX
        if abs(dot_x - x) > tol_x:
            return None
    return i


def _settings_goto(i: int) -> None:
    if i != _SET["page"]:
        _SET["page"] = i
        print(f"settings: dot -> {SET_PAGES[i]}", flush=True)
    else:
        print("settings: dot tap (already on this page)", flush=True)


def _settings_tap(x: float, y: float) -> None:
    if _SET["hint_until"] > time.time():
        # The coach plate covers real controls; the first tap dismisses
        # it rather than landing on something the user cannot see.
        _SET["hint_until"] = 0.0
        print("settings: coach dismissed by tap", flush=True)
        return
    # A VISIBLE dot outranks DONE's invisible padding. Found while adding
    # the CONNECT page (2026-08-02): DONE's hit radius is 88 around
    # (540, 920), which reaches y=832 — over the rail at y=838. With six
    # pages the two middle dots sat inside it, so tapping a dot the user
    # could plainly see THREW THEM OUT of the book to the home face. The
    # five-page rail had the same wart on its centre dot and nobody had
    # tapped it. DONE's drawn ring starts at y=856 and is untouched by
    # this tight pass; the generous rail band still runs after DONE, so
    # padding keeps winning wherever it is the only thing there.
    hit = _settings_dot_at(x, y, 18.0, 24.0)
    if hit is not None:
        _settings_goto(hit)
        return
    if math.hypot(x - SET_DONE_XY[0], y - SET_DONE_XY[1]) <= SET_DONE_HIT_R:
        _settings_close("DONE")
        return
    if math.hypot(x - SET_ARROW_L[0], y - SET_ARROW_L[1]) <= SET_ARROW_HIT_R:
        _settings_page(-1)
        return
    if math.hypot(x - SET_ARROW_R[0], y - SET_ARROW_R[1]) <= SET_ARROW_HIT_R:
        _settings_page(1)
        return
    # The dot rail is TAPPABLE (round 2): each dot is a direct jump to
    # its page — the chevrons alone were "not that intuitive at first".
    # This is the GENEROUS pass — a near-miss anywhere along the rail —
    # and it stays after the DONE ring, which must keep winning where a
    # finger is plausibly aiming at it. The exact-dot pass ran first.
    hit = _settings_dot_at(x, y, 36.0)
    if hit is not None:
        _settings_goto(hit)
        return
    page = SET_PAGES[_SET["page"]]
    if page == "WI-FI":
        _settings_tap_wifi(x, y)
    elif page == "CONNECT":
        # The page owns its own hit-tests (one control), consumes every
        # tap, and logs each one — the settings book's modal law applies
        # unchanged: nothing here reaches the wedge ring underneath.
        if connect_page is None:
            print("settings: tap consumed (connect page unavailable)",
                  flush=True)
        else:
            connect_page.tap(x, y)
    elif page == "CONTACT":
        _settings_tap_contact(x, y)
    elif page == "ALERTS":
        _settings_tap_alerts(x, y)
    elif page == "TIME ZONE":
        _settings_tap_tz(x, y)
    elif page == "WALLET":
        _settings_tap_wallet(x, y)
    else:
        print("settings: tap consumed (system page)", flush=True)


def _settings_tap_wifi(x: float, y: float) -> None:
    x0, y0, x1, y1 = SET_WIFI_RESCAN
    if x0 - 14 <= x <= x1 + 14 and y0 - 14 <= y <= y1 + 14:
        _BACKEND.request_rescan()
        print("settings: wifi rescan requested", flush=True)
        return
    rows = _SET.get("wifi_rows") or []
    if SET_WIFI_ROW_X0 <= x <= SET_WIFI_ROW_X1 and y >= SET_WIFI_ROW_Y0:
        i = int((y - SET_WIFI_ROW_Y0) // SET_WIFI_ROW_H)
        if 0 <= i < len(rows):
            net = rows[i]
            if net.get("in_use"):
                print(f"settings: wifi tap on current ({net['ssid']!r})",
                      flush=True)
            elif net.get("known") or not net.get("sec"):
                # Known profile or open network: we can join it ourselves.
                # The spinner and the honest verdict come from the
                # backend's connect state.
                _BACKEND.connect(net["ssid"], known=bool(net.get("known")))
                print(f"settings: wifi connect {net['ssid']!r} "
                      f"(known={bool(net.get('known'))})", flush=True)
            else:
                # Secured and unknown: the puck has no keyboard for the
                # password — that is a voice job. The flag is the phase-2
                # contract with the conductor.
                if _flag_write(WIFI_ASSIST, net["ssid"]):
                    _SET["assist_ssid"] = net["ssid"]
                    _SET["assist_until"] = time.time() + 14.0
                    print(f"settings: wifi assist flagged for "
                          f"{net['ssid']!r}", flush=True)
                else:
                    _settings_err("COULD NOT FLAG WIFI ASSIST")
            return
    print("settings: tap consumed (wifi page)", flush=True)


def _settings_tap_contact(x: float, y: float) -> None:
    for field, rect in (("phone", SET_FIELD_PHONE),
                        ("email", SET_FIELD_EMAIL)):
        rx0, ry0, rx1, ry1 = rect
        if rx0 <= x <= rx1 and ry0 <= y <= ry1:
            if _flag_write(EDIT_FIELD, field):
                print(f"settings: edit_field -> {field}", flush=True)
            else:
                _settings_err("COULD NOT FLAG THE EDIT")
            return
    print("settings: tap consumed (contact page)", flush=True)


def _settings_tap_alerts(x: float, y: float) -> None:
    if SET_WIFI_ROW_X0 <= x <= SET_WIFI_ROW_X1 and y >= SET_ALERT_Y0:
        i = int((y - SET_ALERT_Y0) // SET_ALERT_H)
        if 0 <= i < 3:
            key = ("text", "call", "email")[i]
            al = _STORE.data["alerts"]
            al[key] = not al[key]
            if _STORE.save():
                print(f"settings: alerts.{key} -> {al[key]}", flush=True)
            else:
                # Revert: the glass must show what the DISK holds, not
                # what we wish it held (PRINCIPLES §1).
                al[key] = not al[key]
                _settings_err("NOT SAVED — SETTINGS DISK ERROR")
            return
    print("settings: tap consumed (alerts page)", flush=True)


def _settings_tap_tz(x: float, y: float) -> None:
    bx, by = SET_TZ_CONFIRM_XY
    if math.hypot(x - bx, y - by) <= SET_TZ_CONFIRM_R + 22:
        tz = _BACKEND.snapshot().get("tz")
        if not tz:
            # Stamping "unknown" would be a confirmation of nothing.
            _settings_err("TIME ZONE UNKNOWN — CANNOT CONFIRM")
            print("settings: tz confirm refused (tz unknown)", flush=True)
            return
        prev = _STORE.data.get("timezone_confirmed")
        _STORE.data["timezone_confirmed"] = {
            "tz": tz, "at": time.strftime("%Y-%m-%dT%H:%M:%S%z")}
        if _STORE.save():
            print(f"settings: timezone confirmed {tz}", flush=True)
        else:
            _STORE.data["timezone_confirmed"] = prev
            _settings_err("NOT SAVED — SETTINGS DISK ERROR")
        return
    print("settings: tap consumed (timezone page)", flush=True)


_ENT_CACHE = {"mtime": None, "data": None}


def _entitlements():
    """entitlements.json, stat-cached by mtime — one stat per frame while
    the WALLET page is up, a parse only on change. The bridge writes it;
    this face only ever reads. Unreadable is LOGGED, not shrugged off
    (PRINCIPLES §1) — a malformed file must not read as 'not linked
    forever' in silence."""
    try:
        m = ENTITLEMENTS.stat().st_mtime
    except (FileNotFoundError, NotADirectoryError):
        _ENT_CACHE["mtime"] = _ENT_CACHE["data"] = None
        return None
    if _ENT_CACHE["mtime"] != m:
        _ENT_CACHE["mtime"] = m
        try:
            _ENT_CACHE["data"] = json.loads(ENTITLEMENTS.read_text())
            print("settings: entitlements loaded", flush=True)
        except Exception as e:
            print(f"settings: entitlements unreadable {e!r}", flush=True)
            _ENT_CACHE["data"] = None
    return _ENT_CACHE["data"]


def _wallet_linked():
    """The entitlements dict when the device is linked, else None. An
    explicit linked:false outranks a present address — unlink must win."""
    ent = _entitlements()
    if not isinstance(ent, dict) or ent.get("linked") is False:
        return None
    if ent.get("linked") or ent.get("wallet") or ent.get("address"):
        return ent
    return None


def _wallet_qr_image(payload: str):
    """The payload as a baked QR plate, or None (loudly) when no QR lib
    made it onto this puck. qrcode is pure python and already in aura-env;
    segno is the fallback spelling. Either way the MATRIX is drawn by
    hand onto a white plate — no image factory, no network, nothing per
    frame but one paste."""
    matrix = None
    try:
        import qrcode
        q = qrcode.QRCode(border=0,
                          error_correction=qrcode.constants.ERROR_CORRECT_M)
        q.add_data(payload)
        q.make(fit=True)
        matrix = [[bool(v) for v in row] for row in q.get_matrix()]
    except Exception:
        try:
            import segno
            matrix = [[bool(v) for v in row]
                      for row in segno.make(payload, error="m").matrix]
        except Exception as e:
            print(f"settings: NO QR LIBRARY — wallet page cannot render "
                  f"({e!r})", flush=True)
            return None
    n = len(matrix)
    quiet = 4                       # the spec's quiet zone, in modules
    cells = n + 2 * quiet
    scale = max(3, SET_WALLET_QR_PX // cells)
    side = cells * scale
    img = Image.new("RGB", (side, side), (255, 255, 255))
    d = ImageDraw.Draw(img)
    for r, row in enumerate(matrix):
        for c, v in enumerate(row):
            if v:
                x0, y0 = (quiet + c) * scale, (quiet + r) * scale
                d.rectangle([x0, y0, x0 + scale - 1, y0 + scale - 1],
                            fill=(0, 0, 0))
    return img


def _wallet_qr_open() -> None:
    """One tap, one fresh nonce, one baked QR. The click fires FIRST
    (§13 — the first hundred milliseconds belong to acknowledgment); the
    QR build is a one-off cost at tap time, never per frame. A nonce that
    could not reach disk gets no QR at all: the bridge verifies against
    the file, so a QR without it is a link that silently cannot work."""
    _click()
    nonce = os.urandom(16).hex()
    if not _flag_write(WALLET_NONCE, nonce):
        _settings_err("COULD NOT WRITE NONCE — NOT SHOWING QR")
        return
    payload = json.dumps({"device": os.uname().nodename, "nonce": nonce,
                          "ts": int(time.time())}, separators=(",", ":"))
    img = _wallet_qr_image(payload)
    if img is None:
        _settings_err("NO QR LIBRARY ON THIS PUCK")
        return
    _WALLET.update(qr_open=True, qr_img=img, nonce=nonce)
    print(f"settings: wallet QR open (nonce {nonce[:8]}..., "
          f"{img.width}px)", flush=True)


def _settings_tap_wallet(x: float, y: float) -> None:
    if _wallet_linked():
        print("settings: tap consumed (wallet page, linked)", flush=True)
        return
    if _WALLET["qr_open"]:
        # The cheap direction (§8): anywhere on the page cancels the QR.
        _WALLET["qr_open"] = False
        _WALLET["qr_img"] = None
        print("settings: wallet QR cancelled", flush=True)
        return
    x0, y0, x1, y1 = SET_WALLET_ROW
    if x0 <= x <= x1 and y0 <= y <= y1:
        _wallet_qr_open()
        return
    print("settings: tap consumed (wallet page)", flush=True)


_EDIT_CACHE = {"mtime": None, "val": None}


def _edit_field_pending():
    """Which field the voice side is being asked to fill, or None. The
    conductor removes the flag when the value lands, and the banner drops
    with it. Stat-cached: one stat per frame while the page is up."""
    try:
        m = EDIT_FIELD.stat().st_mtime
    except (FileNotFoundError, NotADirectoryError):
        _EDIT_CACHE["mtime"] = _EDIT_CACHE["val"] = None
        return None
    if _EDIT_CACHE["mtime"] != m:
        _EDIT_CACHE["mtime"] = m
        try:
            _EDIT_CACHE["val"] = EDIT_FIELD.read_text().strip() or None
        except Exception:
            _EDIT_CACHE["val"] = None
    return _EDIT_CACHE["val"]


def _sig_bars(d: ImageDraw.ImageDraw, x: float, y_base: float, sig) -> None:
    """Four rising bars, `sig` 0..100 — the same glyph on the header and
    every network row, so signal reads at a glance everywhere."""
    for i in range(4):
        h = 8 + i * 7
        on = (sig or 0) >= (i + 1) * 22
        d.rounded_rectangle([x + i * 14, y_base - h, x + i * 14 + 9, y_base],
                            radius=2, fill=SET_CYAN if on else (52, 62, 74))


def _spinner(d: ImageDraw.ImageDraw, x: float, y: float, now: float,
             r: float = 14) -> None:
    a0 = (now * 320.0) % 360.0
    d.arc([x - r, y - r, x + r, y + r], start=a0, end=a0 + 260,
          fill=SET_CYAN, width=4)


def _draw_set_wifi(d: ImageDraw.ImageDraw, now: float, snap: dict) -> None:
    ssid, sig, ip = snap.get("ssid"), snap.get("signal"), snap.get("ip")
    if not snap.get("at"):
        _spinner(d, SIZE / 2 - 150, 232, now)
        msg = "CHECKING THE RADIO"
        d.text((SIZE / 2 - 118, 214), msg, font=_font(32), fill=SET_DIM)
    elif ssid:
        s = ssid[:16]
        tw = d.textlength(s, font=_font(54))
        d.text(((SIZE - tw) / 2, 190), s, font=_font(54), fill=SET_TEXT)
        sub = (f"{sig}%  ·  {ip}" if sig is not None and ip
               else (f"{sig}%" if sig is not None else (ip or "")))
        tw = d.textlength(sub, font=_font(26))
        bx = (SIZE - (tw + 66)) / 2
        _sig_bars(d, bx, 296, sig)
        d.text((bx + 66, 270), sub, font=_font(26), fill=SET_STEEL)
    else:
        msg = "NOT CONNECTED"
        tw = d.textlength(msg, font=_font(44))
        d.text(((SIZE - tw) / 2, 198), msg, font=_font(44), fill=SET_AMBER)
        sub = "tap a network below to join"
        tw = d.textlength(sub, font=_font(24))
        d.text(((SIZE - tw) / 2, 264), sub, font=_font(24), fill=SET_DIM)
    # The list. What is drawn is what taps index — see SET_WIFI_ROWS note.
    rows = (snap.get("networks") or [])[:SET_WIFI_ROWS]
    _SET["wifi_rows"] = rows
    if not rows and snap.get("at"):
        msg = "no networks seen — RESCAN"
        tw = d.textlength(msg, font=_font(26))
        d.text(((SIZE - tw) / 2, 460), msg, font=_font(26), fill=SET_DIM)
    for i, net in enumerate(rows):
        ry = SET_WIFI_ROW_Y0 + i * SET_WIFI_ROW_H
        d.line([(SET_WIFI_ROW_X0, ry), (SET_WIFI_ROW_X1, ry)],
               fill=(40, 50, 62), width=1)
        cy_ = ry + SET_WIFI_ROW_H / 2
        if net["in_use"]:
            d.ellipse([SET_WIFI_ROW_X0 + 2, cy_ - 5,
                       SET_WIFI_ROW_X0 + 12, cy_ + 5], fill=SET_CYAN)
        d.text((SET_WIFI_ROW_X0 + 28, cy_ - 17), net["ssid"][:14],
               font=_font(30),
               fill=SET_CYAN if net["in_use"] else SET_TEXT)
        _sig_bars(d, 660, cy_ + 14, net["signal"])
        chip = ("KNOWN" if net["known"]
                else ("OPEN" if not net["sec"] else "SECURED"))
        col = (SET_GREEN if net["known"]
               else (SET_CYAN if not net["sec"] else SET_DIM))
        tw = d.textlength(chip, font=_font(20))
        d.text((SET_WIFI_ROW_X1 - tw, cy_ - 11), chip, font=_font(20),
               fill=col)
    if rows:
        ry = SET_WIFI_ROW_Y0 + len(rows) * SET_WIFI_ROW_H
        d.line([(SET_WIFI_ROW_X0, ry), (SET_WIFI_ROW_X1, ry)],
               fill=(40, 50, 62), width=1)
    # RESCAN — a real button with a real busy state.
    x0, y0, x1, y1 = SET_WIFI_RESCAN
    scanning = bool(snap.get("scanning"))
    d.rounded_rectangle([x0, y0, x1, y1], radius=16,
                        outline=SET_CYAN if scanning else SET_STEEL, width=3)
    lbl = "SCANNING" if scanning else "RESCAN"
    tw = d.textlength(lbl, font=_font(28))
    lx = (x0 + x1 - tw) / 2 + (14 if scanning else 0)
    d.text((lx, (y0 + y1) / 2 - 17), lbl, font=_font(28), fill=SET_TEXT)
    if scanning:
        _spinner(d, lx - 32, (y0 + y1) / 2, now)
    # Status line — the red error banner (drawn by the caller) outranks it.
    if _SET["err_until"] > now:
        return
    if _SET["assist_until"] > now:
        m1 = "ASK STERLING TO CONNECT"
        tw = d.textlength(m1, font=_font(30))
        d.text(((SIZE - tw) / 2, 736), m1, font=_font(30), fill=SET_CYAN)
        m2 = f'say: "connect wifi {_SET["assist_ssid"]}"'
        tw = d.textlength(m2, font=_font(25))
        d.text(((SIZE - tw) / 2, 780), m2, font=_font(25),
               fill=(150, 200, 235))
        return
    con = snap.get("connect") or {}
    st, age = con.get("state"), now - con.get("at", 0.0)
    if st == "working":
        msg = f"CONNECTING TO {con.get('ssid', '')[:14]}"
        tw = d.textlength(msg, font=_font(28))
        cx0 = (SIZE - tw) / 2 + 18
        _spinner(d, cx0 - 36, 760, now)
        d.text((cx0, 744), msg, font=_font(28), fill=SET_TEXT)
    elif st == "ok" and age < 10.0:
        msg = f"CONNECTED TO {con.get('ssid', '')[:14]}"
        tw = d.textlength(msg, font=_font(28))
        d.text(((SIZE - tw) / 2, 746), msg, font=_font(28), fill=SET_GREEN)
    elif st == "fail" and age < 14.0:
        # The honest verdict, verbatim from nmcli — never a quiet shrug.
        msg = f"FAILED — {con.get('detail') or 'see log'}"[:46]
        tw = d.textlength(msg, font=_font(26))
        d.text(((SIZE - tw) / 2, 748), msg, font=_font(26), fill=SET_RED)


def _draw_set_contact(d: ImageDraw.ImageDraw, now: float) -> None:
    c = _STORE.data.get("contact", {})
    pending = _edit_field_pending()
    for key, label, val, rect, big in (
            ("phone", "PHONE", c.get("phone", ""), SET_FIELD_PHONE, 62),
            ("email", "EMAIL", c.get("email", ""), SET_FIELD_EMAIL, 48)):
        x0, y0, x1, y1 = rect
        hot = pending == key
        d.rounded_rectangle([x0, y0, x1, y1], radius=24,
                            outline=SET_CYAN if hot else (70, 84, 104),
                            width=4 if hot else 3)
        d.text((x0 + 34, y0 + 22), label, font=_font(24), fill=SET_STEEL)
        if val:
            sz = big
            while sz > 24 and d.textlength(val, font=_font(sz)) > x1 - x0 - 70:
                sz -= 6                     # long emails shrink to fit
            tw = d.textlength(val, font=_font(sz))
            d.text(((x0 + x1 - tw) / 2, (y0 + y1) / 2 - sz * 0.42 + 12),
                   val, font=_font(sz), fill=SET_TEXT)
        else:
            msg = "TAP TO SET"
            tw = d.textlength(msg, font=_font(36))
            d.text(((x0 + x1 - tw) / 2, (y0 + y1) / 2 - 8), msg,
                   font=_font(36), fill=SET_DIM)
    if pending in ("phone", "email"):
        k = 0.7 + 0.3 * math.sin(now * math.tau * 0.7)
        m1 = "SAY THE NEW VALUE TO AURA"
        tw = d.textlength(m1, font=_font(32))
        d.text(((SIZE - tw) / 2, 660), m1, font=_font(32),
               fill=tuple(int(v * k) for v in SET_CYAN))
        m2 = f"listening for your {pending}"
        tw = d.textlength(m2, font=_font(24))
        d.text(((SIZE - tw) / 2, 712), m2, font=_font(24),
               fill=(150, 200, 235))
    else:
        m = "tap a field — Aura takes the new value by voice"
        tw = d.textlength(m, font=_font(24))
        d.text(((SIZE - tw) / 2, 680), m, font=_font(24), fill=SET_DIM)


def _draw_set_alerts(d: ImageDraw.ImageDraw, now: float) -> None:
    al = _STORE.data.get("alerts", {})
    c = _STORE.data.get("contact", {})
    rows = (("text", "TEXT ME", c.get("phone")),
            ("call", "CALL ME", c.get("phone")),
            ("email", "EMAIL ME", c.get("email")))
    for i, (key, label, dest) in enumerate(rows):
        ry = SET_ALERT_Y0 + i * SET_ALERT_H
        on = bool(al.get(key))
        d.line([(235, ry), (845, ry)], fill=(40, 50, 62), width=1)
        d.text((260, ry + 26), label, font=_font(40),
               fill=SET_TEXT if on else SET_DIM)
        # Where it would go — and an amber flag when ON with nowhere to
        # send, which is a promise the system cannot keep.
        if dest:
            d.text((260, ry + 84), ("to " + dest)[:34], font=_font(22),
                   fill=SET_STEEL)
        else:
            missing = "no " + ("email" if key == "email" else "phone") \
                + " on file"
            d.text((260, ry + 84), missing, font=_font(22),
                   fill=SET_AMBER if on else SET_DIM)
        px0, px1, py0, py1 = 668, 816, ry + 36, ry + 96
        if on:
            d.rounded_rectangle([px0, py0, px1, py1], radius=30,
                                outline=SET_GREEN, width=4)
            d.ellipse([px1 - 54, py0 + 6, px1 - 6, py1 - 6], fill=SET_GREEN)
            d.text((px0 + 24, (py0 + py1) / 2 - 14), "ON", font=_font(24),
                   fill=SET_GREEN)
        else:
            d.rounded_rectangle([px0, py0, px1, py1], radius=30,
                                outline=SET_DIM, width=3)
            d.ellipse([px0 + 6, py0 + 6, px0 + 54, py1 - 6],
                      outline=SET_DIM, width=3)
            tw = d.textlength("OFF", font=_font(24))
            d.text((px1 - 24 - tw, (py0 + py1) / 2 - 14), "OFF",
                   font=_font(24), fill=SET_DIM)
    d.line([(235, SET_ALERT_Y0 + 3 * SET_ALERT_H),
            (845, SET_ALERT_Y0 + 3 * SET_ALERT_H)], fill=(40, 50, 62),
           width=1)
    m = "tap a row to flip it — saved instantly"
    tw = d.textlength(m, font=_font(22))
    d.text(((SIZE - tw) / 2, 700), m, font=_font(22), fill=SET_DIM)


def _draw_set_tz(d: ImageDraw.ImageDraw, now: float, snap: dict) -> None:
    """The cool one: 24 hour markers around the rim with noon riding the
    top, a day/night arc (the crude 6a-6p split), the local hour glowing
    on the ring, and the big local time dead center."""
    cx = cy = SIZE // 2
    tz = snap.get("tz")
    lt = time.localtime(now)
    # Day over the top of the ring, night under the bottom.
    bb = [cx - 505, cy - 505, cx + 505, cy + 505]
    d.arc(bb, start=180, end=360, fill=(96, 74, 28), width=9)
    d.arc(bb, start=0, end=180, fill=(30, 44, 84), width=9)
    for h in range(24):
        a = math.radians((h - 12) * 15 - 90)     # noon at 12 o'clock high
        major = h % 6 == 0
        r0, r1 = (452, 486) if major else (461, 479)
        day = 6 <= h < 18
        col = ((196, 160, 70) if day else (86, 110, 168)) if major \
            else ((150, 122, 52) if day else (56, 76, 122))
        d.line([(cx + r0 * math.cos(a), cy + r0 * math.sin(a)),
                (cx + r1 * math.cos(a), cy + r1 * math.sin(a))],
               fill=col, width=5 if major else 3)
    # 06/18 sit at r=350 to stay clear of the page chevrons on the rim;
    # 00 is under the DONE ring and goes unlabeled.
    for h, r_lbl in ((12, 420), (6, 350), (18, 350)):
        a = math.radians((h - 12) * 15 - 90)
        lbl = f"{h:02d}"
        tw = d.textlength(lbl, font=_font(22))
        d.text((cx + r_lbl * math.cos(a) - tw / 2,
                cy + r_lbl * math.sin(a) - 12), lbl, font=_font(22),
               fill=SET_DIM)
    # The local hour, glowing on the ring, creeping with the minutes.
    fh = lt.tm_hour + lt.tm_min / 60.0
    a = math.radians((fh - 12.0) * 15.0 - 90.0)
    gx, gy = cx + 469 * math.cos(a), cy + 469 * math.sin(a)
    pulse = 0.5 + 0.5 * math.sin(now * math.tau * 0.6)
    d.ellipse([gx - 30, gy - 30, gx + 30, gy + 30],
              outline=(24, 66, 92), width=2)
    d.ellipse([gx - 21, gy - 21, gx + 21, gy + 21],
              outline=(36, 118, 160), width=3)
    rr = 10 + 3 * pulse
    d.ellipse([gx - rr, gy - rr, gx + rr, gy + rr],
              fill=(120 + int(60 * pulse), 215, 255))
    txt = time.strftime("%H:%M", lt)
    tw = d.textlength(txt, font=_font(150))
    d.text(((SIZE - tw) / 2, 300), txt, font=_font(150), fill=SET_TEXT)
    zone = (tz or "time zone unknown").upper().replace("_", " ")
    tw = d.textlength(zone, font=_font(34))
    d.text(((SIZE - tw) / 2, 500), zone, font=_font(34),
           fill=SET_CYAN if tz else SET_AMBER)
    off = lt.tm_gmtoff or 0
    oh, om = divmod(abs(off) // 60, 60)
    sub = f"UTC{'+' if off >= 0 else '-'}{oh:02d}:{om:02d}  ·  " \
        + ("DAY" if 6 <= lt.tm_hour < 18 else "NIGHT")
    tw = d.textlength(sub, font=_font(24))
    d.text(((SIZE - tw) / 2, 556), sub, font=_font(24), fill=SET_STEEL)
    conf = _STORE.data.get("timezone_confirmed")
    confirmed_here = (isinstance(conf, dict) and tz
                      and conf.get("tz") == tz)
    if confirmed_here:
        msg = f"CONFIRMED · {str(conf.get('at', ''))[:10]}"
        tw = d.textlength(msg, font=_font(28))
        x0 = (SIZE - tw + 56) / 2            # room for the seal at left
        d.text((x0, 724), msg, font=_font(28), fill=SET_GREEN)
        d.ellipse([x0 - 56, 722, x0 - 16, 762], outline=SET_GREEN, width=3)
        d.line([x0 - 47, 742, x0 - 38, 751, x0 - 24, 731],
               fill=SET_GREEN, width=4, joint="curve")
    else:
        bx, by = SET_TZ_CONFIRM_XY
        k = 0.75 + 0.25 * math.sin(now * math.tau * 0.7)
        d.ellipse([bx - SET_TZ_CONFIRM_R, by - SET_TZ_CONFIRM_R,
                   bx + SET_TZ_CONFIRM_R, by + SET_TZ_CONFIRM_R],
                  outline=tuple(int(v * k) for v in SET_GREEN), width=5)
        tw = d.textlength("CONFIRM", font=_font(21))
        d.text((bx - tw / 2, by - 13), "CONFIRM", font=_font(21),
               fill=SET_TEXT)
        if isinstance(conf, dict) and conf.get("tz") and conf.get("tz") != tz:
            m = f"was {conf['tz']}"
            tw = d.textlength(m, font=_font(20))
            d.text(((SIZE - tw) / 2, 654), m, font=_font(20), fill=SET_AMBER)


#: The health strip's geometry. Five pills across the page's own column
#: (235..845, the width every row on every page in this book uses), then the
#: rows. MEASURED AGAINST THE CHROME, not chosen: the page title's ink ends
#: at ~176, the dot rail is at SET_DOTS_Y (838) and the error toast at 798,
#: so 196..262 for the strip and 278..768 for ten rows is the whole of the
#: free space with a margin at each end.
SET_SYS_PILL = (192, 62)                 # y0, height
SET_SYS_PILL_N, SET_SYS_PILL_GAP = 5, 8
SET_SYS_ROW = (270, 48)                  # y0, pitch
#: The rendered page is what moved these: at 278/49 the staleness footer
#: sat ON the settings-file error line. Both are now measured DOWN from the
#: last rule (750): error at +12, footer at +44, dot rail at 838.
SET_SYS_FOOT_DY = 44


def _draw_set_system(d: ImageDraw.ImageDraw, now: float, snap: dict) -> None:
    """BUILD/UPTIME/WI-FI/IP said nothing about whether she can hear or
    think, so this page was entirely green on both pucks that had actually
    failed (see the block at HEALTH_REFRESH_S for the two incidents).

    THE STRIP IS AT THE TOP AND IT IS PILLS, NOT ROWS, deliberately. Ten
    right-aligned values all read at the same weight and the eye has to
    audit them one at a time; the five facts that can be WRONG get shape and
    colour and sit where the eye lands first, so the page answers "is she
    well" before it is read at all. The rest is reference and stays rows.

    Every fact here comes off `health()` — the background poller — or off
    the settings backend's snapshot. NOTHING in this function shells out;
    that rule is older than this page.
    """
    h = health()
    checking = not h.get("at")
    ssid, sig = snap.get("ssid"), snap.get("signal")
    wifi_val = (f"{ssid[:12]} · {sig}%" if ssid and sig is not None
                else (ssid[:16] if ssid else "not connected"))
    pw = snap.get("pipewire") or "unknown"
    vol = snap.get("volume")

    #: One table for every systemd state on this page — the units AND
    #: pipewire, which used to be a row saying "INACTIVE" and became
    #: "INACTI" the moment it was a pill. One place states the words (§15),
    #: and none of them is longer than a pill.
    _SYSD_WORD = {"active": ("OK", SET_GREEN),
                  "activating": ("START", SET_AMBER),
                  "deactivating": ("STOP", SET_AMBER),
                  "inactive": ("OFF", SET_RED),
                  "failed": ("FAILED", SET_RED)}

    def sysd_pill(st) -> tuple:
        #: No state yet is NOT a bad state (§2) — it is dim, and the footer
        #: says which gatherer has not answered.
        if not st:
            return "…", SET_DIM
        return _SYSD_WORD.get(st, ("?", SET_AMBER))

    def unit_pill(unit: str) -> tuple:
        return sysd_pill(None if checking else h.get(unit))

    def hearing_pill() -> tuple:
        if checking:
            return "…", SET_DIM
        if h.get("mute_tmp"):
            return "MUTED", SET_AMBER
        age = h.get("room_age")
        if age is not None and age <= HEALTH_DEAF_S:
            return "OK", SET_GREEN
        #: Same grace the fault uses, for its reason — see _HEALTH_T0. A
        #: page opened during the ears' cold init must say "I don't know
        #: yet", not "NO FEED".
        if h["at"] - (_HEALTH_T0[0] or h["at"]) <= HEALTH_DEAF_S:
            return "…", SET_DIM
        return ("NO FEED" if age is None else "STALE"), SET_RED

    def brain_pill() -> tuple:
        if checking:
            return "…", SET_DIM
        o = h.get("ollama")
        return {"ok": ("OK", SET_GREEN), "refused": ("NONE", SET_RED),
                "timeout": ("SLOW", SET_RED),
                "down": ("DOWN", SET_RED)}.get(o, ("ERR", SET_RED))

    pills = [(lbl, unit_pill(unit)) for lbl, unit, _s in HEALTH_UNITS]
    pills += [("HEARING", hearing_pill()),
             ("BRAIN", brain_pill()),
             ("AUDIO", sysd_pill(None if pw == "unknown" else pw))]
    py0, ph = SET_SYS_PILL
    span = 845 - 235
    pw_px = (span - SET_SYS_PILL_GAP * (SET_SYS_PILL_N - 1)) / SET_SYS_PILL_N
    for i, (lbl, (state, col)) in enumerate(pills):
        px0 = 235 + i * (pw_px + SET_SYS_PILL_GAP)
        d.rounded_rectangle([px0, py0, px0 + pw_px, py0 + ph], radius=14,
                            fill=tuple(int(v * 0.17) for v in col),
                            outline=col, width=2)
        tw = d.textlength(lbl, font=_font(17))
        d.text((px0 + (pw_px - tw) / 2, py0 + 8), lbl, font=_font(17),
               fill=SET_STEEL)
        tw = d.textlength(state, font=_font(22))
        d.text((px0 + (pw_px - tw) / 2, py0 + 31), state, font=_font(22),
               fill=col)

    t = h.get("temp_c")
    #: Stated WITH its band, because 87C is this puck working exactly as
    #: designed and a bare "87 C" on a settings page is how the baker came
    #: to refuse 771 bakes. See thermal_policy.
    temp_val = ("…" if checking else "—" if t is None
                else f"{t:.0f} C   (hot at {HEALTH_HOT_C:.0f})")
    temp_col = (SET_DIM if checking or t is None
                else SET_RED if t >= HEALTH_HOT_C else SET_TEXT)
    fg = h.get("disk_free_gb")
    disk_val = ("…" if checking else "—" if fg is None
                else f"{fg:.1f} GB free   ({h.get('disk_pct')}% used)")
    disk_col = (SET_DIM if checking or fg is None
                else SET_RED if fg < HEALTH_DISK_LOW_GB else SET_TEXT)
    pa = h.get("pulse_age")
    #: The pulse is NOT the capture heartbeat (see rule 4 at the poller) —
    #: it is the last time somebody actually spoke, which is worth knowing
    #: and is a different question. Labelled as what it is.
    heard_val = ("…" if checking else "never" if pa is None
                 else f"{pa:.0f}s ago" if pa < 90
                 else f"{pa / 60:.0f}m ago" if pa < 5400
                 else f"{pa / 3600:.0f}h ago")
    #: The mute row exists because the /tmp flag is a PROJECTION: a puck can
    #: be audibly unmuted and still be armed to re-mute itself at the next
    #: ears restart, which is eleven silent hours of Bob's puck in one line.
    if checking:
        mute_val, mute_col = "…", SET_DIM
    elif h.get("mute_tmp"):
        mute_val = ("ON · persists a reboot" if h.get("mute_persist")
                    else "ON · this boot only")
        mute_col = SET_AMBER
    elif h.get("mute_persist"):
        mute_val, mute_col = "OFF · RE-MUTES AT RESTART", SET_RED
    else:
        mute_val, mute_col = "OFF", SET_TEXT

    rows = [
        ("DIE TEMP", temp_val, temp_col),
        ("DISK", disk_val, disk_col),
        ("LAST HEARD", heard_val, SET_DIM if checking else SET_TEXT),
        ("MUTE", mute_val, mute_col),
        ("BUILD", _BUILD, SET_TEXT),
        ("UPTIME", snap.get("uptime") or "—", SET_TEXT),
        ("WI-FI", wifi_val, SET_TEXT if ssid else SET_AMBER),
        ("IP", snap.get("ip") or "—", SET_TEXT),
        ("VOLUME", f"{vol}%" if vol is not None else "—", SET_TEXT),
        ("SETTINGS FILE", "OK" if _STORE.error is None else "ERROR",
         SET_GREEN if _STORE.error is None else SET_RED),
    ]
    y0, rh = SET_SYS_ROW
    for i, (lbl, val, col) in enumerate(rows):
        ry = y0 + i * rh
        d.line([(235, ry), (845, ry)], fill=(40, 50, 62), width=1)
        d.text((260, ry + 13), lbl, font=_font(21), fill=SET_STEEL)
        tw = d.textlength(str(val), font=_font(24))
        d.text((820 - tw, ry + 10), str(val), font=_font(24), fill=col)
    d.line([(235, y0 + len(rows) * rh), (845, y0 + len(rows) * rh)],
           fill=(40, 50, 62), width=1)
    if _STORE.error:
        e = _STORE.error[:52]
        tw = d.textlength(e, font=_font(20))
        d.text(((SIZE - tw) / 2, y0 + len(rows) * rh + 12), e,
               font=_font(20), fill=SET_RED)
    # Staleness is stated, not hidden — old facts that look fresh are the
    # quiet cousin of silent success. TWO ages, because there are two
    # gatherers with two lifetimes and a reader who does not know which one
    # went quiet has learned nothing.
    foot = ("gathering facts..." if not snap.get("at")
            else f"facts {now - snap['at']:.0f}s ago  ·  health "
                 + ("checking..." if checking
                    else f"{now - h['at']:.0f}s ago"))
    tw = d.textlength(foot, font=_font(19))
    d.text(((SIZE - tw) / 2, y0 + len(rows) * rh + SET_SYS_FOOT_DY), foot,
           font=_font(19), fill=SET_DIM)


def _draw_set_wallet(frame: Image.Image, d: ImageDraw.ImageDraw,
                     now: float) -> None:
    """Three states, watched live: LINKED (entitlements.json says so),
    the QR ceremony, or the LINK WALLET row. Takes the frame as well as
    the draw because the QR is a baked plate that gets PASTED — the one
    page in the book that composites an image per frame, and only while
    its QR is up."""
    ent = _wallet_linked()
    if ent:
        if _WALLET["qr_open"]:
            # The bridge answered while the QR was up — the flip IS the
            # confirmation, and the stale nonce plate goes with it.
            _WALLET["qr_open"] = False
            _WALLET["qr_img"] = None
            print("settings: wallet linked — QR retired", flush=True)
        # The gold seal: premium unlocked, in the house metal (AURA_INK).
        sx, sy, sr = SIZE / 2, 330, 44
        d.ellipse([sx - sr, sy - sr, sx + sr, sy + sr],
                  fill=(58, 48, 26), outline=AURA_INK, width=5)
        d.line([(sx - 18, sy + 2), (sx - 6, sy + 15), (sx + 20, sy - 14)],
               fill=AURA_INK, width=7, joint="curve")
        cap = "PREMIUM UNLOCKED"
        tw = d.textlength(cap, font=_font(24))
        d.text(((SIZE - tw) / 2, sy + sr + 22), cap, font=_font(24),
               fill=AURA_INK)
        addr = str(ent.get("wallet") or ent.get("address") or "")
        short = addr if len(addr) <= 14 else f"{addr[:6]}...{addr[-4:]}"
        tw = d.textlength(short, font=_font(40))
        d.text(((SIZE - tw) / 2, 468), short, font=_font(40), fill=SET_STEEL)
        bal = ent.get("balance", ent.get("balance_at_check"))
        if bal is not None:
            bal_txt = (f"{bal:,.0f} $LEDGER"
                       if isinstance(bal, (int, float)) else f"{bal} $LEDGER")
            tw = d.textlength(bal_txt, font=_font(28))
            d.text(((SIZE - tw) / 2, 540), bal_txt, font=_font(28),
                   fill=AURA_INK)
        foot = "LINKED"
        tw = d.textlength(foot, font=_font(20))
        d.text(((SIZE - tw) / 2, 610), foot, font=_font(20), fill=SET_GREEN)
        return
    if _WALLET["qr_open"] and _WALLET["qr_img"] is not None:
        img = _WALLET["qr_img"]
        frame.paste(img, (int(SIZE / 2 - img.width / 2),
                          int(SET_WALLET_QR_CY - img.height / 2)))
        cap = "SCAN WITH YOUR WALLET"
        tw = d.textlength(cap, font=_font(28))
        d.text(((SIZE - tw) / 2, 218), cap, font=_font(28), fill=SET_STEEL)
        sub = "TAP TO CANCEL"
        tw = d.textlength(sub, font=_font(20))
        d.text(((SIZE - tw) / 2, SET_WALLET_QR_CY + SET_WALLET_QR_PX / 2 + 24),
               sub, font=_font(20), fill=SET_DIM)
        return
    x0, y0, x1, y1 = SET_WALLET_ROW
    d.line([(x0, y0), (x1, y0)], fill=(40, 50, 62), width=1)
    d.line([(x0, y1), (x1, y1)], fill=(40, 50, 62), width=1)
    d.text((x0 + 25, y0 + 20), "LINK WALLET", font=_font(30), fill=SET_TEXT)
    tw = d.textlength("›", font=_font(34))
    d.text((x1 - 25 - tw, y0 + 17), "›", font=_font(34), fill=SET_STEEL)
    hint = "unlock the premium collection with $LEDGER"
    tw = d.textlength(hint, font=_font(22))
    d.text(((SIZE - tw) / 2, 470), hint, font=_font(22), fill=SET_DIM)
    # The redline, stated ON the glass: this ceremony never wants a key.
    red = "signature only — no keys ever enter this device"
    tw = d.textlength(red, font=_font(20))
    d.text(((SIZE - tw) / 2, 512), red, font=_font(20), fill=SET_DIM)


_CONNECT_FAIL = [0.0]        # last time the CONNECT page's draw threw


def _draw_set_connect(d: ImageDraw.ImageDraw, now: float) -> None:
    """AuraConnect — delegated to connect_page.py, which owns the whole
    page (state, hit-test, drawing). The only thing that lives here is
    what to show when that module did not make it onto the puck: naming
    the missing FILE, because "this page is broken" sends nobody
    anywhere, and a blank page would look like a working drop box that
    simply has nothing to say."""
    if connect_page is not None:
        try:
            connect_page.draw(d, now)
            return
        except Exception as e:
            # draw_settings is called UNGUARDED from the frame loop, and
            # this is the only page whose facts come from another
            # process's JSON. A malformed status file must cost one page,
            # never the compositor — a dead dj_face is a black puck.
            # Rate-limited because a bad file stays bad at 14 fps.
            if now - _CONNECT_FAIL[0] > 5.0:
                _CONNECT_FAIL[0] = now
                print(f"connect: page draw failed {e!r}", flush=True)
            msg = "CONNECT PAGE ERROR"
            tw = d.textlength(msg, font=_font(40))
            d.text(((SIZE - tw) / 2, 420), msg, font=_font(40), fill=SET_RED)
            sub = str(e)[:52]
            tw = d.textlength(sub, font=_font(22))
            d.text(((SIZE - tw) / 2, 486), sub, font=_font(22), fill=SET_DIM)
            return
    msg = "CONNECT PAGE NOT INSTALLED"
    tw = d.textlength(msg, font=_font(40))
    d.text(((SIZE - tw) / 2, 420), msg, font=_font(40), fill=SET_RED)
    sub = "connect_page.py is missing on this puck"
    tw = d.textlength(sub, font=_font(24))
    d.text(((SIZE - tw) / 2, 486), sub, font=_font(24), fill=SET_DIM)


def draw_settings(frame: Image.Image, now: float) -> Image.Image:
    """The settings book: five pages under one steel chrome. Drawn in
    SCREEN coordinates AFTER the dial rotation — exactly like draw_volume,
    for exactly its reason: every hit-test here is in raw screen coords,
    so the paint must be too. And NOTHING in here may shell out: every
    fact is a backend snapshot (background thread) or already in memory."""
    frame = frame.point(lambda p: int(p * 0.30))
    d = ImageDraw.Draw(frame)
    page = SET_PAGES[_SET["page"]]
    snap = _BACKEND.snapshot()
    cap = f"SETTINGS — {page}"
    tw = d.textlength(cap, font=_font(28))
    d.text(((SIZE - tw) / 2, 142), cap, font=_font(28), fill=SET_STEEL)
    if page == "WI-FI":
        _draw_set_wifi(d, now, snap)
    elif page == "CONNECT":
        _draw_set_connect(d, now)
    elif page == "CONTACT":
        _draw_set_contact(d, now)
    elif page == "ALERTS":
        _draw_set_alerts(d, now)
    elif page == "TIME ZONE":
        _draw_set_tz(d, now, snap)
    elif page == "WALLET":
        _draw_set_wallet(frame, d, now)
    else:
        _draw_set_system(d, now, snap)
    # Chrome: rim chevrons (pages wrap), the dot rail, the DONE ring.
    n = len(SET_PAGES)
    for sgn, (ax, ay) in ((-1, SET_ARROW_L), (1, SET_ARROW_R)):
        d.line([(ax - sgn * 16, ay - 32), (ax + sgn * 16, ay),
                (ax - sgn * 16, ay + 32)], fill=SET_STEEL, width=6,
               joint="curve")
        # Round 2: the chevron says "somewhere"; the neighbour page's
        # NAME says where ("< >" alone was "not that intuitive").
        nb = SET_PAGES[(_SET["page"] + sgn) % n]
        tw = d.textlength(nb, font=_font(17))
        d.text((ax - tw / 2, ay + 46), nb, font=_font(17), fill=SET_DIM)
    for i in range(n):
        cxd = SIZE / 2 + (i - (n - 1) / 2) * SET_DOT_DX
        if i == _SET["page"]:
            d.ellipse([cxd - 7, SET_DOTS_Y - 7, cxd + 7, SET_DOTS_Y + 7],
                      fill=SET_CYAN)
        else:
            d.ellipse([cxd - 6, SET_DOTS_Y - 6, cxd + 6, SET_DOTS_Y + 6],
                      outline=SET_DIM, width=2)
    # DONE — the volume ring's idiom: one obvious exit, and no timeout
    # that dumps the owner out mid-thought.
    bx, by = SET_DONE_XY
    d.ellipse([bx - SET_DONE_R, by - SET_DONE_R,
               bx + SET_DONE_R, by + SET_DONE_R],
              outline=SET_STEEL, width=5)
    tw = d.textlength("DONE", font=_font(30))
    d.text((bx - tw / 2, by - 19), "DONE", font=_font(30), fill=SET_TEXT)
    # First-open coach overlay (round 2): a dark plate in the enroll-
    # caption idiom, centred, gone after 5s. It deliberately sits OVER
    # the page — a coach mark whispered from the margin of a dense page
    # is a coach mark nobody reads.
    if _SET["hint_until"] > now:
        lines = ("SWIPE OR TAP A DOT TO BROWSE",
                 "DRAG THE OUTER RIM TO FACE YOU")
        w = max(d.textlength(m, font=_font(24)) for m in lines)
        x0, x1 = (SIZE - w) / 2 - 46, (SIZE + w) / 2 + 46
        d.rounded_rectangle([x0, 452, x1, 596], radius=22,
                            fill=(16, 26, 34), outline=SET_CYAN, width=2)
        k = 0.7 + 0.3 * math.sin(now * math.tau * 0.6)
        for j, m in enumerate(lines):
            tw = d.textlength(m, font=_font(24))
            d.text(((SIZE - tw) / 2, 478 + j * 52), m, font=_font(24),
                   fill=tuple(int(v * k) for v in SET_CYAN))
    if _SET["err_until"] > now:
        tw = d.textlength(_SET["err"], font=_font(26))
        d.text(((SIZE - tw) / 2, 798), _SET["err"], font=_font(26),
               fill=SET_RED)
    return frame


#: Sterling concierge screen (round 2 rebuild — the old static card
#: "isn't sexy"). House language kept: DejaVu-Bold, violet for the
#: concierge, steel for captions, cyan for the voice coach. A monogram
#: seal under a slow three-ring guilloché, orbiting service markers,
#: LIVE status lines when the conductor writes sterling_status.json
#: (graceful STANDING BY when it hasn't), and one DONE exit. No 6s
#: auto-fallback: the mode is modal exactly like volume and settings —
#: DONE or a takeover, nothing else closes it.
STER_VIOLET = (123, 92, 255)
STER_LILAC = (186, 172, 240)
STER_INK = (232, 226, 255)
STER_SEAL_CY = 396
#: The DONE button's geometry, kept as a headstone. There is no button any
#: more — 2026-08-05, the owner: "i think anytime you have to click done is a
#: mistake." The desk now finishes when you SAY so, when the room goes quiet,
#: or on a tap anywhere. Left named so the next person to wonder where the
#: button went finds the answer here rather than reinventing it.
STERLING_STATUS = Path("/tmp/aura_face/sterling_status.json")
#: ── THE DESK IS OPEN: THE ONE FLAG THE CONDUCTOR READS ────────────────────
#:
#: "you as a concierge basically — you can press it and give it feedback about
#: what you want changed ... and they will update the code" (2026-08-04, said
#: to the puck rather than typed, which is the entire point).
#:
#: Pressing STERLING arms a microphone. Everything said while this card is up
#: is a REQUEST, not a question — it must never reach the model, or the first
#: thing a person says to the concierge gets answered instead of written down.
#:
#: The FACE owns the mode and this file is its only export; the conductor
#: reads it and never writes it. One owner, one opinion about whether the desk
#: is open (§7 — two gates on the same state is how modes get stuck).
CONCIERGE_OPEN = Path("/tmp/aura_face/concierge_open")
#: The conductor cannot open or close the desk — it ASKS, here, and the face
#: acts. The owner wants this hands-free ("anytime you have to click done is
#: a mistake"), which means voice has to reach the mode; it must not mean two
#: processes writing one flag. The face stays the only owner (§7).
CONCIERGE_OPEN_REQ = Path("/tmp/aura_face/concierge_open_req")
CONCIERGE_CLOSE_REQ = Path("/tmp/aura_face/concierge_close_req")
_STERLING = {"open": False, "view_deg": 0.0, "view_prev_ang": None,
             "grab_deg": 0.0, "opened_at": 0.0, "flag_error": False}


def _sterling_set(is_open: bool, why: str) -> None:
    """Open or close the desk, and say so on disk and in the log.

    Every path that changes this mode goes through here. The old code set the
    flag in three places; a fourth would have been written eventually and the
    conductor would have gone on listening to a room with no card up — a
    microphone that is armed with nothing on screen to say so is the exact
    silent state PRINCIPLES §1 exists about.
    """
    _STERLING["open"] = is_open
    _STERLING["opened_at"] = time.time() if is_open else 0.0
    try:
        if is_open:
            CONCIERGE_OPEN.parent.mkdir(parents=True, exist_ok=True)
            CONCIERGE_OPEN.write_text(str(time.time()))
        else:
            CONCIERGE_OPEN.unlink(missing_ok=True)
    except Exception as exc:
        # A card that says LISTENING while nothing is listening is worse than
        # no card. Say it loudly; the status line below also goes red.
        print(f"sterling: DESK FLAG NOT WRITTEN {exc!r} — the conductor "
              f"cannot know the desk is open", flush=True)
        _STERLING["flag_error"] = True
        return
    _STERLING["flag_error"] = False
    print(f"sterling: {'OPEN — listening' if is_open else 'closed'} ({why})",
          flush=True)


_STER_STATUS = {"mtime": None, "lines": None}


def _sterling_status_lines():
    """What Sterling is working on, stat-cached by mtime (one stat per
    frame, a parse only on change). Accepts {"lines": [...]} (preferred),
    {"status": "..."}, or a bare list/string. Absent or unreadable ->
    None and the card says STANDING BY — a placeholder, never a pretend
    task; an unreadable file is LOGGED, not shrugged off (PRINCIPLES §1)."""
    try:
        m = STERLING_STATUS.stat().st_mtime
    except (FileNotFoundError, NotADirectoryError):
        _STER_STATUS["mtime"] = _STER_STATUS["lines"] = None
        return None
    if _STER_STATUS["mtime"] != m:
        _STER_STATUS["mtime"] = m
        lines = None
        try:
            raw = json.loads(STERLING_STATUS.read_text())
            v = raw.get("lines", raw.get("status")) \
                if isinstance(raw, dict) else raw
            if isinstance(v, str):
                v = [v]
            if isinstance(v, list):
                lines = [str(s).strip()[:38] for s in v
                         if str(s).strip()][:3]
        except Exception as e:
            print(f"sterling: status unreadable {e!r}", flush=True)
        if not lines:
            # A file that parsed to nothing is a contract mismatch with
            # the conductor, not an idle desk — say so, once per change.
            print("sterling: status present but no usable lines",
                  flush=True)
        _STER_STATUS["lines"] = lines or None
    return _STER_STATUS["lines"]


#: ── THE BOW TIE IS THE PRODUCT ────────────────────────────────────────────
#:
#: The seal carried a letter S, which is a monogram of a NAME. The owner,
#: 2026-08-05: "make the S go away, use the bow tie as the canonical symbol
#: of the sterling product."
#:
#: A letter says who he is; the tie says what he is — the concierge at the
#: desk. It also survives being small, being one colour, and being seen at
#: arm's length on a 1080px disc, which a serif capital does not.
#:
#: Drawn rather than loaded: a shape this simple is four polygons, and a PNG
#: would be a second asset to ship to every puck and keep in step with the
#: colours it sits beside.
def _draw_bowtie(d: ImageDraw.ImageDraw, cx: float, cy: float,
                 scale: float = 1.0) -> None:
    """A bow tie centred on (cx, cy).

    Round 2 of the shape. The first was four straight-sided quadrilaterals
    and read as an hourglass slab — a bow tie's outer edges are PINCHED in
    the middle, its knot is small, and each wing carries a fold. All three
    matter at this size; without them it is a butterfly.
    """
    W = 122 * scale          # outer half-width
    H = 70 * scale           # outer half-height, at the corners
    N = 26 * scale           # how far the outer edge pinches inward
    K = 17 * scale           # knot half-width
    I = 26 * scale           # inner half-height, where the wing meets the knot
    wings = []
    for sgn in (-1, 1):
        wings.append([
            (cx + sgn * W, cy - H),          # outer top corner
            (cx + sgn * (W - N), cy),        # the pinch
            (cx + sgn * W, cy + H),          # outer bottom corner
            (cx + sgn * K, cy + I),          # inner bottom, at the knot
            (cx + sgn * K, cy - I),          # inner top
        ])
    sh = 4 * scale
    for poly in wings:
        d.polygon([(px + sh, py + sh) for px, py in poly], fill=(40, 30, 84))
    for poly in wings:
        d.polygon(poly, fill=STER_INK)
    # The folds: one line per wing from the knot toward the pinch, which is
    # what makes fabric out of two flat shapes.
    for sgn in (-1, 1):
        d.line([(cx + sgn * K, cy - I * 0.6),
                (cx + sgn * (W - N * 1.4), cy - H * 0.24)],
               fill=(176, 162, 232), width=max(1, int(2 * scale)))
        d.line([(cx + sgn * K, cy + I * 0.6),
                (cx + sgn * (W - N * 1.4), cy + H * 0.24)],
               fill=(176, 162, 232), width=max(1, int(2 * scale)))
    kn = [cx - K - 6 * scale, cy - 27 * scale,
          cx + K + 6 * scale, cy + 27 * scale]
    d.rounded_rectangle([kn[0] + sh, kn[1] + sh, kn[2] + sh, kn[3] + sh],
                        radius=9 * scale, fill=(40, 30, 84))
    d.rounded_rectangle(kn, radius=9 * scale, fill=STER_VIOLET,
                        outline=STER_INK, width=max(2, int(2.5 * scale)))


#: Built once: a HUD scanline wash and a soft violet bloom for the seal.
#: The card redraws about ten times a second and neither of these changes,
#: so they are made on first use and screened on afterwards — the same
#: bargain _cat_glow() strikes.
_STER_ASSETS = {}


def _ster_assets():
    if not _STER_ASSETS:
        # Scanlines: one hairline every 6px, very dim, clipped to the disc.
        # A flat dark field reads as "off"; a field with structure in it
        # reads as an instrument that is powered up.
        scan = Image.new("RGB", (SIZE, SIZE), 0)
        sd = ImageDraw.Draw(scan)
        for yy in range(0, SIZE, 6):
            sd.line([(0, yy), (SIZE, yy)], fill=(9, 7, 20), width=1)
        mask = Image.new("L", (SIZE, SIZE), 0)
        ImageDraw.Draw(mask).ellipse([0, 0, SIZE - 1, SIZE - 1], fill=255)
        scan.putalpha(mask)
        _STER_ASSETS["scan"] = scan.convert("RGB")
        # The bloom behind the seal — violet, wide, soft.
        r = 260
        g = Image.new("L", (r * 2, r * 2), 0)
        gd = ImageDraw.Draw(g)
        for i in range(r, 0, -5):
            gd.ellipse([r - i, r - i, r + i, r + i],
                       fill=int(120 * (1.0 - i / r) ** 2.4))
        g = g.filter(ImageFilter.GaussianBlur(30))
        bloom = Image.new("RGB", (r * 2, r * 2), 0)
        bloom.paste(Image.new("RGB", (r * 2, r * 2), (92, 66, 210)),
                    (0, 0), g)
        _STER_ASSETS["bloom"] = bloom
    return _STER_ASSETS


def draw_sterling(frame: Image.Image, now: float) -> Image.Image:
    """The concierge, rebuilt round 3 (2026-08-05).

    The owner, on the version this replaces: "make the concierge screen
    sexier overall, it's really dull at this point. redo the whole layout
    and present it as it is, a professional, yet futuristic concierge."

    Which is a brief about POSTURE, not decoration. A concierge is somebody
    standing at a desk waiting for you to speak — so the composition is a
    plate with a name on it, a seal above it, and a live status line saying
    he is listening. The futurism is in the instrument treatment (rim ticks,
    scanlines, a sweep) rather than in anything blinking for its own sake.

    Drawn in SCREEN coordinates AFTER the dial rotation, like every modal
    overlay, so paint and hit-tests agree; the caller applies the per-mode
    view rotation afterwards (see _apply_view).
    """
    a = _ster_assets()
    # A deeper wash than the old 0.30: the desk is its own room, not a
    # translucent note stuck over the home face.
    frame = frame.point(lambda p: int(p * 0.16))
    frame = ImageChops.screen(frame, a["scan"])
    cx = SIZE // 2
    cy = STER_SEAL_CY
    # Bloom first — everything else sits on top of it.
    bl = a["bloom"]
    canvas = Image.new("RGB", (SIZE, SIZE), 0)
    canvas.paste(bl, (int(cx - bl.width // 2), int(cy - bl.height // 2)))
    frame = ImageChops.screen(frame, canvas)
    d = ImageDraw.Draw(frame)

    # ── the instrument rim ────────────────────────────────────────────────
    #
    # CENTRED ON THE DISPLAY, not on the seal. Round 1 drew this ring around
    # the seal's centre (y=430) while the glass is centred at 540, so the
    # ticks landed as scattered debris around the edges and one of them drew
    # straight through the caption. A round screen only reads as an
    # instrument when its rim agrees with the glass.
    dcx = dcy = SIZE / 2
    R = SIZE / 2 - 10
    # Ticks in two arcs — across the top and across the bottom — rather than
    # all the way round: a full ring of ticks fights the desk plate for
    # attention, and the sides are where the content is widest.
    for deg in list(range(196, 345, 7)) + list(range(16, 165, 7)):
        quarter = deg % 21 == 0
        ln = 20 if quarter else 10
        ra = math.radians(deg)
        d.line([(dcx + (R - ln) * math.cos(ra), dcy + (R - ln) * math.sin(ra)),
                (dcx + R * math.cos(ra), dcy + R * math.sin(ra))],
               fill=STER_VIOLET if quarter else (66, 54, 116),
               width=3 if quarter else 2)
    # One bright arc running the rim: the whole screen is listening, and
    # this is the largest, quietest way to say it.
    sw = (now * 36.0) % 360.0
    for i in range(26):
        k = 1.0 - i / 26.0
        d.arc([dcx - R, dcy - R, dcx + R, dcy + R],
              start=sw - i * 1.9, end=sw - i * 1.9 + 2.1,
              fill=(int(150 * k) + 18, int(112 * k) + 12, int(255 * k) + 34),
              width=4)

    # ── the name plate ────────────────────────────────────────────────────
    # Wide tracking, drawn a letter at a time: a concierge's brass plate,
    # not a headline. Hairlines either side of the sub-label finish it.
    name = "STERLING"
    f_n = _font(52)
    track = 14
    wds = [d.textlength(ch, font=f_n) for ch in name]
    total = sum(wds) + track * (len(name) - 1)
    x = (SIZE - total) / 2
    for ch, w in zip(name, wds):
        d.text((x, 92), ch, font=f_n, fill=STER_INK)
        x += w + track
    sub = "CONCIERGE"
    f_s = _font(21)
    tw = d.textlength(sub, font=f_s)
    d.text(((SIZE - tw) / 2, 158), sub, font=f_s, fill=SET_STEEL)
    for sgn in (-1, 1):
        x0 = cx + sgn * (tw / 2 + 22)
        d.line([(x0, 168), (x0 + sgn * 96, 168)], fill=(70, 58, 140), width=2)

    # ── the seal ──────────────────────────────────────────────────────────
    # Guilloché, kept from round 2 because it was the good part: three thin
    # dashed rings counter-rotating, depth rather than noise.
    for rr, spd, seg, col in ((150, 8.0, 15, (86, 66, 172)),
                              (168, -5.0, 11, (58, 70, 130)),
                              (186, 3.2, 19, (72, 56, 156))):
        base = (now * spd) % 360.0
        span = (360.0 / seg) * 0.55
        for k in range(seg):
            a0 = base + k * (360.0 / seg)
            d.arc([cx - rr, cy - rr, cx + rr, cy + rr],
                  start=a0, end=a0 + span, fill=col, width=2)
    # A plate under the tie, so the seal reads as a solid object rather
    # than a hole cut in the screen.
    d.ellipse([cx - 118, cy - 118, cx + 118, cy + 118], fill=(26, 20, 58))
    throb = 1.0 + 0.03 * math.sin(now * math.tau * 0.7)
    r1 = 122 * throb
    d.ellipse([cx - r1, cy - r1, cx + r1, cy + r1],
              outline=STER_VIOLET, width=4)
    d.ellipse([cx - 134, cy - 134, cx + 134, cy + 134],
              outline=(70, 58, 140), width=2)
    _draw_bowtie(d, cx, cy, 0.92)

    # ── the desk ──────────────────────────────────────────────────────────
    # What he is holding, numbered. The proof that speaking worked is
    # seeing your own words appear here, so this is the part of the screen
    # that must never be decorative.
    lines = _sterling_status_lines()
    n = len(lines or [])
    plate_y0 = 596
    # The empty plate carries a third line now (the worked example below), so
    # it is 30px taller than it was. Only the empty case: a filled plate is
    # sized by its own lines and never showed the guidance anyway.
    plate_y1 = plate_y0 + (78 + 52 * n if n else 208)
    plate = Image.new("RGB", (SIZE, SIZE), 0)
    ImageDraw.Draw(plate).rounded_rectangle(
        [172, plate_y0, SIZE - 172, plate_y1], radius=28, fill=(21, 17, 46))
    frame = ImageChops.screen(frame, plate)
    d = ImageDraw.Draw(frame)
    d.rounded_rectangle([172, plate_y0, SIZE - 172, plate_y1], radius=28,
                        outline=(80, 64, 154), width=2)
    hdr = "ON THE DESK"
    f_h = _font(20)
    tw = d.textlength(hdr, font=f_h)
    # A rule either side of the header, the same idiom as CONCIERGE above:
    # the plate is furniture and furniture has edges.
    d.text(((SIZE - tw) / 2, plate_y0 + 20), hdr, font=f_h, fill=SET_STEEL)
    for sgn in (-1, 1):
        x0 = cx + sgn * (tw / 2 + 18)
        d.line([(x0, plate_y0 + 31), (x0 + sgn * 120, plate_y0 + 31)],
               fill=(62, 50, 118), width=2)
    if lines:
        f_l = _font(26)
        for j, ln in enumerate(lines[-3:]):
            yy = plate_y0 + 66 + j * 52
            d.ellipse([212, yy + 2, 242, yy + 32], fill=STER_VIOLET)
            num = str(j + 1)
            nw = d.textlength(num, font=_font(19))
            d.text((227 - nw / 2, yy + 7), num, font=_font(19),
                   fill=(24, 18, 52))
            d.text((262, yy), ln, font=f_l, fill=STER_LILAC)
    else:
        msg = "nothing filed yet"
        f_m = _font(28)
        tw = d.textlength(msg, font=f_m)
        d.text(((SIZE - tw) / 2, plate_y0 + 74), msg, font=f_m, fill=SET_STEEL)
        msg2 = "just say what you want changed"
        f_m2 = _font(22)
        tw = d.textlength(msg2, font=f_m2)
        d.text(((SIZE - tw) / 2, plate_y0 + 118), msg2, font=f_m2,
               fill=(104, 92, 148))
        # ── WHAT TO TRY FIRST ─────────────────────────────────────────────
        #
        # "what would you like to try first?" — asked at this card,
        # 2026-08-05. The line above describes the SHAPE of a request; it
        # does not give you one, and a person standing at a desk for the
        # first time is asking for the sentence, not the grammar. So here is
        # one that works, in quotes, so it reads as something to say out loud
        # rather than another caption.
        #
        # "make the wordmark bigger" is the example this file already uses
        # for a filed request (see the REQUESTS block below) — a real change
        # the desk can take, not an invented one.
        #
        # EMPTY PLATE ONLY, like the guidance it sits under: once a line is
        # filed, the person has found the first thing and the plate belongs
        # to their own words.
        msg3 = 'try: "make the wordmark bigger"'
        f_m3 = _font(20)
        tw = d.textlength(msg3, font=f_m3)
        d.text(((SIZE - tw) / 2, plate_y0 + 152), msg3, font=f_m3,
               fill=(92, 80, 138))

    # ── the armed lamp ────────────────────────────────────────────────────
    #
    # Opening this card ARMS A MICROPHONE. A microphone that is armed with
    # nothing on screen to say so is the state §1 exists about, so the lamp
    # reads the same flag the conductor reads — never a local guess — and
    # goes RED if that flag could not be written, because the one
    # unforgivable version of this screen is the one that looks live and is
    # not.
    #
    # It sits just under the plate, on the same centre line: the desk, then
    # the man behind it saying he is listening.
    armed = CONCIERGE_OPEN.exists() and not _STERLING.get("flag_error")
    k = 0.5 + 0.5 * math.sin(now * math.tau * 0.8)
    lamp, col = (("LISTENING", SET_CYAN) if armed else
                 ("NOT LISTENING — DESK FLAG FAILED", SET_RED))
    if not armed:
        k = 1.0                        # a fault does not breathe, it stares
    f_lamp = _font(26)
    lw = d.textlength(lamp, font=f_lamp)
    meter_w = (5 * 10 + 4 * 5) if armed else 0
    grp = 18 + 16 + lw + (18 + meter_w if armed else 0)
    gx = (SIZE - grp) / 2
    ly = plate_y1 + 34
    d.ellipse([gx, ly, gx + 18, ly + 18], fill=tuple(int(v * k) for v in col))
    d.text((gx + 34, ly - 6), lamp, font=f_lamp,
           fill=tuple(int(v * max(0.5, k)) for v in col))
    if armed:
        mx = gx + 34 + lw + 18
        for b in range(5):
            h = 6 + 15 * (0.5 + 0.5 * math.sin(now * 6.0 + b * 1.1)) ** 2
            d.rounded_rectangle([mx + b * 15, ly + 18 - h,
                                 mx + b * 15 + 10, ly + 18],
                                radius=3, fill=SET_CYAN)

    # ── HIS ANSWER, STANDING ON THE GLASS ─────────────────────────────────
    #
    # "present and accounted for." — said into the room 2026-08-05 12:59:25,
    # twenty-two seconds after somebody asked the desk whether it was there.
    # He now says that line aloud when asked (puck_conduct.DESK_LINES
    # ["here"]); this is the same answer printed on the card, so it can be
    # read from across the room instead of only heard, and so the question
    # is already answered before anybody has to ask it.
    #
    # ARMED ONLY. When the desk flag could not be written the lamp above is
    # red, and a plate declaring him present beside a fault would be exactly
    # the confident-and-wrong screen §1 exists to prevent.
    #
    # Tracked like the name plate above rather than set as a sentence: this
    # is the concierge's brass, not a caption.
    if armed:
        ans = "PRESENT AND ACCOUNTED FOR"
        f_a = _font(21)
        a_track = 3
        a_wds = [d.textlength(ch, font=f_a) for ch in ans]
        ax = (SIZE - (sum(a_wds) + a_track * (len(ans) - 1))) / 2
        for ch, w in zip(ans, a_wds):
            d.text((ax, ly + 38), ch, font=f_a, fill=(156, 142, 206))
            ax += w + a_track

    # ── WHAT HE NEEDS FROM YOU ────────────────────────────────────────────
    #
    # "what do you need?" — asked into the room 2026-08-05, standing at this
    # card. Nothing on the glass answered it. The plate DOES say "just say
    # what you want changed", but only while the desk is empty: the moment
    # one line is filed that guidance is replaced by the line itself, so the
    # answer disappears exactly when somebody has started using the thing and
    # is most likely to ask what shape the next sentence should take.
    #
    # So it is stated permanently, in his voice, as an answer rather than a
    # caption — the same move as the brass line above, one step dimmer than
    # it and one step brighter than the exit hint, which is the order you
    # want to read them in.
    #
    # ARMED ONLY, for the reason the brass line is: telling somebody what to
    # say, beside a red lamp that means nothing they say will be filed, is
    # the confident-and-wrong screen §1 exists to prevent.
    if armed:
        need = "WHAT I NEED: ONE SENTENCE, WHAT TO CHANGE"
        f_need = _font(19)
        tw = d.textlength(need, font=f_need)
        d.text(((SIZE - tw) / 2, 946), need, font=f_need, fill=(134, 122, 180))

    # ── how you leave, which is also with your voice ──────────────────────
    #
    # There is no DONE button any more. The owner: "i think anytime you have
    # to click done is a mistake, i want it as hands free / voice only as
    # possible." Saying so is the primary exit; a tap anywhere still works
    # because a mode must always have an exit you can reach with a finger.
    #
    # Dropped from 946 to 978 to make room for the line above. Still well
    # inside the disc: at y=1001 the glass is 281px wide either side of
    # centre and this line is ~350px in total.
    hint = 'SAY "THAT\'S ALL" WHEN YOU\'RE FINISHED'
    f_hint = _font(19)
    tw = d.textlength(hint, font=f_hint)
    d.text(((SIZE - tw) / 2, 978), hint, font=f_hint, fill=(112, 100, 156))
    return frame


#: ── STERLING'S LIVE OVERLAY — THE WEDGE'S OWN SECTOR, NOT A BOX ───────────
#:
#: 2026-08-07, the owner's third ask. The baked STERLING tile is a correct
#: gold sector like its neighbours; his live status reached the glass as a
#: straight-edged box over it. It now wears the tile's own geometry: the
#: sector polygon at the baked band's exact radii (WEDGE_R0..WEDGE_R1, both
#: through DIAL_K), the concierge gold, the same fill and stroke weights as
#: home.html's MENU (0.14 fill, 0.55 stroke) — and it is painted BEFORE the
#: dial rotate, so it turns with the ring it belongs to, over the tile it
#: lights. Rows are horizontal on the spoke like every wedge's.
STER_WEDGE_A0, STER_WEDGE_A1, STER_GOLD = WEDGES[WEDGE_KEYS.index("sterling")]
#: Below the tile's baked icon and label (the spoke line is y≈487) and above
#: the sector's bottom corner at y≈604. Three rows, matching the desk
#: plate's own lines[-3:].
STER_WEDGE_ROW_Y = (544.0, 570.0, 596.0)
_STER_WEDGE = {"sig": None, "tile": None, "box": None, "said": None}


def draw_sterling_wedge(frame: Image.Image, now: float,
                        hold: bool = False) -> None:
    """Sterling's live status, on the STERLING wedge itself. In place,
    before the rotate, like the two live wedges.

    Nothing to say -> nothing painted, and the baked tile stands alone.
    Wrapped whole: new paint in a compositor that must never stop; a failure
    degrades to the baked tile and says so once — never per frame.
    """
    if hold:
        return
    try:
        lines = _sterling_status_lines()
        if not lines:
            if _STER_WEDGE["sig"] is not None:
                _STER_WEDGE.update(sig=None, tile=None)
            return
        sig = tuple(lines)
        if _STER_WEDGE["sig"] != sig or _STER_WEDGE["tile"] is None:
            canvas = Image.new("RGB", (SIZE, SIZE), 0)
            d = ImageDraw.Draw(canvas, "RGBA")
            poly = _wedge_sector_poly(STER_WEDGE_A0, STER_WEDGE_A1,
                                      WEDGE_R0, WEDGE_R1, pad=0.0,
                                      flat=False)
            d.polygon(poly, fill=STER_GOLD + (36,))
            d.line(poly + [poly[0]], fill=STER_GOLD + (140,), width=2)
            bright = tuple(min(255, int(c * 0.35) + 168) for c in STER_GOLD)
            for yy, ln in zip(STER_WEDGE_ROW_Y, lines[-3:]):
                sp = span_across(yy, 16.0, STER_WEDGE_A0, STER_WEDGE_A1,
                                 WEDGE_R0, WEDGE_R1, None)
                if sp is None:
                    continue
                f = face_for(ln, "label", script_size(ln, 14))
                draw_centred(d, (sp[0] + sp[1]) / 2.0, yy, ln, f, bright,
                             0.0, max(0.0, sp[1] - sp[0] - 2 * FIT_MARGIN))
            xs = [p[0] for p in poly]
            ys = [p[1] for p in poly]
            box = (max(0, int(min(xs)) - 10), max(0, int(min(ys)) - 10),
                   min(SIZE, int(max(xs)) + 12), min(SIZE, int(max(ys)) + 12))
            _STER_WEDGE.update(sig=sig, tile=canvas.crop(box), box=box)
        x0, y0, x1, y1 = _STER_WEDGE["box"]
        frame.paste(ImageChops.screen(frame.crop((x0, y0, x1, y1)),
                                      _STER_WEDGE["tile"]), (x0, y0))
    except Exception as e:                      # noqa: BLE001
        if _STER_WEDGE["said"] != repr(e):
            _STER_WEDGE["said"] = repr(e)
            print(f"sterling: wedge overlay failed {e!r} — baked tile only",
                  flush=True)


#: ── THE CONCIERGE TILE BREATHES — 2026-08-07, the owner's fourth ask ──────
#:
#: "In a lot of ways this is the ultimate end product for our customers":
#: the concierge is the product, so his tile is the one thing on the ring
#: that moves at idle — a slow gold swell on the STERLING sector's border.
#: Motion reads as life, and the concierge is the one element always awake.
#: (The applied-gold STERLING label and the inset gold hairline are the
#: BAKED half of this brief and live in home.html, same commit.)
#:
#: Tourbillon-style budget discipline: the eased curve is a TABLE indexed
#: by time, the border is baked ONCE to a small tile, and the frame pays
#: one point() and one screen() over the sector's own crop box (~5% of the
#: glass) — nothing per-frame is computed that could be precomputed.
#:
#: Two states, both read from flags that ALREADY EXIST (the brief: "read
#: them, do not invent new ones"): IDLE breathes over the table; ACTIVE —
#: the desk open (_STERLING["open"], the same bit CONCIERGE_OPEN carries)
#: or a request live (_REQ_UI's head in REQ_ACTIVE) — holds steady above
#: the breath's own top, and resumes breathing when the desk closes.
STER_GLOW_PERIOD_S = 4.6      # the brief: a four-to-five second swell
STER_GLOW_N = 64
#: Cosine ease-in-out, bottom 0.28 -> top 0.90: a 62-point swing against
#: the brief's 35% floor. ACTIVE holds at 1.00 — visibly over the top of
#: the idle breath, so the two states read apart at a glance.
STER_GLOW_TABLE = tuple(
    0.28 + 0.62 * (0.5 - 0.5 * math.cos(i * math.tau / STER_GLOW_N))
    for i in range(STER_GLOW_N))
STER_GLOW_ACTIVE_K = 1.0
_STER_GLOW = {"tile": None, "box": None, "mix": 0.0, "last_t": 0.0,
              "idx": None, "wraps": 0, "said": None}


def draw_sterling_glow(frame: Image.Image, now: float,
                       hold: bool = False) -> None:
    """The breathing border on the STERLING tile. In place, before the
    rotate, like the wedge overlays; a failure degrades to the baked
    border and says so once — never per frame.
    """
    if hold:
        return
    try:
        if _STER_GLOW["tile"] is None:
            canvas = Image.new("RGB", (SIZE, SIZE), 0)
            d = ImageDraw.Draw(canvas)
            poly = _wedge_sector_poly(STER_WEDGE_A0, STER_WEDGE_A1,
                                      WEDGE_R0, WEDGE_R1, pad=0.0,
                                      flat=False)
            d.line(poly + [poly[0]], fill=STER_GOLD, width=5)
            canvas = canvas.filter(ImageFilter.GaussianBlur(2.5))
            xs = [p[0] for p in poly]
            ys = [p[1] for p in poly]
            box = (max(0, int(min(xs)) - 8), max(0, int(min(ys)) - 8),
                   min(SIZE, int(max(xs)) + 8), min(SIZE, int(max(ys)) + 8))
            _STER_GLOW.update(tile=canvas.crop(box), box=box)
        idx = int((now % STER_GLOW_PERIOD_S) / STER_GLOW_PERIOD_S
                  * STER_GLOW_N) % STER_GLOW_N
        # The period, verifiable from the log: the first three wraps of the
        # table index are stamped, then it goes quiet — enough to measure
        # the cycle against wall time without narrating forever.
        if (_STER_GLOW["idx"] is not None and idx < _STER_GLOW["idx"]
                and _STER_GLOW["wraps"] < 3):
            _STER_GLOW["wraps"] += 1
            print(f"sterling glow: table index wrapped to 0 at {now:.3f} "
                  f"(cycle {_STER_GLOW['wraps']}, N={STER_GLOW_N}, "
                  f"period {STER_GLOW_PERIOD_S}s)", flush=True)
        _STER_GLOW["idx"] = idx
        head = _REQ_UI["head"]
        active = (_STERLING["open"]
                  or (head is not None
                      and head.get("state") in REQ_ACTIVE))
        # A short crossfade between the states rather than a jump — the
        # hold arrives in ~0.4s and the breath resumes as gently. When the
        # mix is 0 the value IS the table's, so the idle period stays exact.
        dt = max(0.0, min(0.5, now - (_STER_GLOW["last_t"] or now)))
        _STER_GLOW["last_t"] = now
        _STER_GLOW["mix"] = (min(1.0, _STER_GLOW["mix"] + dt / 0.4)
                             if active else
                             max(0.0, _STER_GLOW["mix"] - dt / 0.4))
        mix = _STER_GLOW["mix"]
        k = STER_GLOW_TABLE[idx] * (1.0 - mix) + STER_GLOW_ACTIVE_K * mix
        x0, y0, x1, y1 = _STER_GLOW["box"]
        tile = _STER_GLOW["tile"].point(lambda p, kk=k: int(p * kk))
        frame.paste(ImageChops.screen(frame.crop((x0, y0, x1, y1)), tile),
                    (x0, y0))
    except Exception as e:                      # noqa: BLE001
        if _STER_GLOW["said"] != repr(e):
            _STER_GLOW["said"] = repr(e)
            print(f"sterling glow: failed {e!r} — baked border only",
                  flush=True)


# ═══════════════════════════════════════════════════════════════════════════
#  REQUESTS — the work you asked for, while it is being done (2026-08-05)
# ═══════════════════════════════════════════════════════════════════════════
#
# STERLING takes the request. This is the other half: what happened to it.
# Somebody says "make the wordmark bigger" at the concierge desk, walks away,
# and until now the glass said nothing until the change simply appeared —
# which is indistinguishable from the request having been dropped
# (PRINCIPLES §1, and §10: the wait cannot be shortened, so it is made
# legible instead).
#
# ── WHY THIS WEDGE IS NOT IN `WEDGES` ─────────────────────────────────────
#
# The five sectors in WEDGES are BAKED into base.png by home.html's MENU, and
# every one of them is permanent furniture. This one is not furniture: it is
# present only while there is work, and it FADES. A baked wedge cannot fade
# (the RTX ships a still every ~20s), and appending to WEDGES would also add
# a sixth stagger step to the unlock entrance and a sixth cover mask for a
# sector base.png has never drawn.
#
# So it is drawn HERE, live, in its own geometry — but it obeys the ring's
# rules exactly: same band (WEDGE_R0..WEDGE_R1), same 34° width, same fill
# and stroke weights as home.html's MENU, same horizontal content on the
# spoke at r≈416, and it is painted BEFORE the dial rotate so it TURNS WITH
# THE RING it belongs to (docs/PUCK-STANDALONE.md §12.1 — the split that
# caused every layout bug in this file).
#
# ── WHY THE UPPER LEFT ────────────────────────────────────────────────────
#
# It is the only free arc left, and that is a measurement rather than a
# preference. Going clockwise from BRIEFING the band is occupied by the five
# baked wedges (-62..124), the POWER button (~150°), SLEEP (~180°), the
# $LEDGER meter and its track arc (~-150..-180), and the clock pill, whose
# corner reaches r≈451 between -101° and -79°. That leaves -137..-103, and
# the wedge fills it with two degrees to spare at each end.
REQUESTS_FILE = Path("/tmp/aura_face/requests.json")
#: ── 2026-08-14, owner: "the 12 o'clock is really really empty. why do
#: we not have the AI custom wedge expand more around the circumference
#: to show its prominence." The conjured slot grows -103 -> -70: it now
#: sweeps THROUGH twelve (-90) and stops 8 deg short of BRIEFING's baked
#: start at -62 — the same finger-padding the arc's other end keeps. The
#: -137 end does NOT move; the $LEDGER corner contract at -145 stands.
REQUESTS_A0, REQUESTS_A1 = -137.0, -70.0
#: The gauge rides OUTSIDE the sector, on clear rim, so the number and the
#: arc are never fighting the text for the same pixels. Same idiom as
#: draw_enroll_ring: a dim full track, a bright fill, a hot head.
#: 470 -> 502 with the band correction: the gauge has to stay OUTSIDE the
#: sector, and the sector's outer edge moved from 458 to 494.6. The rim
#: budget here is 495 (wedge edge) to 528 (bezel inner edge), both measured
#: on base.png, and 502±3 sits in the middle of it. The left tick scale was
#: trimmed to 219° in the same commit so it no longer runs under this arc.
#:
#: ── THE RIM BUDGET NOW HAS A CHAPTER RING IN IT, 2026-08-06 evening ───────
#: That trimmed tick scale is gone. home.html bakes a full 60-tick chapter
#: ring in its place, and it is CONTINUOUS — it passes through this wedge's
#: own sector — so the two were fitted against each other rather than one
#: being cut back again. In display px, on this file's units:
#:
#:     this gauge          499.0 .. 505.0   (REQ_ARC_R ± REQ_ARC_W/2)
#:     applied batons      507.6 .. 516.8   (viewBox 470 .. 478.5)
#:     minute / 5-min      513.8 .. 526.0   (viewBox 476 .. 487)
#:     bezel inner edge    528.0
#:
#: So the whole ring is OUTBOARD of this arc, by 2.6 px at the tightest point
#: — the 11 o'clock baton, which is the one hour index that falls inside this
#: sector (240° in home.html's frame). That is the number to re-measure if
#: either radius moves; the two halves ship together or the rim collides.
#: x DIAL_K, 2026-08-06 night. The budget the section above measures is
#: gone with the old bezel — its inner edge is 428.7 display px now, not
#: 528 — and the ring it was fitted against moved by the same factor, so
#: the 11 o'clock baton stays the tightest point: this arc lands at
#: 399.1..404.1 and the batons at 406.1..413.4, so 2.0px — the same fraction
#: of a dial that is 20% smaller. That is still the number to re-measure if
#: either radius moves.
#: 2026-08-06, late night: THERE IS NO CHAPTER RING TO CLEAR ANY MORE. The
#: printed track is deleted and the twelve batons moved onto the bezel's
#: inner bevel, which is OUTSIDE #dial and therefore unscaled — the nearest
#: of them now sits at 455 display px against this arc's 404.1. The 2.0px
#: budget the paragraph above defends is 51. This radius is unchanged: it
#: was measured against a ring that has gone, and it has more room, not
#: less. The clearance that was always the real one still holds — the arc
#: starts at 399.1, just outside the wedge sector's outer edge at 395.7, so
#: the gauge and the text it reports on are still not fighting for pixels.
#:
#: ── 2026-08-06: THE BAND IS DELETED, AND THE BEZEL TOOK THE JOB ──────────
#: Owner, by voice at the puck: "the live gauge band costs a whole annulus to
#: say something the BEZEL can say for free ... eight flats and eight screws
#: are a natural eight-segment indicator, sitting exactly where the eye
#: already goes. A request in progress lights the flats in sequence around
#: the bezel; a finished one settles them ... The frame becomes the
#: instrument."
#: Nothing above is wrong and all of it is kept: every clearance it measures
#: was true, and it is the record of the four concentric bands this rim used
#: to carry. What changed is a COUNT OF BANDS, for the third time on this rim
#: — printed track, then applied batons, now this. The radius survives only
#: as _req_box's padding, so the tile still has room for the wedge's own
#: 2px stroke; the percentage it used to draw is on the bezel (see BEZ_SEQ)
#: and, as a numeral, on the wedge's own big row.
# The arc rides the STEEL RING, and the steel ring is a baked PNG that
# does not scale with DIAL_K — so neither may this radius. At 502*K it
# swept mid-dial through the wedges (the owner's giant blue circle).
# Ring: rim 540-13.6=526.4 out, chapter to 504.4; centre of the polished
# lip = 533.
REQ_ARC_R, REQ_ARC_W = 533.0, 5
#: Row baselines, MEASURED against _req_span rather than spaced evenly: the
#: sector is a diagonal annulus slice, so the room a horizontal line gets
#: runs 24px at the top, 238px at y=210 and 20px again at the bottom. The
#: two text rows sit on the widest part; the label and the number, which are
#: short, take the narrow ends.
#: Moved with the band correction above. The sector's y extent runs from
#: 540 + WEDGE_R1·sin(-103°) to 540 + WEDGE_R0·sin(-137°) — that was
#: [93.8, 310.9] and is now [58.1, 292.5], so the five rows keep the
#: fractions they were measured at rather than being re-guessed. Everything
#: downstream (the per-row span, the shared centre, the ellipsis limits)
#: is computed FROM the geometry by _req_span, so only these move.
#: 2026-08-06: only REQ_ROW_Y[0] is still read as a position — the other
#: four are now STACKED from it by layout_rows, so a label that grows for
#: its script pushes the rows below it down instead of colliding with them.
#: The tuple stays whole because it is the measurement that stacking has to
#: agree with: at the old Latin sizes the stack reproduces (104, 128, 155,
#: 182, 201) against the measured (104, 130, 154, 179, 200), within 3px on
#: every row. See ROW_LEADING.
#: x DIAL_K, 2026-08-06 night: the sector these were measured inside came
#: in with the ring, so its y extent went from [58.1, 292.5] to
#: [154.4, 342.1] — and these rows keep the fractions of it they were
#: measured at rather than being re-guessed, which is what that same
#: paragraph did at the last band correction.
#: 2026-08-06, late night: THE SAME RULE, A FOURTH TIME, AND THEN SWEPT.
#: The ring's inner edge went 336 -> 368 viewBox (see WEDGE_R0), so this
#: sector's bottom — 540 + WEDGE_R0·sin(-137°) — came up from 342.1 to 323.2
#: while its top stayed at 154.4. The fractions rule puts the five rows at
#: (187, 206, 223, 241, 257) and the leading is those old gaps x 0.899.
#:
#: BUT ONLY [0] IS READ, and the note above says so, so it is the one number
#: worth measuring rather than deriving — and this sector's own comment
#: already records that the curve is not monotonic. Swept against
#: tests/test_type_fitting.py in all three scripts, top x REQ_BLOCK_BOTTOM
#: over 178..199 x 272..304: 185/298 is the ONLY pair in that grid where no
#: row overflows its span and no ink passes the budget. 187/285 — what the
#: fractions alone give — leaves three overflows, and one neighbour either
#: way of 185/298 leaves one or two. Same five residual failures as the old
#: band, and they are all the pre-existing "this script cannot reach its
#: floor in this sector" kind, which is type that is small and INSIDE the
#: wedge rather than type that is outside it.
#:
#: ── 2026-08-07: 185 -> 146, BECAUSE THE PANEL GREW UPWARDS ────────────────
#: The five residual failures the paragraph above signs off on are the ones
#: the owner has now called unreadable, measured: 33/13/13/13/20 against
#: floors of 18/18/18/18/14. Two things changed to fix them — floors-first
#: allocation (see layout_rows) and a STRAIGHT outer edge cut to the bezel's
#: opening (see PANEL_CLEAR) — and the second one moves this number, because
#: the panel's usable top went from y≈156 to y≈100 and its widest rows are
#: now at 210..230 rather than 188.
#:
#: SWEPT AGAIN, the same way and against the same file: top x
#: REQ_BLOCK_BOTTOM over 142..162 x 264..292, all three scripts, both
#: wedges. There is a real PLATEAU this time rather than a single point —
#: every pair in 142..150 x 268..282 passes clean, and 152 upward never
#: does — so this is its interior rather than its edge, which is the one
#: thing the old 185/298 never had. Anybody re-running that sweep after
#: touching the panel geometry should expect the plateau to move with it.
#:
#: The other four entries are STILL NOT READ and are left at their
#: 2026-08-06 values on purpose: they are the measurement the stacking was
#: checked against, and overwriting them would delete the evidence and keep
#: the conclusion (PRINCIPLES §11).
REQ_ROW_Y = (146, 204, 221, 239, 254)
#: The last row's ink may not pass this. MEASURED on the sector rather than
#: taken as its geometric bottom (292.5): the annulus slice is 256px wide at
#: y=188, 194 at 212, 158 at 224, 126 at 236 and 68 at 260. 232 is where a
#: real row of type stops being settable — and the first render of this
#: change proved the point, by growing the rows above until the clinic
#: list's total landed at y=230 and had to be set at 12px, SMALLER than the
#: 14 it had before the change that was supposed to enlarge it. The budget
#: is what stops a block from spending the wide part of a sector and
#: leaving its last row the point.
#:
#: 240 IS A MEASURED OPTIMUM AND THE CURVE IS NOT MONOTONIC, which is the
#: part worth writing down. Swept against both wedges in Persian:
#:
#:     236   sentence 19  ·  clinic rows 19  ·  clinic total 21
#:     240   sentence 20  ·  clinic rows 20  ·  clinic total 22
#:     244   sentence 20  ·  clinic rows 20  ·  clinic total 17
#:
#: A LOOSER budget is worse. At 244 the block no longer overruns, so the
#: leading squeeze never fires, so the rows spread — and the clinic's total
#: lands at y=224 where the sector is 158px wide and it has to shrink to 17.
#: The squeeze is not damage control here; it is what keeps the last row in
#: the part of the sector that can hold it. Anyone raising this number to
#: "give the wedge more room" will make it smaller.
#: x DIAL_K — 240 was measured as a POSITION in the sector, so it moves
#: with the sector. Everything the sweep above proves about it is about
#: where it sits in that annulus, and that is unchanged.
#: 2026-08-06, late night: 300 -> 298 with the ring's inner edge (336 -> 368
#: viewBox), and it is TWO units rather than the fifteen the sector's own
#: fractions would give — which is this note's whole point made again on a
#: shorter sector. 285 is where 0.776 of the new extent lands and it leaves
#: three rows overflowing; 298 leaves none. Swept in all three scripts
#: against tests/test_type_fitting.py together with REQ_ROW_Y[0]; see there
#: for the grid. Anybody "correcting" this to the proportional 285 will
#: reproduce the exact failure the paragraph above describes.
#:
#: ── 2026-08-07: 298 -> 276, AND THE ARGUMENT ABOVE IS WHY ────────────────
#: Everything the note above says still holds and is the reason this number
#: came DOWN while the panel got BIGGER. The straight outer edge
#: (PANEL_CLEAR) widened the panel between y=200 and y=260 by 90-110px, and
#: at 298 the block simply spread into that room and put its last two rows
#: back down in the point where the panel is 40px wide — which is exactly
#: the "a looser budget is worse" failure recorded above, one geometry
#: later. 276 keeps the block in the part of the panel that can hold type.
#: Swept with REQ_ROW_Y[0]; the plateau and its edges are recorded there.
REQ_BLOCK_BOTTOM = 276.0
#: How much the wedge's own name may grow past the size its script needs.
#:
#: THE LIVE WEDGES ARE THE CONSTRAINED ONES, and that is worth stating
#: because the owner's ask was the opposite ("plenty of room for the wedges
#: to expand"). The five BAKED wedges carry an icon and two rows in a 122px
#: band and have room to spare; these two carry FIVE rows in the same band,
#: so anything one row takes comes off the row at the bottom, where the
#: sector has narrowed to a point. Set at 1.55 first, this made بیماران 29px
#: — handsome, and it pushed the clinic's total down to y=224 where only
#: 13px would fit, SMALLER than the 14 it had before. 1.25 is where the
#: label reads as the biggest thing on the wedge without spending the last
#: row's room. The growth the owner asked for lands on the baked wedges in
#: home.html; what these two gain is the per-script sizing.
REQ_LABEL_GROW = 1.25
#: How much further inside the sector a CUT is made than a row's own limit,
#: in display px. 2026-08-06, from the glass: "the two grey lines extend past
#: the wedge's right-hand edge onto the bare dial."
#:
#: They did not, arithmetically — a row's `limit` already holds FIT_MARGIN
#: (9px) off the span, and the ink measured 9px inside the border every time.
#: 9px is the wrong number against a DIAGONAL edge: the sector's sides are
#: radial lines, so a row that clears them by 9px at its own baseline is
#: reading against a border that is itself 2px of stroke, and at 1080 on a
#: round panel the two touch. This is the §6 rule — the margin was never
#: measured against the thing it competes with — and 10 more px is what makes
#: the gap visible rather than provable. It costs about two characters.
REQ_CLIP_PAD = 10.0
REQ_ACTIVE = ("queued", "working", "verifying", "deploying")
#: House palette, one colour per state — colour IS the differentiator here,
#: same as the wordmark and the interest carousel.
#: GOLD, BECAUSE THIS IS A CONCIERGE DESK.
#:
#: The owner, on the amber this replaces: "let's make the wedge color pop.
#: like a gold, perhaps... keeping with the 'sterling' high end feel.
#: concierge feel, etc."
#:
#: That is a brief, not a colour swap, and it is worth writing down: the
#: REQUESTS wedge is the visible half of Sterling, and Sterling is a
#: CONCIERGE — a good hotel's front desk, not a progress bar in a build
#: system. Gold is what that costs. The other wedges are instruments
#: (briefing blue, lock red, volume teal); this one is service, and service
#: is brass and warm light.
#:
#: The working state is the one anybody actually watches, so it carries the
#: real gold — 255,193,94 renders at luminance 189 against the amber's 175,
#: brighter AND warmer, which is what "pop" meant. The rest of the ladder
#: is pulled toward the same family so the wedge reads as one object
#: changing state rather than six unrelated colours: queued is a cool
#: brushed pewter, verifying a pale champagne, deploying the deep brass it
#: is about to become. Done and failed stay green and red, deliberately —
#: those two are read at a glance from across a room and must not be
#: subtle. Everything else may be tasteful; an outcome may not.
REQ_COL = {
    "queued":    (166, 172, 184),    # pewter — accepted, not started
    "working":   (255, 193, 94),     # GOLD — the state anybody watches
    "verifying": (240, 214, 150),    # champagne — lighter, still the family
    "deploying": (214, 158, 62),     # deep brass — nearly there
    "done":      (53, 208, 127),     # green — an outcome, read at a glance
    "failed":    (255, 94, 94),      # red   — likewise, never subtle
}
REQ_FADE_S = 0.4
#: A FAILURE LEAVES SLOWER THAN A SUCCESS, AND FADES INSTEAD OF BLINKING.
#:
#: The owner, watching the first real request fail on his own puck: "at
#: least have the wedge disappear more gracefully or something." He is
#: right, and the reason is not decoration. A success is self-explanatory
#: — the thing he asked for is now on the screen in front of him. A
#: FAILURE is the only state where the wedge is carrying the entire
#: message, and it was given the same six seconds as a result he can
#: already see, then cut.
#:
#: Twice the dwell so the reason can actually be read, and four times the
#: fade so it recedes rather than disappearing. A thing that vanishes
#: reads as a glitch; a thing that fades reads as finished.
REQ_FADE_OUT_FAIL_S = 1.6
REQ_HOLD_FAIL_S = 12.0
#: How long a finished request stays on the ring before it fades. The owner
#: has to SEE that it landed — a bar that reaches 100% and vanishes in the
#: same frame is the completion nobody witnessed.
REQ_HOLD_S = 6.0
#: A file that stopped moving with work still "in progress" is a producer
#: that died. Four minutes is generous for a real deploy and short enough
#: that nobody watches a frozen 60% through a demo. §1: it is LOGGED.
REQ_STALE_S = 240.0
REQ_CARD_ROWS = 5

_REQ_CACHE = {"mtime": None, "at": 0.0, "items": []}
_REQ_UI = {"fade": 0.0, "head": None, "sig": None, "tile": None,
           "seen_active": set(), "term_id": None, "term_at": 0.0,
           "last_t": 0.0, "stale_said": None}
_REQ_SAID: set = set()
_REQ_BOX = None
_REQ_PLATES: dict = {}


def _req_say(key: str, msg: str) -> None:
    """Say it ONCE. This runs in the compose path at 14 fps; a failure that
    logs per frame is a failure nobody can read the log around."""
    if key not in _REQ_SAID:
        _REQ_SAID.add(key)
        print(msg, flush=True)


#: DISPLAY-ONLY DRIFT BETWEEN TWO HONEST NUMBERS.
#:
#: Owner, twice (2026-08-06): "i hate the 10% being stuck there", and then
#: "the sterling tab is stuck at 0% for too long before it just finished. we
#: at least have to give an illusion of continuous progress ok? ... even if
#: it fails".
#:
#: request_worker's PCT note is right and is not being overruled: a bar that
#: ADVANCES ON A CLOCK is a lie, and the way it fails is 90% for ten minutes.
#: So the worker now publishes an INTERVAL — `pct` is the rung that has
#: completed, `pct_next` is the one that has not — and this drifts across it
#: asymptotically and never arrives. Every position the bar can occupy is
#: between a thing that happened and a thing that has not yet, which is a
#: true statement about the work; arriving would be the false one.
#:
#: It lives HERE, in the face, and nothing is written back: the queue on disk
#: stays exactly as honest as it was, and a second reader of that file sees
#: the ladder rather than the animation. This is the same trade PRINCIPLES
#: §10 makes for fillers — the wait is not shortened, it is made legible.
_REQ_EASE: dict = {}

#: Seconds to cross HALF the gap. The curve is t/(t+tau), not the obvious
#: 1-exp(-t/tau), and that was measured rather than chosen: an exponential
#: with tau=55 reached 19 of a 13->20 gap after 150s and then sat there for
#: the remaining six minutes of a nine-minute stage — which is precisely the
#: complaint, moved up the bar by six points. A hyperbola never saturates,
#: so the integer keeps ticking over for as long as the stage runs.
_EASE_TAU = 90.0

#: Never quite touch the next rung. Two tenths is under the width of a pixel
#: on this arc and it is the difference between drifting and claiming.
_EASE_GAP = 0.2


def _eased_pct(rid: str, state: str, pct: int, nxt: int) -> int:
    """What the wedge should DRAW, given what the worker last recorded."""
    now = time.time()
    prev = _REQ_EASE.get(rid)
    if prev is None or prev["real"] != pct:
        # A new rung: restart the drift from it, but never below what has
        # already been drawn — a bar that steps backwards is worse than one
        # that sticks, and the worker legitimately re-reports a lower pct
        # when a stage restarts.
        prev = {"real": pct, "since": now,
                "shown": max(float(pct), (prev or {}).get("shown", 0.0))}
        _REQ_EASE[rid] = prev
    if state == "done":
        prev["shown"] = 100.0
    elif nxt > pct:
        span = float(nxt - pct) - _EASE_GAP
        age = max(0.0, now - prev["since"])
        eased = pct + span * (age / (age + _EASE_TAU))
        prev["shown"] = max(prev["shown"], eased)
    # Terminal and going nowhere (failed, or a queued row the worker has not
    # reached): hold whatever ground was taken. `_next_rung` returns pct
    # itself for those, so the branch above does not run.
    if len(_REQ_EASE) > 64:                    # a long queue is not a leak
        for k in list(_REQ_EASE)[:-32]:
            _REQ_EASE.pop(k, None)
    return int(max(0.0, min(100.0, prev["shown"])))


def _req_parse():
    """requests.json -> a normalised list, newest first.

    THE CONTRACT (written by the conductor, read here, never written here):

        [{"id": "r7", "text": "make the wordmark bigger", "who": "Paul",
          "state": "queued|working|verifying|deploying|done|failed",
          "pct": 0-100, "detail": "short phrase", "at": <unix ts>}, ...]

    A bare list is preferred; {"requests": [...]} / {"items": [...]} /
    {"queue": [...]} are accepted because the other half of this handshake
    is being written by somebody else today and a wrapper key is the
    likeliest divergence.

    EVERY malformed shape resolves to "nothing in progress" and SAYS SO on
    stdout — once per file change, because that is how often we parse.
    """
    try:
        txt = REQUESTS_FILE.read_text()
    except Exception as e:
        print(f"requests: unreadable {e!r} — nothing in progress", flush=True)
        return []
    if not txt.strip():
        return []                      # an empty file is an empty queue
    try:
        raw = json.loads(txt)
    except Exception as e:
        print(f"requests: not JSON {e!r} — nothing in progress", flush=True)
        return []
    if isinstance(raw, dict):
        raw = raw.get("requests", raw.get("items", raw.get("queue")))
    if raw is None:
        return []
    if isinstance(raw, dict):
        raw = [raw]
    if not isinstance(raw, list):
        print(f"requests: expected a list, got {type(raw).__name__} — "
              f"nothing in progress", flush=True)
        return []
    out = []
    for i, e in enumerate(raw):
        if not isinstance(e, dict):
            continue
        try:
            state = str(e.get("state") or "working").strip().lower()
            if state not in REQ_COL:
                # An unknown state is not a reason to HIDE the work — it is
                # a reason to say so and carry on showing it as active.
                _req_say(f"state:{state}",
                         f"requests: unknown state {state!r} — treated as "
                         f"working")
                state = "working"
            try:
                pct = float(e.get("pct") or 0.0)
            except (TypeError, ValueError):
                pct = 0.0
            if not math.isfinite(pct):
                pct = 0.0
            pct = int(max(0.0, min(100.0, pct)))
            if state == "done":
                pct = 100                     # done is done, whatever it said
            try:
                nxt = int(float(e.get("pct_next") or pct))
            except (TypeError, ValueError):
                nxt = pct
            pct = _eased_pct(str(e.get("id") or i), state, pct, nxt)
            try:
                at = float(e.get("at") or 0.0)
            except (TypeError, ValueError):
                at = 0.0
            out.append({
                "id": str(e.get("id") or f"#{i}"),
                "text": str(e.get("text") or "").strip() or "(no description)",
                "who": str(e.get("who") or "").strip(),
                "state": state,
                "pct": pct,
                "detail": str(e.get("detail") or "").strip(),
                "at": at if math.isfinite(at) else 0.0,
            })
        except Exception as ex:                # noqa: BLE001 — one bad row
            _req_say(f"row:{ex!r}",
                     f"requests: skipped a malformed entry {ex!r}")
    if raw and not out:
        print("requests: file present but no usable entries", flush=True)
    return out[:24]


def _requests():
    """The list, stat-cached by mtime: one stat per frame, a parse only when
    the conductor actually writes. Same bargain _sterling_status_lines()
    strikes, for the same reason — this runs inside the frame budget."""
    try:
        st = REQUESTS_FILE.stat()
    except (FileNotFoundError, NotADirectoryError):
        if _REQ_CACHE["mtime"] is not None:
            _REQ_CACHE.update(mtime=None, at=0.0, items=[])
        return []
    except Exception as e:
        _req_say(f"stat:{e!r}", f"requests: cannot stat {REQUESTS_FILE} {e!r}")
        return []
    if _REQ_CACHE["mtime"] != st.st_mtime:
        _REQ_CACHE["mtime"] = st.st_mtime
        _REQ_CACHE["at"] = st.st_mtime
        _REQ_CACHE["items"] = _req_parse()
    return _REQ_CACHE["items"]


def _requests_head(now: float):
    """The one request the wedge is about, or None.

    Newest-first, so the head is normally requests[0] while it is active.
    When nothing is active the most recently FINISHED one is held for
    REQ_HOLD_S — the completion has to be witnessed, and a 100% bar that
    disappears in the frame it fills was never seen by anybody.
    """
    items = _requests()
    if not items:
        _REQ_UI["term_id"] = None
        return None
    active = [it for it in items if it["state"] in REQ_ACTIVE]
    if active and (now - (_REQ_CACHE["at"] or 0.0)) > REQ_STALE_S:
        # A STUCK BAR IS A LIE, and it is the specific lie this file is
        # least allowed to tell: it says work is happening. Drop to
        # "nothing in progress" and put the reason where somebody can
        # read it (PRINCIPLES §1).
        if _REQ_UI["stale_said"] != _REQ_CACHE["mtime"]:
            _REQ_UI["stale_said"] = _REQ_CACHE["mtime"]
            print(f"requests: {len(active)} active but requests.json has not "
                  f"moved in {now - _REQ_CACHE['at']:.0f}s — showing nothing "
                  f"in progress", flush=True)
        active = []
    if active:
        head = active[0]
        seen = _REQ_UI["seen_active"]
        seen.add(head["id"])
        if len(seen) > 64:
            _REQ_UI["seen_active"] = set(list(seen)[-32:])
        _REQ_UI["term_id"] = None
        return head
    top = items[0]
    if top["state"] not in ("done", "failed"):
        return None
    # Only hold a terminal request we watched arrive there, or one that
    # finished seconds ago — otherwise every restart of this process
    # replays somebody's last deploy as if it had just happened.
    if not (top["id"] in _REQ_UI["seen_active"]
            or (top["at"] and 0 <= now - top["at"] <= REQ_HOLD_S)):
        return None
    if _REQ_UI["term_id"] != top["id"]:
        _REQ_UI["term_id"] = top["id"]
        _REQ_UI["term_at"] = now
        print(f"requests: {top['id']} {top['state'].upper()} — "
              f"{top['text'][:56]!r}", flush=True)
    # A failure gets twice the dwell: it is the only state whose whole
    # message lives on the wedge, and the reason has to be readable.
    hold = REQ_HOLD_FAIL_S if top["state"] == "failed" else REQ_HOLD_S
    if now - _REQ_UI["term_at"] > hold:
        return None
    return top


def _req_span(y: float):
    """[x0, x1] of the wedge sector at row y, in face coordinates.

    Measured rather than derived: the sector is a diagonal annulus slice, so
    the width available to a horizontal line changes down the wedge and the
    arithmetic for it is three cases. Sampling is exact, costs 540 hypots,
    and is paid only when the tile is rebuilt.

    2026-08-06: the body moved to sector_span(), which is the same sampling
    with the sector passed in rather than closed over. This wedge's rows are
    only one of the things being fitted now, and two copies of an exact
    sampler would drift.
    """
    # PANEL_R0: the fitter must measure the same shape the panel draws.
    return sector_span(y, REQUESTS_A0, REQUESTS_A1, PANEL_R0, WEDGE_R1)


def _req_box():
    """The tile's crop box — sector plus gauge, padded. Constant, so it is
    computed once: everything per-frame is confined to this rectangle
    rather than to the 1080² canvas."""
    global _REQ_BOX
    if _REQ_BOX is None:
        xs, ys = [], []
        # 69 samples, not 25: the outer edge is STRAIGHT now (PANEL_CLEAR),
        # so its farthest point is the mitre at -114.4° rather than an end
        # of the arc, and a coarse sample walks straight past it. A crop
        # that misses the panel's corner is the silent kind of wrong — the
        # tile is composited through this box and the rest simply never
        # reaches the glass.
        for i in range(69):
            ad = REQUESTS_A0 + (REQUESTS_A1 - REQUESTS_A0) * i / 68.0
            a = math.radians(ad)
            for r in (WEDGE_R0 - 6, _opening_r(ad) + 4):
                xs.append(SIZE / 2 + r * math.cos(a))
                ys.append(SIZE / 2 + r * math.sin(a))
        _REQ_BOX = (max(0, int(min(xs)) - 10), max(0, int(min(ys)) - 10),
                    min(SIZE, int(max(xs)) + 12), min(SIZE, int(max(ys)) + 12))
    return _REQ_BOX


def _ellipsize(d, text: str, font, limit: float, track: float = 0.0) -> str:
    """Trim to fit, with a real ellipsis. Truncation is where a request
    stops being readable, so it happens on a character boundary with a mark
    that says so — never a hard cut that reads as a different sentence."""
    def w(s):
        return track_len(d, s, font, track) if track else d.textlength(s,
                                                                       font=font)
    if w(text) <= limit:
        return text
    cut = text
    while cut and w(cut.rstrip() + "…") > limit:
        cut = cut[:-1]
    return (cut.rstrip() + "…") if cut.strip() else "…"


def _req_tile(head: dict):
    """The whole wedge, baked to a small RGB tile on black.

    Rebuilt ONLY when the request data changes; every frame in between costs
    one point() and one screen() over ~330×420 px. The ember work this
    morning is the reason that matters — a careless per-frame redraw on this
    device spikes a core and spins the fan.
    """
    sig = (head["id"], head["state"], head["pct"], head["text"],
           head["who"], head["detail"])
    if _REQ_UI["sig"] == sig and _REQ_UI["tile"] is not None:
        return _REQ_UI["tile"]
    col = REQ_COL.get(head["state"], REQ_COL["working"])
    bright = tuple(min(255, int(c * 0.35) + 168) for c in col)
    cx = cy = SIZE / 2.0
    canvas = Image.new("RGB", (SIZE, SIZE), 0)
    d = ImageDraw.Draw(canvas, "RGBA")

    # ── the panel, in home.html's own weights: 0.14 fill, 0.55 stroke ─────
    # STRAIGHT OUTER EDGE, out to the bezel's opening — see PANEL_CLEAR for
    # the owner's words and the measurement. Fill and stroke come off the
    # SAME outline, so the border can never drift off the shape it borders.
    poly = _wedge_sector_poly(REQUESTS_A0, REQUESTS_A1,
                              PANEL_R0, WEDGE_R1, pad=0.0, flat=False)
    d.polygon(poly, fill=PANEL_FILL + (36,))
    d.line(poly + [poly[0]], fill=col + (140,), width=2)

    # ── the gauge: DELETED 2026-08-06, it is the bezel now ────────────────
    #
    # A dim full track, a bright fill and a hot travelling head used to ride
    # r=401.6 here. The whole of it — the empty-track argument, the "a
    # failure keeps no percentage" mark, the head dot — has moved onto the
    # octagon, where the same three facts are said by eight flats that were
    # already on the glass. See draw_bezel_state; the argument for the move
    # is at REQ_ARC_R and the owner's words are there verbatim.
    #
    # The wedge keeps the number. `big` is still "63%" while work is live,
    # so the precise reading did not go with the arc — an eight-segment
    # frame is a glance, and a glance is not a measurement (§6).

    # ── the content, horizontal on the spoke, like every baked wedge ──────
    #
    # Horizontal, not curved and not radial: the five baked wedges set their
    # labels flat (home.html builds them at x=ix, no transform), and one
    # sector reading at a different angle to its neighbours would look like
    # a mistake rather than a distinction.
    who = head["who"].upper() or FA_SOMEONE
    # The STATE reads in Dutch; the percentage stays a numeral in the
    # house bold, which is the one row on this wedge that is a measurement
    # rather than a word.
    fa_state = FA_REQ_STATE.get(head["state"], head["state"].upper())
    big = {"done": FA_REQ_STATE["done"],
           "failed": FA_REQ_STATE["failed"]}.get(head["state"],
                                                 f"{head['pct']}%")
    if head["state"] in REQ_ACTIVE:
        sub = fa_state + " · " + who
    else:
        # The big row already says DONE or FAILED; repeating it here wastes
        # the one line that could carry WHY. A failure with no reason on it
        # is only half a visible failure (PRINCIPLES §1).
        sub = who + (" · " + head["detail"].upper() if head["detail"] else "")
    # ── SIZED BY MEASUREMENT, NOT BY NUMBER (2026-08-06) ──────────────────
    #
    # Every size here used to be a constant chosen for Latin caps, and this
    # wedge now sets Persian, Han or Latin depending on what the room asked
    # for. layout_rows stacks the five rows, asks the sector how wide each
    # one's row actually is, and takes the largest size that fits it.
    #
    # THE GROW ALLOWANCES ARE THE PER-ROW JUDGEMENT, and there is no global
    # multiplier on purpose:
    #
    #  * the LABEL may take 1.55 of its script's own size. It is one short
    #    word at the narrow top of the sector, so the SPAN binds long before
    #    this does — the allowance only stops it becoming a headline in a
    #    language whose word for "requests" happens to be two characters.
    #  * the SENTENCE MAY NOT GROW AT ALL (1.0). It is the thing somebody
    #    walked over to read, it already wraps to two lines, and every point
    #    of size buys itself with words off the end. Trading words for size
    #    is the wrong trade on the one row that carries meaning. It still
    #    rises for its SCRIPT — a Han request is set at the Han floor — it
    #    just never takes room from itself.
    #  * the SUB gets 1.2. It is the quiet row; past that it competes with
    #    the label above it and the wedge stops having a hierarchy.
    #  * the BIG row gets 1.35 and sits on the widest part of the sector.
    #    It is usually "45%", which is Latin whatever the face is set in —
    #    a percentage is a measurement, not a word (see below).
    who_up = head["who"].upper() or FA_SOMEONE
    # The STATE reads in Dutch; the percentage stays a numeral in the
    # house bold, which is the one row on this wedge that is a measurement
    # rather than a word.
    fa_state = FA_REQ_STATE.get(head["state"], head["state"].upper())
    big = {"done": FA_REQ_STATE["done"],
           "failed": FA_REQ_STATE["failed"]}.get(head["state"],
                                                 f"{head['pct']}%")
    if head["state"] in REQ_ACTIVE:
        sub = fa_state + " · " + who_up
    else:
        # The big row already says DONE or FAILED; repeating it here wastes
        # the one line that could carry WHY. A failure with no reason on it
        # is only half a visible failure (PRINCIPLES §1).
        sub = who_up + (" · " + head["detail"].upper() if head["detail"]
                        else "")
    # The sentence's size is known before its layout, because its allowance
    # is 1.0 — so the wrap can be done once, at the size it will be set in,
    # instead of iterating layout against wrap.
    sent = script_size(head["text"], 20)
    f_txt = face_for(head["text"], "text", sent)
    # KLAAR / MISLUKT are Latin caps like the percentage they replace, so the
    # big row is the house bold, tracked, in every state again. The split was
    # there for Persian: انجام شد had to leave the Latin ramp for a face that
    # carries the script, and tracking an Arabic run severs its joins. Both
    # reasons are script facts, and face_for still applies them from the
    # string's own codepoints if the room asks for Persian back.
    big_role = "bold"
    big_track = 1.5

    def lay(a: str, b: str, quiet: bool = False):
        return layout_rows(d, (
            (FA_REQUESTS, "label", 18, script_size(FA_REQUESTS, 18, REQ_LABEL_GROW),
             0.0),
            (a, "text", 20, sent, 0.0),
            (b, "text", 20, sent, 0.0),
            (sub, "label", 14, script_size(sub, 14, 1.20), 0.0),
            (big, big_role, 26, script_size(big, 26, 1.35), big_track),
        ), REQ_ROW_Y[0], REQ_BLOCK_BOTTOM,
            (REQUESTS_A0, REQUESTS_A1, WEDGE_R0, WEDGE_R1, True),
            who="requests wedge", quiet=quiet)

    # WRAPPED AGAINST THE ROOM THE ROWS ACTUALLY GET, which means laying the
    # block out once with placeholders first. The geometry does not depend on
    # what the two sentence rows SAY — their allowance is 1.0, so their size
    # is fixed before the layout runs and only their emptiness could move the
    # stack, which the placeholders prevent. The old code wrapped against a
    # span sampled at a hardcoded y; those y values are now computed.
    probe = lay("·", "·", quiet=True)
    _share_centre(probe[1], probe[2])

    def clip(txt: str, font, limit: float, track: float = 0.0) -> str:
        """`txt` cut to `limit` on a word boundary, with the cut MARKED."""
        if text_w(d, txt, font, track) <= limit:
            return txt
        cut = txt
        while cut and text_w(d, cut + "…", font, track) > limit:
            cut = cut[:cut.rfind(" ")] if " " in cut else ""
        return (cut.rstrip(" ·-") + "…") if cut else "…"

    # It wraps to TWO lines. One line truncates almost every real sentence —
    # "make the wordmark bigger" alone needs 236px against ~200 of room —
    # and the request text is the thing somebody walked over to read.
    #
    # ── THE WORDS GIVE WAY, NOT THE TYPE (2026-08-06, at the glass) ───────
    #
    # `l2` used to be EVERY remaining word, on the assumption that a request
    # is a phrase. Spoken ones are not: the room's last four arrived at ~150
    # characters each, so the second row asked for 647px of a 199px line, and
    # fit_size answered the only way it is allowed to — it walked the type
    # down to its absolute floor and set the row at 10px. The owner, reading
    # the result off the glass: "a run of micro-text ... truncated with
    # ellipses and far too small to read on a device screen."
    #
    # Note what that failure looks like in the log: fit_size DID say so, once
    # ("cannot give latin its 20px in 232x0 — set at 10px"). It was not a
    # silent shrink. It was a shrink nobody was reading, on a row nobody
    # could read either — which is the same outcome (§1).
    #
    # So the second line is now FILLED to the same limit as the first, at the
    # size the design asked for, and whatever is left becomes an ellipsis.
    # That is the trade the "SENTENCE MAY NOT GROW" rule above makes in the
    # other direction: this row keeps its size and loses words, rather than
    # keeping every word at a size that is not reading matter. The whole text
    # is one tap away on the card, which is where a 150-character request
    # belongs.
    #
    # THE SUB ROW GETS THE SAME TREATMENT and needs it for the same reason:
    # `who · detail` carries a completion reason of any length, and it was
    # landing at 10px beside the sentence. It is cut against the probe's own
    # limit, which was measured on the LONG string — so it is measured a
    # couple of px wide, and REQ_CLIP_PAD covers that as well.
    lim_wrap = min(probe[1]["limit"], probe[2]["limit"]) - REQ_CLIP_PAD
    words, l1 = head["text"].split(), ""
    while words and text_w(d, (l1 + " " + words[0]).strip(),
                           f_txt) <= lim_wrap:
        l1 = (l1 + " " + words.pop(0)).strip()
    if not l1 and words:                    # one unbreakable word
        l1, words = words[0], words[1:]
    l2 = ""
    while words and text_w(d, (l2 + " " + words[0]).strip(),
                           f_txt) <= lim_wrap:
        l2 = (l2 + " " + words.pop(0)).strip()
    if words:
        l2 = clip((l2 + " " + words[0]).strip(), f_txt, lim_wrap)
    if probe[3]:
        sub = clip(sub, face_for(sub, "label", script_size(sub, 14)),
                   probe[3]["limit"] - REQ_CLIP_PAD)

    laid = lay(l1, l2)
    # THE TWO LINES OF THE REQUEST SHARE ONE CENTRE — see _share_centre.
    _share_centre(laid[1], laid[2])
    draw_rows(d, laid, (ROW_INK_LABEL, ROW_INK_BODY, ROW_INK_BODY,
                        bright, bright))

    tile = canvas.crop(_req_box())
    _REQ_UI["sig"], _REQ_UI["tile"] = sig, tile
    return tile


def _req_wedge_live() -> bool:
    """Is there a wedge under the finger? The sector is only tappable while
    it is actually painted — a hit box over empty glass that opens an empty
    card is a control the user cannot see and cannot predict."""
    return _REQ_UI["fade"] > 0.05


def draw_requests_wedge(frame: Image.Image, now: float,
                        hold: bool = False, rot_deg: float = 0.0) -> None:
    """Composite the wedge, fading in and out. In place, before the rotate.

    Wrapped whole: this is new paint in a compositor that must never stop.
    Any failure degrades to NO WEDGE and says so once — never per frame.

    `rot_deg` is the dial. It is here because overflow lives on the dial:
    this wedge outranks the clinic list, but a spin can still page the
    clinic list into the slot over a running request (see ring_holds_slot).
    """
    try:
        head = (None if (hold or not ring_holds_slot("requests", now, rot_deg))
                else _requests_head(now))
    except Exception as e:                      # noqa: BLE001
        _req_say(f"head:{e!r}", f"requests: status read failed {e!r} — "
                                f"no wedge")
        head = None
    last = _REQ_UI["last_t"] or now
    _REQ_UI["last_t"] = now
    dt = max(0.0, min(0.5, now - last))
    if head is not None:
        _REQ_UI["fade"] = min(1.0, _REQ_UI["fade"] + dt / REQ_FADE_S)
        _REQ_UI["head"] = head
    else:
        # LEAVING IS SLOWER THAN ARRIVING, AND SLOWEST AFTER A FAILURE.
        # 0.4s in reads as the wedge answering; 0.4s out reads as a glitch.
        # The last thing shown decides which of those the owner remembers.
        _out = (REQ_FADE_OUT_FAIL_S
                if (_REQ_UI["head"] or {}).get("state") == "failed"
                else REQ_FADE_S * 2.0)
        _REQ_UI["fade"] = max(0.0, _REQ_UI["fade"] - dt / _out)
        if _REQ_UI["fade"] <= 0.0:
            _REQ_UI["head"] = _REQ_UI["sig"] = _REQ_UI["tile"] = None
    head = _REQ_UI["head"]
    if head is None or _REQ_UI["fade"] <= 0.01:
        return
    try:
        k = _REQ_UI["fade"]
        if head["state"] in REQ_ACTIVE:
            # A slow breath while the work is live — the same "alive, not a
            # sticker" treatment the seal and the wordmark get. Nothing
            # fast: this is text somebody is reading.
            k *= 0.88 + 0.12 * (0.5 + 0.5 * math.sin(now * math.tau * 0.45))
        tile = _req_tile(head)
        if k < 0.995:
            tile = tile.point(lambda p, kk=k: int(p * kk))
        x0, y0, x1, y1 = _req_box()
        frame.paste(ImageChops.screen(frame.crop((x0, y0, x1, y1)), tile),
                    (x0, y0))
    except Exception as e:                      # noqa: BLE001
        _req_say(f"draw:{e!r}", f"requests: wedge draw failed {e!r} — "
                                f"no wedge")


# ── THE CLINIC LIST ────────────────────────────────────────────────────────
#
# Owner, spoken at the puck 2026-08-05: "add a wedge that basically shows
# upcoming patients that I have to see today. You can make the data
# fictional."
#
# ── WHY IT SHARES THE REQUESTS ARC ─────────────────────────────────────────
#
# The census above ("WHY THE UPPER LEFT") found exactly ONE free 34° slot on
# the ring, and REQUESTS took it. What is left over is 11–17° wide, which is
# not enough to set a surname in. So the upper left is now THE LIVE SLOT:
# the clinic list is its resting state, and REQUESTS pre-empts it — a change
# the owner asked for seconds ago is the more urgent of the two, and unlike
# the clinic list it leaves again on its own.
#
# They CROSSFADE rather than overlap: this wedge's alpha is the complement
# of the REQUESTS fade, so the two are never both on the glass and there is
# no state to keep in sync. Each handover prints a line — a list that
# vanishes while somebody is reading it must never be mysterious
# (PRINCIPLES §1).
#
# ── WHY THE DATA IS A CONSTANT ─────────────────────────────────────────────
#
# Fictional, as asked, and it lives HERE rather than in a /tmp handshake
# file: nothing produces a real clinic list yet, and an absent file would
# render an empty wedge, which looks exactly like a broken one. When a real
# feed arrives it replaces _patients_upcoming() and nothing else moves.
#
# SURNAMES ARE KEPT SHORT ON PURPOSE. The list shifts up as the day passes,
# so every name eventually lands on the top text row — the narrowest of the
# three, measured at 154px of usable width against an 18px face. A patient
# name truncated to "OKONKW…" is worse than no wedge at all.
#
# ── 2026-08-07: THE CONSTANT IS RETIRED; THE SCHEDULE IS A FILE ────────────
# The "WHY THE DATA IS A CONSTANT" note above stands as written, and its
# fear arrived from the other direction: the constant shipped to EVERY
# puck, and a fresh demo device greeted its first user with another man's
# patient list in the slot his own request should have held. The schedule
# now lives in data/notes/clinic.json — per-device, gitignored like its
# neighbours, same shape as the old tuple — and ABSENCE MEANS ABSENT: no
# file, or an empty one, and this wedge never claims the slot at all
# (_pat_relevant), so the REQUESTS wedge owns the arc outright. That is not
# the "empty wedge that looks broken" the old note feared, because no wedge
# renders — the slot shows the requests wedge instead, which is what a
# fresh device should show. A file that EXISTS but has run out of rows
# still renders CLINIC CLEAR (§1): a clinic day that ended is news; a
# schedule that never existed is not.
PAT_A0, PAT_A1 = REQUESTS_A0, REQUESTS_A1
#: Rose, because every other hue on this ring is already spoken for
#: (briefing cyan, sterling violet, lock red, settings steel, volume teal,
#: requests gold) and green/red are reserved for outcomes. It also lands
#: outside the amber colourway — deliberately: desertify() runs BEFORE this
#: wedge is composited, so the clinic list reads as the one thing on the
#: glass that is about the owner's day rather than about the device.
#:
#: 2026-08-06, late, by voice at the glass: "the PATIENTS wedge is still
#: violet, which is neither rose gold nor charcoal — bring it into the
#: palette." That OVERRULES the paragraph above, which stands as written and
#: was right for every colourway before this one. What changed is the dial
#: underneath: against amber, oranje or pounamu a pink sector read as a
#: deliberate exception, and against rose gold it reads as the same colour
#: missed by twenty degrees of hue — which is not "the owner's day", it is a
#: leftover. The mechanism the old note describes is unchanged and is the
#: reason this line exists at all: this wedge is composited AFTER desertify(),
#: so its hue survives and has to be chosen rather than inherited.
#:
#: So it is now the dial's own rose gold, the SAME triple as DESERT_MID.
#: Written out rather than referenced because DESERT_MID is defined ~1200
#: lines below this one and moving it is a bigger change than this is: if the
#: colourway moves, this moves with it, in the same commit. The aperture frame
#: in _pat_tile already reaches forward to DESERT_MID at draw time and does
#: not need changing — it is now the same gold as the wedge it sits in, which
#: is exactly what an applied frame on a dial is.
#: 2026-08-06, night: rose gold -> BRUSHED STEEL with the Royal Oak pass.
#: Same rule as the line it replaces and for the same reason — this wedge is
#: composited AFTER desertify() so its hue survives, and a wedge in last
#: colourway's metal reads as a leftover rather than as a signal. It tracks
#: DESERT_MID, written out here because DESERT_MID is defined ~1500 lines
#: further down; the two move together.
#: 2026-08-06, night, later: tracks DESERT_MID to its BLUE-CAST CORRECTION,
#: (143,148,154) -> (187,131,126), in the same commit exactly as the two notes
#: above promise. This wedge is composited AFTER desertify(), so its triple
#: reaches the panel raw and takes the panel's cast on its own — which is why
#: it has to carry the same warm numbers rather than the neutral ones. Left
#: alone it would have been the one blue-grey patch on a dial whose steel had
#: just been corrected, which is the leftover-colour failure the note above
#: exists to prevent, arriving from the other direction.
#: 2026-08-07: and again, to the COOLED ramp, (187,131,126) -> (100,154,230).
#: Same clause, third time it has been honoured: the three notes above all
#: promise this triple moves with DESERT_MID in the same commit, and the
#: alternative here is the exact failure they describe — a rose sector on a
#: blue dial, which is a leftover rather than a signal.
#: 2026-08-08: and back to rose gold with the return to the Patek colourway,
#: (100,154,230) -> (210,127,88) — the same clause, honoured a fourth time,
#: in the same commit as DESERT_MID.
#: 2026-08-08, later: back to steel-blue with the return to the Royal Oak,
#: (210,127,88) -> (100,154,230) — the same clause, honoured a fifth time,
#: in the same commit as DESERT_MID.
#: 2026-08-08, latest: the clause goes STRUCTURAL — this triple now rides
#: the theme table (_THEMES, top of file), where every row sets `pat` to
#: its own mid, so the promise the five notes above kept by hand cannot be
#: forgotten a sixth time.
PAT_COL = _THEME["pat"]
PAT_ROWS = 3                       # rows the sector has for names
#: The aperture's margins round its numeral, x and y (px on the 1080 panel).
#: A date window is CLOSE work — the frame has to read as cut into the dial,
#: which means the numeral nearly fills it. 9 and 5 put ~19px of frame round a
#: single digit set at 17, and the widest thing this window can ever hold is
#: the clinic's whole list, which is two digits. Its own constant because the
#: numeral's size is decided by measurement (layout_rows) and these are the
#: only two numbers left that were chosen by eye.
APERTURE_PAD = (9.0, 5.0)
#: The schedule the DEVICE owns: [["HH:MM", "SURNAME"], ...], the shape the
#: retired constant had. Under data/notes/ with the other per-device files
#: that never reach git — patient names are exactly the kind of thing that
#: directory exists to keep local.
PATIENTS_FILE = (Path(__file__).resolve().parents[2]
                 / "data" / "notes" / "clinic.json")
#: FIXTURE ROWS, NOT A SCHEDULE — nothing on the glass reads these. The
#: renderer reads PATIENTS_FILE above. The tuple keeps its old name because
#: tests/test_type_fitting.py pins the wedge's row sizes by baking a
#: three-row tile from it, and that gate needs stable rows to measure — it
#: must keep guarding the layout whatever any device's clinic.json says.
PATIENTS_TODAY = (
    ("08:20", "HALDANE"),
    ("09:05", "ADEYEMI"),
    ("10:40", "PRUITT"),
    ("11:30", "NDIAYE"),
    ("14:00", "MERCER"),
    ("15:45", "VARGAS"),
)

_PAT_UI = {"fade": 0.0, "last_t": 0.0, "sig": None, "tile": None,
           "said": None, "yielded": None}
_PAT_SCHED = {"mtime": None, "rows": ()}


def _clinic_rows():
    """The device's own clinic day, stat-cached by mtime like _requests().

    () when the file is absent, empty or unusable — and UNUSABLE SAYS SO
    (§1), once per file change, while absent stays silent: a device with no
    clinic.json is not a broken clinic, it is most devices.
    """
    try:
        st = PATIENTS_FILE.stat()
    except (FileNotFoundError, NotADirectoryError):
        if _PAT_SCHED["mtime"] is not None:
            _PAT_SCHED.update(mtime=None, rows=())
        return ()
    except Exception as e:                      # noqa: BLE001
        _req_say(f"pat:stat:{e!r}",
                 f"patients: cannot stat {PATIENTS_FILE} {e!r}")
        return ()
    if _PAT_SCHED["mtime"] != st.st_mtime:
        _PAT_SCHED["mtime"] = st.st_mtime
        try:
            raw = json.loads(PATIENTS_FILE.read_text())
        except Exception as e:                  # noqa: BLE001
            _req_say(f"pat:read:{e!r}",
                     f"patients: {PATIENTS_FILE} unreadable {e!r} — "
                     f"no clinic list")
            raw = []
        if not isinstance(raw, list):
            _req_say(f"pat:shape:{type(raw).__name__}",
                     f"patients: clinic.json holds a {type(raw).__name__}, "
                     f"wanted a list — no clinic list")
            raw = []
        rows = []
        for i, e in enumerate(raw):
            if (isinstance(e, (list, tuple)) and len(e) == 2
                    and all(isinstance(x, str) for x in e)):
                rows.append((e[0], e[1]))
            else:
                _req_say(f"pat:row:{i}",
                         f"patients: clinic.json row {i} is not "
                         f"[time, name] — row skipped")
        _PAT_SCHED["rows"] = tuple(rows)
    return _PAT_SCHED["rows"]


def _patients_upcoming(now: float):
    """Today's list from `now` onward — the ones still to be seen.

    Local wall clock, because the list is about the owner's day and not
    about anything this process measures. An entry stays upcoming until its
    own minute has passed, so the row does not vanish from under a finger
    at the moment the appointment starts.
    """
    lt = time.localtime(now)
    mins = lt.tm_hour * 60 + lt.tm_min
    out = []
    for hhmm, name in _clinic_rows():
        h, _, m = hhmm.partition(":")
        try:
            at = int(h) * 60 + int(m)
        except ValueError:
            _req_say(f"pat:time:{hhmm}",
                     f"patients: unreadable time {hhmm!r} — row skipped")
            continue
        if at >= mins:
            out.append((hhmm, name))
    return out


def _pat_tile(shown, total: int) -> Image.Image:
    """The whole wedge, baked to a small RGB tile on black.

    Rebuilt only when the list changes — which is a handful of times a day.
    Everything in between is one point() and one screen() over the same
    crop the REQUESTS wedge uses.
    """
    sig = (shown, total)
    if _PAT_UI["sig"] == sig and _PAT_UI["tile"] is not None:
        return _PAT_UI["tile"]
    col = PAT_COL
    bright = tuple(min(255, int(c * 0.35) + 168) for c in col)
    cx = cy = SIZE / 2.0
    canvas = Image.new("RGB", (SIZE, SIZE), 0)
    d = ImageDraw.Draw(canvas, "RGBA")

    # ── the panel, in home.html's own weights: 0.14 fill, 0.55 stroke ─────
    # Straight outer edge on the bezel's opening, exactly as the REQUESTS
    # panel it shares this arc with — the two take turns in one slot and a
    # shape difference between them would read as a bug (see PANEL_CLEAR).
    poly = _wedge_sector_poly(PAT_A0, PAT_A1, PANEL_R0, WEDGE_R1, pad=0.0,
                              flat=False)
    d.polygon(poly, fill=PANEL_FILL + (36,))
    d.line(poly + [poly[0]], fill=col + (140,), width=2)

    # ── the content, horizontal on the spoke, like every wedge on the ring ─
    if shown:
        # The rows themselves are a clock time and a patient's name — not
        # ours to translate, and the name least of all.
        body = [f"{t}  {n}" for t, n in shown]
    else:
        # AN EMPTY CLINIC SAYS SO. A wedge with three blank rows is the same
        # picture as a wedge whose data never loaded (PRINCIPLES §1).
        body = ["", FA_CLINIC_CLEAR, ""]
    # ── THE APERTURE, 2026-08-06 evening ──────────────────────────────────
    # Owner, by voice: "put patients remaining in a small aperture like a
    # date window in a rose-gold frame". So the last row is ONE NUMERAL and
    # the frame is drawn round it below; the sentence it replaces (FA_TO_SEE)
    # is still in this file with a note saying it no longer reaches the glass.
    #
    # ZERO IS SHOWN, NOT HIDDEN. An empty clinic renders CLINIC CLEAR on the
    # body row and a 0 in the window, which is the same rule the empty branch
    # above already follows: a window with nothing in it is indistinguishable
    # from a window whose feed died (§1).
    tail = str(total)
    body = (list(body) + ["", "", ""])[:PAT_ROWS]
    # SIZED BY MEASUREMENT, 2026-08-06 — the same policy as the REQUESTS
    # wedge one screen up, because the two share an arc and a face that set
    # one of them bigger than the other would read as a bug rather than a
    # distinction. The grow allowances differ in exactly one place: the
    # BODY rows may take 1.15 rather than 1.0, because unlike a request
    # sentence they never wrap — a patient row is one time and one surname,
    # so a point of size costs nothing here, and the note above about
    # "OKONKW…" is about the SPAN, which the fit already respects.
    if shown:
        body_want, body_grow = 18, 1.10
    else:
        # GEEN SPREEKUUR MEER is one phrase alone on the wedge and is the
        # only thing on it; it gets the room.
        body_want, body_grow = 18, 1.35
    laid = layout_rows(d, (
        (FA_PATIENTS, "label", 18, script_size(FA_PATIENTS, 18, REQ_LABEL_GROW), 0.0),
        (body[0], "text", body_want, script_size(body[0], body_want,
                                                 body_grow), 0.0),
        (body[1], "text", body_want, script_size(body[1], body_want,
                                                 body_grow), 0.0),
        (body[2], "text", body_want, script_size(body[2], body_want,
                                                 body_grow), 0.0),
        # The total, so a fourth patient is never hidden without saying so.
        # 1.20 -> 1.45 with the aperture (2026-08-06 evening): the row used to
        # be a five-word sentence and is now a single numeral, so the same
        # width buys a bigger glyph, and a number read through a window at 45°
        # is the one thing on this wedge that has to survive the angle. It is
        # a GROW allowance and not a floor, so layout_rows can still take it
        # back if the block overruns. MEASURED after the change, all three
        # scripts, against the 240 budget: Latin 22/20/20/20/20 ending at 230,
        # Persian 29/20/20/20/20 at 239, Han 32/19/19/19/19 at 227.
        #
        # HAN PAYS FOR IT, ONE POINT PER ROW, and that is the trade rather than
        # an accident: at 1.45 the block overran, the squeeze fired, and the
        # label and the three body rows each came back 1px smaller than they
        # were at 1.20 (33/20/20/20/17) so the numeral could go from 17 to 19.
        # Worth it — a surname a point smaller is unnoticeable, and the count
        # is the one figure on this wedge somebody reads from across a room.
        # All four rows are still above the >=18 floor tests/
        # test_type_fitting.py pins, which is where this stops being taste.
        (tail, "label", 14, script_size(tail, 14, 1.45), 0.0),
    ), REQ_ROW_Y[0], REQ_BLOCK_BOTTOM,
        # PANEL_R0 and flat=False — the geometry the panel actually draws
        # since the arcs came back; a fitter measuring a straight panel that
        # no longer exists hands out room the glass does not have.
        (PAT_A0, PAT_A1, PANEL_R0, WEDGE_R1, False),
        who="patients wedge")
    # THE THREE BODY ROWS SHARE ONE SIZE. They are one list, and a list whose
    # rows step between sizes because one surname is longer reads as three
    # unrelated things — worse than the shorter row simply having air. So
    # they are levelled to the smallest of the three and re-centred at it.
    live = [r for r in laid[1:4] if r]
    if len(live) > 1:
        small = min(r["size"] for r in live)
        for r in live:
            if r["size"] != small:
                r["size"] = small
                r["font"] = face_for(r["text"], "text", small)
    # ── THE ROSE-GOLD FRAME ROUND THE LAST ROW ────────────────────────────
    #
    # Drawn from the row's OWN measured ink, not from a rectangle somebody
    # placed: layout_rows has already decided where that numeral sits and how
    # big it is, and a window positioned by hand would drift off it the first
    # time the block squeezes (which it does — see REQ_BLOCK_BOTTOM).
    #
    # THE GOLD IS DESERT_MID ITSELF, and that is the reason to reach across
    # the file for it rather than pick a colour here. desertify() has already
    # run by the time this wedge is composited, so the dial underneath is
    # literally duotoned through DESERT_MID; using the same triple makes the
    # frame the dial's own gold instead of a second, nearly-identical one.
    # Anybody changing the colourway changes this in the same edit, for free.
    #
    # Painted BEFORE the rows so the numeral lands on top of its own window,
    # and NOT filled dark: this tile is composited with a SCREEN blend, where
    # black is transparent and nothing can be made darker than the dial. An
    # aperture here is therefore a frame plus a faint lift, not a hole.
    ap = laid[4]
    if ap:
        bb = ap["font"].getbbox(ap["text"])
        w = text_w(d, ap["text"], ap["font"], ap["track"])
        box = [ap["cx"] - w / 2.0 - APERTURE_PAD[0],
               ap["y"] + bb[1] - APERTURE_PAD[1],
               ap["cx"] + w / 2.0 + APERTURE_PAD[0],
               ap["y"] + bb[3] + APERTURE_PAD[1]]
        d.rounded_rectangle(box, radius=4, fill=DESERT_MID + (26,),
                            outline=DESERT_MID + (238,), width=2)
    draw_rows(d, laid, (ROW_INK_LABEL, ROW_INK_BODY, ROW_INK_BODY,
                        ROW_INK_BODY, bright))

    tile = canvas.crop(_req_box())          # same arc, so the same crop
    _PAT_UI["sig"], _PAT_UI["tile"] = sig, tile
    return tile


def _pat_wedge_live() -> bool:
    """Is the clinic list under the finger RIGHT NOW?

    The same rule as _req_wedge_live and the same arithmetic the draw uses:
    this wedge's alpha is its own fade TIMES the complement of the REQUESTS
    fade, because the two share one arc and cross-fade. Asking only about
    `_PAT_UI["fade"]` would make the clinic list tappable underneath a
    concierge wedge that is covering it — a hit box you cannot see, on top
    of a control you can, which is the worse half of PRINCIPLES §1.

    IT SHIPPED WITHOUT ONE. The wedge was built from a spoken request,
    painted correctly, and had no hit-test at all; the owner reached for it
    the moment he saw it and the glass did nothing. tests/
    test_wedge_reachability.py exists so the next voice-built wedge cannot
    repeat it.
    """
    return _PAT_UI["fade"] * max(0.0, 1.0 - _REQ_UI["fade"]) > 0.05


def draw_patients_wedge(frame: Image.Image, now: float,
                        hold: bool = False, rot_deg: float = 0.0) -> None:
    """Composite the clinic list. In place, before the rotate.

    MUST be called AFTER draw_requests_wedge: the alpha here is the
    complement of that wedge's fade, so it reads the value that call just
    wrote. Wrapped whole, like its neighbour — this is new paint in a
    compositor that must never stop, and any failure degrades to NO WEDGE
    and says so once rather than per frame.

    Whether it gets the arc at all is now the ring policy's answer, not a
    local guess: outside clinic hours it does not claim a slot, and while a
    request is running it is one spin away rather than gone.
    """
    try:
        upcoming = _patients_upcoming(now)
    except Exception as e:                      # noqa: BLE001
        _req_say(f"pat:list:{e!r}", f"patients: list failed {e!r} — no wedge")
        upcoming = []
    last = _PAT_UI["last_t"] or now
    _PAT_UI["last_t"] = now
    dt = max(0.0, min(0.5, now - last))
    # Held at zero through the unlock entrance, for the reason the REQUESTS
    # wedge is: a sector arriving mid-reveal steps on the choreography.
    # And held at zero when the policy has not given it the arc — out of
    # clinic hours, or while a spin has paged something else in.
    holds = (not hold) and ring_holds_slot("patients", now, rot_deg)
    _PAT_UI["fade"] = (min(1.0, _PAT_UI["fade"] + dt / REQ_FADE_S) if holds
                       else max(0.0, _PAT_UI["fade"] - dt / (REQ_FADE_S * 2)))

    sig = tuple(upcoming)
    if _PAT_UI["said"] != sig:
        _PAT_UI["said"] = sig
        nxt = (f"next {upcoming[0][0]} {upcoming[0][1]}" if upcoming
               else "clinic clear")
        print(f"patients: {len(upcoming)} still to see — {nxt}", flush=True)
    yielded = _req_wedge_live()
    if _PAT_UI["yielded"] != yielded:
        _PAT_UI["yielded"] = yielded
        print("patients: slot " + ("yielded to REQUESTS" if yielded
                                   else "back to the clinic list"), flush=True)

    k = _PAT_UI["fade"] * max(0.0, 1.0 - _REQ_UI["fade"])
    if k <= 0.01:
        return
    try:
        tile = _pat_tile(tuple(upcoming[:PAT_ROWS]), len(upcoming))
        if k < 0.995:
            tile = tile.point(lambda p, kk=k: int(p * kk))
        #: _req_box, NOT _world_box — the clinic tile is cropped from its
        #: own arc; a bulk find-replace once pasted it at the crown box
        #: and this comment is the tombstone.
        x0, y0, x1, y1 = _req_box()
        frame.paste(ImageChops.screen(frame.crop((x0, y0, x1, y1)), tile),
                    (x0, y0))
    except Exception as e:                      # noqa: BLE001
        _req_say(f"pat:draw:{e!r}", f"patients: wedge draw failed {e!r} — "
                                    f"no wedge")


# ═══════════════════════════════════════════════════════════════════════════
#  THE CONJURED CLASS — platinum and light, for wedges asked into being
# ═══════════════════════════════════════════════════════════════════════════
#
# Owner's brief, spoken 2026-08-07: "the custom AI tile / view the users
# generate, we need to differentiate that wedge from others. make it really
# pop." A wedge that exists because somebody asked out loud is the product's
# magic, and it must read as a DIFFERENT SUBSTANCE from both the stock
# controls and the gold concierge (whose jewel treatment is untouched). The
# language is PLATINUM AND LIGHT, where Sterling is gold. Three marks, worn
# by every conjured wedge automatically:
#
#   1. A white-gold DOUBLE HAIRLINE border — brighter and cooler than the
#      concierge's gold pair; unmistakably the other precious metal.
#   2. A slow SHIMMER: a soft highlight that sweeps the border once every
#      CONJ_SHIM_PERIOD_S, like light moving down a polished edge.
#   3. A four-pointed SPARK beside the label — the quiet "this one was made
#      for you" mark, the same glyph on every conjured wedge so the class
#      reads at a glance.
#
# Fill sits a touch brighter than a stock tile, still in the navy family.
#
# A DECORATOR, NOT A STYLE HAND-PAINTED ON WORLD: everything keys off the
# ring entry's `conjured` flag (RING_WEDGES). A future spoken widget is born
# wearing all three marks by declaring the flag and calling the same two
# hooks WORLD does — conjured_dress()/conjured_spark() in its tile bake,
# draw_conjured_shimmer() after its paste. WORLD is the first customer.
#
# THE FRAME BUDGET RULES (IDLE_FPS note above, FAILURES 2026-08-04) ARE LAW
# HERE. The hairlines, fill lift and spark are baked INTO the tenant's
# cached tile, so they cost nothing per frame. The shimmer is a TABLE of
# border states — small segment-sized tiles, baked once on first draw —
# indexed by time; a frame pays one point() and one screen() paste over a
# segment-sized box inside the wedge's own crop, never a full-frame
# allocation. Same discipline as the sterling glow's table, one section up.
#: Cooler and brighter than STER_GOLD (198,166,100)-ish and AURA_INK
#: (212,175,92): blue-side of neutral, high L — white gold, not silver grey.
CONJ_PT = (216, 224, 238)
#: The sweep's peak: near-white with the same cool cast — light itself.
CONJ_HI = (248, 251, 255)
#: The fill lift, screen-composited over the tenant's own PANEL_FILL wash:
#: still navy, a touch brighter than a stock tile, nowhere near the metal.
#: 2026-08-08: on the theme, with PANEL_FILL it lifts (_TILES["panel_lift"]).
#: The METAL above (CONJ_PT/CONJ_HI) does NOT move — the platinum caste keeps
#: its identity in either colourway, which is the whole point of a caste.
CONJ_FILL_LIFT = _TILES["panel_lift"]
CONJ_SHIM_PERIOD_S = 7.0    # the brief: once every six to eight seconds
CONJ_SHIM_N = 56            # one state per idle frame: N/period = IDLE_FPS
CONJ_SHIM_WIN = 120.0       # px of border lit by the sweep at any moment
_CONJ = {"states": None, "idx": None, "wraps": 0, "said": None}


def _conjured(key: str) -> bool:
    """Is this wedge one the user asked into being? The ring table is the
    single source of the flag, so the class and the slot policy can never
    disagree about what a wedge is."""
    return bool(RING_BY_KEY.get(key, {}).get("conjured"))


def conjured_dress(key, d, a0, a1, r0, r1) -> bool:
    """The BAKED marks: fill lift and the platinum double hairline. Called
    from a tenant's tile bake after its panel wash; returns False for a
    wedge that is not conjured, so the caller keeps its own border."""
    if not _conjured(key):
        return False
    poly = _wedge_sector_poly(a0, a1, r0, r1, pad=0.0, flat=False)
    #: ── THE BLUE TRAY (2026-08-14, owner: "the center has a background
    #: that is more alike to the faded blue of the dial hands"). Authored
    #: in SCREEN-space: the tile reaches the glass through
    #: ImageChops.screen, which only adds light, so the wash inverts
    #: out = 255-(255-t)(255-dial)/255 for a target near (75,95,190) over
    #: the tapisserie — low red, committed blue, graded deeper at the
    #: inner arc. (Three earlier attempts edited a copy of this function
    #: that a silent no-op replace had never created — see FAILURES.)
    #: the flat blue tray survives only as the fallback for a puck the
    #: sky pack has not reached — the living nebula pastes per frame in
    #: the draw path, not in this bake.
    if _vision_sky() is None:
        for _i in range(22):
            _f0 = r0 + (r1 - r0) * _i / 22.0
            _f1 = r0 + (r1 - r0) * (_i + 1) / 22.0 + 0.8
            _ab = int(215 - 90 * (_i / 21.0))
            _band = _wedge_sector_poly(a0, a1, _f0, _f1, pad=0.0,
                                       flat=False)
            d.polygon(_band, fill=(30, 72, 218, _ab))
    #: ── 2026-08-14, the idealface aftermath: THE CASTE WHISPERS NOW ────
    #: The platinum pair was set against the old near-black dial; on the
    #: simplified face it had become the single brightest line anywhere —
    #: the owner's "how about the AI widgets" was the same complaint the
    #: bolts and speckles got. The metal does NOT move (the 2026-08-07
    #: caste brief stands: platinum, not gold) but its VOICE drops to
    #: hairline: alpha 220/130 -> 130/70, outer width 2 -> 1. The shimmer
    #: still sweeps it, and light moving down a quiet edge reads as more
    #: expensive than a bright box, not less.
    #: ── v3, the same day: A MOLDING, NOT A LINE (owner: "try again the
    #: platinum border … we want it to be really special compared to the
    #: other wedges outside of its size"). Three strokes make machined
    #: metal where one made a box: the dark seat the rail sits in, the
    #: platinum body, and a polished arris catching light one step in.
    #: The shimmer sweeps the same edge it always did.
    d.line(poly + [poly[0]], fill=(58, 62, 74, 170), width=5)
    d.line(poly + [poly[0]], fill=CONJ_PT + (245,), width=3)
    arr = _wedge_sector_poly(a0 + 0.4, a1 - 0.4, r0 + 3.0, r1 - 3.0,
                             pad=0.0, flat=False)
    d.line(arr + [arr[0]], fill=CONJ_HI + (215,), width=1)
    # The inner of the pair: angles come in ~1.1° so the gap between the
    # two lines holds roughly steady along both arcs at these radii.
    inn = _wedge_sector_poly(a0 + 1.1, a1 - 1.1, r0 + 9.0, r1 - 9.0,
                             pad=0.0, flat=False)
    d.line(inn + [inn[0]], fill=CONJ_PT + (80,), width=1)
    return True


def conjured_spark(key, d, row) -> None:
    """The four-pointed star beside the label — one glyph for the class.
    `row` is the label's laid row (layout_rows dict); centred text, so the
    spark hangs off its right edge at the ink's own middle."""
    if not (_conjured(key) and row):
        return
    bb = row["font"].getbbox(row["text"])
    w = text_w(d, row["text"], row["font"])
    r = max(4.0, row["size"] * 0.30)
    cx = row["cx"] + w / 2.0 + r + 7.0
    cy = row["y"] + (bb[1] + bb[3]) / 2.0

    def star(rr, col):
        wst = rr * 0.30
        d.polygon([(cx, cy - rr), (cx + wst, cy - wst), (cx + rr, cy),
                   (cx + wst, cy + wst), (cx, cy + rr), (cx - wst, cy + wst),
                   (cx - rr, cy), (cx - wst, cy - wst)], fill=col)

    star(r, CONJ_PT + (235,))
    star(r * 0.45, CONJ_HI + (255,))    # the hot core — metal catching light


def _conj_shim_states():
    """The shimmer, as a table. Baked once: the free arc's border as a
    closed path, and for each of CONJ_SHIM_N phases a CONJ_SHIM_WIN-px
    window of it drawn with a cosine brightness profile, blurred soft, and
    cropped to ITS OWN segment-sized box. Geometry is the shared live slot
    (all conjured tenants use it), so one table serves the whole class."""
    if _CONJ["states"] is not None:
        return _CONJ["states"]
    poly = _wedge_sector_poly(REQUESTS_A0, REQUESTS_A1, PANEL_R0, WEDGE_R1,
                              pad=0.0, flat=False)
    pts = poly + [poly[0]]
    cum = [0.0]
    for (xa, ya), (xb, yb) in zip(pts, pts[1:]):
        cum.append(cum[-1] + math.hypot(xb - xa, yb - ya))
    total = cum[-1]

    def at(s):
        s %= total
        for i in range(len(cum) - 1):
            if s <= cum[i + 1]:
                t = (s - cum[i]) / ((cum[i + 1] - cum[i]) or 1.0)
                return (pts[i][0] + (pts[i + 1][0] - pts[i][0]) * t,
                        pts[i][1] + (pts[i + 1][1] - pts[i][1]) * t)
        return pts[-1]

    states, chunks = [], 12
    for i in range(CONJ_SHIM_N):
        centre = total * i / CONJ_SHIM_N
        seg = [at(centre + (c / chunks - 0.5) * CONJ_SHIM_WIN)
               for c in range(chunks + 1)]
        xs = [p[0] for p in seg]
        ys = [p[1] for p in seg]
        x0, y0 = max(0, int(min(xs)) - 6), max(0, int(min(ys)) - 6)
        x1, y1 = min(SIZE, int(max(xs)) + 7), min(SIZE, int(max(ys)) + 7)
        tile = Image.new("RGB", (x1 - x0, y1 - y0), 0)
        td = ImageDraw.Draw(tile)
        for c in range(chunks):
            k = math.cos(math.pi * ((c + 0.5) / chunks - 0.5))
            td.line([(seg[c][0] - x0, seg[c][1] - y0),
                     (seg[c + 1][0] - x0, seg[c + 1][1] - y0)],
                    fill=tuple(int(ch * k) for ch in CONJ_HI), width=3)
        states.append((tile.filter(ImageFilter.GaussianBlur(1.4)), (x0, y0)))
    _CONJ["states"] = states
    print(f"conjured: shimmer table baked — {CONJ_SHIM_N} border states, "
          f"period {CONJ_SHIM_PERIOD_S}s, perimeter {total:.0f}px",
          flush=True)
    return states


def draw_conjured_shimmer(frame: Image.Image, now: float, key: str,
                          k: float) -> None:
    """The mark that MOVES: paste this instant's border state, scaled by
    the tenant's own fade. Called after the tenant's tile paste, same
    frame, same pre-rotate stage. A failure degrades to hairlines only and
    says so once — never per frame."""
    if k <= 0.01 or not _conjured(key):
        return
    try:
        states = _conj_shim_states()
        idx = int((now % CONJ_SHIM_PERIOD_S) / CONJ_SHIM_PERIOD_S
                  * CONJ_SHIM_N) % CONJ_SHIM_N
        # The period, verifiable from the log, exactly as the sterling
        # glow does it: the first three wraps are stamped, then quiet.
        if (_CONJ["idx"] is not None and idx < _CONJ["idx"]
                and _CONJ["wraps"] < 3):
            _CONJ["wraps"] += 1
            print(f"conjured shimmer: table index wrapped to 0 at {now:.3f} "
                  f"(cycle {_CONJ['wraps']}, N={CONJ_SHIM_N}, "
                  f"period {CONJ_SHIM_PERIOD_S}s)", flush=True)
        _CONJ["idx"] = idx
        tile, (x0, y0) = states[idx]
        if k < 0.995:
            tile = tile.point(lambda p, kk=k: int(p * kk))
        frame.paste(ImageChops.screen(
            frame.crop((x0, y0, x0 + tile.width, y0 + tile.height)), tile),
            (x0, y0))
    except Exception as e:                      # noqa: BLE001
        if _CONJ["said"] != repr(e):
            _CONJ["said"] = repr(e)
            print(f"conjured shimmer: failed {e!r} — hairlines only",
                  flush=True)


# ── THE WORLD BRIEF: international affairs, on the home ring ───────────────
#
# Spoken request, 2026-08-07: "add an AI widget that tells me what's going
# on with international affairs on my home screen." The content ALREADY
# exists on this device: brief_baker keeps an AI-condensed briefing per
# topic in ~/aura_assets/briefings/, refreshed when the room is quiet, and
# INTERNATIONAL AFFAIRS is one of the six. The headlines in that file are
# REAL — fetched from the topic feed; the model only condenses (the baker's
# own rule, for the reason build_briefing states: a model asked what is
# happening in the world invents the news). So this wedge invents nothing.
# It reads the newest bake and puts one headline at a time on the glass.
#
# It is the THIRD tenant of the one free arc, behind REQUESTS and the
# clinic list, and follows the patients wedge deliberately: same sector,
# same crop, the same crossfade arithmetic extended by one term, the same
# ring policy deciding when it holds the slot. A tap opens the briefing
# card the conductor already draws — full headlines, any tap closes —
# rather than a third card that would have to be kept in step with two.
#: -137 -> -134 and R0 371 (2026-08-14, measured): the baked ring's
#: inner copper edge sits at r=369 display (sampled through MUTE,
#: SETTINGS and BRIEFING — the 363 VIEWBOX conversion was 6px proud),
#: and the -137 corner at band radius passed ~20px from the RESERVE
#: gauge's F. The crown slot decouples from the requests card's angles.
WORLD_A0, WORLD_A1 = -134.0, -70.0
#: ── THE CROWN BAND (2026-08-14). The slot stops borrowing the requests
#: card's radii and crop: at 12 o'clock the octagon's flat side cut the
#: tile ("clipped horizontally at the top") and the borrowed band sat
#: deeper than the baked ring (owner: "same symmetry with the other
#: wedges in terms of how deep it goes into the center"). The baked
#: wedges are sector(336,458) in VIEWBOX units = 363..494.6 display; the
#: crown slot now wears exactly that band, hugging the tick circle, and
#: its crop is its own annulus box — the bezel opening plays no part.
CONJ_R0, CONJ_R1 = 371.0, 494.6
#: the raymarched platinum frame (scripts/render_plat_frame.py) — a
#: 1080px RGBA sprite aligned 1:1 with the logical frame. When present
#: it IS the rail; the stroke molding below is the fallback for a puck
#: the render has not reached.
PLAT_FRAME = Path.home() / "aura_face" / "pushers" / "plat_frame.png"
_PLAT = {"im": None}


def _plat_frame():
    if _PLAT["im"] is None:
        _PLAT["im"] = (Image.open(PLAT_FRAME).convert("RGBA")
                       if PLAT_FRAME.exists() else False)
        if _PLAT["im"] is not False:
            print("world: raymarched platinum frame loaded", flush=True)
    return _PLAT["im"] if _PLAT["im"] is not False else None


#: ── THE VISION SKY (2026-08-14, owner: "it represents the 'vision' of
#: Aura Vision so it should be this mystical, cloudy, starry type
#: thing"). A 48-frame seamless nebula loop rendered on the RTX
#: (scripts/render_vision_sky.py), screen-space authored and black
#: outside the sector, so the compositor screens it straight into the
#: crown box with no mask. One frame every 2s — a sky that breathes.
VISION_SKY_DIR = Path.home() / "aura_face" / "vision_sky"
_VSKY = {"frames": None}


def _vision_sky():
    if _VSKY["frames"] is None:
        fs = sorted(VISION_SKY_DIR.glob("frame_*.png"))
        if not fs:
            _VSKY["frames"] = False
        else:
            bx = _world_box()
            sz = (bx[2] - bx[0], bx[3] - bx[1])
            frames = []
            for f in fs:
                im = Image.open(f).convert("RGB")
                if im.size != sz:
                    im = im.resize(sz, Image.BILINEAR)
                frames.append(im)
            _VSKY["frames"] = frames
            print(f"vision sky: {len(frames)} frames loaded at {sz}",
                  flush=True)
    return _VSKY["frames"] or None


def _screen_sky(frame, now: float, k: float) -> None:
    sky = _vision_sky()
    if sky is None:
        return
    sf = sky[int(now / 2.0) % len(sky)]
    if k < 0.995:
        sf = sf.point(lambda p, kk=k: int(p * kk))
    x0, y0, x1, y1 = _world_box()
    frame.paste(ImageChops.screen(frame.crop((x0, y0, x1, y1)), sf),
                (x0, y0))
WORLD_ROW_Y0 = 74.0
WORLD_BLOCK_BOTTOM = 172.0
_WORLD_BOX = None


def _world_box():
    global _WORLD_BOX
    if _WORLD_BOX is None:
        xs, ys = [], []
        for i in range(69):
            ad = WORLD_A0 + (WORLD_A1 - WORLD_A0) * i / 68.0
            a = math.radians(ad)
            for r in (CONJ_R0 - 8, CONJ_R1 + 6):
                xs.append(SIZE / 2 + r * math.cos(a))
                ys.append(SIZE / 2 + r * math.sin(a))
        _WORLD_BOX = (max(0, int(min(xs)) - 10),
                      max(0, int(min(ys)) - 10),
                      min(SIZE, int(max(xs)) + 12),
                      min(SIZE, int(max(ys)) + 12))
    return _WORLD_BOX
#: Ivory, because the neighbouring hues are spoken for (briefing cyan,
#: sterling violet, lock red, settings steel, volume teal, requests gold,
#: patients in the dial's own metal) and green/red are reserved for
#: outcomes. Composited AFTER desertify(), so the triple reaches the panel
#: raw — the same clause PAT_COL carries, and the same duty to move with
#: the colourway if it changes.
#: 2026-08-08: that duty goes STRUCTURAL, exactly as PAT_COL's did — the
#: triple rides the theme (_TILES["world"]), so it cannot be forgotten.
WORLD_COL = _TILES["world"]
#: The newest bake for the topic. Written by brief_baker (one wav + one
#: json per topic, {"topic", "text", "lines", "at"}); READ here, never
#: written. The name comes from slug("INTERNATIONAL AFFAIRS").
#: 2026-08-16, owner ("this is his / our industry"): the crown wedge's
#: TOPIC is a per-puck choice, not a constant — Bob's puck reads CRYPTO.
#: Env-gated like AURA_ROSTER_FACE: AURA_WORLD_TOPIC names any key of
#: brief_baker's FEEDS; unset, every other puck renders byte-identically.
#: The label on the glass is the topic's first word — the bake json's own
#: "topic" field already says the rest.
WORLD_TOPIC = os.environ.get("AURA_WORLD_TOPIC", "INTERNATIONAL AFFAIRS")
WORLD_FILE = Path.home() / "aura_assets" / "briefings" / \
    (re.sub(r"[^a-z0-9]+", "_", WORLD_TOPIC.lower()).strip("_") + ".json")
#: Older than this and the wedge leaves the ring rather than presenting
#: yesterday as news. The baker re-bakes within hours whenever the puck is
#: healthy, so a day-old file means the baker is down — and a wedge that
#: leaves (with a ring log line, and its age visible on the glass until
#: then) is the visible version of that failure.
WORLD_FRESH_S = 24 * 3600.0
#: One headline at a time, this long each. The sector fits ~2 short rows
#: of reading matter, so cycling shows the whole bake where a static tile
#: would show a fifth of it. One tile bake per dwell — nowhere near the
#: per-frame cost that spins the fan.
WORLD_DWELL_S = 12.0
FA_WORLD = ("WORLD" if WORLD_TOPIC == "INTERNATIONAL AFFAIRS"
            else WORLD_TOPIC.split()[0])

_WORLD_UI = {"fade": 0.0, "last_t": 0.0, "sig": None, "tile": None,
             "said": None, "mtime": None, "data": None}


def _world_brief():
    """The baked briefing, stat-cached by mtime like _requests(). None when
    absent or unusable — and unusable SAYS SO, once per file change."""
    try:
        st = WORLD_FILE.stat()
    except (FileNotFoundError, NotADirectoryError):
        _WORLD_UI["mtime"] = _WORLD_UI["data"] = None
        return None
    except Exception as e:                      # noqa: BLE001
        _req_say(f"world:stat:{e!r}", f"world: cannot stat {WORLD_FILE} "
                                      f"{e!r}")
        return None
    if _WORLD_UI["mtime"] != st.st_mtime:
        _WORLD_UI["mtime"] = st.st_mtime
        data = None
        try:
            raw = json.loads(WORLD_FILE.read_text())
            lines = [str(ln).strip() for ln in (raw.get("lines") or [])
                     if str(ln).strip()]
            at = float(raw.get("at") or 0.0)
            if lines and math.isfinite(at):
                data = {"topic": str(raw.get("topic") or "WORLD"),
                        "lines": lines[:5], "at": at}
            else:
                _req_say(f"world:empty:{st.st_mtime}",
                         "world: brief has no headlines — no wedge")
        except Exception as e:                  # noqa: BLE001
            _req_say(f"world:parse:{e!r}",
                     f"world: brief unreadable {e!r} — no wedge")
        _WORLD_UI["data"] = data
    return _WORLD_UI["data"]


def _world_relevant(now: float) -> bool:
    """Fresh news claims arc; an absent or day-old bake claims nothing.
    Absence here is RELEVANCE, not failure — the parse paths above are the
    loud ones, and the ring logs the tenancy change."""
    b = _world_brief()
    return b is not None and (now - b["at"]) <= WORLD_FRESH_S


def _world_age_text(now: float, at: float) -> str:
    """How old the bake is, in the units a glance wants. Clamped at zero:
    a clock-skewed 'fresh in -3 minutes' is nonsense on a dial."""
    m = max(0.0, (now - at) / 60.0)
    return f"{m / 60:.0f}H OLD" if m >= 90 else f"{m:.0f}M OLD"


def _world_tile(headline: str, idx: int, n: int, age_txt: str,
                key: str = "world", label: str = FA_WORLD, col=None,
                ui=None, a0: float = WORLD_A0, a1: float = WORLD_A1):
    """One headline, baked to the same tile shape the arc's other tenants
    use. Rebuilt when the headline or the age text changes — once per
    dwell, or once a minute for the age, whichever comes first.

    2026-08-09: the last five arguments exist so a SECOND topic tenant can
    bake through this same function rather than beside it (the IRAN watch,
    below). Every default is WORLD's own value, so the world brief renders
    byte-identically; a second tenant passes its key, label, ink and its
    OWN state dict — sharing one cache would make two tenants thrash it
    through a crossfade. One bake path means the two cannot drift apart
    about what a headline tile looks like.
    """
    col = WORLD_COL if col is None else col
    ui = _WORLD_UI if ui is None else ui
    sig = (headline, idx, n, age_txt)
    if ui["sig"] == sig and ui["tile"] is not None:
        return ui["tile"]
    bright = tuple(min(255, int(c * 0.35) + 168) for c in col)
    canvas = Image.new("RGB", (SIZE, SIZE), 0)
    d = ImageDraw.Draw(canvas, "RGBA")
    # The panel, exactly as the two wedges it takes turns with — a shape
    # difference between arc-mates would read as a bug (see PANEL_CLEAR).
    poly = _wedge_sector_poly(a0, a1, CONJ_R0, CONJ_R1,
                              pad=0.0, flat=False)
    d.polygon(poly, fill=PANEL_FILL + (36,))
    # WORLD is conjured (RING_WEDGES): the class dress — fill lift and the
    # platinum double hairline — replaces the tenant's own single border.
    #: 2026-08-14: THE DRESS GETS THE CROWN RADII TOO. The band moved to
    #: CONJ_R0/R1 but this call kept passing the requests card's numbers,
    #: so the rail and tray painted at 335..458 under a layout at
    #: 371..494.6 — measured on the glass as platinum ink to r=335, the
    #: owner's "still, still not lined up". One geometry now.
    if not conjured_dress(key, d, a0, a1, CONJ_R0, CONJ_R1):
        d.line(poly + [poly[0]], fill=col + (140,), width=2)
    else:
        _pf = _plat_frame()
        if _pf is not None:
            #: paste-with-mask, NOT alpha_composite: the tile canvas is
            #: RGB and alpha_composite raises on it — which it did,
            #: silently, and the whole crown wedge vanished from the
            #: glass for four minutes (§1: this comment is the sound).
            canvas.paste(_pf, (0, 0), _pf)

    #: ── "2/5 · 4H OLD" WAS BOOKKEEPING, NOT HOROLOGY (2026-08-13) ──────
    #: Story position becomes the settings rail's own dot idiom (drawn after
    #: layout, below); age keeps only its compact form. A complication
    #: carries state in marks, not in fractions.
    sub = age_txt.replace(" OLD", "")
    #: 18 -> 20 and TWO rows -> THREE (2026-08-14, owner: "expand on the
    #: text. it was always too short and unreadable with the smaller
    #: wedge, now we have a much larger canvas"). The crown arc's chords
    #: run 500+px; three rows of 20 carry roughly triple the words the
    #: old corner slot managed.
    #: 20 -> 26 same hour (owner: the headline "is way smaller than the
    #: other wedges right now") — floor 20, and the block top rises 4px
    #: to buy the leading. Three rows still beat two bigger ones for
    #: words on glass; the fitter lands where the band allows.
    hl_size = script_size(headline, 26)
    #: BOLD (owner: "make the headline pop more … it is, after all, the
    #: topic headline") — the story rows take the display weight, white
    #: ink, and a dark under-shadow to lift off the vision sky.
    f_txt = face_for(headline, "bold", hl_size)

    def lay(a: str, b: str, c: str, quiet: bool = False):
        return layout_rows(d, (
            (label, "label", 16,
             script_size(label, 18, REQ_LABEL_GROW), 0.0),
            # The headline rows MAY NOT GROW (cap == want): like the
            # request sentence, every point of size buys itself with words
            # off the end, and the words are the point.
            (a, "bold", 20, hl_size, 0.0),
            (b, "bold", 20, hl_size, 0.0),
            (c, "bold", 20, hl_size, 0.0),
            (sub, "label", 14, script_size(sub, 14, 1.20), 0.0),
        ), WORLD_ROW_Y0, WORLD_BLOCK_BOTTOM,
            (a0, a1, CONJ_R0, CONJ_R1, False),
            who=f"{key} wedge", quiet=quiet)

    # Wrapped against the room the rows actually get — the requests
    # wedge's own probe-then-fill, because a headline is the same shape of
    # problem as a spoken request: the WORDS give way, never the type, and
    # the full list is one tap away on the card.
    probe = lay("·", "·", "·", quiet=True)
    _share_centre(probe[1], probe[2])
    #: ── PER-ROW WIDTHS, 2026-08-14 (owner: "you are not using the full
    #: width of the tile. it should fill it up left to right completely").
    #: One shared minimum let the top row — the shortest chord, up
    #: against the outer arc — starve all three. Each row now fills ITS
    #: OWN span: a fan of text, short line under the arc, longest line on
    #: the widest chord, which is how type sits in a sector.
    #: +26 of air per side (2026-08-14, owner: "text is too close to the
    #: wedge border") — the rail is a rendered object now and type needs
    #: clearance from metal, same as every cap and pocket on this dial.
    #: -52 -> -16 (owner: "the typeface spacing is not using the space
    #: well at all") — the rail thinned in the same pass, so type can sit
    #: closer to a finer edge.
    lims = [probe[i]["limit"] - REQ_CLIP_PAD - 16 for i in (1, 2, 3)]
    words = headline.split()
    rows_txt = []
    for li in lims:
        row = ""
        while words and text_w(d, (row + " " + words[0]).strip(),
                               f_txt) <= li:
            row = (row + " " + words.pop(0)).strip()
        if not row and words and not rows_txt:  # one unbreakable word
            row, words = words[0], words[1:]
        rows_txt.append(row)
    l1, l2, l3 = rows_txt
    #: ── 2026-08-13, the idealface critique: NO ELLIPSIS ─────────────────
    #: "A text box with an ellipsis is a widget; everything around it is a
    #: watch." A clean cut at the last whole word — the full headline is
    #: still one tap away, and a complication states, it does not trail off.
    laid = lay(l1, l2, l3)
    _share_centre(laid[1], laid[2])
    #: ── THE AGE IS A NEEDLE NOW (2026-08-14; "dots landed, needle
    #: didn't"). The last bookkeeping glyph becomes horology: the sub row
    #: keeps its place in the layout but its TEXT is not drawn — in its
    #: box sits a two-tick age gauge, needle sweeping 0..8h. Text was
    #: state spelled out; a complication carries state in marks (the same
    #: rule that removed "2/5 · 4H OLD" — this retires its last word).
    _sh = [None] + [(dict(r, y=r["y"] + 1.6, cx=r["cx"] + 1.2)
                     if isinstance(r, dict) else None)
                    for r in laid[1:4]] + [None]
    draw_rows(d, _sh, (None, (10, 8, 22), (10, 8, 22), (10, 8, 22)))
    draw_rows(d, laid, (ROW_INK_LABEL, (255, 255, 255), (255, 255, 255),
                        (255, 255, 255)))
    _sr = laid[4] if len(laid) > 4 and isinstance(laid[4], dict) else None
    if _sr:
        _m = re.match(r"(\d+)\s*([HM])", sub or "")
        _mins = (int(_m.group(1)) * (60 if _m.group(2) == "H" else 1)
                 if _m else 0)
        _frac = min(1.0, _mins / 480.0)         # 8h = pinned at the stop
        #: v2 same morning (owner could not FIND v1 on the page): radius
        #: 13 -> 19 and every stroke doubled — a gauge nobody notices is
        #: bookkeeping with extra steps.
        _gx, _gy = _sr["cx"], _sr["y"] + 13.0
        _gr = 19.0
        d.arc([_gx - _gr, _gy - _gr, _gx + _gr, _gy + _gr],
              210, 330, fill=col + (200,), width=2)
        for _te in (210, 270, 330):
            _tr = math.radians(_te)
            d.line([_gx + math.cos(_tr) * (_gr - 5),
                    _gy + math.sin(_tr) * (_gr - 5),
                    _gx + math.cos(_tr) * _gr,
                    _gy + math.sin(_tr) * _gr], fill=col + (200,), width=2)
        _na = math.radians(210.0 + 120.0 * _frac)
        d.line([_gx, _gy, _gx + math.cos(_na) * (_gr - 3),
                _gy + math.sin(_na) * (_gr - 3)],
               fill=bright + (245,), width=3)
        d.ellipse([_gx - 2.5, _gy - 2.5, _gx + 2.5, _gy + 2.5],
                  fill=bright + (245,))
    conjured_spark(key, d, laid[0])             # the made-for-you mark
    #: the story-rail: n dots, current one lit — the settings pages' idiom,
    #: centred under the sub row. Graphic, not glyphs: the label face has
    #: no reliable ● and a tofu box would be worse than the fraction was.
    try:
        _rows = laid
        _suby = _rows[-1]["y"] if isinstance(_rows[-1], dict) else None
    except Exception:
        _suby = None
    if n > 1:
        _mid = (a0 + a1) / 2.0
        #: v2 same evening: +10 below the block brushed the wordmark — the
        #: rail tucks INSIDE the panel's last row instead, tighter pitch.
        _cy = WORLD_BLOCK_BOTTOM - 12
        _cx = SIZE / 2 + math.cos(math.radians(_mid)) * ((CONJ_R0 + CONJ_R1) / 2)
        _dx0 = _cx - (n - 1) * 5.5
        for _i in range(n):
            _r = 2.4 if _i == idx else 1.5
            _fill = bright + (235,) if _i == idx else col + (110,)
            d.ellipse([_dx0 + _i * 11 - _r, _cy - _r,
                       _dx0 + _i * 11 + _r, _cy + _r], fill=_fill)
    tile = canvas.crop(_world_box())            # the crown slot's own crop
    ui["sig"], ui["tile"] = sig, tile
    return tile


def _world_wedge_live() -> bool:
    """Is the world brief under the finger RIGHT NOW? The same rule as its
    two arc-mates, with BOTH complements in the product — it is third in
    the crossfade, so it is tappable only while it is the thing actually
    painted (tests/test_wedge_reachability.py is the guard)."""
    return (_WORLD_UI["fade"] * max(0.0, 1.0 - _REQ_UI["fade"])
            * max(0.0, 1.0 - _PAT_UI["fade"])) > 0.05


def draw_world_wedge(frame: Image.Image, now: float,
                     hold: bool = False, rot_deg: float = 0.0) -> None:
    """Composite the world brief. In place, before the rotate.

    MUST be called AFTER draw_requests_wedge AND draw_patients_wedge: its
    alpha carries the complement of both their fades, so it reads the
    values those calls just wrote. Wrapped whole, like its neighbours —
    new paint in a compositor that must never stop, so any failure
    degrades to NO WEDGE and says so once rather than per frame.
    """
    try:
        brief = _world_brief()
    except Exception as e:                      # noqa: BLE001
        _req_say(f"world:read:{e!r}", f"world: read failed {e!r} — no wedge")
        brief = None
    last = _WORLD_UI["last_t"] or now
    _WORLD_UI["last_t"] = now
    dt = max(0.0, min(0.5, now - last))
    # Held at zero through the unlock entrance, like its neighbours, and
    # held at zero when the ring policy has not given it the arc.
    holds = (not hold) and ring_holds_slot("world", now, rot_deg)
    _WORLD_UI["fade"] = (min(1.0, _WORLD_UI["fade"] + dt / REQ_FADE_S)
                         if holds else
                         max(0.0, _WORLD_UI["fade"] - dt / (REQ_FADE_S * 2)))
    sig = brief["at"] if brief else None
    if _WORLD_UI["said"] != sig:
        _WORLD_UI["said"] = sig
        if brief:
            print(f"world: brief loaded — {len(brief['lines'])} headlines, "
                  f"top {brief['lines'][0][:56]!r}", flush=True)
        else:
            print("world: brief gone — no wedge", flush=True)
    k = (_WORLD_UI["fade"] * max(0.0, 1.0 - _REQ_UI["fade"])
         * max(0.0, 1.0 - _PAT_UI["fade"]))
    if k <= 0.01 or not brief:
        return
    try:
        idx = int(now // WORLD_DWELL_S) % len(brief["lines"])
        #: the tile carries the story AND what follows it (owner:
        #: "increase the text even if you have to generate it randomly")
        #: — not random: the NEXT headlines chain on until the rows are
        #: full, so the crown wedge is a rolling column of real news.
        _chain = " — ".join((brief["lines"][idx:] + brief["lines"])[:3])
        tile = _world_tile(_chain, idx, len(brief["lines"]),
                           _world_age_text(now, brief["at"]))
        if k < 0.995:
            tile = tile.point(lambda p, kk=k: int(p * kk))
        x0, y0, x1, y1 = _world_box()
        _screen_sky(frame, now, k)
        frame.paste(ImageChops.screen(frame.crop((x0, y0, x1, y1)), tile),
                    (x0, y0))
        draw_conjured_shimmer(frame, now, "world", k)
    except Exception as e:                      # noqa: BLE001
        _req_say(f"world:draw:{e!r}", f"world: wedge draw failed {e!r} — "
                                      f"no wedge")


# ── THE IRAN WATCH: one subject, monitored on the same arc ─────────────────
#
# Spoken request, 2026-08-09 18:54: "add an AI widget that monitors
# developments in Iran." This puck's ASR handed it over as "...developments
# in run"; the Ferrari puck, hearing the same sentence across the room,
# wrote "monitors developments in Iran." — which is what settled the word.
# The room's grammar is whatever the ASR emits, and two ears beat one.
#
# It is the FOURTH tenant of the one free arc and the second member of the
# conjured class, so it is built the way the WORLD brief is and not beside
# it: same sector, same crop, the same crossfade arithmetic extended by one
# term, the same ring policy deciding when it holds the slot, the same tile
# bake (_world_tile, now parameterised) and the same tap — the briefing card
# the conductor already draws.
#
# WHERE THE CONTENT COMES FROM, AND WHY IT INVENTS NOTHING. brief_baker
# gained one FEEDS entry, "IRAN", pointed at a real news search feed; the
# baker then treats it exactly like the other six — fetches the headlines,
# lets the model CONDENSE them and nothing else, and leaves iran.json in
# ~/aura_assets/briefings/ beside the rest. This wedge only READS that file.
# A widget on this face never fetches: it runs in the frame loop, and the
# frame loop does no network (the ember lesson, FAILURES 2026-08-04).
#
# WHAT IT LOOKS LIKE WHEN IT IS NOT WORKING (§1). No bake, an unreadable
# bake, or a bake older than IRAN_FRESH_S and the wedge does not claim arc —
# the ring logs the tenancy change, and the parse paths say why, once per
# file change. A monitor that quietly shows day-old news is the failure this
# is written to avoid; a monitor that is visibly absent is not.
IRAN_A0, IRAN_A1 = REQUESTS_A0, REQUESTS_A1
#: The topic name brief_baker bakes under, and the file it leaves. The name
#: comes from slug("IRAN") — the same derivation WORLD_FILE documents.
IRAN_TOPIC = "IRAN"
IRAN_FILE = Path.home() / "aura_assets" / "briefings" / "iran.json"
#: The same freshness rule as the world brief, and deliberately the same
#: constant: both are news, both come off the same baker, and two numbers
#: that must agree are one number waiting to drift.
IRAN_FRESH_S = WORLD_FRESH_S
#: The world brief's ink, on purpose. Every other hue on the ring is spoken
#: for (briefing cyan, sterling violet, lock red, settings steel, volume
#: teal, requests gold, patients rose) and green/red are reserved for
#: outcomes — and these two tenants are the same substance from the same
#: baker, never on the glass at the same moment. Riding _TILES through
#: WORLD_COL also keeps it correct in every colourway for free.
IRAN_COL = WORLD_COL
IRAN_DWELL_S = WORLD_DWELL_S
FA_IRAN = "IRAN"

_IRAN_UI = {"fade": 0.0, "last_t": 0.0, "sig": None, "tile": None,
            "said": None, "mtime": None, "data": None}


def _iran_brief():
    """The baked Iran briefing, stat-cached by mtime — _world_brief's twin,
    against its own file and its own state. None when absent or unusable,
    and unusable SAYS SO, once per file change."""
    try:
        st = IRAN_FILE.stat()
    except (FileNotFoundError, NotADirectoryError):
        _IRAN_UI["mtime"] = _IRAN_UI["data"] = None
        return None
    except Exception as e:                      # noqa: BLE001
        _req_say(f"iran:stat:{e!r}", f"iran: cannot stat {IRAN_FILE} {e!r}")
        return None
    if _IRAN_UI["mtime"] != st.st_mtime:
        _IRAN_UI["mtime"] = st.st_mtime
        data = None
        try:
            raw = json.loads(IRAN_FILE.read_text())
            lines = [str(ln).strip() for ln in (raw.get("lines") or [])
                     if str(ln).strip()]
            at = float(raw.get("at") or 0.0)
            if lines and math.isfinite(at):
                data = {"topic": str(raw.get("topic") or IRAN_TOPIC),
                        "lines": lines[:5], "at": at}
            else:
                _req_say(f"iran:empty:{st.st_mtime}",
                         "iran: brief has no headlines — no wedge")
        except Exception as e:                  # noqa: BLE001
            _req_say(f"iran:parse:{e!r}",
                     f"iran: brief unreadable {e!r} — no wedge")
        _IRAN_UI["data"] = data
    return _IRAN_UI["data"]


def _iran_relevant(now: float) -> bool:
    """Fresh developments claim arc; an absent or day-old bake claims
    nothing. Same reading as _world_relevant, for the same reason."""
    b = _iran_brief()
    return b is not None and (now - b["at"]) <= IRAN_FRESH_S


def _iran_wedge_live() -> bool:
    """Is the Iran watch under the finger RIGHT NOW? Fourth in the
    crossfade, so ALL THREE complements are in the product — it is tappable
    only while it is the thing actually painted there
    (tests/test_wedge_reachability.py is the guard)."""
    return (_IRAN_UI["fade"] * max(0.0, 1.0 - _REQ_UI["fade"])
            * max(0.0, 1.0 - _PAT_UI["fade"])
            * max(0.0, 1.0 - _WORLD_UI["fade"])) > 0.05


def draw_iran_wedge(frame: Image.Image, now: float,
                    hold: bool = False, rot_deg: float = 0.0) -> None:
    """Composite the Iran watch. In place, before the rotate.

    MUST be called AFTER draw_requests_wedge, draw_patients_wedge AND
    draw_world_wedge: its alpha carries the complement of all three fades,
    so it reads the values those calls just wrote. Wrapped whole, like its
    neighbours — any failure degrades to NO WEDGE and says so once rather
    than per frame.
    """
    try:
        brief = _iran_brief()
    except Exception as e:                      # noqa: BLE001
        _req_say(f"iran:read:{e!r}", f"iran: read failed {e!r} — no wedge")
        brief = None
    last = _IRAN_UI["last_t"] or now
    _IRAN_UI["last_t"] = now
    dt = max(0.0, min(0.5, now - last))
    # Held at zero through the unlock entrance, like its neighbours, and
    # held at zero when the ring policy has not given it the arc.
    holds = (not hold) and ring_holds_slot("iran", now, rot_deg)
    _IRAN_UI["fade"] = (min(1.0, _IRAN_UI["fade"] + dt / REQ_FADE_S)
                        if holds else
                        max(0.0, _IRAN_UI["fade"] - dt / (REQ_FADE_S * 2)))
    sig = brief["at"] if brief else None
    if _IRAN_UI["said"] != sig:
        _IRAN_UI["said"] = sig
        if brief:
            print(f"iran: watch loaded — {len(brief['lines'])} headlines, "
                  f"top {brief['lines'][0][:56]!r}", flush=True)
        else:
            print("iran: no watch bake — no wedge", flush=True)
    k = (_IRAN_UI["fade"] * max(0.0, 1.0 - _REQ_UI["fade"])
         * max(0.0, 1.0 - _PAT_UI["fade"])
         * max(0.0, 1.0 - _WORLD_UI["fade"]))
    if k <= 0.01 or not brief:
        return
    try:
        idx = int(now // IRAN_DWELL_S) % len(brief["lines"])
        tile = _world_tile(brief["lines"][idx], idx, len(brief["lines"]),
                           _world_age_text(now, brief["at"]),
                           key="iran", label=FA_IRAN, col=IRAN_COL,
                           ui=_IRAN_UI, a0=IRAN_A0, a1=IRAN_A1)
        if k < 0.995:
            tile = tile.point(lambda p, kk=k: int(p * kk))
        x0, y0, x1, y1 = _world_box()
        _screen_sky(frame, now, k)
        frame.paste(ImageChops.screen(frame.crop((x0, y0, x1, y1)), tile),
                    (x0, y0))
        draw_conjured_shimmer(frame, now, "iran", k)
    except Exception as e:                      # noqa: BLE001
        _req_say(f"iran:draw:{e!r}", f"iran: wedge draw failed {e!r} — "
                                     f"no wedge")


# ── THE RING IS FULL: RELEVANCE, PRIORITY, AND OVERFLOW ON THE DIAL ────────
#
# Count what is on the glass: five baked wedges, three left-hand controls,
# the clock pill on top, and ONE free 34° arc in the upper left which
# REQUESTS and PATIENTS are already taking turns in. The next wedge somebody
# asks for by voice has nowhere to go, and the two failure modes are both
# bad — refuse it (and the owner learns the device says no), or shrink
# everything to fit (and the ring stops being a ring).
#
# This is the third answer, and it is deliberately a POLICY and not a
# framework: three rules, one table, five short functions.
#
#   1. RELEVANCE. A wedge declares WHEN it is worth arc. A clinic list
#      matters at 08:00 and not at 21:00; a request wedge matters while
#      there is work and at no other time. A wedge outside its window does
#      not claim a slot, and that is not a failure — it is the whole point.
#      It still says so once when it goes quiet (§1: a thing that vanishes
#      without a word is indistinguishable from a thing that broke).
#
#   2. PRIORITY resolves a contest BY RULE, not by whoever was written last.
#      Two wedges wanting one slot is the normal case here, not the edge
#      case, and "the newest code wins" is how a demo loses the wedge the
#      owner was actually looking at.
#
#   3. OVERFLOW LIVES ON THE DIAL. The ring already turns, the owner likes
#      turning it, and every wedge on the face already rotates with it —
#      so a wedge that lost the contest is not gone, it is one spin away.
#      No new affordance, no chevron, nothing extra to learn. RING_PAGE_DEG
#      of dial travel advances the slot to the next claimant.
#
# WHY THE SLOT COUNT IS A MEASUREMENT. RING_SLOTS is 1 because the census in
# the REQUESTS section counted the free arc and found exactly one. It is not
# a taste decision and it must not be raised without re-running that census
# against a current base.png — the last time somebody assumed a radius here
# instead of measuring it, every live wedge came out 8% small.
RING_SLOTS = 1
#: Dial travel that turns the slot to the next claimant. 120° is roughly a
#: third of a turn: far enough that inertia from a casual flick does not
#: page through three wedges, near enough to reach with one gesture.
RING_PAGE_DEG = 120.0
#: Clinic hours, local. The owner's own example of relevance.
PAT_HOURS = (6, 19)
#: The bulletin is a morning object; by evening it is yesterday's news. This
#: window is what makes BRIEFING the natural thing for Sterling to offer to
#: retire at 21:00, which is exactly the trade the owner described.
BRIEFING_HOURS = (5, 14)


def _in_hours(now: float, window) -> bool:
    lo, hi = window
    return lo <= time.localtime(now).tm_hour < hi


def _req_relevant(now: float) -> bool:
    """While there is work, and not otherwise. Reads the same mtime-cached
    head the wedge draws from, so this costs a dict lookup per frame."""
    try:
        return _requests_head(now) is not None
    except Exception:                           # noqa: BLE001
        return False


def _pat_relevant(now: float) -> bool:
    # AND the device actually has a clinic day: no clinic.json (or an empty
    # one) means NO CLAIM, not an empty wedge — a fresh device shows its own
    # requests in this slot, never a hardcoded stranger's schedule.
    return _in_hours(now, PAT_HOURS) and bool(_clinic_rows())


def _brief_relevant(now: float) -> bool:
    return _in_hours(now, BRIEFING_HOURS)


def _always(now: float) -> bool:
    return True


#: THE RING, AS DATA. Everything that owns arc, baked and live, with the two
#: facts a negotiation needs: how important it is, and when it is relevant.
#:
#: `human` and `colour` are here because the concierge has to SAY this, not
#: print it — "might I suggest we retire the cyan one, your daily bulletin?"
#: needs a colour word and a plain-English name, and neither belongs in a
#: clip written by hand for one wedge that might be renamed tomorrow.
#:
#: `baked` marks the five that live in base.png. They are furniture and are
#: costed accordingly (see ring_negotiate), but they are NOT exempt: the
#: owner's own example offers to retire one.
RING_WEDGES = (
    {"key": "meetings",  "human": "your daily bulletin", "colour": "cyan",
     "priority": 70, "relevant": _brief_relevant, "baked": True},
    {"key": "sterling",  "human": "the concierge desk", "colour": "violet",
     "priority": 95, "relevant": _always, "baked": True},
    {"key": "lock",      "human": "the lock", "colour": "red",
     "priority": 90, "relevant": _always, "baked": True},
    {"key": "settings",  "human": "settings", "colour": "steel",
     "priority": 60, "relevant": _always, "baked": True},
    {"key": "volume",    "human": "the volume dial", "colour": "teal",
     "priority": 65, "relevant": _always, "baked": True},
    # The live slot's tenants, in the one free arc.
    {"key": "requests",  "human": "the work you asked for", "colour": "gold",
     "priority": 100, "relevant": _req_relevant, "baked": False},
    {"key": "patients",  "human": "today's clinic list", "colour": "rose",
     "priority": 50, "relevant": _pat_relevant, "baked": False},
    # Ambient news yields to the owner's own work and his clinic day: out
    # of clinic hours it holds the slot; inside them it is one spin away.
    # `conjured` marks the class asked into being by voice — the platinum
    # dress (conjured_dress / conjured_spark / draw_conjured_shimmer) keys
    # off this flag, so the next spoken widget is born wearing it.
    {"key": "world",     "human": "the world affairs brief",
     "colour": "ivory", "priority": 45, "relevant": _world_relevant,
     "baked": False, "conjured": True},
    # The Iran watch: one subject rather than the whole world, so it sits
    # BELOW the general brief — when both have fresh bakes the wider one
    # holds the arc and this is one spin away, which is the right way round
    # for somebody glancing at a dial. Conjured: it was asked for by voice.
    {"key": "iran",      "human": "the Iran watch",
     "colour": "ivory", "priority": 40, "relevant": _iran_relevant,
     "baked": False, "conjured": True},
)
RING_BY_KEY = {w["key"]: w for w in RING_WEDGES}

#: Recomputed at most this often. The predicates are cheap, but this runs in
#: the compose path at ~12fps on a Jetson and the ember work already proved
#: what a careless per-frame cost does to the fan.
_RING_TTL_S = 0.5
_RING_CACHE = {"at": -1e9, "claimants": (), "page": -1, "said": None}


def ring_claimants(now: float):
    """Live-slot tenants that are relevant RIGHT NOW, most important first.

    Ties break on declaration order, so the table above is the tiebreak and
    it is readable — which is the whole complaint about "whoever was written
    last wins".
    """
    if now - _RING_CACHE["at"] < _RING_TTL_S:
        return _RING_CACHE["claimants"]
    got = []
    for i, w in enumerate(RING_WEDGES):
        if w["baked"]:
            continue
        try:
            ok = w["relevant"](now)
        except Exception as e:                  # noqa: BLE001
            # §2: "I cannot tell" is not "yes". A predicate that throws
            # must not silently claim arc; it declines, loudly, once.
            _req_say(f"ring:rel:{w['key']}:{e!r}",
                     f"ring: {w['key']} relevance failed {e!r} — not claiming")
            ok = False
        if ok:
            got.append((-w["priority"], i, w["key"]))
    got.sort()
    out = tuple(k for _p, _i, k in got)
    _RING_CACHE["at"], _RING_CACHE["claimants"] = now, out
    return out


def ring_page(rot_deg: float, n: int) -> int:
    """Which claimant the dial has turned to. Overflow, with no new
    affordance — the gesture is the one already on the device."""
    if n <= RING_SLOTS:
        return 0
    return int(abs(rot_deg) // RING_PAGE_DEG) % n


def ring_visible(now: float, rot_deg: float = 0.0):
    """The claimants holding a slot, in slot order."""
    c = ring_claimants(now)
    if not c:
        return ()
    p = ring_page(rot_deg, len(c))
    return tuple(c[(p + i) % len(c)] for i in range(min(RING_SLOTS, len(c))))


def ring_overflow(now: float, rot_deg: float = 0.0):
    """Relevant, and one spin away. Never silently dropped."""
    vis = set(ring_visible(now, rot_deg))
    return tuple(k for k in ring_claimants(now) if k not in vis)


def ring_holds_slot(key: str, now: float, rot_deg: float = 0.0) -> bool:
    """The one question the draw functions ask."""
    return key in ring_visible(now, rot_deg)


def _ring_log(now: float, rot_deg: float) -> None:
    """One line per CHANGE of tenancy, never per frame. A wedge that leaves
    the glass while somebody is reading it must not be mysterious."""
    vis, over = ring_visible(now, rot_deg), ring_overflow(now, rot_deg)
    sig = (vis, over)
    if _RING_CACHE["said"] != sig:
        _RING_CACHE["said"] = sig
        tail = (f"; {', '.join(over)} one spin away" if over
                else "; nothing waiting")
        print(f"ring: slot -> {', '.join(vis) or 'empty'}{tail}", flush=True)


# ── WHAT THE CONCIERGE HAS TO KNOW BEFORE HE OFFERS A TRADE ───────────────
#
# The owner's idea, and it is a good one: when a spoken request would add a
# wedge and the ring cannot comfortably carry another, Sterling should not
# refuse and should not quietly shrink things. He should OFFER A TRADE, in
# the register of a good hotel's front desk —
#
#     "the ring is rather full; might I suggest we retire the cyan one,
#      your daily bulletin? You can always have it back."
#
# The clips for that are somebody else's half and are already written. THIS
# half is the facts underneath them, as one pure function, so that the line
# he speaks and the thing that actually happens cannot drift apart. Which
# they will, if the wedge to retire is chosen in a prompt.
#
# ── THE SIGNATURE, so the worker can be wired to it ───────────────────────
#
#     ring_negotiate(key, now, rot_deg=0.0, priority=None) -> dict
#
#       key       the wedge being asked for. Unknown keys are fine — that is
#                 the normal case, since it has not been built yet.
#       now       epoch seconds; relevance is a function of the time of day.
#       rot_deg   the dial, because overflow lives on it.
#       priority  what the newcomer would be worth. None means "assume it
#                 sits at the bottom", which is the safe assumption: a wedge
#                 nobody has ranked must not evict one somebody did.
#
#     Returns a flat dict, every key always present:
#
#       verdict            "room" | "trade" | "known"
#       room               bool — it fits with nothing displaced
#       slots, claimants   RING_SLOTS, and who is relevant right now
#       crowd              how many claimants there would be, and the limit
#       displaces          key of what would be retired, or None
#       displaces_human    "your daily bulletin"      — for the clip
#       displaces_colour   "cyan"                     — for the clip
#       displaces_baked    bool: retiring it means re-baking base.png
#       reachable          bool: the displaced wedge is still one spin away
#       least_relevant     the weakest thing on the ring right now
#       why                one sentence, for the log and for choosing a clip
#
#     It NEVER raises and it NEVER mutates anything. It answers three
#     questions and nothing else: is there room, what is least relevant right
#     now, and what would be displaced.
#
# WHY THERE IS A CROWD LIMIT AND NOT JUST A SLOT COUNT. With overflow on the
# dial nothing is ever truly lost, so a naive reading says the ring can hold
# any number of wedges and no trade is ever needed. That is true and useless:
# at six claimants the "nice gesture" is five spins to find the one you
# wanted, and the owner would be right to say the feature got worse. The
# limit is where paging stops being a flourish and starts being a chore.
#: Three claimants against one slot is at most two spins. Past that, ask.
RING_CROWD = 3


def _ring_least_relevant(now: float, exclude: str = "", claimants=()):
    """The weakest thing ACTUALLY OCCUPYING ARC right now.

    Candidates are the five baked wedges — which hold their sectors
    unconditionally, that being what baked means — plus whichever live
    wedges are currently claiming the free slot. A live wedge outside its
    window is deliberately NOT a candidate: it is holding nothing, so
    offering to retire it would be offering to give up something the owner
    is not being shown, which is a trade that costs him and buys nothing.

    Sorted on (is it relevant now, how important is it): an object OUT OF
    ITS WINDOW is a better thing to retire than a less important one that is
    currently doing its job. At 21:00 that picks the bulletin — the cyan
    one, a morning object sitting on a permanent arc at night — which is
    exactly the trade the owner described, arrived at by rule rather than
    hard-coded.
    """
    best, best_k = None, None
    for w in RING_WEDGES:
        if w["key"] == exclude:
            continue
        if not w["baked"] and w["key"] not in claimants:
            continue
        try:
            rel = bool(w["relevant"](now))
        except Exception:                       # noqa: BLE001
            rel = True          # §2 again: cannot tell is not "retire it"
        k = (rel, w["priority"])
        if best is None or k < best:
            best, best_k = k, w
    return best_k


def ring_negotiate(key: str, now: float, rot_deg: float = 0.0,
                   priority=None) -> dict:
    """Is there room on the ring, what is least relevant, what is displaced.

    Pure, total, and cheap. See the section header above for the contract —
    it is written there rather than here because the worker reads the header
    when it wires the offer up, and a signature buried in a docstring is a
    signature somebody re-invents.
    """
    out = {"key": key, "verdict": "room", "room": True,
           "slots": RING_SLOTS, "claimants": (), "crowd": 0,
           "crowd_limit": RING_CROWD, "displaces": None,
           "displaces_human": None, "displaces_colour": None,
           "displaces_baked": False, "reachable": True,
           "least_relevant": None, "why": ""}
    try:
        claimants = ring_claimants(now)
        out["claimants"] = claimants
        known = key in RING_BY_KEY
        # Already on the ring: there is nothing to negotiate, and saying
        # otherwise would have Sterling offer to trade for something the
        # owner can already see.
        if known:
            out["verdict"] = "known"
            out["why"] = f"{key} is already on the ring"
            weakest = _ring_least_relevant(now, exclude=key,
                                           claimants=claimants)
            out["least_relevant"] = weakest["key"] if weakest else None
            return out
        crowd = len(claimants) + 1
        out["crowd"] = crowd
        weakest = _ring_least_relevant(now, exclude=key,
                                       claimants=claimants)
        out["least_relevant"] = weakest["key"] if weakest else None
        if crowd <= RING_CROWD:
            # It fits. It may not hold the slot at rest — a newcomer with no
            # declared priority sits at the bottom — but it is on the ring
            # and the dial reaches it, and NOTHING has to be given up.
            out["verdict"], out["room"] = "room", True
            pri = 0 if priority is None else int(priority)
            top = max((RING_BY_KEY[k]["priority"] for k in claimants),
                      default=-1)
            out["why"] = (
                f"room for {key}: {crowd} claimants against a limit of "
                f"{RING_CROWD}"
                + ("" if pri > top else ", reached by turning the dial"))
            return out
        # Full. Somebody has to go, and it is the weakest thing on the ring
        # rather than whoever happens to be in the slot at this instant.
        out["verdict"], out["room"] = "trade", False
        if weakest is not None:
            out["displaces"] = weakest["key"]
            out["displaces_human"] = weakest["human"]
            out["displaces_colour"] = weakest["colour"]
            out["displaces_baked"] = bool(weakest["baked"])
            # A LIVE wedge that loses its slot is still one spin away, so
            # "you can always have it back" is literally true and costs
            # nothing. A BAKED one is furniture in base.png — retiring it
            # means a re-bake, and the offer has to mean it.
            out["reachable"] = not weakest["baked"]
            out["why"] = (
                f"no room for {key}: {crowd} claimants against a limit of "
                f"{RING_CROWD}; {weakest['key']} is the least relevant "
                f"({'out of its window' if not _ring_rel(weakest, now) else 'lowest priority'})")
        else:
            out["why"] = f"no room for {key} and nothing to trade"
        return out
    except Exception as e:                      # noqa: BLE001
        # §1: it must not be able to fail silently, and it must not be able
        # to take the compose path down. A negotiation that cannot be made
        # is reported as one, once, and reads as "no room" — the direction
        # that asks a human rather than the one that quietly rearranges the
        # ring (§8: the expensive error stays the hard one to make).
        _req_say(f"ring:neg:{e!r}", f"ring: negotiation failed {e!r} — "
                                    f"answering 'no room'")
        out.update(verdict="trade", room=False,
                   why=f"negotiation failed {e!r}")
        return out


def _ring_rel(w: dict, now: float) -> bool:
    try:
        return bool(w["relevant"](now))
    except Exception:                           # noqa: BLE001
        return True


#: THE CARD. Same modal law as Sterling, settings and volume: it owns the
#: whole glass, any tap leaves, the dial is pinned while it is up, a real
#: takeover screen closes it LOUDLY, and it is painted after the dial rotate
#: in raw screen coordinates so paint and hit-tests agree.
_REQ_CARD = {"open": False, "view_deg": 0.0, "view_prev_ang": None,
             "grab_deg": 0.0, "opened_at": 0.0}


def _requests_card_set(is_open: bool, why: str) -> None:
    _REQ_CARD["open"] = is_open
    _REQ_CARD["opened_at"] = time.time() if is_open else 0.0
    print(f"requests: card {'open' if is_open else 'closed'} ({why})",
          flush=True)


def _req_plates(n: int) -> Image.Image:
    """The row plates, screened on in one pass. Cached per row count — the
    only six shapes this card can take."""
    got = _REQ_PLATES.get(n)
    if got is None:
        got = Image.new("RGB", (SIZE, SIZE), 0)
        pd = ImageDraw.Draw(got)
        for i in range(n):
            top = 250 + i * 128
            pd.rounded_rectangle([150, top, 930, top + 112], radius=22,
                                 fill=(26, 30, 48))
        _REQ_PLATES[n] = got
    return got


def draw_requests_card(frame: Image.Image, now: float) -> Image.Image:
    """The queue, newest first, capped at five.

    The wedge answers "is anything happening"; this answers "what, for whom,
    and how far". Composed in Sterling's visual language on purpose — they
    are two halves of one conversation, and the desk's scanline wash is
    already built and cached.
    """
    try:
        items = _requests()[:REQ_CARD_ROWS]
    except Exception as e:                      # noqa: BLE001
        _req_say(f"card:{e!r}", f"requests: card read failed {e!r} — empty")
        items = []
    # Deeper than Sterling's 0.16: five plates cover most of the glass, and
    # at 0.16 the $LEDGER counter and the baked wedge labels read straight
    # THROUGH them — the queue has to be the only legible thing on screen.
    frame = frame.point(lambda p: int(p * 0.09))
    try:
        frame = ImageChops.screen(frame, _ster_assets()["scan"])
    except Exception:
        pass                                    # the wash is decoration
    cx = SIZE // 2
    frame = ImageChops.screen(frame, _req_plates(len(items)))
    d = ImageDraw.Draw(frame, "RGBA")

    # ── the plate ─────────────────────────────────────────────────────────
    draw_tracked(d, cx, 92, "REQUESTS", _font(52), (232, 238, 250), 14)
    n_act = sum(1 for it in items if it["state"] in REQ_ACTIVE)
    sub = (f"{n_act} IN PROGRESS" if n_act else "NOTHING IN PROGRESS")
    f_s = _font(21)
    tw = draw_tracked(d, cx, 158, sub, f_s, SET_STEEL, 3.0)
    for sgn in (-1, 1):
        x0 = cx + sgn * (tw / 2 + 22)
        d.line([(x0, 168), (x0 + sgn * 110, 168)], fill=(62, 74, 100), width=2)

    if not items:
        msg, f_m = "nothing in progress", _font(30)
        d.text(((SIZE - d.textlength(msg, font=f_m)) / 2, 470), msg,
               font=f_m, fill=SET_STEEL)
        msg2, f_m2 = "ask Sterling for a change and watch it here", _font(22)
        d.text(((SIZE - d.textlength(msg2, font=f_m2)) / 2, 522), msg2,
               font=f_m2, fill=(96, 106, 128))
    for i, it in enumerate(items):
        col = REQ_COL.get(it["state"], REQ_COL["working"])
        top = 250 + i * 128
        d.rounded_rectangle([150, top, 930, top + 112], radius=22,
                            outline=col + (110,), width=2)
        # The dial: pct as an arc, because the arc is this device's way of
        # saying "how far" and repeating it makes the card and the wedge
        # read as one object.
        gx, gy, gr = 220.0, top + 56.0, 38.0
        gbox = [gx - gr, gy - gr, gx + gr, gy + gr]
        d.arc(gbox, 0, 360, fill=(255, 255, 255, 28), width=7)
        if it["state"] == "failed":
            d.line([gx - 15, gy - 15, gx + 15, gy + 15], fill=col + (255,),
                   width=5)
            d.line([gx - 15, gy + 15, gx + 15, gy - 15], fill=col + (255,),
                   width=5)
        elif it["pct"] > 0:
            d.arc(gbox, -90, -90 + 360.0 * it["pct"] / 100.0,
                  fill=col + (235,), width=7)
        if it["state"] != "failed":
            num = f"{it['pct']}"
            f_n = _font(26)
            nw = d.textlength(num, font=f_n)
            d.text((gx - nw / 2, gy - 17), num, font=f_n,
                   fill=(232, 238, 250))
        f_t = _font(28)
        d.text((288, top + 22), _ellipsize(d, it["text"], f_t, 610), font=f_t,
               fill=(236, 242, 250))
        who = it["who"].upper() or "SOMEONE"
        line2 = who + " · " + it["state"].upper()
        if it["detail"]:
            line2 += " · " + it["detail"]
        f_l = _font(19)
        track_text(d, (288, top + 66), _ellipsize(d, line2, f_l, 610, 1.8),
                   f_l, tuple(min(255, int(c * 0.4) + 120) for c in col), 1.8)
        # A linear repeat of the gauge along the plate's foot: at a glance,
        # five bars of different lengths say more than five numbers.
        bx0, bx1, by = 288.0, 898.0, top + 96.0
        d.line([bx0, by, bx1, by], fill=(255, 255, 255, 24), width=4)
        if it["state"] != "failed" and it["pct"] > 0:
            d.line([bx0, by, bx0 + (bx1 - bx0) * it["pct"] / 100.0, by],
                   fill=col + (225,), width=4)

    hint = "TAP ANYWHERE TO CLOSE"
    f_h = _font(19)
    draw_tracked(d, cx, 946, hint, f_h, (104, 114, 136), 4.0)
    return frame


#: THE CLINIC CARD. The worked precedent is _REQ_CARD directly above and
#: this follows it verbatim, on purpose: modal law (it owns the glass), any
#: tap leaves, the dial is PINNED while it is up, it is orientable by drag,
#: it is closed LOUDLY by any takeover screen, and it blocks a voice-opened
#: Sterling desk exactly as the queue card does. Two cards that behave
#: differently is how the stacked-screens bug got in the first time.
_PAT_CARD = {"open": False, "view_deg": 0.0, "view_prev_ang": None,
             "grab_deg": 0.0, "opened_at": 0.0}
#: The card has room for the whole day, not just the three the sector fits.
PAT_CARD_ROWS = 6
_PAT_PLATES: dict = {}


def _patients_card_set(is_open: bool, why: str) -> None:
    _PAT_CARD["open"] = is_open
    _PAT_CARD["opened_at"] = time.time() if is_open else 0.0
    print(f"patients: card {'open' if is_open else 'closed'} ({why})",
          flush=True)


def _pat_plates(n: int) -> Image.Image:
    """Row plates, screened on in one pass and cached per row count — the
    face runs at ~12fps on a Jetson and this shape never changes."""
    got = _PAT_PLATES.get(n)
    if got is None:
        got = Image.new("RGB", (SIZE, SIZE), 0)
        pd = ImageDraw.Draw(got)
        for i in range(n):
            top = 246 + i * 106
            pd.rounded_rectangle([150, top, 930, top + 92], radius=20,
                                 fill=(30, 22, 30))
        _PAT_PLATES[n] = got
    return got


def draw_patients_card(frame: Image.Image, now: float) -> Image.Image:
    """The whole clinic day, past rows included, at the size of a page.

    The wedge answers "who is next"; this answers "what is the day". Same
    visual language as the queue card — they are two readings of the same
    ring — but in the wedge's own rose, so tapping a rose sector never
    opens a gold page.
    """
    try:
        upcoming = set(_patients_upcoming(now))
    except Exception as e:                      # noqa: BLE001
        _req_say(f"pat:card:{e!r}", f"patients: card read failed {e!r} — "
                                    f"empty")
        upcoming = set()
    rows = list(_clinic_rows())[:PAT_CARD_ROWS]
    frame = frame.point(lambda p: int(p * 0.09))
    try:
        frame = ImageChops.screen(frame, _ster_assets()["scan"])
    except Exception:
        pass                                    # the wash is decoration
    cx = SIZE // 2
    frame = ImageChops.screen(frame, _pat_plates(len(rows)))
    d = ImageDraw.Draw(frame, "RGBA")

    draw_tracked(d, cx, 92, "PATIENTS", _font(52), (232, 238, 250), 14)
    n_left = len(upcoming)
    sub = (f"{n_left} STILL TO SEE" if n_left else "CLINIC CLEAR")
    f_s = _font(21)
    tw = draw_tracked(d, cx, 158, sub, f_s, SET_STEEL, 3.0)
    for sgn in (-1, 1):
        x0 = cx + sgn * (tw / 2 + 22)
        d.line([(x0, 168), (x0 + sgn * 110, 168)], fill=(62, 74, 100), width=2)

    if not rows:
        msg, f_m = "no clinic today", _font(30)
        d.text(((SIZE - d.textlength(msg, font=f_m)) / 2, 470), msg,
               font=f_m, fill=SET_STEEL)
    for i, (hhmm, name) in enumerate(rows):
        top = 246 + i * 106
        # SEEN AND STILL-TO-SEE ARE DIFFERENT WEIGHTS, NOT DIFFERENT WORDS.
        # A day list where every row shouts is a day list nobody reads; the
        # ones already past recede and the next one is the brightest thing
        # on the page.
        done = (hhmm, name) not in upcoming
        col = (92, 98, 106) if done else PAT_COL
        ink = (128, 118, 128) if done else (240, 232, 240)
        d.rounded_rectangle([150, top, 930, top + 92], radius=20,
                            outline=col + (110,), width=2)
        d.text((196, top + 26), hhmm, font=_font(34), fill=ink)
        d.text((360, top + 28), _ellipsize(d, name, _font(30), 420),
               font=_font(30), fill=ink)
        tag = "SEEN" if done else ("NEXT" if (hhmm, name) == _pat_next(upcoming)
                                   else "TO SEE")
        f_g = _font(17)
        track_text(d, (930 - track_len(d, tag, f_g, 2.4) - 34, top + 36),
                   tag, f_g, col, 2.4)

    hint = "TAP ANYWHERE TO CLOSE"
    f_h = _font(19)
    draw_tracked(d, cx, 946, hint, f_h, (104, 114, 136), 4.0)
    return frame


def _pat_next(upcoming):
    """The earliest still-to-see row, or None. Its own function so the card
    and any future caller agree on what "next" means."""
    return min(upcoming) if upcoming else None


def _power_down() -> None:
    """The confirmed path: last frame, log, then ask PID 1 to stop. If
    the call fails we SAY so on the glass — a puck that claims to power
    off and keeps glowing is the cardinal sin here (PRINCIPLES §1:
    prefer a visible failure to a silent success)."""
    frame = Image.new("RGB", (SIZE, SIZE), 0)
    d = ImageDraw.Draw(frame)
    f = face("text", 44)
    msg = "POWERING DOWN"
    tw = d.textlength(msg, font=f)
    d.text(((SIZE - tw) / 2, SIZE / 2 - 30), msg, font=f, fill=(255, 94, 94))
    try:
        blit(frame)
    except Exception as e:
        print(f"blit: {e!r}", flush=True)
    print("power: SHUTDOWN CONFIRMED", flush=True)
    try:
        rc = subprocess.run(["systemctl", "poweroff"], timeout=20).returncode
    except Exception as e:
        print(f"power: poweroff raised {e!r}", flush=True)
        rc = -1
    if rc != 0:
        _POWER["error_until"] = time.time() + 4.0
        print("power: poweroff DENIED (needs polkit/sudoers)", flush=True)


def draw_power_confirm(frame: Image.Image, remaining: float) -> Image.Image:
    """The 5s decision screen: dimmed face, red tile, and a distinct red
    ring that is the ONLY yes. A countdown arc drains around the ring so
    the deadline is visible, not sprung."""
    # 0.35 -> 0.12. The owner, live: "power screen is hard to read, dim the
    # background even more or make the font stronger". Both, in fact — a
    # confirmation for an action whose only undo is the wall plug should not
    # be competing with a starfield for contrast (§8: the expensive
    # direction gets the clearer prompt, not just the harder gesture).
    frame = frame.point(lambda p: int(p * 0.12))
    d = ImageDraw.Draw(frame)
    cx = SIZE // 2
    red = (255, 94, 94)
    f_lbl = face("bold", 48)          # was text/44: heavier, and bigger
    f_sub = face("text", 28)          # was label/26: the consequence lines
                                      # are a sentence to READ, not a chip
    d.rounded_rectangle([cx - 350, 320, cx + 350, 560], radius=28,
                        outline=red, width=4)
    # Plain text, not track_text: that helper draws glyph-by-glyph and
    # throws kerning away, which its own docstring says is only acceptable
    # for short ALL-CAPS labels. This is sentence case.
    msg = "Power down"
    tw = d.textlength(msg, font=f_lbl)
    d.text(((SIZE - tw) / 2, 348), msg, font=f_lbl, fill=(255, 238, 236))

    # THE CONSEQUENCE, STATED BEFORE THE ACTION. This is a full power down;
    # the only way back on is the wall plug. A person who does not know that
    # is one gesture away from a puck they think has died.
    for k, line in enumerate(("This is a full shut down.",
                              "To start her again, unplug the puck",
                              "and plug it back in.")):
        tw = d.textlength(line, font=f_sub)
        d.text(((SIZE - tw) / 2, 430 + k * 34), line, font=f_sub,
               fill=(246, 206, 204))

    # -- the track ------------------------------------------------------
    prog = max(0.0, min(1.0, _POWER.get("slide", 0.0)))
    y0, y1 = SLIDE_Y - SLIDE_H // 2, SLIDE_Y + SLIDE_H // 2
    d.rounded_rectangle([SLIDE_X0, y0, SLIDE_X1, y1], radius=SLIDE_H // 2,
                        fill=(38, 12, 12), outline=(120, 40, 40), width=3)
    # Filled portion: the gesture reports its own progress, so a finger that
    # stops halfway can SEE that it stopped halfway.
    if prog > 0.01:
        fx = SLIDE_X0 + (SLIDE_X1 - SLIDE_X0) * prog
        d.rounded_rectangle([SLIDE_X0, y0, max(SLIDE_X0 + 8, fx), y1],
                            radius=SLIDE_H // 2, fill=(92, 22, 22))
    hint = "slide to power off"
    tw = d.textlength(hint, font=f_sub)
    # The hint fades out as the knob travels over it.
    hv = int(190 * (1.0 - prog))
    d.text(((SIZE - tw) / 2 + 20, SLIDE_Y - 16), hint, font=f_sub,
           fill=(hv + 60, hv, hv))
    kx = SLIDE_X0 + SLIDE_KNOB_R + (SLIDE_X1 - SLIDE_X0
                                    - 2 * SLIDE_KNOB_R) * prog
    ph = 0.5 + 0.5 * math.sin(remaining * math.tau * 1.2)
    kv = int(190 + 60 * ph) if prog < SLIDE_DONE else 255
    d.ellipse([kx - SLIDE_KNOB_R, SLIDE_Y - SLIDE_KNOB_R,
               kx + SLIDE_KNOB_R, SLIDE_Y + SLIDE_KNOB_R],
              fill=(kv, 48, 44), outline=(255, 210, 206), width=3)
    # A chevron on the knob: which way, without a word.
    d.polygon([(kx - 9, SLIDE_Y - 14), (kx + 11, SLIDE_Y),
               (kx - 9, SLIDE_Y + 14)], fill=(255, 226, 222))
    if prog >= SLIDE_DONE:
        rel = "release to shut down"
        tw = d.textlength(rel, font=f_sub)
        d.text(((SIZE - tw) / 2, SLIDE_Y + 62), rel, font=f_sub,
               fill=(255, 210, 206))
    return frame


def draw_power_error(frame: Image.Image) -> Image.Image:
    """poweroff was refused — say so, plainly. Never pretend it worked."""
    # 0.35 -> 0.12. The owner, live: "power screen is hard to read, dim the
    # background even more or make the font stronger". Both, in fact — a
    # confirmation for an action whose only undo is the wall plug should not
    # be competing with a starfield for contrast (§8: the expensive
    # direction gets the clearer prompt, not just the harder gesture).
    frame = frame.point(lambda p: int(p * 0.12))
    d = ImageDraw.Draw(frame)
    cx = cy = SIZE // 2
    red = (255, 94, 94)
    f_lbl = face("text", 40)
    f_sub = face("label", 26)
    d.rounded_rectangle([cx - 360, cy - 130, cx + 360, cy + 130], radius=28,
                        outline=red, width=4)
    msg = "STILL RUNNING"
    tw = d.textlength(msg, font=f_lbl)
    d.text(((SIZE - tw) / 2, cy - 90), msg, font=f_lbl, fill=(255, 224, 220))
    sub = "power-down needs privileges — ask Sterling"
    tw = d.textlength(sub, font=f_sub)
    d.text(((SIZE - tw) / 2, cy + 20), sub, font=f_sub, fill=(220, 150, 146))
    return frame


#: ── MORE $LEDGER, BEHIND THE SAME SLIDE THE POWER BUTTON USES ────────────
#:
#: Owner: "A tap on it opens a card offering more $LEDGER. Make that tap
#: DELIBERATE — use the slide-to-confirm gesture the power-off overlay
#: already uses, never a bare tap, because an accidental brush must never
#: begin a purchase."
#:
#: So this is draw_power_confirm's twin, deliberately: same track, same
#: constants, same finger. §8 with money in it — the two directions cost
#: different amounts, so the expensive one keeps the gesture a sleeve cannot
#: produce. Opening the card is the cheap direction and stays a tap; a tap
#: anywhere on the card is a cancel, like the power overlay's.
#:
#: WHAT THE SLIDE ACTUALLY DOES, STATED ON THE CARD. Nothing here can charge
#: anybody: it writes a request file and says on the glass that it has done
#: exactly that and no more. A card that said "purchased" would be the
#: cardinal silent success — the one failure this house rules out first.
TOPUP_FILE = Path("/tmp/aura_face/ledger_topup.json")

#: ── ...AND IT COMES IN SIZES (2026-08-06, later the same day) ────────────
#:
#: Owner, by voice at the puck: "the refill card needs tiers ... a small
#: number of fixed amounts of $LEDGER — ten dollars worth, fifty, a hundred —
#: laid out as large targets a thumb can hit without aiming, in the same rose
#: gold as the dial. One is preselected: the one that would restore roughly a
#: week of range at the current burn rate, since that is the number the gauge
#: already knows. Turning the dial moves between tiers ... The slide confirms,
#: and it confirms THE SELECTED TIER, so the card must show what is about to
#: be bought in words directly above the slider — never just an amount and a
#: slider that could mean anything."
#:
#: THE EXCHANGE RATE IS DECLARED HERE AND NOWHERE ELSE, because nothing in
#: this tree prices a credit: there is no /status field for it, no stamp patch
#: carries one and home.html has no line that does. So it is ANCHORED rather
#: than invented — this card has offered exactly 50,000 credits since it
#: shipped, and the owner named fifty dollars as the middle tier, so 1,000
#: credits to the dollar keeps the amount already on the glass and makes it
#: the middle target. If a real price ever arrives it lands on this one line
#: and the three tiers re-price themselves.
LEDGER_CREDITS_PER_USD = 1000
#: Small, fixed, cheapest first — the order a thumb reads them. Three, because
#: the selector is a dial and a fourth would make it a menu.
TOPUP_TIERS = (10, 50, 100)
#: What preselection aims at ("roughly a week of range"). NOT a threshold: the
#: nearest tier wins, so there is always a selection and never a "none fits".
TOPUP_TARGET_DAYS = 7.0
#: The plates. Sized as TARGETS first — 196x120 against the 64px this face
#: treats as a comfortable finger elsewhere, so a thumb lands on one without
#: aiming. MEASURED against the round glass: the row spans x 222..858 at
#: y 356..476, and the panel's chord at y=356 runs x 32..1048, so no corner of
#: it leaves the circle. It clears the slide track (top edge y=648) by 172.
TOPUP_TIER_W, TOPUP_TIER_H, TOPUP_TIER_GAP = 196, 120, 24
TOPUP_TIER_Y = 356
#: Degrees of dial travel per tier — the volume ring's own detent pitch, so
#: the two dial gestures on this face feel like one mechanism, and the same
#: click marks each crossing.
TOPUP_TIER_DEG = 30.0
#: The failure has a voice (see _topup_say_failed). Polled by puck_conduct.
TOPUP_FAILED = Path("/tmp/aura_face/ledger_topup_failed")
_TOPUP = {"open": False, "slide": 0.0, "grab_deg": 0.0, "filed_until": 0.0,
          "error_until": 0.0, "tier": 1, "filed_usd": TOPUP_TIERS[1],
          "turn_prev_ang": None, "turn_acc": 0.0}


def _topup_tier_box(i: int):
    """Screen box of tier i — DRAWN and HIT-TESTED from this one function.

    Raw screen coordinates, like the slide it sits above: this card is painted
    after the display rotate, so there is no frame to convert between and the
    paint cannot drift from the target (volume mode's hard-won rule).
    """
    n = len(TOPUP_TIERS)
    total = n * TOPUP_TIER_W + (n - 1) * TOPUP_TIER_GAP
    x0 = (SIZE - total) / 2.0 + i * (TOPUP_TIER_W + TOPUP_TIER_GAP)
    return (x0, TOPUP_TIER_Y, x0 + TOPUP_TIER_W, TOPUP_TIER_Y + TOPUP_TIER_H)


def _topup_buys(led, usd: int):
    """How much RANGE that money buys, as words — or None.

    The owner: "State how much range it buys, not only what it costs: 'about
    nine days at your current rate' is the honest unit here."

    None is §2's third answer rather than a zero: with nothing burning there
    is no projection to make, and the card says so instead of showing the
    infinity the division would produce. Same ladder as the range plate
    (_range_text) so the two never disagree about what "a day" is.
    """
    rate = (led or {}).get("rate_real", 0.0)
    if rate <= 0.0:
        return None
    mins = usd * LEDGER_CREDITS_PER_USD / rate
    if mins < 90.0:
        n = int(round(mins))
        return f"{n} minute" + ("" if n == 1 else "s")
    hours = mins / 60.0
    if hours < 48.0:
        n = int(round(hours))
        return f"{n} hour" + ("" if n == 1 else "s")
    n = int(round(hours / 24.0))
    return f"{n} day" + ("" if n == 1 else "s")


def _topup_preselect(led) -> int:
    """The tier that restores roughly a week, per the owner's rule.

    Nearest-in-days rather than a cutoff, so it always names one: when even
    the largest tier falls short of a week it picks the largest, which is the
    honest answer to "which of these gets me closest".

    With no rate there is nothing to be nearest TO, so it falls back to the
    middle tier — which is the 50,000 credits this card offered before it had
    any (§2: the uncertain case gets its own branch, not the arithmetic's).
    """
    mid = len(TOPUP_TIERS) // 2
    rate = (led or {}).get("rate_real", 0.0)
    if rate <= 0.0:
        return mid
    best, best_d = mid, None
    for i, usd in enumerate(TOPUP_TIERS):
        days = usd * LEDGER_CREDITS_PER_USD / rate / 1440.0
        gap = abs(days - TOPUP_TARGET_DAYS)
        if best_d is None or gap < best_d:
            best, best_d = i, gap
    return best


def _topup_step(step: int) -> None:
    """One tier along, CLAMPED at the ends. The volume ring's seam stop for
    the volume ring's reason: a dial that wrapped $100 round to $10 would let
    a continuous turn change the amount by a factor of ten with no edge to
    feel, and this one has money on it (§8)."""
    i = max(0, min(len(TOPUP_TIERS) - 1, _TOPUP["tier"] + step))
    if i == _TOPUP["tier"]:
        return
    _TOPUP["tier"] = i
    _click()
    print(f"ledger: tier ${TOPUP_TIERS[i]} selected by the dial", flush=True)


def _topup_say_failed(usd: int, why) -> None:
    """A purchase that cannot be completed is SAID, not only shown.

    Owner: "If a purchase cannot be completed, say that too, out loud, rather
    than showing a card that quietly does nothing." The red card still goes
    up; this is its other half. dj_face owns no voice — the conductor owns the
    speaker — so it asks the way everything else on this face asks: a file
    puck_conduct polls and speaks.

    BEST EFFORT BY CONSTRUCTION, and stated because it matters: the thing that
    just failed was a write to this very directory, so this write can fail for
    the same reason. When it does it says so in the log rather than swallowing
    it — a failure to report a failure is the one outcome worse than the
    failure itself (§1).
    """
    try:
        TOPUP_FAILED.parent.mkdir(parents=True, exist_ok=True)
        TOPUP_FAILED.write_text(json.dumps(
            {"at": int(time.time()), "usd": usd, "why": repr(why)[:200]}))
        print(f"ledger: asked the conductor to SAY the ${usd} request failed",
              flush=True)
    except Exception as e2:
        print(f"ledger: could not even ask for the failure to be spoken "
              f"{e2!r} — the red card is the only notice", flush=True)


def _topup_file(now: float) -> None:
    """The confirmed path: file the SELECTED tier, say so, NEVER claim more."""
    usd = TOPUP_TIERS[_TOPUP["tier"]]
    credits = usd * LEDGER_CREDITS_PER_USD
    _TOPUP["filed_usd"] = usd
    try:
        part = TOPUP_FILE.with_suffix(".part")
        part.write_text(json.dumps({"at": int(now), "usd": usd,
                                    "credits": credits,
                                    "source": "puck face slide"}))
        part.replace(TOPUP_FILE)
        _TOPUP["filed_until"] = now + 5.0
        print(f"ledger: top-up REQUESTED — ${usd} ({credits:,} credits) filed "
              f"to {TOPUP_FILE}", flush=True)
    except Exception as e:
        _TOPUP["error_until"] = now + 5.0
        print(f"ledger: top-up could NOT be filed {e!r}", flush=True)
        _topup_say_failed(usd, e)


def draw_topup_card(frame: Image.Image, now: float) -> Image.Image:
    """The offer, its tiers, and the one gesture that accepts ONE of them."""
    frame = frame.point(lambda p: int(p * 0.12))
    d = ImageDraw.Draw(frame)
    cx = SIZE // 2
    # STEEL, because the dial is steel (Royal Oak pass, 2026-08-06 night).
    # The name stays `gold` on purpose: it is the card's one metal, every
    # weight below is stated against it, and renaming it would touch twelve
    # lines to say nothing. Was (236,176,132) L=188.9; this is L=188.9, so
    # not one element on this card changed weight when the hue moved.
    gold = (182, 190, 202)
    f_lbl = face("bold", 44)
    f_sub = face("text", 26)
    f_amt = face("bold", 46)
    f_cap = face("label", 17)
    d.rounded_rectangle([cx - 350, 236, cx + 350, 644], radius=28,
                        outline=gold, width=4)
    msg = "More $LEDGER"
    tw = d.textlength(msg, font=f_lbl)
    d.text(((SIZE - tw) / 2, 252), msg, font=f_lbl, fill=(233, 241, 250))
    led = _ledger_now(now)
    fig = None
    if led is not None:
        fig, _cap = _range_text(led)
    if fig and fig != "—":
        head = f"About {fig.lower()} left at this rate."
    elif led is not None:
        head = "Nothing burning — no range to project."
    else:
        head = "No reading from the reserve."
    tw = d.textlength(head, font=f_sub)
    d.text(((SIZE - tw) / 2, 312), head, font=f_sub, fill=(196, 204, 214))
    # THE TIERS. Selected = a filled rose-gold plate with dark numerals, which
    # reads as pressed from across the room; the others are the same plate
    # empty. Each carries what it BUYS as well as what it costs, so the answer
    # is on the target and not only in the confirm line under it.
    sel = _TOPUP["tier"]
    for i, usd in enumerate(TOPUP_TIERS):
        x0, y0, x1, y1 = _topup_tier_box(i)
        on = (i == sel)
        d.rounded_rectangle([x0, y0, x1, y1], radius=20,
                            fill=gold if on else (18, 24, 34),
                            outline=(231, 238, 247) if on else gold,
                            width=5 if on else 3)
        amt = f"${usd}"
        tw = d.textlength(amt, font=f_amt)
        d.text(((x0 + x1 - tw) / 2, y0 + 16), amt, font=f_amt,
               fill=(14, 20, 28) if on else gold)
        buys = _topup_buys(led, usd)
        cap = buys.upper() if buys else "RANGE UNKNOWN"
        tw = d.textlength(cap, font=f_cap)
        d.text(((x0 + x1 - tw) / 2, y0 + 82), cap, font=f_cap,
               fill=(36, 46, 60) if on else (158, 166, 178))
    hint = "turn the dial or tap to change the amount"
    tw = d.textlength(hint, font=f_cap)
    d.text(((SIZE - tw) / 2, 486), hint, font=f_cap, fill=(146, 154, 166))
    # WHAT IS ABOUT TO BE BOUGHT, IN WORDS, DIRECTLY ABOVE THE SLIDER — the
    # owner's whole point: "never just an amount and a slider that could mean
    # anything". The slide confirms THIS line, and it names the tier and the
    # range it buys before it names the gesture.
    usd = TOPUP_TIERS[sel]
    buys = _topup_buys(led, usd)
    f_ask = face("bold", 30)
    ask = f"Requesting ${usd} of $LEDGER"
    tw = d.textlength(ask, font=f_ask)
    d.text(((SIZE - tw) / 2, 516), ask, font=f_ask, fill=(233, 241, 250))
    line2 = (f"about {buys} at your current rate" if buys
             else "nothing burning — cannot say how long that lasts")
    tw = d.textlength(line2, font=f_sub)
    d.text(((SIZE - tw) / 2, 556), line2, font=f_sub, fill=(196, 204, 214))
    # THE CONSEQUENCE, STATED BEFORE THE ACTION — the power card's rule, and
    # here it is the reassuring direction: nothing is bought by this glass.
    f_note = face("text", 24)
    note = "The slide files the request. Nothing is charged."
    tw = d.textlength(note, font=f_note)
    d.text(((SIZE - tw) / 2, 596), note, font=f_note, fill=(176, 184, 196))
    prog = max(0.0, min(1.0, _TOPUP.get("slide", 0.0)))
    y0, y1 = SLIDE_Y - SLIDE_H // 2, SLIDE_Y + SLIDE_H // 2
    d.rounded_rectangle([SLIDE_X0, y0, SLIDE_X1, y1], radius=SLIDE_H // 2,
                        fill=(18, 24, 34), outline=(84, 94, 108), width=3)
    if prog > 0.01:
        fx = SLIDE_X0 + (SLIDE_X1 - SLIDE_X0) * prog
        d.rounded_rectangle([SLIDE_X0, y0, max(SLIDE_X0 + 8, fx), y1],
                            radius=SLIDE_H // 2, fill=(60, 70, 82))
    hint = f"slide to request ${usd}"
    tw = d.textlength(hint, font=f_sub)
    hv = int(190 * (1.0 - prog))
    d.text(((SIZE - tw) / 2 + 20, SLIDE_Y - 16), hint, font=f_sub,
           fill=(int(hv * 0.96), int(hv * 1.01), min(255, int(hv * 1.12))))
    kx = SLIDE_X0 + SLIDE_KNOB_R + (SLIDE_X1 - SLIDE_X0
                                    - 2 * SLIDE_KNOB_R) * prog
    ph = 0.5 + 0.5 * math.sin(now * math.tau * 1.2)
    kv = int(190 + 60 * ph) if prog < SLIDE_DONE else 255
    d.ellipse([kx - SLIDE_KNOB_R, SLIDE_Y - SLIDE_KNOB_R,
               kx + SLIDE_KNOB_R, SLIDE_Y + SLIDE_KNOB_R],
              fill=(int(kv * 0.66), int(kv * 0.70), int(kv * 0.80)),
              outline=(231, 238, 247), width=3)
    d.polygon([(kx - 9, SLIDE_Y - 14), (kx + 11, SLIDE_Y),
               (kx - 9, SLIDE_Y + 14)], fill=(20, 28, 40))
    if prog >= SLIDE_DONE:
        rel = f"release to file the ${usd} request"
        tw = d.textlength(rel, font=f_sub)
        d.text(((SIZE - tw) / 2, SLIDE_Y + 62), rel, font=f_sub,
               fill=(212, 220, 232))
    return frame


def draw_topup_notice(frame: Image.Image, ok: bool) -> Image.Image:
    """What happened, in the words that are true (§1)."""
    frame = frame.point(lambda p: int(p * 0.12))
    d = ImageDraw.Draw(frame)
    cx = cy = SIZE // 2
    gold = (182, 190, 202) if ok else (255, 94, 94)
    f_lbl = face("text", 40)
    f_sub = face("label", 26)
    d.rounded_rectangle([cx - 360, cy - 130, cx + 360, cy + 130], radius=28,
                        outline=gold, width=4)
    msg = "REQUEST FILED" if ok else "NOT FILED"
    tw = d.textlength(msg, font=f_lbl)
    d.text(((SIZE - tw) / 2, cy - 90), msg, font=f_lbl,
           fill=(233, 241, 250) if ok else (255, 224, 220))
    # The receipt names the TIER, because the tier is what was confirmed.
    _usd = _TOPUP["filed_usd"]
    sub = (f"${_usd} of $LEDGER — nothing has been charged" if ok
           else f"the ${_usd} request could not be written — see the log")
    tw = d.textlength(sub, font=f_sub)
    d.text(((SIZE - tw) / 2, cy + 20), sub, font=f_sub,
           fill=(186, 194, 206) if ok else (220, 150, 146))
    return frame


def make_stars(n: int = 150):
    """Seeded star field: (x, y, radius, phase, period). Deterministic so
    every frame agrees where the sky is."""
    s = 20260801
    out = []
    for _ in range(n):
        row = []
        for _ in range(5):
            s = (s * 1103515245 + 12345) % (1 << 31)
            row.append(s / float(1 << 31))
        x = 40 + row[0] * (SIZE - 80)
        y = 40 + row[1] * (SIZE - 80)
        out.append((x, y, 0.8 + row[2] * 2.2, row[3] * math.tau,
                    2.5 + row[4] * 4.5))
    return out


def render_lock(backdrop: Image.Image, stars, t: float) -> Image.Image:
    frame = backdrop.copy()
    d = ImageDraw.Draw(frame)
    for x, y, r, ph, period in stars:
        k = 0.18 + 0.82 * (0.5 + 0.5 * math.sin(t * math.tau / period + ph))
        v = int(220 * k)
        d.ellipse([x - r, y - r, x + r, y + r], fill=(v, v, min(255, v + 20)))
    return frame


#: ── THE DIAL'S SKY, 2026-08-06 night (Royal Oak pass) ─────────────────────
#:
#: Owner, by voice: "put a STARFIELD behind the whole dial — this face
#: already draws one on the lock screen, so reuse it rather than inventing a
#: second kind." Taken literally: make_stars() IS the generator, unchanged,
#: and its LCG is deterministic from a fixed seed — so make_stars(340) begins
#: with exactly the 150 stars the lock screen draws. The home face and the
#: door are not two skies that look alike; they are one sky, and the home
#: face simply sees further into it.
#:
#: WHAT IS NOT REUSED IS THE TWINKLE, and that is the frame-cost half of the
#: brief ("cache anything that does not change every frame"). render_lock
#: recomputes 150 ellipses every frame because the lock screen has nothing
#: else to do; the home face composites nine other things on a puck measured
#: at 96C. So the sky is baked ONCE into a tile the size of the dial field
#: and screened in — one crop and one screen of a 712px box, the idiom the
#: bolt already uses, against 135-odd ellipse draws every frame forever.
#: MEASURED on this box: 3.32 ms a frame, ~5% of the 64.5 ms compositing
#: budget the note at the top of this file states.
#:
#: A PASTE THROUGH THE STARS' OWN MASK COSTS 1.34 MS AND WAS REJECTED, which
#: is worth writing down because 2.5x is a real saving and somebody will
#: reach for it. Paste REPLACES; screen can only add. Most of this disc is
#: at L 6..26 and a star at L 40..70 would look identical either way — but
#: the power-reserve rim, the shards and the tapisserie's lit chamfers all
#: live inside this circle and are brighter than the sky, so a pasted star
#: landing on one punches a dim hole THROUGH it. A sky that eats the
#: instrument it is behind is not behind it.
#:
#: IT STOPS AT THE WEDGE RING, for the reason home.html's own texture stops
#: there: 356 display px is GUI_R1 (330 viewBox), and stars running on under
#: five translucent sector fills read as the fills being dirty rather than as
#: sky. SCREENED, never pasted — it adds light and takes none away, so the
#: tapisserie, the shards and the power-reserve sub-dial all still read
#: through it.
#: x DIAL_K, 2026-08-06 night: this radius is the WEDGE RING'S INNER EDGE and
#: nothing else — the paragraph above is an argument about where the sector
#: fills start, not about a number. They start at 285 now. Left at 356 the
#: field would have run out under all five of them, which is the one thing
#: this constant exists to prevent.
#: 2026-08-06, late night: 356 -> 397.4, the ring's inner edge again (336 ->
#: 368 viewBox). Same argument, other direction: left at 356 the sky would
#: stop 27px short of the wedges and leave a bare ring of dial between the
#: starfield and the sector fills — the "let the centre grow" half of that
#: brief, unpaid. home.html's tapisserie clip moved by the same amount in
#: the same commit, and these two edges are one edge.
DIAL_SKY_R = round(397.4 * DIAL_K)
#: DIAL_SKY_N is NOT scaled and that is deliberate: it is a count over the
#: whole 1080 canvas, from which this circle takes whatever falls inside it,
#: so it is already a DENSITY. Scaling it would thin the sky as well as
#: shrink it, which is not what compressing a dial does to its stars.
#: 340 over the full canvas is ~135 inside the dial disc (the disc is 39.8%
#: of 1080^2): dense enough to read as sky at a glance, sparse enough that no
#: two stars merge into a smudge at the owner's 45 degrees.
DIAL_SKY_N = 340
_DIAL_SKY: dict = {"tile": None, "box": None}


def dial_sky() -> tuple:
    """(tile, box) for the dial's starfield. Built once, then held."""
    if _DIAL_SKY["tile"] is None:
        r = DIAL_SKY_R
        c = SIZE // 2
        box = (c - r, c - r, c + r, c + r)
        tile = Image.new("RGB", (2 * r, 2 * r), 0)
        d = ImageDraw.Draw(tile)
        for x, y, rad, _ph, _per in make_stars(DIAL_SKY_N):
            sx, sy = x - box[0], y - box[1]
            if math.hypot(sx - r, sy - r) > r - 3:
                continue
            # BRIGHTNESS RIDES SIZE rather than a second random, because a
            # star that is large and dim reads as a smudge on this panel.
            # MEASURED THROUGH THE DUOTONE, as every weight on this dial is:
            # the field runs L 40..70 against a dial ground at 6, the
            # tapisserie's lit chamfers at 61 and the chapter ring's minute
            # hairline at 88. So only the largest stars come past the
            # machining and none of them comes near the rim — which is what
            # BEHIND the dial has to mean if the word is to mean anything.
            v = int(38 + 30 * (rad / 3.0))
            d.ellipse([sx - rad, sy - rad, sx + rad, sy + rad],
                      fill=(v, v, min(255, v + 14)))
        _DIAL_SKY["tile"], _DIAL_SKY["box"] = tile, box
    return _DIAL_SKY["tile"], _DIAL_SKY["box"]


#: ── MOONPHASE AT SIX, 2026-08-06 night (Royal Oak pass) ───────────────────
#:
#: Owner: "add a MOONPHASE and design it in rather than bolting it on: a disc
#: seen through an aperture at six o'clock showing the moon's illuminated
#: fraction computed from the real date, waxing and waning correctly, the
#: disc's own sky carrying stars ... the moonphase and the starfield are one
#: idea: the aperture should read as a window onto the same sky the dial sits
#: in."
#:
#: SO IT IS THE SAME SKY, from the same make_stars(), and the field TURNS
#: with the month — the disc of a real moonphase rotates once every synodic
#: month and the window shows a different part of it every night. That is one
#: line (MOON_SHIFT) and it is the difference between a complication and a
#: picture of one.
#:
#: WHERE IT SITS, and every clearance it had to prove. Centre (540,812) on
#: the 1080 panel, box 132x84, so ink spans x 474..606 and y 770..854 and the
#: furthest corner is r=321 from the dial centre:
#:
#:     wedge ring, inner edge      362.9   -> 42 clear, so no wedge, hit-test
#:                                            or label is touched at all
#:     power-reserve sub-dial      x<=411  -> 63 clear to the aperture's west
#:     RANGE plate (RANGE_XY/W)    x<=455  -> 19 clear
#:     #core veil (home.html)      r<=162  -> nowhere near
#:
#: IT IS DRAWN AFTER THE BOLT AND THAT IS THE POINT, not a compromise. The
#: fracture crosses six o'clock — at y=790 it is at x=488 and at y=821 at
#: x=524, straight through any aperture centred on 540 — and an APPLIED
#: window is metal laid on the dial while the bolt is light coming through
#: the dial behind it. A window the fracture crossed in FRONT of would be a
#: window made of nothing. It is still drawn before desertify(), so the moon
#: wears the colourway's polished steel and its sky the dial's own bleu nuit:
#: the aperture and the field are then literally the same two colours, which
#: is the whole of "one idea".
#: x DIAL_K, 2026-08-06 night, AND IT WAS NOT OPTIONAL: the note above
#: proves this window by its 42px of clearance to the wedge ring's inner
#: edge at 362.9. That edge is now 290.3, so an unmoved aperture would have
#: had its corners 31px INSIDE the wedges — an applied window laid across
#: five live tap targets. At DIAL_K the corner sits at r=257 and the
#: clearance comes back as 33.
#: 2026-08-06 late night: 758 -> 739, AND IT IS THE ONLY THING THE THIRD
#: COMPLICATION ASKED OF THIS ONE. Owner: "lay the three out with the balance
#: a watch would use — evenly spaced about the centre". The RESERVE's pivot
#: sits r=198.5 from the dial centre and ROOM_PIVOT mirrors it; the aperture
#: at 758 sat at r=218, so the three read as two sub-dials and something
#: hanging lower between them. 739 puts it on the same circle at exactly six
#: o'clock, 60 degrees from each. NOTHING ELSE MOVES: the window is unchanged
#: in size and shape, and it travels 19px AWAY from the wedge ring. MEASURED
#: off the rendered aperture: it inks x 494..586, y 712..766, furthest point
#: r=229.3 against that ring's inner edge at 317.9 — 88.6 clear, where at 758
#: it was 70. Its flanks keep 50px to each sub-dial's rim. The RANGE plate is
#: the one thing it approaches, and not in this axis: that plate ends at
#: x=472 and this aperture's ink starts at x=494, unchanged, because only y
#: moved.
#: ── 2026-08-06, night: IT STOPS BEING A WINDOW AND BECOMES A REGISTER ────
#: Owner, superseding the even spacing the note directly above implements:
#: "the MOONPHASE as the largest of the three, lower-left around seven, with
#: its own pointer for a date or count."
#:
#: So MOON_XY is no longer the centre of an aperture hanging on the dial. It
#: is the PIVOT of a sub-dial — flange, date track, thirty-one graduations
#: and a pointer — with the moon window sitting inside it, above the pivot,
#: which is exactly the 5712's own seven-o'clock register. r=192 at 120 deg
#: from the dial centre IS seven o'clock, and a flange of 88 makes it the
#: largest of the three by a clear margin (88 against the RESERVE's 69.1 and
#: the ROOM's 50) while still stopping at r=280 against the wedge ring's
#: padded inner edge at 287.9. POWER's disc is 60.9 clear, the RANGE plate's
#: nearest corner 17.4, the ROOM dial's flange 53.
#:
#: THE APERTURE HAD TO SHRINK SO THE REGISTER COULD GROW, and that is the
#: one trade in this pass that costs something visible. The date graduations
#: occupy r 88 down to 70, so the window's furthest corner has to stay under
#: 74 of the pivot: at 88x58, raised 28 above the pivot, it reaches 72.0. The
#: moon disc inside it therefore goes 19 -> 14 — a smaller moon inside a very
#: much larger complication. Stated rather than hidden, because "the
#: moonphase is the largest of the three" is true of the register and NOT of
#: the disc, and somebody reading this later will want to know which was
#: meant. If the disc is what he wants back, the date track is what pays.
#:
#: NO NUMERALS ON THE DATE SCALE, and it was tried before it was dropped. At
#: r=62 — the only radius inside the graduations — the numerals nearest the
#: top of the register land INSIDE the moon window, whichever day the scale
#: starts on: five of the six positions collide for a start at day 1, and two
#: do for a start at day 16. The reference watch interrupts its own numerals
#: for the same window; here the window is proportionally larger, so the
#: scale is read the way the ROOM dial is read — by a hand moving on a
#: graduated track, with day one heavy enough to be the datum.
#:
#: WHAT DID NOT CHANGE: it is still drawn after the bolt and before
#: desertify() for both the reasons above, the sky is still make_stars() so
#: it is the dial's own sky sampled rather than a second one, and the window
#: still turns with the month.
#: ── 2026-08-06, late night: THE MOONPHASE BECOMES THE SHOWPIECE ───────────
#: Owner, by voice: "make the moonphase the showpiece ... the largest thing
#: on the dial after the wordmark, and the element people notice first. Right
#: now it is a small plain aperture and it deserves better." Then, in order:
#: a DOUBLE ARCH aperture ("two curves meeting in points at either side"),
#: framed in the bezel's own polished metal and gradient; an AVENTURINE sky,
#: deep blue shot with gold flecks, darker than the dial around it; a moon
#: with a FACE (the maria) in slightly darker gold and a soft edge; and a
#: TERMINATOR that is "SOFT and curved, not a straight line and not a hard
#: cut". "Keep the 5712 asymmetry — this is the lower-left dial and the
#: largest of the three."
#:
#: IT MOVES TO AFTER desertify(), AND THAT SUPERSEDES THE TWO NOTES ABOVE
#: THAT SAY IT MUST NOT. Both of them are about colour and both were right
#: while the brief was "the moon wears the dial's own steel and blue". This
#: brief is the opposite one: warm gold against cool blue is a CONTRAST
#: between two hues, and desertify() opens with convert("L") — a duotone
#: cannot hold two hues, it can hold one ramp. Drawn before it, an aventurine
#: sky and a gold moon arrive on the glass as two greys, i.e. as a perfect
#: silent success (§1): a real edit, plausible in the diff, with no effect
#: whatsoever on what the owner asked to see. So the register is composited
#: AFTER the duotone, with the wedges and the reserve lamp, on their rule:
#: everything below desertify() carries meaning in its colour. It is still
#: after the bolt (the applied-window argument above is untouched — the bolt
#: is drawn earlier still) and still before the dial rotate, so it turns with
#: the face exactly as it did.
#:
#: WHAT THAT COSTS, PAID HERE AND NOT HIDDEN: the flange, the date track, the
#: 31 graduations and the pointer used to get their steel FROM the duotone.
#: They now have to carry it themselves, or this sub-dial would be the one
#: cool-blue instrument on a warm-neutral face. _dial_metal() puts each of
#: their source luminances through desertify()'s own ramp by hand, so they
#: land on precisely the triples they landed on yesterday and still match the
#: RESERVE and the ROOM dial beside them.
#:
#: THE APERTURE IS A LENS, which is what "two curves meeting in points at
#: either side" is: the intersection of two equal discs. One radius follows
#: from the half-width a and half-height b — R = (a^2 + b^2) / 2b — and the
#: two centres sit (R - b) above and below the window's own centre, so the
#: arcs cross at (+/-a, 0) in a cusp. Two shapes, no join to disagree at:
#: the notch the old arch-over-flanks window had to be fixed for (see the
#: note in moon_tile) cannot occur, because there is no seam.
#:
#: THE WINDOW GROWS 88x58 -> 124x84 AND THE DATE SCALE PAYS FOR IT, exactly
#: as the note above predicted it would have to ("if the disc is what he
#: wants back, the date track is what pays"). MEASURED, on the lens rather
#: than on a bounding box, because a lens has no corners: the register's
#: ticks are the only thing near it, and the closest approach of any of the
#: 31 inner tick-ends to the aperture's outline is 5.8 px, at day one —
#: which is the tick that points straight down at the window's cusp-free top
#: and therefore the one that had to move. Its inner end goes 67.2 -> 70.8
#: (0.84 -> 0.885 of MOON_TRACK) and every fifth goes 70.4 -> 72.8 (0.88 ->
#: 0.91); the other 24 do not move at all. Day one is still the longest and
#: still the heaviest, so the datum survives. Every other tick clears by
#: 8.2 or more. The flange (88) and the track circle (80) are untouched, so
#: the register's own size — the thing "largest of the three" is about — is
#: exactly what it was: 88 against the RESERVE's 69.1 and the ROOM's 50.
#:
#: THE MOON GOES 14 -> 26, by the same arithmetic the r=26/19/14 chain above
#: uses and not by scaling: the mask now inks 110x70, the frame's erosions
#: take 5 off each end, so the sky runs 60 px tall about its centre and a
#: disc of r=26 keeps 4 px of night above and below at the full moon. That
#: is 3.4x the lit area it had.
#:
#: THE POINTER NOW CROSSES THE WINDOW ON MORE DAYS THAN IT DID, and that is
#: accepted rather than worked around: today (the 6th) its centreline passes
#: 25.5 from the moon's centre against a radius of 26, so it clips the lower
#: right limb. A pointer date on the watch this is adapted from does the same
#: thing. It is drawn last for that reason and stays drawn last.
#:
#: THE FRAME IS THE BEZEL'S METAL AND NOT A LIGHTER GREY, which is the whole
#: of "the same polished metal as the bezel, with the same gradient". The
#: numbers in MOON_BEZ_L are home.html's BEZ_FLAT_L verbatim — the luminance
#: sweep ACROSS a bezel flat, 236 at the outer crease to 18 at the inner —
#: and they are then put through desertify()'s duotone by the same
#: _dial_metal ramp, which is what that page's own note says its greys are
#: for. Applied here across the frame's width, outward edge bright, inward
#: edge near-black, so the metal turns into the hole. MOON_LIT_HI/LO is
#: home.html's `up` axis, kept for the same reason it kept it: without it a
#: ring of one ramp is a washer, not a case part.
#: ── 2026-08-07: SIX O'CLOCK, AND NOW THE SIZE THE OTHER TWO COPY ─────────
#: (444,706) -> (540,732). The Royal Oak note at REG_R puts the third
#: register at six, below centre, with the other two on the horizontal
#: centreline — so this pivot goes onto the dial's own vertical axis at the
#: same r=192 it already had. NOTHING INSIDE IT CHANGES: the flange, the date
#: track, the 31 graduations, the lens and the pointer are all ratios about
#: this pivot, and the whole point of equalising UPWARD to 88 was that this
#: register — the only one with a fitted interior — did not have to be re-cut
#: to make the three match. "The moonphase is the largest of the three" is
#: therefore superseded: 88 is now simply the size, and the two beside it
#: grew to meet it. Its outward reach is unchanged at r=280 from the dial
#: centre, 7.9 inside the wedge ring's padded band, as it has been since it
#: became the showpiece.
#: (540, 732) -> (540, 748), 2026-08-07 amendment: OUT to r=208 on the same
#: 90-degree ray — all three subdials equidistant at r=208 from the dial
#: centre (see the note at RES_PIVOT). Outward reach goes r=280 -> 296,
#: still well inside the wedge band's inner edge at ~370; the inner edge
#: goes to 118 where it crowded the tourbillon's ~95 at 99. Nothing inside
#: the register changes.
#: (540, 748) -> (540, 775), 2026-08-07 amendment 2: FURTHER OUT to r=235
#: on the same 90-degree ray — all three subdials again (see the note at
#: RES_PIVOT). Outward reach goes 296 -> 325, still 45 inside the wedge
#: band's inner edge at ~370; the inner edge goes to 145 and the
#: tourbillon's ~95 finally has real air. Nothing inside the register
#: changes.
MOON_XY = (540, 775)                # the REGISTER'S PIVOT, six o'clock; was
                                    # (540,748), (540,732), (444,706)
MOON_RIM = 90                       # the flange — REG_RIM, all three now
MOON_TRACK = 80                     # the date track the pointer reads on
#: ── 2026-08-07: THE RING IS A 24-HOUR SCALE, AND THE HAND IS THE TIME ────
#: Owner, by voice at the puck: "the complications should start actually
#: doing something ... the moonphase hand follows a REAL 24-HOUR DAY against
#: its tick ring." Midnight at the BOTTOM, noon at the TOP, one revolution
#: per day, off time.localtime — the puck's own zone, never UTC and never an
#: offset constant that breaks twice a year. His spec fixes THREE points:
#: 00:00 straight down, 12:00 straight up, 18:00 at NINE o'clock — which
#: makes the sweep ANTICLOCKWISE, read as the sun's height over the day
#: rather than as a second clockwise clock. MOON_DAYS = 31 / MOON_DAY1 =
#: -90.0 (the pointer-date scale this ring was) are superseded; the tick
#: lengths that scale measured against the aperture are kept verbatim,
#: because the top tick still points straight at the window.
#: ── 2026-08-09: THE HAND BECOMES A PLAIN 12-HOUR HAND ────────────────────
#: Owner, third complaint on the same thing: "the hand for the moonphase
#: complication is still not aligned with the time right now on the 12 hour
#: scale moving clockwise." MEASURED at 07:40 — the 24-hour hand pointed at
#: the 9.8 o'clock position; a 12-hour hand points at 7.7.
#:
#: NOTHING WAS BROKEN. The scale was a correct 24-hour scale, numerals and
#: all, and the note below was a real attempt at making it say so. Three
#: failed readings by the owner is a verdict on the FORMAT, not on the
#: arithmetic: a dial whose owner has misread it three times is a failed
#: instrument however right its numbers are. So the ring and the hand are
#: 12-hour now — hour mod 12 plus minutes, clockwise, 12 at the top, two
#: revolutions a day — and the digits in the slot below (already 12-hour
#: since 2026-08-07) AGREE with the hand instead of contradicting it.
#: The moon disc behind it is untouched; the phase is real and it stays.
#: THE DAY/NIGHT DISTINCTION LEAVES THE HAND POSITION, which is the part
#: that could be misread, and lives where it cannot be: the register's own
#: sky darkens at night as a whole and its stars come out (see AND THE TWO
#: HALVES STAND ON DIFFERENT GROUND, superseded there), and on a ferrari row
#: the window itself already carries a sun crossing a lightening sky.
#: MOON_HOURS = 24 and MOON_NUMERALS = 24/6/12/18 are superseded.
MOON_HOURS = 12
#: ── 2026-08-08: A 24-HOUR DIAL HAS TO SAY THAT IT IS ONE ─────────────────
#: Owner, at 23:20: "the moon dial complication still doesn't align with
#: 11:20pm, it looks like 5:20 pm from my vantage point." HE IS NOT
#: MISREADING IT, and that is the whole of this note. At 23:20 the hand sits
#: at the 5.7 o'clock POSITION, which is exactly right for the clockwise
#: 24-hour scale above (midnight down, noon up) and indistinguishable from
#: 5:20 to any human eye. It is the inherent trap of the scale — every hour
#: looks like its 12-hour twin — so nothing done to the HAND can fix it, and
#: the two previous passes that moved the hand were both answering the wrong
#: question. The fix is the one real watches use: MAKE THE SCALE
#: UNMISTAKABLE.
#:
#: NUMERALS, four of them, at the quarters the eye already trusts: 24 at the
#: foot, 12 at the head, 6 at nine o'clock, 18 at three. They REPLACE the
#: ticks at those four hours rather than stand beside them — a numeral is a
#: stronger datum than a heavy tick, so the datum/major weights those four
#: carried are now spent on the numeral instead — and they BREAK the track
#: circle where they stand, which is what a printed scale does and what
#: keeps the ring from reading as a numeral with a line through it.
#:
#: r=74 IS MEASURED, AND IT IS THE ONLY RADIUS AVAILABLE. The band a numeral
#: can live in is bounded below by the moon window — the lens's half-height
#: is (MOON_H-14)/2 = 35 about a centre 30 above the pivot, so its highest
#: ink is r=65 — and above by the pocket wall, which _pocket_relief draws
#: inward from the rim for POCKET_WALL_W, i.e. from r=83 out. That is 18px
#: of floor; a 13pt numeral inks about 10 tall, so 74 centres it with 4.5px
#: of air at each end. INSIDE 65 WAS TRIED FIRST and fails for exactly the
#: reason the 2026-08-06 note above records the date numerals failing: the
#: window owns the top of this register, and a scale that skips its own head
#: is not a scale.
MOON_NUM_R = 74.0
MOON_NUM_SIZE = 13
#: (hour, what is printed). 2026-08-09: 12 at the head, 3/6/9 at the other
#: quarters — the four a 12-hour dial carries, standing where the 24-hour
#: ring's 24/6/12/18 stood, so the track's four gaps and the r=74 measurement
#: above are unchanged. Superseded: ((0, "24"), (6, "6"), (12, "12"),
#: (18, "18")), whose "6" at nine o'clock is exactly what was misread.
MOON_NUMERALS = ((12, "12"), (3, "3"), (6, "6"), (9, "9"))
#: The gap the track circle opens either side of a numeral, in degrees. 12 at
#: r=80 is 16.7px of clear arc against the widest numeral's 7.5px half-width.
MOON_NUM_GAP = 12.0
#: ── AND THE TWO HALVES STAND ON DIFFERENT GROUND ─────────────────────────
#: "A day-night indicator that cannot distinguish day from night is
#: decoration; this is the fix that makes it an instrument." On this scale
#: the split is exactly the horizontal diameter — 06h is nine o'clock and 18h
#: is three — so NIGHT (18h through 24h to 06h) IS the lower semicircle and
#: DAY is the upper one. Darker below with a star-field sprinkled into it,
#: lighter above. The hand's HALF is then readable before its position is,
#: which is the failure this whole block exists for.
#:
#: THE WASH STOPS AT 83, the pocket wall's inner edge, so the floor's own
#: relief is untouched by it. The two alphas are set against the ground they
#: land on rather than in the abstract (§6): the tapisserie's tops arrive at
#: luminance 40 through the duotone, SNAIL_GROUND's 44 takes the pocket floor
#: to 33.1, another 34 of black takes the night half to 28.7, and 22 of white
#: lifts the day half to 52.2 — 23.5 levels across the diameter, on a floor
#: whose whole range is 33. Neither half leaves the pocket.
MOON_WASH_R = 83.0
MOON_NIGHT_A, MOON_DAY_A = 34, 22
#: The star-field, and it is SEEDED — which is not a style point. This
#: register rebuilds once a minute (tm_min is in the cache key), so an
#: unseeded sprinkle would re-roll the sky on every rebuild: a field that
#: twinkles once a minute at random is the one thing on a dial that says
#: "software" out loud.
MOON_STAR_SEED = 4207
MOON_STARS = 42
#: -28, and the two units came off a MEASUREMENT of the tick ends rather than
#: off taste. At -30 the day-4 graduation's inner end passed 2.7 from the
#: window's steel frame, which on this panel reads as the scale running INTO
#: the window; at -28 it is 4.7 and every other tick is further. The cost is
#: that the aperture's foot now sits one unit BELOW the pivot — which the
#: hand's cap covers, and which is where the reference watch puts it anyway.
#: -30, and it is two units further up than the -28 the note above measured
#: for the same reason that note gives: the constraint is the day-one tick's
#: inner end, and the window is now 26 units taller. At -30 the aperture's
#: foot sits 5 below the pivot, which the hand's cap (5.8) still covers.
MOON_AP_DY = -30                    # the window, above the pivot
MOON_W, MOON_H = 124, 84            # was 88, 58; 106, 68; 132, 84
#: 26, MEASURED FROM THE HOLE and not chosen: the aperture's sky runs y
#: 12..72 once the frame's two erosions are taken off, so a disc of r=26
#: centred in it keeps 4px of night above and below at its widest. The first
#: cut was r=30 sitting at y=37 and the render showed the moon touching the
#: arch — full moon read as a shape cut off by the window rather than as a
#: moon behind it, which is the one thing this complication cannot do.
#: 19, not 26·0.80=21, and the two extra units are the same measurement the
#: note above makes rather than a second opinion: the frame's two erosions
#: are 3px each WHATEVER the window is, so a smaller aperture loses its
#: night from both ends. The sky now runs y 12..56 and a disc of r=19 keeps
#: 3px of it above and below at the full moon, against the 4 it had.
#: 14, 2026-08-06 night, by that same arithmetic and not by scaling: the mask
#: now runs y 7..51, the two erosions take 5 off each end, so the sky is
#: y 12..46 about a centre at 29 and r=14 keeps the same 3px of night above
#: and below at the full moon.
#: 26, 2026-08-06 late night, by that same arithmetic a fourth time: the lens
#: inks y 7..77, MOON_FRAME_W takes 5 off each end, so the sky runs y 12..72
#: about a centre at 42 and r=26 keeps 4px of night above and below at the
#: full moon. It is the radius the very first cut of this complication had,
#: recovered because the window is now large enough to hold it.
MOON_R = 26                         # the moon on the disc; 14, 19, 26
#: 2000-01-06 18:14 UTC — the reference new moon — and the mean synodic
#: month in seconds. Mean, not true: the real interval wanders about +/-7
#: hours over a year, which is under half of one step of the cache key below
#: and invisible on a 60px disc. A watch's moonphase gear is a mean-motion
#: approximation too, and a better one is not what makes this read.
MOON_EPOCH = 947182440.0
MOON_SYNODIC = 2551442.9
#: How far the disc's sky slides across the window in one month, in window
#: widths. Four is enough that no two nights show the same stars and slow
#: enough that nobody watching for a minute sees it move.
MOON_SHIFT = 4.0
#: 4x, and everything curved in this complication is drawn on it: the lens's
#: two cusps, the moon's limb and the terminator all land at angles no
#: integer-pixel ellipse can hold, and a stepped edge is the one thing that
#: says "printed on the dial" rather than "cut through it". Paid once every
#: 1.8 h behind the cache below, on a 124x84 tile — 167k supersampled pixels,
#: which is a sixth of one frame's worth and is not in the frame loop at all.
MOON_SS = 4
#: The frame's width in real pixels, and the number the MOON_R note's "5 off
#: each end" comes from: 5 erosions of ramp plus the antialiased fringe.
MOON_FRAME_W = 5
#: home.html's BEZ_FLAT_L, verbatim: (t across the band, source luminance),
#: 0 at the outer crease and 1 at the inner one. Bright silhouette, a fast
#: fall through the mid where the panel's colour correction actually works,
#: near-black where the metal turns into the hole.
MOON_BEZ_L = ((0.0, 236.0), (0.18, 168.0), (0.55, 92.0), (1.0, 18.0))
#: The other axis, home.html's `up`: the case is lit from above, so the top
#: of the frame runs brighter than its foot. Without it the ring is a washer.
MOON_LIT_HI, MOON_LIT_LO = 1.20, 0.72
#: AVENTURINE. Deep blue glass, and DARKER THAN THE DIAL AROUND IT, which is
#: the measurement this pair is set by rather than the hue: the tapisserie's
#: raised tops land at (51,36,34) through the duotone, luminance 40, and its
#: grooves at (12,9,8), luminance 10. This sky runs luminance 23 at the head
#: to 11 at the foot — under the machining it sits in and at the grooves by
#: the time it reaches the bottom of the window, so the aperture reads as a
#: hole with a lit sky behind it and never as a blue plate laid on top.
MOON_SKY_TOP = (16, 26, 62)
MOON_SKY_FOOT = (7, 11, 30)
#: The flecks. 96 in a 124x84 window against the 21 the old 88x58 one had:
#: 2.2x the density, which is the "higher density" half of the brief, and
#: 0.30 of make_stars()'s radius against the 0.55 it used, which is the
#: "finer grain" half. The count IS the density here — every star is wrapped
#: into the window — and the note above records that 180 in a window this
#: size read as a nebula. These are a third that many at a third the area
#: each, so the field is glass with gold in it rather than cloud.
MOON_FLECKS = 96
MOON_FLECK = (176, 138, 72)
#: Every ninth one catches the light, drawn a shade larger with a bloom
#: behind it — the thing that separates aventurine from blue paint with dots.
MOON_GLINT = (240, 212, 146)
#: WARM GOLD AGAINST THE COOL BLUE. Core, limb (a real disc is not flat), and
#: the maria a step darker again — "the face that makes the man in the moon".
MOON_GOLD = (247, 224, 164)
MOON_GOLD_LIMB = (214, 182, 116)
MOON_MARIA_COL = (196, 158, 96)
#: The maria, in units of the moon's own radius, x right and y down, in the
#: orientation a northern-hemisphere eye sees them: Imbrium and Procellarum
#: filling the west, Serenitatis and Tranquillitatis the eye and cheek,
#: Crisium the small dark bead on the east limb. (cx, cy, rx, ry).
MOON_MARIA = (
    (-0.34, -0.30, 0.26, 0.20),     # Imbrium
    (-0.50, 0.08, 0.22, 0.34),      # Procellarum
    (0.05, -0.27, 0.16, 0.14),      # Serenitatis
    (0.27, -0.09, 0.19, 0.16),      # Tranquillitatis
    (0.43, 0.15, 0.13, 0.15),       # Fecunditatis
    (-0.20, 0.36, 0.18, 0.13),      # Nubium
    (0.55, -0.34, 0.10, 0.09),      # Crisium
)
#: THE TERMINATOR'S SOFTNESS, in real pixels of Gaussian sigma. "A real moon
#: emerges gradually and the gradient across that edge is most of the
#: realism." 1.6 on a 52 px disc is 3% of the diameter — visible as a ramp at
#: the owner's 45 degrees, narrow enough that a quarter moon still reads as a
#: half-lit sphere and not as a smudge. The same blur softens the limb, which
#: is the other half of the brief ("a soft edge rather than a hard circle"),
#: and the disc mask it is multiplied by keeps it from bleeding into the sky.
MOON_TERM_SOFT = 1.6
#: WHICH LIMB IS LIT depends on which way up you see the moon. Owner: "make
#: the moon phase accurate in appearance given what we know about their time
#: zone" — waxing lights the RIGHT limb to a northern eye and the LEFT to a
#: southern one, and the zone NAME is hemisphere enough for a dial. Prefix
#: zones are wholly southern; the city set covers the southern entries of the
#: shared regions (America/, Pacific/, Africa/, Indian/). Near the equator
#: either answer is wrong by the same amount — the terminator there lies
#: nearly flat — so a zone missing from the set costs nothing visible on a
#: 52 px disc. Read once at import: a puck does not change hemisphere while
#: the process lives, and it restarts constantly anyway.
_MOON_SOUTH_PREFIX = ("Australia/", "Antarctica/", "America/Argentina/")
_MOON_SOUTH_CITY = frozenset((
    "Auckland", "Chatham", "Fiji", "Apia", "Noumea", "Norfolk", "Rarotonga",
    "Tahiti", "Easter", "Pitcairn", "Efate", "Guadalcanal", "Funafuti",
    "Port_Moresby", "Bougainville", "Tongatapu", "Niue", "Tarawa",
    "Santiago", "Punta_Arenas", "Sao_Paulo", "Montevideo", "Asuncion",
    "La_Paz", "Lima", "Cuiaba", "Campo_Grande", "Fortaleza", "Recife",
    "Bahia", "Maceio", "Araguaina", "Belem", "Manaus", "Porto_Velho",
    "Rio_Branco", "Eirunepe", "Santarem",
    "Johannesburg", "Windhoek", "Maputo", "Harare", "Lusaka", "Gaborone",
    "Maseru", "Mbabane", "Kigali", "Bujumbura", "Dar_es_Salaam",
    "Lubumbashi", "Luanda", "Blantyre", "Antananarivo", "Mauritius",
    "Reunion", "Mahe", "Kerguelen", "Cocos", "Christmas",
))


def _tz_south() -> bool:
    tz = os.environ.get("TZ", "")
    if not tz:
        try:
            tz = os.readlink("/etc/localtime")
        except OSError:
            try:
                tz = Path("/etc/timezone").read_text().strip()
            except OSError:
                tz = ""
    tz = tz.split("zoneinfo/")[-1].strip()
    return (tz.startswith(_MOON_SOUTH_PREFIX) or
            tz.rsplit("/", 1)[-1] in _MOON_SOUTH_CITY)


MOON_SOUTH = _tz_south()
_MOON: dict = {"key": None, "tile": None, "mask": None}


def _dial_metal(lum: float, alpha: int = 255) -> tuple:
    """A SOURCE luminance through desertify()'s own duotone, by hand.

    The moonphase register is composited AFTER the colourway now (see the
    note at MOON_XY), so it no longer gets the dial's metal for free. This is
    the same piecewise ramp ImageOps.colorize applies — black at 0, mid at
    128, white at 255 — so a tick written as _dial_metal(224) lands on the
    triple it landed on when the duotone was doing it, and this sub-dial goes
    on matching the two beside it, which still pass through desertify().
    """
    lo, hi, t = ((DESERT_BLACK, DESERT_MID, lum / 128.0) if lum <= 128 else
                 (DESERT_MID, DESERT_WHITE, (lum - 128.0) / 127.0))
    return tuple([int(round(lo[i] + t * (hi[i] - lo[i]))) for i in range(3)]
                 + [alpha])


#: ── 2026-08-09: THE DAY/NIGHT, ferrari's answer to the moonphase ──────────
#: A row that sets `moon="daynight"` shows the sun crossing this window
#: instead of a phased moon. Everything else about the register — the
#: double-arch aperture, its derived frame, the recessed time slot, the
#: 24-hour ring and hand — is untouched and was already a day/night's
#: furniture; see the branch in moon_tile.
#: THE COLOURS ARE VALUE, NOT HUE, on purpose: this layer is composited AFTER
#: desertify(), so whatever it carries reaches the panel raw, and a blue sky
#: on a carbon dial is the leftover-colour failure PAT_COL keeps a note on.
#: Day is aluminium, night is carbon, and the only saturated thing in the
#: window is the sun.
MOON_DAYNIGHT = _THEME.get("moon") == "daynight"
DN_NIGHT_TOP, DN_NIGHT_FOOT = (11, 11, 13), (4, 4, 6)
DN_DAY_TOP, DN_DAY_FOOT = (152, 154, 162), (84, 86, 94)
DN_SUN = (255, 186, 84)
DN_SUN_HOT = (255, 240, 212)
DN_SUN_R = 0.115                    # of the window's width
#: The mix band is deliberately wider than the sun's own track, so the window
#: goes through dusk and dawn instead of snapping between two states at six
#: o'clock: at 19:00 the sky still carries 13% of the day.
DN_MIX_LO, DN_MIX_SPAN = -0.34, 0.75   # solar altitude -> how much day


def _day_frac(now: float) -> float:
    """Local time of day as 0..1 from midnight. LOCAL and not UTC — the
    register beside it (_moon12_ang) reads the wall clock, and a sun an hour
    out of step with the hand pointing at it is worse than no sun."""
    lt = time.localtime(now)
    return ((lt.tm_hour * 3600 + lt.tm_min * 60 + lt.tm_sec) / 86400.0)


def _daynight_sky(now: float, sw: int, sh: int, ss: int) -> "Image.Image":
    """The window's interior on a day/night row: sky by the hour, sun by the
    hour, nothing else. Supersampled like the sky it replaces."""
    f = _day_frac(now)
    alt = -math.cos(f * math.tau)               # -1 at midnight, +1 at noon
    k = max(0.0, min(1.0, (alt - DN_MIX_LO) / DN_MIX_SPAN))
    top = tuple(int(round(a + (b - a) * k))
                for a, b in zip(DN_NIGHT_TOP, DN_DAY_TOP))
    foot = tuple(int(round(a + (b - a) * k))
                 for a, b in zip(DN_NIGHT_FOOT, DN_DAY_FOOT))
    sky = Image.new("RGB", (sw, sh), top)
    ds = ImageDraw.Draw(sky)
    for yy in range(sh):
        t = yy / (sh - 1.0)
        ds.line([(0, yy), (sw, yy)],
                fill=tuple(int(round(top[i] + t * (foot[i] - top[i])))
                           for i in range(3)))
    # The sun's own track: up at the left cusp at 06:00, over the top at
    # noon, down at the right cusp at 18:00. Outside that it is below the
    # horizon and simply is not drawn — which is what makes the window read
    # as night rather than as a dimmer day.
    u = (f - 0.25) / 0.5
    if 0.0 <= u <= 1.0:
        r = DN_SUN_R * sw
        x = sw * (0.12 + 0.76 * u)
        y = sh * (0.74 - 0.50 * math.sin(math.pi * u))
        # ...and it FADES UP over the first and last twenty minutes of its
        # own track, or the disc would blink into existence at 06:00 sharp.
        g = min(1.0, math.sin(math.pi * u) * 3.0)
        glow = Image.new("RGB", (sw, sh), 0)
        ImageDraw.Draw(glow).ellipse([x - r * 2.6, y - r * 2.6,
                                      x + r * 2.6, y + r * 2.6],
                                     fill=tuple(int(c * 0.34 * g)
                                                for c in DN_SUN))
        sky = ImageChops.screen(sky, glow.filter(
            ImageFilter.GaussianBlur(ss * 1.6)))
        ds = ImageDraw.Draw(sky)
        sun = Image.new("RGB", (sw, sh), 0)
        dsu = ImageDraw.Draw(sun)
        dsu.ellipse([x - r, y - r, x + r, y + r], fill=DN_SUN)
        dsu.ellipse([x - r * 0.5, y - r * 0.5, x + r * 0.5, y + r * 0.5],
                    fill=DN_SUN_HOT)
        m = Image.new("L", (sw, sh), 0)
        ImageDraw.Draw(m).ellipse([x - r, y - r, x + r, y + r],
                                  fill=int(round(255 * g)))
        sky.paste(sun, (0, 0), m)
    return sky


def moon_phase(now: float) -> tuple:
    """(phase 0..1 from new moon, illuminated fraction, waxing?)."""
    p = ((now - MOON_EPOCH) % MOON_SYNODIC) / MOON_SYNODIC
    return p, (1.0 - math.cos(p * math.tau)) / 2.0, p < 0.5


def moon_tile(now: float) -> tuple:
    """(tile, mask) for the aperture. Rebuilt ~every 1.8 h, not every frame.

    The key is the phase quantised to 400 steps: one step is 1.8 hours and
    moves the terminator by well under a pixel on a 60px moon, so a finer
    key would buy nothing and pay for it in the frame loop.
    """
    p, _frac, waxing = moon_phase(now)
    # On a day/night row the phase is not what moves — the SUN is. Key on the
    # local hour in 6-minute steps (240 a day), which walks the sun about
    # 0.7px across this window: the same "well under a pixel, so a finer key
    # would buy nothing" rule the 400 phase steps above are set by. The
    # +1000 keeps the two key spaces from ever colliding.
    key = (1000 + int(_day_frac(now) * 240.0) if MOON_DAYNIGHT
           else int(p * 400))
    if _MOON["key"] == key and _MOON["tile"] is not None:
        return _MOON["tile"], _MOON["mask"]
    w, h = MOON_W, MOON_H
    ss = MOON_SS
    sw, sh = w * ss, h * ss

    # THE DOUBLE ARCH, cut as the intersection of two equal discs — which is
    # what "two curves meeting in points at either side" is, exactly. R
    # follows from the half-width and half-height (see the note at MOON_XY);
    # the two centres sit (R - b) either side of the window's own middle, so
    # the arcs cross in a cusp at each flank and there is NO JOIN AT ALL.
    # That is the point of doing it this way rather than as two drawn edges:
    # the arch-over-flanks window this replaces had to be fixed once for a
    # notch where its two shapes disagreed, and an intersection cannot have
    # one. Supersampled, because a cusp on the integer grid is a staircase.
    a, b = (w - 14) / 2.0, (h - 14) / 2.0
    rr_lens = (a * a + b * b) / (2.0 * b)
    cx, cy = w / 2.0, h / 2.0
    lobes = []
    for sgn in (1.0, -1.0):
        lo = Image.new("L", (sw, sh), 0)
        ccy = cy + sgn * (rr_lens - b)
        ImageDraw.Draw(lo).ellipse(
            [(cx - rr_lens) * ss, (ccy - rr_lens) * ss,
             (cx + rr_lens) * ss, (ccy + rr_lens) * ss], fill=255)
        lobes.append(lo)
    mask = ImageChops.darker(lobes[0], lobes[1]).resize(
        (w, h), Image.BILINEAR)

    # ── 2026-08-09: ON THE FERRARI THIS WINDOW IS A DAY/NIGHT ──────────
    # Owner: "the moonphase becomes a plain 24-hour day-night in this
    # theme (a moon on a race car is wrong)". The APERTURE is untouched —
    # the double-arch mask above, the derived frame below, the recessed
    # time slot inside it and the 24-hour ring outside it are the
    # register, and they are all correct for a day/night already. The one
    # thing that changes is WHAT IS BEHIND THE GLASS, so this branch
    # replaces the aventurine sky and the phased gold moon with a sky the
    # hour drives and a sun that crosses it (_daynight_sky).
    # WHY THE NIGHT WINDOW IS ALLOWED TO BE EMPTY, which would normally be
    # the silent-failure smell (§1): it is not empty. The digital TIME is
    # read in this window (_moon_time_aperture), and the 24-hour hand runs
    # round its rim — a dark sky with the time in it is a night reading,
    # and there is no state in which this register shows nothing.
    if MOON_DAYNIGHT:
        sky = _daynight_sky(now, sw, sh, ss)
    else:
        # THE AVENTURINE SKY, drawn on the supersampled grid so a fleck can be
        # smaller than a pixel — which is what "finer grain" has to mean on a
        # window this size. A vertical fall from head to foot before anything
        # else: the depth in the window is most of what makes it read as a hole.
        sky = Image.new("RGB", (sw, sh), MOON_SKY_TOP)
        ds = ImageDraw.Draw(sky)
        for yy in range(sh):
            k = yy / (sh - 1.0)
            ds.line([(0, yy), (sw, yy)],
                    fill=tuple(int(round(MOON_SKY_TOP[i] +
                                         k * (MOON_SKY_FOOT[i] - MOON_SKY_TOP[i])))
                               for i in range(3)))
        # THE GOLD IN THE GLASS. Still make_stars(), still wrapped into the
        # window, so this is the dial's own sky seen at closer range and not a
        # second one drawn — the "one idea" the first note here is about. What
        # changed is what the flecks are made of: gold rather than starlight,
        # because aventurine is glass with metal in it.
        shift = p * sw * MOON_SHIFT
        glint = Image.new("RGB", (sw, sh), 0)
        dg = ImageDraw.Draw(glint)
        for i, (sx, sy, rad, _ph, _per) in enumerate(make_stars(MOON_FLECKS)):
            px, py = (sx * ss + shift) % sw, (sy * ss) % sh
            r1 = rad * ss * 0.30
            k = rad / 3.0
            col = tuple(int(round(MOON_FLECK[j] * (0.62 + 0.38 * k)))
                        for j in range(3))
            ds.ellipse([px - r1, py - r1, px + r1, py + r1], fill=col)
            # A FEW BRIGHTER FLECKS CATCHING LIGHT: a hard core and a bloom
            # behind it, screened in so it can only add. Aventurine glitters at
            # a handful of points and lies quiet everywhere else; every fleck
            # catching light is a glitter texture, not a stone.
            if i % 9 == 0:
                r2 = r1 * 1.5
                ds.ellipse([px - r2, py - r2, px + r2, py + r2], fill=MOON_GLINT)
                r3 = r1 * 3.0
                dg.ellipse([px - r3, py - r3, px + r3, py + r3],
                           fill=tuple(int(c * 0.45) for c in MOON_GLINT))
        sky = ImageChops.screen(sky, glint.filter(
            ImageFilter.GaussianBlur(ss * 1.1)))

        # THE MOON. A disc with a soft limb, a face, and a terminator that is a
        # gradient rather than an edge — built as three separate images because
        # each is a different question: WHERE the moon is, WHAT it is made of,
        # and HOW MUCH of it the sun is on tonight.
        mx, my = sw / 2.0, sh / 2.0
        rm = MOON_R * ss
        disc = Image.new("L", (sw, sh), 0)
        ImageDraw.Draw(disc).ellipse([mx - rm, my - rm, mx + rm, my + rm],
                                     fill=255)
        disc = disc.filter(ImageFilter.GaussianBlur(ss * 0.55))
        # The body, limb-darkened: a sphere is not a flat disc and the edge of
        # one is turning away from the light. Concentric, from the limb inward.
        body = Image.new("RGB", (sw, sh), MOON_GOLD_LIMB)
        db = ImageDraw.Draw(body)
        for step in range(int(rm), 0, -1):
            k = 1.0 - (step / rm) ** 3
            db.ellipse([mx - step, my - step, mx + step, my + step],
                       fill=tuple(int(round(lo + k * (hi - lo))) for lo, hi
                                  in zip(MOON_GOLD_LIMB, MOON_GOLD)))
        # THE MARIA, blurred and then held back to 82%: they are a shading on the
        # same gold, not a second colour painted on it. At full strength they
        # read as holes in the moon; the man in the moon is a smudge you resolve
        # rather than a stencil.
        maria = Image.new("L", (sw, sh), 0)
        dmr = ImageDraw.Draw(maria)
        for fx, fy, frx, fry in MOON_MARIA:
            dmr.ellipse([mx + (fx - frx) * rm, my + (fy - fry) * rm,
                         mx + (fx + frx) * rm, my + (fy + fry) * rm], fill=255)
        maria = maria.filter(ImageFilter.GaussianBlur(ss * 1.3))
        body.paste(Image.new("RGB", (sw, sh), MOON_MARIA_COL), (0, 0),
                   maria.point(lambda v: int(v * 0.82)))
        # THE TERMINATOR, ROW BY ROW AND THEN BLURRED. The shadow edge on a
        # sphere lit from the side is an ellipse sharing the disc's minor axis,
        # so at row dy the lit limb runs from w*cos(theta) to +w (waxing) or -w
        # to -w*cos(theta) (waning), where theta is 2*pi*phase. That single
        # expression is what makes the crescent open on the RIGHT going into full
        # and close on the LEFT coming out of it — the thing "waxing and waning
        # correctly" means, and the thing a fraction alone cannot say. The blur
        # over it is the SOFTNESS the brief asks for and the multiply by the disc
        # is what stops that softness leaking past the limb into the sky.
        lit = Image.new("L", (sw, sh), 0)
        dl = ImageDraw.Draw(lit)
        cth = math.cos(p * math.tau)
        for dy in range(-int(rm), int(rm) + 1):
            hw = math.sqrt(max(0.0, rm * rm - dy * dy))
            if hw < 0.6:
                continue
            # A southern eye sees the same phase mirrored, so "waxing lights
            # the right limb" holds only north of the equator (MOON_SOUTH).
            la, lb = (hw * cth, hw) if waxing is not MOON_SOUTH \
                else (-hw, -hw * cth)
            if lb - la < 0.6:
                continue
            dl.line([(mx + la, my + dy), (mx + lb, my + dy)], fill=255)
        lit = ImageChops.multiply(
            lit.filter(ImageFilter.GaussianBlur(MOON_TERM_SOFT * ss)), disc)
        sky.paste(body, (0, 0), lit)

    tile = Image.new("RGB", (w, h), 0)
    tile.paste(sky.resize((w, h), Image.BILINEAR), (0, 0), mask)
    # THE FRAME, DERIVED FROM THE MASK rather than drawn a second time. An
    # outline drawn round a cusp meets itself at an angle and leaves a spur;
    # an erosion difference follows whatever the aperture actually is, so the
    # frame can never disagree with the hole. What is new is that it is the
    # BEZEL'S METAL: MOON_BEZ_L's sweep laid across the band one erosion at a
    # time, bright at the silhouette and near-black where it turns into the
    # hole, top-lit by MOON_LIT_HI/LO, and finally put through desertify()'s
    # own duotone — because this layer is composited after that pass now and
    # has to carry the colourway itself (the note at MOON_XY).
    # THRESHOLDED FIRST, and that is a fix rather than a tidy: eroding the
    # ANTIALIASED mask makes every ring soft, the five of them blend into one
    # another, and the 236 at the outer crease — the specular that says
    # polished — lands on a fringe that is half transparent and arrives dim.
    # The rings come off a hard edge so each is exactly one pixel of the
    # ramp; the tile is still pasted through the soft mask, so the only thing
    # feathered is the aperture's own outline against the dial.
    band = Image.new("L", (w, h), 0)
    prev = mask.point(lambda v: 255 if v >= 128 else 0)
    outer = prev
    for step in range(MOON_FRAME_W):
        er = prev.filter(ImageFilter.MinFilter(3))
        t = (step + 0.5) / MOON_FRAME_W
        lum = MOON_BEZ_L[-1][1]
        for (t0, l0), (t1, l1) in zip(MOON_BEZ_L, MOON_BEZ_L[1:]):
            if t <= t1:
                lum = l0 + (l1 - l0) * (t - t0) / (t1 - t0)
                break
        ramp = Image.new("L", (w, h), 0)
        dr = ImageDraw.Draw(ramp)
        for yy in range(h):
            up = MOON_LIT_HI + (MOON_LIT_LO - MOON_LIT_HI) * (yy / (h - 1.0))
            dr.line([(0, yy), (w, yy)],
                    fill=max(0, min(255, int(round(lum * up)))))
        band.paste(ramp, (0, 0), ImageChops.difference(prev, er))
        prev = er
    # A HALF-PIXEL OF BLUR ON THE RAMP, not on the shape: the hard edge above
    # buys a crisp specular and pays for it with a one-pixel staircase along
    # the two arcs. Blurring the LUMINANCE smooths that back out while the
    # band's own outline — which is what the eye reads as the aperture — is
    # still the antialiased mask it was cut from.
    tile.paste(ImageOps.colorize(band.filter(ImageFilter.GaussianBlur(0.7)),
                                 DESERT_BLACK, DESERT_WHITE, mid=DESERT_MID),
               (0, 0), ImageChops.difference(outer, prev))
    _MOON["key"], _MOON["tile"], _MOON["mask"] = key, tile, mask
    return tile, mask


#: The whole register, cached on (moon step, day of month) — the only two
#: things on it that can move. Both change on the order of hours, so the
#: frame loop pays one paste of a 184px tile and nothing else; the aperture
#: alone used to cost the same. Keyed rather than built once because the day
#: DOES turn while this process is up, and a pointer that stops on the 6th
#: because the register was cached on the 6th is the silent failure this file
#: keeps a section on.
_MOON_REG: dict = {"key": None, "lay": None}


def _moon12_ang(h: float, m: float = 0.0, s: float = 0.0) -> float:
    """The hand's angle, degrees, in pt()'s cos/sin frame (0 is three
    o'clock, 90 is straight DOWN — y runs down).

    TWELVE-HOUR, 2026-08-09 (THE HAND BECOMES A PLAIN 12-HOUR HAND): hour
    mod 12 plus the minutes, clockwise, 12 straight up, two revolutions a
    day. -90 is the offset that puts hour 0 at the head.

    Superseded, and kept because the reasoning below is still why this hand
    runs clockwise: it was `90 + 360 * (h + m/60 + s/3600) / 24`, one
    revolution a day with midnight at the foot.

    CLOCKWISE, 2026-08-08. It ran anticlockwise because an early brief put
    18:00 at nine o'clock and the direction followed from that point. On
    the glass the owner read 21:32 as wrong twice ("the hand should be past
    the 9 o'clock tick and it's at the 7") — the hand was obeying the rule
    and the RULE was the problem. His ruling: "the hand on the dial should
    definitely move clockwise, that's just intuitive for the average
    person." He is right, and it is also the standard day-night indicator:
    midnight down, noon up, 06:00 at nine and 18:00 at three, travelling
    the way every other hand on every other watch travels. Angles increase
    clockwise in this frame (0 right -> 90 down), so the sign flips.
    """
    return -90.0 + 360.0 * (((h % 12) + m / 60.0 + s / 3600.0) / 12.0)


_MOON12_CHECKED = False


def _moon12_check() -> None:
    """The bake check, once per process and LOUD on a mismatch (§1): the
    three times the owner named, each angle turned back into a CLOCK
    POSITION from its own vector — which is the unit he read the dial in and
    complained in — and compared with what he asked for.

    Reported in clock positions and not compass words (which is what the
    24-hour check printed) because the failure this replaces was a hand at
    the 9.8 o'clock position at 07:40: "nine o'clock" was the right compass
    word for it and told nobody anything."""
    global _MOON12_CHECKED
    if _MOON12_CHECKED:
        return
    _MOON12_CHECKED = True
    for hh, mm, want in ((7, 40, 7.7), (15, 20, 3.3), (0, 0, 12.0)):
        a = _moon12_ang(hh, mm)
        t = math.radians(a)
        # angle -> clock position: -90 deg is 12, and 30 deg is one hour.
        pos = ((a + 90.0) / 30.0) % 12.0
        got = 12.0 if abs(pos) < 1e-6 else pos
        ok = abs(got - want) < 0.06 or abs(got - want) > 11.94
        print(f"moon12: {hh:02d}:{mm:02d} hand a={a:+.1f} "
              f"(dx={math.cos(t):+.2f} dy={math.sin(t):+.2f}) points to "
              f"{got:.1f} o'clock ({'ok' if ok else 'WRONG'}, "
              f"want {want:.1f})", flush=True)


_MOON_TIME_CHECKED = False


def _moon_time_check() -> None:
    """The slot's bake check, once per process and LOUD on a mismatch (§1):
    the two numbers the owner asked for by name.

    THE CLEARANCE IS NOT A SWEPT DISTANCE. The hand is cut out of the mouth
    before the digits are set (THE TIME COMES BACK INSIDE at MOON_TIME_DY),
    so the closest hand ink can EVER come to digit ink is the gap from the
    ink to the mouth's outline — the same figure at every minute of every
    hour, which is why one number covers all 24.

    MEASURED ON THE INK, not on the bounding box, and the difference is most
    of the answer: the box's own corners are what come nearest the mouth's
    rounded ends and they are exactly where there is no ink (the widest
    strings end in 'm', whose right edge stops at the baseline while the box
    runs on down to the 'p' descender). The box gives 1.8px here and the ink
    gives more than twice that. So each hour's worst string is rendered — the
    widest and the tallest of its sixty minutes, the two that can own the
    extremes — set exactly as the live path sets it, and scanned row by row
    through crop().getbbox(), which keeps the scan in C. The mouth is a
    stadium: inside it the distance to the wall is h/2 - |y| under the
    straight run and radial from the cap centre beyond it.
    """
    global _MOON_TIME_CHECKED
    if _MOON_TIME_CHECKED:
        return
    _MOON_TIME_CHECKED = True
    w, h = MOON_TIME_AP
    rr, flat = h / 2.0, w / 2.0 - h / 2.0

    def wall(dx: float, dy: float) -> float:
        return (rr - abs(dy) if abs(dx) <= flat else
                rr - math.hypot(abs(dx) - flat, dy))

    cand, far = set(), None
    for hh in range(24):
        wide = tall = None
        for mm in range(60):
            txt = f"{hh % 12 or 12}:{mm:02d}{'am' if hh < 12 else 'pm'}"
            bb = face_for(txt, "text", MOON_TIME_SIZE).getbbox(txt)
            iw, ih = (bb[2] - bb[0]) / 2.0, (bb[3] - bb[1]) / 2.0
            if wide is None or iw > wide[0]:
                wide = (iw, txt)
            if tall is None or ih > tall[0]:
                tall = (ih, txt)
            reach = math.hypot(iw, MOON_TIME_DY + ih)
            if far is None or reach > far[0]:
                far = (reach, txt)
        cand.update((wide[1], tall[1]))
    worst = None
    for txt in sorted(cand):
        tf = face_for(txt, "text", MOON_TIME_SIZE)
        bb = tf.getbbox(txt)
        ink = Image.new("L", (w, h), 0)
        draw_centred(ImageDraw.Draw(ink), w / 2.0,
                     h / 2.0 - (bb[1] + bb[3]) / 2.0, txt, tf, 255)
        for yy in range(h):
            row = ink.crop((0, yy, w, yy + 1)).getbbox()
            if row is None:
                continue
            dy = yy + 0.5 - h / 2.0
            for xx in (row[0] + 0.5, row[2] - 0.5):
                gap = wall(xx - w / 2.0, dy)
                if worst is None or gap < worst[0]:
                    worst = (gap, txt)
    gap, txt = worst
    print(f"moon-time: slot at +{MOON_TIME_DY:.0f}, mouth {w}x{h}; the hand "
          f"is cut out of it, so the digits keep {gap:.1f}px of it at every "
          f"one of the 24 hours (worst string {txt}) "
          f"({'ok' if gap > 0 else 'WRONG, the hand reaches the digits'}); "
          f"digit box reaches r={far[0]:.1f} on {far[1]} against the "
          f"register's {MOON_RIM} "
          f"({'inside' if far[0] < MOON_RIM else 'OUTSIDE THE SUBDIAL'})",
          flush=True)


#: ── 2026-08-08, PREMIUM PASS: THE TIME RECESSES ───────────────────────────
#: Owner, by voice: "the time at the 12 o'clock should look recessed like
#: some watches have." The twelve-o'clock pill is retired (headstone at
#: CLOCK_BOX) and the digital time reads in this register on every theme, so
#: the recess lands here: the digits' patch of pocket floor becomes a
#: pill-shaped aperture under the ONE upper-left sky (POCKET_KEY), per the
#: docs/PREMIUM.md standard — interior wall lit BACKWARDS (bright
#: lower-right, the pocket walls' own arithmetic), floor a step darker than
#: the pocket ground it is cut into, a polished chamfer where the mouth
#: meets the dial (the rims' relief pair), and the dial's overhang laying a
#: whisper of shadow inside the upper edge. Baked ONCE per process into a
#: tile _moon_register pastes at each rebuild; the digits keep their
#: existing live path and are simply set ON the new floor.
#:
#: THE MOUTH IS MEASURED, NOT CHOSEN. The widest 12-hour time in the "text"
#: face at 22 is 10:00am at 86px and the tallest ink spans 22 (a meridiem
#: descender), so the mouth is 86+2*7 wide by 22+2*5 tall. The side pad is
#: 7 where the patients aperture keeps 9 because of what stands nearby: at
#: half-width 52 the 3/21-hour ticks' inner ends (53.2, 53.2 off the pivot)
#: pass 3.5px from the mouth — the scale reads as running INTO the window
#: (the -28 note above measured 2.7 as exactly that) — and at 50 they pass
#: 5.3. The foot tick's inner end keeps 10.8 below the mouth, the moon
#: window's foot 16 above it, and the register's own wall 11.4 beyond the
#: mouth's furthest point.
#:
#: ── 2026-08-08: THE TIME CLEARS THE HAND ─────────────────────────────────
#: Owner, by voice: "the moonphase clock is being EATEN BY ITS OWN HAND ...
#: what he read was a 9 with the 24-hour hand lying across it ... the time
#: is periodically unreadable and, worse, MISREADABLE — a wrong number is
#: worse than no number." (The zone was never wrong: 21:34 local, correct
#: to the minute. He read 6:23 off a hand lying over the digits.)
#:
#: MEASURED FIRST, AND THE MEASUREMENT KILLED BOTH OF THE OBVIOUS FIXES.
#: The hand turns once a day, so its ink covers the WHOLE disc of radius
#: 68*(MOON_TRACK/72) = 75.6 about the pivot: every radius inside that is
#: crossed at some hour, wherever on the register the digits are put. A day
#: simulated at one-minute steps against the old +44 gave 0.00 px of gap
#: between hand ink and digit ink from 20:00 through 03:59, and 4.00 px at
#: noon where the counterpoise comes down. Seven hours a day of a wrong
#: number, which is exactly what he read.
#:   - "below the pivot but OUTSIDE the hand's length", kept inside the
#:     flange, means the annulus 75.6..90 — 14.4 px of room for ink that is
#:     22 px tall, and the tick band and the 00 datum tick already live
#:     there. It does not fit at any font this dial is allowed to use (the
#:     micro-typography note at _MICRO_TILES: these captions were already
#:     "hard to read", so shrinking them is not available).
#:   - "the hand shortened so it cannot reach" needs the tip at 44 px for a
#:     slot that still fits inside the flange: 40 of the 72-unit track, less
#:     than half the register, stopping 27 px short of the scale it exists
#:     to point at. A hand that cannot reach its own graduations is not a
#:     24-hour hand — see WHAT DELIBERATELY SURVIVES THE BATON at HAND_SHAFT.
#:
#: So THE HAND IS UNTOUCHED — full length, tip still into the tick band,
#: identity intact — and the digits leave the flange instead: the slot drops
#: to +112, centred in the open dial between the register's rim (90 off the
#: pivot) and the wedge ring's inner edge (WEDGE_R0 minus this pivot's own
#: 235 = 134.6). 6.3 px of air above the mouth, 6.6 below, and the digit ink
#: clears the hand's farthest reach by 25.4 px at every minute of the day.
#: The mouth itself is unchanged, so the measurements above still describe
#: it; what they measure it AGAINST is superseded, because its neighbours
#: are now the flange above and the wedge band below rather than the ticks.
#: The slot keeps its own floor, wall and chamfer, so the time still stands
#: on its own ground — the dial it is now cut into, not the register pocket.
#: ── 2026-08-08, LATER: THE TIME COMES BACK INSIDE ────────────────────────
#: Owner, at 23:20: "the time should be still within the complication itself
#: — it got moved south underneath it and is now crowding out the tiles." The
#: note directly above is what moved it, and it overshot: +112 is outside
#: this register's own rim (90) altogether, standing on the open dial in the
#: wedge band's approach. So it comes back in — +40, the lower third of the
#: subdial, slot and digits both wholly inside the track.
#:
#: WHICH RE-OPENS THE HAND PROBLEM THE NOTE ABOVE SOLVED BY LEAVING, and
#: neither escape it measured has improved: the hand's ink still sweeps every
#: radius inside 75.6, so NO position inside this register is clear of it,
#: and a hand short enough to miss digits centred at +40 would have to stop
#: at 29 — well under half the 75.6 it needs to reach its own graduations.
#: So the OTHER option the owner named is the one taken: the digits keep
#: their recessed slot and THE SLOT IS CUT OUT OF THE HAND. The pocket ground
#: under the mouth is stashed before the hand is drawn and pasted back
#: through the mouth's own pill mask afterwards; the recess and the digits go
#: on top of that. The hand therefore runs up to the polished lip, disappears
#: behind it and comes out the far side — what it does behind an applied
#: plate — and digit ink NEVER meets hand ink at any minute of any hour. The
#: clearance is consequently the mouth's own padding rather than a swept
#: distance, and _moon_time_check prints it once per process (§1).
#:
#: +40 IS MEASURED against the four things that box it in, all radii about
#: the pivot: the moon window's foot is at +5 and the mouth's lip starts at
#: +24, so 19 clear; the surviving ticks' inner ends are at 75.2 and the
#: closest the mouth comes to one is 7.3 (the 21h tick, on the bearing
#: through the mouth's own cap centre); the "24" numeral inks from 69 down
#: and the mouth's foot is at 56, so 13 clear; and the digit ink's own box
#: reaches r=66.7, inside the rim's 90 and inside the track's 80 both.
#:
#: AND THE COUNTERPOISE IS CUT BY THE LIP AROUND NOON, deliberately, because
#: the alternative measured worse. Its far edge reaches 29.3 below the pivot
#: when the hand stands up, and the mouth's own lip starts at 24, so about
#: 5px of the lobe goes behind the plate between roughly 09:45 and 14:15. To
#: clear it the slot would have to sit at +46 or lower, and the sweep of that
#: move (every tick, every numeral, the track arcs) closes the 22h tick's gap
#: to 3.5 and the track's to 3.8 at +46 and to 2.5 and 3.0 at +47 — under the
#: 4.7 the aperture note above set as the figure at which a scale stops
#: reading as running INTO a window (it measured 2.7 as exactly that). A lobe
#: half-hidden behind a plate is the same sentence the rest of this hand is
#: already saying at the same lip; a scale crowding the slot is a new fault.
MOON_TIME_DY = 40.0                  # the digits' centreline below the pivot
                                     # (was 112.0 outside the rim, 44.0 under
                                     # the hand — both above)
MOON_TIME_AP = (100, 32)             # the mouth, display px
MOON_TIME_SIZE = 22                  # the digits; the size the mouth above
                                     # was measured for, named so the check
                                     # and the live path cannot drift apart
MOON_TIME_WALL_W = 4                 # visible wall; the pockets' 7, scaled
                                     # to a mouth a third their size
#: Over the pocket floor's own wash this multiplies whatever shows through
#: by exactly 1 - 38/255 = 0.851 in every channel, so the floor lands 14.9%
#: darker than the ground beside it — mid the owner's 10-20 band.
MOON_TIME_FLOOR_A = 38
MOON_TIME_SHADOW_A = 110             # the whisper; the pockets' 150, eased
_MOON_TIME = {"tile": None, "mask": None}


def _moon_time_aperture() -> tuple:
    """The recessed time aperture, baked once — THE TIME RECESSES above.
    Returns (tile, mask); the mask is the mouth's own pill, which is what
    THE TIME COMES BACK INSIDE cuts the hand out of.

    A pill is two half-bores and two straight walls, so the caps take
    _pocket_relief's 5-degree-segment arithmetic verbatim and each straight
    edge is one segment whose bearing is its outward normal: the wall
    dotted with -POCKET_KEY (an interior catches the key light on the far
    side), the chamfer with +POCKET_KEY (lit where the sky strikes the
    lip). _dial_metal throughout — this tile rides the register onto the
    far side of desertify()."""
    if _MOON_TIME["tile"] is not None:
        return _MOON_TIME["tile"], _MOON_TIME["mask"]
    w, h = MOON_TIME_AP
    pad = 3                             # air for the chamfer's outer half
    tile = Image.new("RGBA", (w + 2 * pad, h + 2 * pad), (0, 0, 0, 0))
    d = ImageDraw.Draw(tile)
    x0, y0, x1, y1 = pad, pad, pad + w, pad + h
    rr = h / 2.0                        # full-radius ends: a pill
    d.rounded_rectangle([x0, y0, x1, y1], radius=rr,
                        fill=(0, 0, 0, MOON_TIME_FLOOR_A))
    caps = ([x0, y0, x0 + 2 * rr, y1], [x1 - 2 * rr, y0, x1, y1])
    edges = ((x0 + rr, x1 - rr, y0, -1.0), (x0 + rr, x1 - rr, y1, 1.0))

    def relief(key, lo, hi, alpha, width):
        for box, a_lo in zip(caps, (90.0, 270.0)):
            for seg in range(36):
                a0 = a_lo + seg * 5.0
                t = math.radians(a0 + 2.5)
                f = 0.5 + 0.5 * (math.cos(t) * key[0]
                                 + math.sin(t) * key[1])
                d.arc(box, a0 - 0.6, a0 + 5.6,
                      fill=_dial_metal(lo + (hi - lo) * f, alpha),
                      width=width)
        for xa, xb, yy, ny in edges:
            f = 0.5 + 0.5 * ny * key[1]
            yc = yy - ny * width / 2.0
            d.line([(xa, yc), (xb, yc)],
                   fill=_dial_metal(lo + (hi - lo) * f, alpha), width=width)

    relief((-POCKET_KEY[0], -POCKET_KEY[1]),
           POCKET_WALL_DARK, POCKET_WALL_LIT, 255, MOON_TIME_WALL_W)
    sh = Image.new("RGBA", tile.size, (0, 0, 0, 0))
    ds = ImageDraw.Draw(sh)
    ib = MOON_TIME_WALL_W - 1
    ds.arc([x0 + ib, y0 + ib, x0 + 2 * rr - ib, y1 - ib], 150.0, 285.0,
           fill=(0, 0, 0, MOON_TIME_SHADOW_A), width=7)
    ds.line([(x0 + rr, y0 + ib + 3.0), (x1 - rr, y0 + ib + 3.0)],
            fill=(0, 0, 0, MOON_TIME_SHADOW_A), width=7)
    tile.alpha_composite(sh.filter(ImageFilter.GaussianBlur(2.5)))
    relief(POCKET_KEY, POCKET_RIM_DARK, SNAIL_RING_LUM, POCKET_RIM_A,
           SNAIL_RING_W)
    # THE MOUTH AS A MASK. Every stroke above is drawn INSIDE the mouth
    # rectangle (PIL's arc and ellipse widths run inward, and the two straight
    # walls are inset by half their own width), so the pill below covers the
    # whole of this tile's ink and nothing beyond it — which is exactly what
    # the hand has to be cut back to.
    mask = Image.new("L", tile.size, 0)
    ImageDraw.Draw(mask).rounded_rectangle([x0, y0, x1, y1], radius=rr,
                                           fill=255)
    _MOON_TIME["tile"], _MOON_TIME["mask"] = tile, mask
    return tile, mask


def _moon_register(now: float) -> "Image.Image":
    p, _f, _w = moon_phase(now)
    lt = time.localtime(now)
    # The MINUTE is in the key: the hand moves 0.5 deg a minute (0.25 until
    # it went 12-hour on 2026-08-09) and the digits below it read HH:MM, and
    # the sky's dayness is an hour-of-day fade, so the layer rebuilds once a
    # minute — the supersampled tile keeps its own ~1.8 h cache and is not
    # re-rendered by this.
    key = (int(p * 400), lt.tm_hour, lt.tm_min)
    if _MOON_REG["key"] == key and _MOON_REG["lay"] is not None:
        return _MOON_REG["lay"]
    # Half-size is whichever reaches further, the flange or the time's slot:
    # since THE TIME CLEARS THE HAND the slot sits BELOW the register, on the
    # open dial, and a layer cut to the flange would clip it off. draw_moonphase
    # reads the size back off the layer, so the paste follows on its own.
    # 2026-08-08 LATER: the slot is back inside the flange (THE TIME COMES
    # BACK INSIDE), so the max() now always picks the flange and the layer is
    # the register again. The max() STAYS — it is what makes the layer follow
    # MOON_TIME_DY instead of assuming it, and this constant has moved three
    # times in two days.
    r = int(math.ceil(max(MOON_RIM + 4.0,
                          MOON_TIME_DY + MOON_TIME_AP[1] / 2.0 + 8.0)))
    lay = Image.new("RGBA", (2 * r, 2 * r), (0, 0, 0, 0))
    px = py = float(r)
    # THE POCKET FIRST, under everything this register carries — the same
    # recessed floor, snail and border ring the ROOM dial stands in, put
    # through _dial_metal because this layer is composited on the far side of
    # the duotone (see SNAIL_GROUND, and MOON_XY for why this one is).
    _snail_pocket(lay, px, py, float(MOON_RIM), _dial_metal)
    d = ImageDraw.Draw(lay)

    def pt(a: float, rr: float):
        t = math.radians(a)
        return px + rr * math.cos(t), py + rr * math.sin(t)

    # THE WHOLE SKY IS DAY OR NIGHT, 2026-08-09 — DAY ABOVE, NIGHT BELOW is
    # superseded (the note still stands at AND THE TWO HALVES STAND ON
    # DIFFERENT GROUND, with the alphas it measured, which are reused here as
    # the two ends of the fade). The split half was legible only because the
    # hand took a day to cross it; a 12-hour hand crosses it twice, so a
    # permanently dark lower half would say "night" at 2pm. The distinction
    # therefore stops being a POSITION and becomes a STATE: the pocket's
    # floor darkens as a whole after dusk and its stars come out, and lifts
    # again at dawn. The mix is the day/night window's own dusk curve
    # (_day_frac / DN_MIX_*), so on a ferrari row the register and the sun in
    # its window turn together instead of at two different hours.
    # Onto a scratch layer and composited, never drawn straight onto `lay`:
    # ImageDraw REPLACES the pixels it writes, alpha and all, so a
    # translucent wash drawn in place would erase the snail it is meant to
    # sit on.
    alt = -math.cos(_day_frac(now) * math.tau)   # -1 midnight, +1 noon
    dayness = max(0.0, min(1.0, (alt - DN_MIX_LO) / DN_MIX_SPAN))
    wash = Image.new("RGBA", lay.size, (0, 0, 0, 0))
    dw = ImageDraw.Draw(wash)
    wbox = [px - MOON_WASH_R, py - MOON_WASH_R,
            px + MOON_WASH_R, py + MOON_WASH_R]
    if dayness >= 0.5:
        dw.ellipse(wbox, fill=(255, 255, 255,
                               int(round(MOON_DAY_A * (2.0 * dayness - 1.0)))))
    else:
        dw.ellipse(wbox, fill=(0, 0, 0,
                               int(round(MOON_NIGHT_A * (1.0 - 2.0 * dayness)))))
    # The stars fade with the same number, so they are out at night and gone
    # by mid-morning rather than sprinkled across a daylit floor. Still the
    # seeded field — an unseeded sprinkle re-rolls the sky every minute.
    star_k = max(0.0, 1.0 - 2.0 * dayness)
    if star_k > 0.0:
        rng = random.Random(MOON_STAR_SEED)
        for _ in range(MOON_STARS):
            a = math.radians(rng.uniform(4.0, 356.0))
            rs = MOON_WASH_R * math.sqrt(rng.uniform(0.05, 0.93))
            sx, sy = px + rs * math.cos(a), py + rs * math.sin(a)
            sr = rng.choice((0.5, 0.5, 0.5, 0.8, 1.1))
            dw.ellipse([sx - sr, sy - sr, sx + sr, sy + sr],
                       fill=_dial_metal(236, int(round(
                           rng.randint(90, 190) * star_k))))
    lay.alpha_composite(wash)
    # The date track, at the RESERVE's own weight and opacity — this is the
    # "same metal treatment" half of the brief, and since 2026-08-07 the
    # sizes are the same too. The luminance is the one this line has always
    # had; _dial_metal is what puts it where the duotone used to, now that
    # this layer is drawn after it. The flange it used to draw beside itself
    # is the pocket's border ring above.
    # FOUR ARCS AND NOT A CIRCLE since 2026-08-08: the numerals stand on this
    # radius and a printed scale BREAKS for its own numerals (A 24-HOUR DIAL
    # HAS TO SAY THAT IT IS ONE). The gaps are centred on the quarters, which
    # in this frame are 0/90/180/270.
    tbox = [px - MOON_TRACK, py - MOON_TRACK,
            px + MOON_TRACK, py + MOON_TRACK]
    for q in range(4):
        d.arc(tbox, 90.0 * q + MOON_NUM_GAP, 90.0 * (q + 1) - MOON_NUM_GAP,
              fill=_dial_metal(233, 41), width=3)
    # Twenty-four graduations — the ring is a 24-HOUR SCALE since 2026-08-07
    # (the argument is at MOON_HOURS): midnight at the foot, noon at the
    # head. The three tick weights are the 31-day track's, kept verbatim:
    # the datum pair (00 at the foot, 12 at the head) takes day one's length
    # and weight, every sixth hour is heavier, the rest are minor. The top
    # tick still ends at 0.885 — the 5.8 px clearance to the aperture's
    # outline was measured for a tick in exactly that place — and hour
    # spacing (15 deg against the date track's 11.6) only moves its
    # neighbours FURTHER from the window.
    # 2026-08-08: 00, 06, 12 and 18 carry a NUMERAL now and their ticks go
    # with the weights they used to have — a numeral is a stronger datum than
    # a heavy line, and a tick under one is a line through a number. Every
    # tick that survives is therefore a minor one, so the 0.885/0.91 lengths
    # the aperture clearance was measured against are no longer reached by
    # anything: 0.94 (75.2) is now the closest any tick comes to the pivot.
    # 2026-08-09: TWELVE graduations, not twenty-four, and the four skipped
    # for a numeral are now 12/3/6/9 (k % 3) — the same four positions on the
    # glass, so every clearance measured above still holds; there is simply
    # one tick per hour of a 12-hour hour instead of two.
    # THE GAUGE RING, so this register joins the other two (2026-08-09).
    # Owner, at the glass: "no red on the moon complication." He was right —
    # its ticks took the accent but a tick is a line, and beside the ROOM and
    # the RESERVE (which had just gained a full painted lip at the bezel's
    # inner seam) this one still read as a steel dress-watch register sitting
    # in a car. Same radius rule as theirs, track+1, so the three agree.
    if INSTR:
        _mr = MOON_TRACK + 1
        d.arc([px - _mr, py - _mr, px + _mr, py + _mr], 0, 360,
              fill=INSTR_RED + (196,), width=2)
    for k in range(MOON_HOURS):
        if k % 3 == 0:
            continue
        a = _moon12_ang(k)
        # RED INDEX MARKS on an instrument row (2026-08-09) — this register
        # is drawn on the far side of the duotone already, so unlike the
        # ROOM's and the RESERVE's (which need the overlay at _instr_scale)
        # its ticks simply take the colour here.
        d.line([pt(a, MOON_RIM), pt(a, MOON_TRACK * 0.94)],
               fill=(INSTR_RED + (204,)) if INSTR else _dial_metal(224, 158),
               width=1)
    # THE NUMERALS, which are the whole point of this pass: 24 at the foot,
    # 12 at the head, 6 and 18 at the flanks, so the hand's HOUR is readable
    # and not merely its position. Set in the register's own metal through
    # _dial_metal, vertically centred on r=74 by their own ink box the way
    # the digits below are.
    # 2026-08-09: they read 12 at the head and 3/6/9 round the quarters now
    # (MOON_NUMERALS) — the same four places, a 12-hour clock's labels.
    for k, lab in MOON_NUMERALS:
        nx, ny = pt(_moon12_ang(k), MOON_NUM_R)
        nfc = face_for(lab, "label", MOON_NUM_SIZE)
        nbb = nfc.getbbox(lab)
        draw_centred(d, nx, ny - (nbb[1] + nbb[3]) / 2.0, lab, nfc,
                     _dial_metal(238, 224))
    # The window, inside the register and above the pivot. Converted to RGBA
    # first: the aperture is APPLIED metal over a hole and must land opaque,
    # and paste()ing an RGB tile onto an RGBA layer through an L mask is a
    # mode mismatch waiting to be discovered on the puck rather than here.
    tile, mask = moon_tile(now)
    lay.paste(tile.convert("RGBA"),
              (int(px) - MOON_W // 2, int(py) + MOON_AP_DY - MOON_H // 2),
              mask)
    # THE TIME RECESSES (2026-08-08): the digits' frame is a recessed
    # aperture, baked once — _moon_time_aperture above. Pasted before the
    # digits so they sit ON its floor; their live path is untouched.
    # 2026-08-08 LATER: the slot is back INSIDE the register (THE TIME COMES
    # BACK INSIDE at MOON_TIME_DY), where the hand sweeps, so the aperture
    # and the digits now go on AFTER the hand and the ground under the mouth
    # is stashed here first. Stash, hand, restore through the mouth's own
    # pill, then recess, then digits — which cuts the hand off at the
    # polished lip instead of letting it lie across a number.
    ap, ap_mask = _moon_time_aperture()
    ap_xy = (int(round(px - ap.width / 2.0)),
             int(round(py + MOON_TIME_DY - ap.height / 2.0)))
    ap_bg = lay.crop((ap_xy[0], ap_xy[1],
                      ap_xy[0] + ap.width, ap_xy[1] + ap.height))
    # THE DIGITS, small, under the pivot — the twelve-o'clock pill is
    # retired (headstone at CLOCK_BOX) and this register is where the time
    # reads now. Set in the register's own metal through _dial_metal,
    # centred on the vertical axis at +44 from the pivot: below the
    # aperture's foot (+12), clear of the hand's counterweight reach (~11)
    # and of the foot tick's inner end (70.8). Drawn BEFORE the hand, so
    # the hand passes over them around midnight the way the old pointer
    # passed over the window — drawn last stays drawn last.
    # 2026-08-08: +44 is superseded by +112 (THE TIME CLEARS THE HAND, at
    # MOON_TIME_DY) and so is the last clause above — the slot is below the
    # flange now and the hand cannot reach it at any hour. The drawing order
    # is kept anyway; nothing depends on it here any more.
    # 12-HOUR since 2026-08-07 ("4:17pm not 16:17"): hour from the struct,
    # `% 12 or 12` so 0 and 12 both read 12, lowercase meridiem, no leading
    # zero. The 24-hour HAND is untouched.
    # 2026-08-09: and the hand is 12-hour too now, so these digits and the
    # hand finally state the same thing (THE HAND BECOMES A PLAIN 12-HOUR
    # HAND) — they contradicted each other for two days.
    txt = (f"{lt.tm_hour % 12 or 12}:{lt.tm_min:02d}"
           f"{'am' if lt.tm_hour < 12 else 'pm'}")
    tf = face_for(txt, "text", MOON_TIME_SIZE)
    bb = tf.getbbox(txt)
    # THE HAND IS THE COMPLICATION DOING SOMETHING: it follows the real
    # 24-hour day (_moon24_ang, local time), one revolution per day,
    # sweeping over the moon disc — a day-night indicator, which is what
    # this register does on a real watch. Still last, so it passes in FRONT
    # of the window. Same hand as the other two (A HAND, NOT A BAR), written
    # in the same 72-unit track and scaled to this one, at s=0.8 so the
    # shaft stays narrow over a busy aperture.
    # 2026-08-09: it follows the 12-hour clock instead — two revolutions a
    # day, _moon12_ang — and it is no longer the day-night indicator; that
    # moved to the sky it stands on (THE WHOLE SKY IS DAY OR NIGHT). It is
    # still drawn last and still passes in front of the window.
    _moon12_check()
    _moon_time_check()
    # The counterpoise and the point go GOLD (amendment 2, "more gold,
    # sprinkled") — the accent the tourbillon cage already wears, passable
    # here directly because this layer lives on the far side of desertify().
    _draw_hand(d, px, py,
               _moon12_ang(lt.tm_hour, lt.tm_min, lt.tm_sec),
               MOON_TRACK / 72.0,
               (_dial_metal(217), _dial_metal(166), _dial_metal(249),
                _dial_metal(230)), s=0.8,
               tail=HAND_TAIL_INK + (255,), tip=HAND_TIP_INK + (255,))
    # AND THE SLOT IS CUT OUT OF IT. The stashed ground goes back through the
    # mouth's pill, which erases whatever the hand just wrote inside it and
    # nothing outside it; the recess is composited onto that restored floor,
    # so its own wall, shadow and chamfer are drawn once and land on the
    # snail they were designed for; and the digits go on last. The hand runs
    # into the lip and out the far side and never touches a digit — see THE
    # TIME COMES BACK INSIDE, and _moon_time_check for the number.
    lay.paste(ap_bg, ap_xy, ap_mask)
    lay.alpha_composite(ap, ap_xy)
    # MOON_TIME_DY, not a second 44: the aperture above and these digits
    # are one instrument and must move together or not at all.
    draw_centred(d, px, py + MOON_TIME_DY - (bb[1] + bb[3]) / 2.0, txt, tf,
                 _dial_metal(238))
    _MOON_REG["key"], _MOON_REG["lay"] = key, lay
    return lay


def draw_moonphase(frame: Image.Image, now: float) -> None:
    """The moonphase register at six: the phase behind a 24-hour hand,
    with the digital time under the pivot (since 2026-08-07)."""
    lay = _moon_register(now)
    r = lay.size[0] // 2
    frame.paste(lay, (MOON_XY[0] - r, MOON_XY[1] - r), lay)


#: ── THE FRAME BECOMES THE INSTRUMENT, 2026-08-06 ──────────────────────────
#:
#: Owner, by voice at the puck, deleting the live gauge band in the same
#: breath: "let the octagon carry the signal instead: eight flats and eight
#: screws are a natural eight-segment indicator, sitting exactly where the eye
#: already goes. A request in progress lights the flats in sequence around the
#: bezel; a finished one settles them; low credits warms them amber."
#:
#: THE GEOMETRY IS home.html's, RE-SOLVED RATHER THAN RE-GUESSED. That page
#: draws the bezel and this file lights it, so the two must agree about where
#: a flat is to the pixel or the tint sits half on the brushed top and half on
#: the bevel. The four constants below are its BEZ_OUT / BEZ_CHAMFER /
#: BEZ_BEVEL / BEZ_BAND(_CARD) verbatim, and _bez_oct is its octPts()
#: verbatim — including the part that page's own comment insists on: A VERTEX
#: IS SOLVED, NOT PLACED. The cardinal flats are deeper than the diagonal
#: ones (40 units against 28), so a corner does NOT sit on the 22.5+45k ray,
#: and a tint drawn to that ray would leave a wedge of untinted metal at every
#: mitre. Each corner is the intersection of flat k's line with flat k+1's.
#: ANY CHANGE TO THOSE FOUR NUMBERS ON THAT PAGE MOVES THESE IN THE SAME
#: COMMIT — the standing DIAL_K contract, one more element on it.
#:
#: IT IS THE BRUSHED TOP ONLY, not the whole band. The chamfer and the inner
#: bevel are planes at other angles taking their light from elsewhere (that
#: page: "A FACET IS NOT A LIGHTER GREY"), and tinting all three would flatten
#: the section this bezel exists to have. So the lit quad runs from the outer
#: crease to the inner one, and the two creases stay steel — which is also
#: what makes a lit flat read as lit rather than as a lit ring.
BEZ_VB = SIZE / 1000.0                          # home.html's unit, in display px
BEZ_OUT_VB = 500.0 * math.cos(math.pi / 8)      # 461.94, corners on r=500
BEZ_CHAMFER_VB = 3.85
BEZ_BEVEL_VB = 7.7
BEZ_BAND_VB = (40.0, 28.0)                      # cardinal flats, diagonal flats
#: The order the flats light in. Flat k faces bearing k·45° from three
#: o'clock, so twelve o'clock is k=6 — and the sequence runs CLOCKWISE from
#: there, which on this panel (y down) is increasing k. A progress indicator
#: that started anywhere but twelve, or ran the other way, would be the one
#: thing on a watch face that everybody reads without being told.
BEZ_SEQ = (6, 7, 0, 1, 2, 3, 4, 5)
#: The three levels, as alpha over the metal. THE UNLIT SEGMENTS ARE NOT
#: NOTHING: the same lesson the deleted arc's empty track was there for (§6) —
#: eight flats with one lit is a lit flat, eight flats with one bright and
#: seven faintly warm is a SCALE with one segment filled. 26 is visible on the
#: bright outer crease and on the near-black inner one both, which is the test
#: that matters on a band whose own luminance sweeps 236 to 18 across it.
BEZ_A_FLOOR, BEZ_A_LIT, BEZ_A_HEAD = 26, 105, 200
#: The leading flat breathes at 0.75 Hz and the reserve warning at 1.15 Hz —
#: the enrolment ring's rate, which draw_reserve already shares so that two
#: things throbbing on one screen never beat against each other. These two
#: are never on the glass together (a request outranks the standing warning),
#: so they are allowed to differ: the request's is slower because it is
#: reporting travel, and the warning's is the house rate for "look at me".
BEZ_WORK_HZ, BEZ_WARN_HZ = 0.75, 1.15
BEZ_FADE_S = 0.4
#: ── 2026-08-07: THE BEZEL IS ROUND NOW, SO THE PROGRESS IS AN ARC ─────────
#: Owner, at a capture with a request at 10%: "strange the texture still is
#: an octagon. i want the whole circular face with that texture." It was
#: never the texture: the eight lit flats were painted onto a bezel that
#: scripts/bake_bezel.py has since rebuilt as a circular ring (ROUND = True
#: there; the octagon bake is kept behind ROUND = False, and the quad path
#: below stays with it for the same reversal). Eight flats on a round ring
#: have no metal to sit on, so every request drew an octagon over a round
#: watch. Progress on a round bezel is a circular ARC — clockwise from
#: twelve, filled to the percentage, which is what a chronograph does — and
#: it is continuous where the flats quantised to 12.5%. Everything the flats
#: said survives: the dim track (a scale, not a stray arc), the gold ladder
#: and green/red in the same colours, the breathing head for travel, a
#: failure that keeps no percentage. TINTED, NOT SCREENED, unchanged — the
#: argument at draw_bezel_state is about the metal's own modelling, not its
#: shape. And one thin arc is less paint than eight polygons were.
#: THE BAND IS bake_bezel.py's, INSET A PIXEL EACH SIDE: the steel runs
#: R_VERT-RING .. R_VERT = 526.4..540 there (measured on the shipped
#: bezel_steel.png), and the arc covers 527..539 so both creases stay steel
#: — the octagon's own rule, which is what makes a lit band read as lit
#: metal rather than as paint. If that script's R_VERT or RING moves, these
#: two move in the same commit.
BEZ_RING_R = 539.0                  # outer radius of the tint, display px
BEZ_RING_PW = 12                    # its width, inward, whole px for PIL
BEZ_HEAD_DEG = 12.0                 # the breathing head, centred on the tip
_BEZ_QUADS = None
_BEZ = {"fade": 0.0, "sig": None, "t": 0.0, "said": None}


def _bez_oct(dof):
    """The eight corners of an octagon whose flat k stands `dof(k)` from the
    centre, in DISPLAY px. home.html's octPts(), unit for unit."""
    s = math.sin(math.pi / 4)
    pts = []
    for k in range(8):
        t0, t1 = k * math.pi / 4, (k + 1) * math.pi / 4
        d0, d1 = dof(k), dof((k + 1) % 8)
        pts.append((SIZE / 2 + BEZ_VB * (d0 * math.sin(t1)
                                         - d1 * math.sin(t0)) / s,
                    SIZE / 2 + BEZ_VB * (d1 * math.cos(t0)
                                         - d0 * math.cos(t1)) / s))
    return pts                      # pts[k] is the corner between k and k+1


def _bez_quads():
    """The eight brushed tops, as polygons. Built once — the bezel is baked
    and cannot move, so this is the definition of something that does not
    change per frame."""
    global _BEZ_QUADS
    if _BEZ_QUADS is None:
        vo = _bez_oct(lambda k: BEZ_OUT_VB - BEZ_CHAMFER_VB)
        vi = _bez_oct(lambda k: BEZ_OUT_VB - BEZ_BAND_VB[k % 2] + BEZ_BEVEL_VB)
        # The quad for flat k runs between the two corners that flat OWNS, on
        # both boundaries — that page's band() exactly, so the eight of them
        # tile the ring and share their mitres with the metal underneath.
        _BEZ_QUADS = [[vo[(k + 7) % 8], vo[k], vi[k], vi[(k + 7) % 8]]
                      for k in range(8)]
    return _BEZ_QUADS


def _bezel_signal(now: float):
    """(colour, track alpha, fill fraction, head alpha) for the ring, or
    None when it is just a bezel.

    TWO CLAIMANTS, AND THE ORDER IS THE POINT. A request is transient and
    somebody is waiting on it; low credits is a standing condition that will
    still be true in a minute. So the request takes the frame while it runs
    and the warning comes back underneath it when it leaves — rather than the
    two blending into a colour that is neither (§8: the expensive error here
    is losing the warning, so it is the one that is never overwritten for
    good, only covered).
    """
    try:
        head = _requests_head(now)
    except Exception as e:                      # noqa: BLE001
        _bez_say(f"head:{e!r}", f"bezel: request read failed {e!r} — "
                                f"the ring is showing nothing")
        head = None
    if head is not None:
        col = REQ_COL.get(head["state"], REQ_COL["working"])
        if head["state"] == "failed":
            # NOTHING TO FILL, and it is the deleted arc's own rule: a
            # failure that keeps its last percentage is the same lie as a
            # stuck bar. A short red tick at twelve, breathing — it stopped
            # here.
            ph = 0.5 + 0.5 * math.sin(now * math.tau * BEZ_WORK_HZ)
            return col, BEZ_A_FLOOR, 0.0, int(BEZ_A_HEAD * (0.45 + 0.55 * ph))
        frac = max(0.0, min(1.0, int(head["pct"]) / 100.0))
        head_a = None
        if frac < 1.0 and head["state"] in REQ_ACTIVE:
            # The head is the travel. It is the one thing the deleted head
            # dot did that a filled arc cannot: say that the number is
            # still moving, on a face somebody glances at for a second.
            ph = 0.5 + 0.5 * math.sin(now * math.tau * BEZ_WORK_HZ)
            head_a = int(BEZ_A_FLOOR + (BEZ_A_HEAD - BEZ_A_FLOOR) * ph)
        return col, BEZ_A_FLOOR, frac, head_a
    # LOW CREDITS WARMS THEM. The test is draw_reserve's own, not a second
    # opinion about what "low" means — one quantity must not have two
    # thresholds on one face, or the lamp and the frame will disagree in
    # front of the owner (§7, in pixels).
    led = _ledger_now(now)
    if led is None:
        return None
    frac = max(0.0, min(1.0, 1.0 - led["real"] / RES_DAY_CREDITS))
    if frac > RES_AMBER_FRAC:
        return None
    ph = 0.5 + 0.5 * math.sin(now * math.tau * BEZ_WARN_HZ)
    a = int(BEZ_A_FLOOR + (BEZ_A_LIT - BEZ_A_FLOOR) * (0.35 + 0.65 * ph))
    return RES_AMBER, a, 0.0, None


def _bez_say(key: str, msg: str) -> None:
    """One line per distinct fault, ever — never per frame."""
    if key not in _REQ_SAID:
        _REQ_SAID.add(key)
        print(msg, flush=True)


#: "Who is in the room" — first-cut roster chips. Env-gated OFF; a first
#: draft for the owner to place. Top-centre, under the wordmark, clear of
#: the wedge ring and the centre tourbillon.
_ROSTER_FACE = os.environ.get("AURA_ROSTER_FACE", "0") == "1"
_ROSTER_ST = {"mtime": None, "names": []}


def _room_roster(now: float):
    try:
        m = ROOM_FEED.stat().st_mtime
    except OSError:
        return []
    if _ROSTER_ST["mtime"] != m:
        _ROSTER_ST["mtime"] = m
        try:
            d = json.loads(ROOM_FEED.read_text())
            fresh = now - float(d.get("roster_at", 0)) < 12.0
            _ROSTER_ST["names"] = list(d.get("roster", [])) if fresh else []
        except Exception:
            _ROSTER_ST["names"] = []
    return _ROSTER_ST["names"]


def draw_room_roster(frame: "Image.Image", now: float) -> None:
    """Small chips naming who the diarizer is tracking. Wrapped whole —
    new paint in a compositor that must never stop."""
    try:
        names = _room_roster(now)
        if not names:
            return
        d = ImageDraw.Draw(frame, "RGBA")
        f = face("label", 22)
        chips = names[:5]
        pad, gap, h = 14, 10, 30
        widths = [int(d.textlength(n, font=f)) + 2 * pad for n in chips]
        total = sum(widths) + gap * (len(chips) - 1)
        x = (SIZE - total) // 2
        y = 350
        for n, w in zip(chips, widths):
            enrolled = n[:1].isupper() and len(n) > 1   # a name, not "A"
            col = (90, 190, 255) if enrolled else (150, 150, 160)
            d.rounded_rectangle([x, y, x + w, y + h], radius=h // 2,
                                outline=col + (220,), width=2,
                                fill=col + (40,))
            tw = int(d.textlength(n, font=f))
            d.text((x + (w - tw) // 2, y + 4), n, font=f,
                   fill=(230, 240, 255))
            x += w + gap
    except Exception:
        pass          # a roster chip is never worth a stopped compositor


def draw_bezel_state(frame: "Image.Image", now: float) -> None:
    """Light the ring: a progress arc, clockwise from twelve, on the steel.
    In place, AFTER the colourway and BEFORE the rotate.

    After the colourway because every one of these tints carries MEANING in
    its colour — the gold ladder, and green and red most of all, which the
    palette note exempts from any house family. Before the rotate because the
    bezel is baked steel pasted under it and the whole frame turns: paint it
    after and the lit arc slides off the metal it is supposed to be.

    TINTED, NOT SCREENED, and that is what "warms them" asks for. A screen
    adds light and would blow the polished top of the ring while barely
    touching its shadowed bottom; an alpha tint takes the metal's own
    modelling and colours it, which is what a lit piece of steel does. That
    argument is the octagon's, and the shape change does not touch it. It
    is also the cheap one: PIL blends the arc's own pixels and nothing else,
    and one arc over a 12px ring is less paint than the eight polygons it
    replaces — this is a passively cooled puck already inside its thermal
    budget, and the idle loop stays at 8 fps.

    Wrapped whole: new paint in a compositor that must never stop.
    """
    try:
        sig = _bezel_signal(now)
        last = _BEZ["t"] or now
        _BEZ["t"] = now
        dt = max(0.0, min(0.5, now - last))
        if sig is not None:
            _BEZ["fade"] = min(1.0, _BEZ["fade"] + dt / BEZ_FADE_S)
            _BEZ["sig"] = sig
        else:
            # Leaving is slower than arriving, the wedge's own rule: 0.4s out
            # reads as a glitch, and the last thing shown is what is
            # remembered.
            _BEZ["fade"] = max(0.0, _BEZ["fade"] - dt / (BEZ_FADE_S * 2.0))
            if _BEZ["fade"] <= 0.0:
                _BEZ["sig"] = None
        sig = _BEZ["sig"]
        word = None if sig is None else str(sig[0])
        if word != _BEZ["said"]:
            _BEZ["said"] = word
            print(f"bezel: {'idle' if word is None else 'lit ' + word}",
                  flush=True)
        if sig is None or _BEZ["fade"] <= 0.01:
            return
        col, track_a, frac, head_a = sig
        d = ImageDraw.Draw(frame, "RGBA")
        box = [SIZE / 2 - BEZ_RING_R, SIZE / 2 - BEZ_RING_R,
               SIZE / 2 + BEZ_RING_R, SIZE / 2 + BEZ_RING_R]
        # PIL's arc angles run clockwise from three o'clock, so twelve is
        # -90 — the enrolment ring's own arithmetic, same idiom throughout.
        tip = -90.0 + 360.0 * frac
        a = int(track_a * _BEZ["fade"])
        if a > 2 and frac < 0.999:
            # The unfilled remainder, dim — the same lesson the unlit flats
            # carried (§6): a track with an arc on it is a SCALE with a
            # reading; an arc alone is a stray mark.
            d.arc(box, tip, 270, fill=col + (a,), width=BEZ_RING_PW)
        a = int(BEZ_A_LIT * _BEZ["fade"])
        if a > 2 and frac > 0.002:
            d.arc(box, -90, tip, fill=col + (a,), width=BEZ_RING_PW)
        if head_a is not None:
            a = int(head_a * _BEZ["fade"])
            if a > 2:
                # Last, over both, the way a hot tip glows over what it is
                # travelling along.
                d.arc(box, tip - BEZ_HEAD_DEG / 2, tip + BEZ_HEAD_DEG / 2,
                      fill=col + (a,), width=BEZ_RING_PW)
    except Exception as e:                      # noqa: BLE001
        _bez_say(f"draw:{e!r}", f"bezel: state draw failed {e!r} — "
                                f"the ring is plain metal")


#: ── THE BEZEL IS THE LISTENING INDICATOR (2026-08-08) ─────────────────────
#:
#: Owner, on dead air after "hey sterling": "why can't we incorporate the
#: voice / thinking indicator to be immediate and render somehow on the
#: steel circular bezel? be creative." Three states on the ring, and every
#: one reports a fact something else already publishes — no theatre:
#:
#:   HEARING  — pulse.json says "hearing", written by the ears at the ONSET,
#:              the instant the endpointer opens a capture and hundreds of
#:              ms before any transcript exists. A soft cool bloom breathes
#:              on the band at the SPEAKER'S BEARING — the wordmark's own
#:              eased DOA angle, so the two track together and the bloom
#:              follows a talker who moves. The metal listens toward you.
#:   THINKING — work genuinely pending: pulse.json says "thinking"
#:              (endpoint → feed line) or the conductor's THINKING flag is
#:              up (answer path → first clip). The bloom detaches and
#:              becomes a comet sweeping the ring clockwise from where it
#:              bloomed, 2.4s a lap — the lock sweep's own rate.
#:   DONE     — the answer path closed, i.e. the reply is beginning: ONE
#:              warm gold pulse of the whole ring, then calm. Overheard
#:              chatter that never entered the answer path closes QUIETLY —
#:              a gold "done" after every sentence she merely filed would
#:              be reporting a reply that never happened (§1's other half:
#:              show nothing that did not occur).
#:
#: TINTED ARCS, NOT THE SPOKEN PRE-BAKED PASTES. The brief asked for a
#: baked table of glow frames; the bezel's own standing argument
#: (draw_bezel_state: TINTED, NOT SCREENED) is why not — a screened bloom
#: would blow the polished top of the band, and an alpha tint has to be
#: blended against the live frame anyway. ~30 short arcs on a 12px band
#: touch ~10k px, LESS work than one full-frame RGBA paste, and the lock
#: screen has shipped 19 arcs a frame in draw_thinking_sweep since it
#: existed. Same budget, same idiom, no new megabytes at startup.
#:
#: The grace before DONE bridges the ears writing "idle" (feed line down)
#: and the conductor raising THINKING moments later — without it the gold
#: would fire mid-hand-off and the comet would come back: three gestures
#: where one was asked for.
#:
#: LATENCY IS LOGGED, BOTH SIDES STAMPED — the verify line for the <150ms
#: budget. pulse.json carries the ears' capture-open time.time(); the
#: HEARING transition prints the glass-side delta. At IDLE_FPS the poll
#: alone can be 125ms of it; the typical line reads well under.
#: 2026-08-15, owner, after not seeing it at all: "stronger bloom, just
#: make it really really noticeable." Spread widened, alpha to the top,
#: breath shallowed so it never fades toward invisible, and the hearing
#: branch now lays a fat half-pen halo under a white-hot core. §13: an
#: acknowledgment the person cannot perceive is not an acknowledgment.
LISTEN_BLOOM_SEGS = 20              # each side of centre: 41 arcs of ~3°
LISTEN_BLOOM_STEP = 3.0             # degrees per segment
LISTEN_A_PEAK = 255                 # bloom centre, before the breath
LISTEN_COOL = (90, 190, 255)        # draw_thinking_sweep's own listening cyan
LISTEN_CORE = (215, 240, 255)       # ...and its hot head
#: ── A THEME MAY RESTATE THE LISTENING LIGHT (2026-08-22) ─────────────────
#: The pair above was chosen against dark bezels, where "she hears you" is
#: LIGHT. On the gallery's porcelain band a near-white core is the comet-
#: on-opaline inversion again — invisible at the exact moment the face
#: promises visibility (§1). A light theme states the bloom as INK and the
#: core as its one metal; a row without the keys keeps the cyan untouched.
LISTEN_COOL = tuple(_THEME.get("listen_cool", LISTEN_COOL))
LISTEN_CORE = tuple(_THEME.get("listen_core", LISTEN_CORE))
#: ...and a light theme restates the bloom's GRAMMAR, not just its colour.
#: The hearing bloom is drawn as overlapping wide-halo arcs — additive glow,
#: correct on a dark band, and MEASURED on the gallery proof it lands as
#: grey scalloped slabs 48px deep across the porcelain (the halo arcs at
#: stepped alphas, visible individually on a light ground). Ink does not
#: halo; it pools. So `listen_ink` draws ONE soft under-arc and a crisp
#: fading band instead — same bearing, same breath, same radii.
LISTEN_INK = bool(_THEME.get("listen_ink"))
#: ── THE ANSWER GOES WHERE HE IS LOOKING (2026-08-25) ────────────────────
#: Owner, twice: "at least have the concentric rings burst out to show
#: it's thinking or something", then "no visible bloom at all" — after the
#: rim bloom had been measured firing at the correct bearing, widened from
#: 18px to 48px, and taken from alpha 44 to 156. Three rounds of making a
#: thing brighter is the tuning trap CLAUDE.md names: stop tuning and ask
#: whether the mechanism can work at all.
#:
#: It cannot, here. BEZ_RING_R is 539 on a 540px dial, so the bloom lives
#: in the outermost 9% of the glass — the part nearest the enclosure lip,
#: furthest from the centre, and the last place a person looks at a face
#: whose whole composition points inward at the stone. On the dark dials
#: it worked because the rim was the brightest thing on an unlit face.
#:
#: So a light theme states it in the CENTRE instead: rings leaving the
#: stone, graphite on plaster, at the radius his eye is already on. The
#: rim bloom stays for the dark faces, which is where it earns its keep.
LISTEN_CENTRE = bool(_THEME.get("listen_centre"))
#: ── 2026-08-26: THE BURST'S THINKING INK ASKS THE THEME TOO ─────────────
#: The centre burst shipped with (38,36,34) written into the draw call
#: below — graphite, chosen against plaster, and 1.1:1 on a near-black
#: dial. It is the same shape as the volume card's teal literals one
#: section away and the fourth instance this week of a treatment that
#: cannot survive the other ground. So it becomes a key carrying the
#: plaster value as its default: gallery keeps its exact pixels, and the
#: carbon row states the thinking ring in titanium because on that face
#: graphite IS the ground.
LISTEN_THINK = tuple(_THEME.get("listen_think", (38, 36, 34)))
#: ...and so does the ALPHA, for a reason that is arithmetic rather than
#: taste: how opaque a ring must be to be SEEN is a property of the ground
#: it is blended into, not of the ring. Ink at alpha 150 on plaster lands
#: 3.4:1 because it is moving away from a bright ground; amber at the same
#: alpha over this file's darkest row lands 2.18:1 (measured, carbon,
#: 2026-08-26) because 45% of a near-black ground is still near-black.
#: Two entries, (hearing, thinking), defaulting to the numbers gallery
#: shipped. Re-measure rather than trusting this note — the harness is
#: scripts/render_listening.py and it takes ten seconds.
LISTEN_C_A = tuple(_THEME.get("listen_c_alpha", (150, 190)))
LISTEN_C_R0, LISTEN_C_R1 = 168.0, 348.0    # stone's edge -> inside wedges
LISTEN_C_PERIOD = 1.7                      # seconds per ring, unhurried
LISTEN_COMET_DPS = 150.0            # 2.4s a lap — inside the 2-3s brief
LISTEN_DONE_S = 0.9
LISTEN_GOLD_A = 165
LISTEN_GRACE_S = 0.6
#: Belt and braces, PULSE_FRESH_S's own reasoning: a conductor that dies
#: holding THINKING up must not leave the comet circling a dead machine.
LISTEN_THINK_MAX_S = 120.0
_LISTEN = {"state": None, "comet_a0": -90.0, "comet_t0": 0.0,
           "armed_t0": 0.0, "answering": False, "done_t0": 0.0}


def draw_listening_ring(frame: "Image.Image", now: float,
                        rot_deg: float = 0.0) -> None:
    """Hearing bloom / thinking comet / done pulse, on the steel band.

    In place, strictly AFTER draw_bezel_state — a live utterance is the
    transient and rides over whatever standing state the ring carries, the
    claimant ordering _bezel_signal already argues. Before the rotate, like
    everything that lights the baked metal; `rot_deg` is compensated so the
    bloom stays on the TALKER's bearing even when the dial has been spun —
    a "listens toward you" that points at nobody is a lie in the one place
    this face promises not to (§1).

    Wrapped whole: new paint in a compositor that must never stop.
    """
    try:
        ph = _pulse_phase(now)
        conduct = False
        if ph != "hearing":
            try:
                conduct = ((now - THINKING.stat().st_mtime)
                           < LISTEN_THINK_MAX_S)
            except OSError:
                conduct = False
        st = ("hearing" if ph == "hearing"
              else "thinking" if (ph == "thinking" or conduct) else None)
        if conduct:
            # The answer path is live: this episode earns the gold when it
            # closes. Chatter that never trips the conductor never sets it.
            _LISTEN["answering"] = True
        # The talker's bearing, in PIL arc degrees on the PRE-rotate frame:
        # 90 is six o'clock (the wordmark's home viewer), _DOA["now"] is the
        # eased screen angle draw_wordmark is already gliding on this frame,
        # and dg undoes the display rotate applied at the bottom of the loop.
        dg = (-rot_deg if INVERT else rot_deg) if rot_deg > 0.05 else 0.0
        ang = 90.0 + _DOA["now"] + dg
        prev = _LISTEN["state"]
        if st != prev:
            _LISTEN["state"] = st
            if st == "hearing":
                _LISTEN["armed_t0"] = 0.0
                d0 = _PULSE["data"] or {}
                dt_ms = (time.time() - float(d0.get("at", now))) * 1000.0
                print(f"bezel: LISTENING bloom at {_DOA['now']:+.0f}° — on "
                      f"glass {dt_ms:.0f}ms after capture-open", flush=True)
            elif st == "thinking":
                _LISTEN["armed_t0"] = 0.0
                # The bloom DETACHES: the comet leaves from where it bloomed
                # (twelve, when the face joined mid-thought).
                _LISTEN["comet_a0"] = ang if prev == "hearing" else -90.0
                _LISTEN["comet_t0"] = now
                print("bezel: THINKING — comet away", flush=True)
            else:
                _LISTEN["armed_t0"] = now
        if st is None and _LISTEN["armed_t0"] \
                and now - _LISTEN["armed_t0"] >= LISTEN_GRACE_S:
            _LISTEN["armed_t0"] = 0.0
            if _LISTEN["answering"]:
                _LISTEN["answering"] = False
                _LISTEN["done_t0"] = now
                print("bezel: DONE — gold pulse, the reply begins",
                      flush=True)
        if st is None and not _LISTEN["done_t0"]:
            return
        d = ImageDraw.Draw(frame, "RGBA")
        box = [SIZE / 2 - BEZ_RING_R, SIZE / 2 - BEZ_RING_R,
               SIZE / 2 + BEZ_RING_R, SIZE / 2 + BEZ_RING_R]
        #: 2026-08-25: and once the centre carries it, the RIM STOPS.
        #: Widened to 48px at alpha 156 the ink bloom is a heavy graphite
        #: band across the bottom of the bezel — owner, seeing it: "the
        #: perimeter is still screwed up". He is right, and it was mine.
        #: Two indicators for one state was never the design; the rim was
        #: only ever the best available place before there was a better
        #: one. One face, one statement.
        if st == "hearing" and LISTEN_INK and not LISTEN_CENTRE:
            #: the light-ground bloom (see LISTEN_INK): one soft under-arc,
            #: a crisp band fading at its ends, and the metal at the exact
            #: bearing — ink pooling on porcelain, not glow on steel.
            breath = 0.90 + 0.10 * math.sin(now * math.tau * BEZ_WORK_HZ)
            span = LISTEN_BLOOM_SEGS * LISTEN_BLOOM_STEP
            #: 2026-08-25, MEASURED (scripts/measure_bloom.py). The owner
            #: reported "still no visible bloom" three times against a log
            #: that says it fires. It fires: the rim scan finds it at
            #: bearing 52..128deg with every other 10deg bin at 0.0, dead
            #: on six o'clock. It is simply not VISIBLE — 19px of a 540px
            #: dial at 1.23:1 against the rim. Both halves of that were
            #: this line: BEZ_RING_PW+6 is 18px where the bright path uses
            #: a 48px halo, and the stacked-span alpha below was 44/255.
            #: A bloom the panel technically contains and the eye cannot
            #: find is the silent-success pattern in pixels.
            _pw = int(BEZ_RING_PW * 4)
            #: STACKED SPANS, NOT ABUTTED SEGMENTS. The steel faces build
            #: their falloff from adjacent arcs, and on ink the AA seam
            #: between neighbours reads as a machined coin edge (seen on
            #: the first gallery proof at 1:1). Nested spans that all
            #: share the bearing stack their alpha smoothly toward the
            #: centre instead — no radial seam exists to show.
            _half = span * 0.75
            _n2 = 10
            #: Alpha per span, stacking toward the bearing. Solved from
            #: the measurement rather than guessed a third time: 44 gave
            #: 1.23:1 and 96 gave 2.09:1 (ground 201, bloom 96), which
            #: pins the effective overlap at ~2.6 spans. 3:1 wants the
            #: graphite at 67, so alpha 156. Re-measure, do not trust
            #: this arithmetic — measure_bloom.py is two minutes.
            for i in range(_n2):
                _sp = _half * (1.0 - i / float(_n2)) ** 0.8
                d.arc(box, ang - _sp, ang + _sp,
                      fill=LISTEN_COOL + (int(156 * breath),),
                      width=(_pw + 10) if i < 2 else _pw)
            #: the core is lit METAL, not a flat block: dark gold, the
            #: face, and a narrow top-light
            for _cw, _cc in ((8.5, (168, 140, 86)),
                             (5.5, LISTEN_CORE),
                             (2.6, (246, 230, 184))):
                d.arc(box, ang - _cw, ang + _cw,
                      fill=_cc + (int(255 * breath),), width=_pw)
        elif st == "hearing" and not LISTEN_CENTRE:
            #: ── 2026-08-26: THE `and not LISTEN_CENTRE` IS THE LEAK THE
            #: NOTE ABOVE THOUGHT IT HAD ALREADY CLOSED ──────────────────
            #: The 08-25 note fifteen lines up says "once the centre
            #: carries it, the RIM STOPS ... one face, one statement", and
            #: the thinking branch below duly carries the guard. This one
            #: did not, so on a LISTEN_CENTRE face the first condition
            #: (which requires `not LISTEN_CENTRE`) fell through to HERE
            #: and the bright dark-ground bloom drew anyway. Visible in
            #: the shipped proof: data/glass/gallery/listen_hearing_*.png
            #: carries a lit gold arc across the bottom of the bezel in
            #: every frame, drawn from that row's LISTEN_CORE — which is
            #: precisely the perimeter the owner called screwed up. A
            #: comment describing behaviour the code does not have is the
            #: silent-success pattern in prose (§1).
            #:
            #: gallery's rendered pixels DO change with this line: the rim
            #: arc goes and the centre burst is the whole statement, which
            #: is what its own row asked for.
            #: 2026-08-15, owner, round two: "make it brighter if possible."
            #: Shallower falloff (edges stay lit), quad-pen halo, an inner
            #: glow ring for band thickness, and the core drawn twice so
            #: the centre saturates to white.
            breath = 0.92 + 0.08 * math.sin(now * math.tau * BEZ_WORK_HZ)
            halo_w = max(BEZ_RING_PW * 4, BEZ_RING_PW + 8)
            inner = [box[0] + halo_w, box[1] + halo_w,
                     box[2] - halo_w, box[3] - halo_w]
            for i in range(-LISTEN_BLOOM_SEGS, LISTEN_BLOOM_SEGS + 1):
                fall = (1.0 - abs(i) / (LISTEN_BLOOM_SEGS + 1.0)) ** 1.1
                a = int(LISTEN_A_PEAK * breath * fall)
                if a <= 2:
                    continue
                c = ang + i * LISTEN_BLOOM_STEP
                a0, a1 = c - LISTEN_BLOOM_STEP / 2, c + LISTEN_BLOOM_STEP / 2
                # the glow: quad-pen on the band, plus an inner ring so the
                # bloom reads as a thick lit arc, not a hairline
                d.arc(box, a0, a1, fill=LISTEN_COOL + (a // 2,), width=halo_w)
                d.arc(inner, a0, a1, fill=LISTEN_COOL + (a // 3,),
                      width=halo_w // 2)
                # the crisp line; white-hot core drawn twice to saturate
                col = LISTEN_CORE if abs(i) <= LISTEN_BLOOM_SEGS // 3 \
                    else LISTEN_COOL
                d.arc(box, a0, a1, fill=col + (a,), width=BEZ_RING_PW)
                if abs(i) <= LISTEN_BLOOM_SEGS // 3:
                    d.arc(box, a0, a1, fill=col + (a,), width=BEZ_RING_PW)
        elif st == "thinking" and not LISTEN_CENTRE:
            head = (_LISTEN["comet_a0"]
                    + (now - _LISTEN["comet_t0"]) * LISTEN_COMET_DPS)
            # draw_thinking_sweep's comet-tail, on the bezel's radius: a
            # bright head fading backwards, so the travel is legible in one
            # glance and a stopped frame never reads as a lit segment.
            for i in range(18):
                a = int(235 * (1.0 - i / 18.0) ** 1.5)
                if a <= 3:
                    break
                t1 = head - i * 4.5
                d.arc(box, t1 - 4.9, t1,
                      fill=LISTEN_COOL + (a,), width=BEZ_RING_PW)
            d.arc(box, head - 2.4, head + 2.4,
                  fill=LISTEN_CORE + (255,), width=BEZ_RING_PW)
        #: THE CENTRE BURST — see LISTEN_CENTRE. Three rings in flight at
        #: any moment, each leaving the stone and fading as it goes, so a
        #: single stopped frame still reads as outward travel rather than
        #: as three standing circles. Thinking runs them faster and darker
        #: than hearing: the same mechanism carries both states, which is
        #: what makes the acceleration legible as "it is working now"
        #: instead of needing a second indicator.
        if LISTEN_CENTRE and st in ("hearing", "thinking"):
            _fast = 0.62 if st == "thinking" else 1.0
            _ink = LISTEN_COOL if st == "hearing" else LISTEN_THINK
            _peak = LISTEN_C_A[1] if st == "thinking" else LISTEN_C_A[0]
            for _k in range(3):
                _t = ((now / (LISTEN_C_PERIOD * _fast)) + _k / 3.0) % 1.0
                _r = LISTEN_C_R0 + _t * (LISTEN_C_R1 - LISTEN_C_R0)
                #: fade in off the stone as well as out at the end — a
                #: ring that appears at full strength looks like a glitch
                _fade = min(1.0, _t / 0.18) * (1.0 - _t) ** 1.25
                _a = int(_peak * _fade)
                if _a <= 3:
                    continue
                d.ellipse([SIZE / 2 - _r, SIZE / 2 - _r,
                           SIZE / 2 + _r, SIZE / 2 + _r],
                          outline=_ink + (_a,), width=5 if _t < 0.5 else 4)
        if _LISTEN["done_t0"]:
            t = now - _LISTEN["done_t0"]
            if t >= LISTEN_DONE_S:
                _LISTEN["done_t0"] = 0.0
            else:
                a = int(LISTEN_GOLD_A * math.sin(math.pi * t / LISTEN_DONE_S))
                if a > 2:
                    d.arc(box, 0, 360,
                          fill=TOURB_GOLD + (a,), width=BEZ_RING_PW)
    except Exception as e:                      # noqa: BLE001
        _bez_say(f"listen:{e!r}", f"bezel: listening draw failed {e!r} — "
                                  f"the ring is not reporting the ears")


#: ── THE CENTRE IS A HOLE, SO PUT THE MOVEMENT IN IT, 2026-08-06 ───────────
#:
#: Owner, by voice at the puck, correcting the empty centre the 5712 cluster
#: deliberately left: "Making the wordmark small was right, but on this panel
#: the middle now reads as empty rather than as restraint, so give it the
#: thing watchmakers use for exactly this: an OPEN-WORKED, SKELETONISED centre
#: showing the movement underneath. On a watch that is bridges, wheels and a
#: tourbillon seen through the dial. On this device the movement is COMPUTE —
#: so show it honestly: a slowly turning escapement or tourbillon cage at the
#: centre that turns FASTER WHEN SHE IS ACTUALLY WORKING and rests when she is
#: idle, with the credits burning through it ... if the cage is spinning she
#: is thinking, and if it is still she is not. An animation that reports a
#: real state is a complication; one that just moves is a screensaver."
#:
#: THAT LAST SENTENCE IS THE SPECIFICATION AND EVERY NUMBER HERE ANSWERS TO
#: IT. The cage is driven by _pulse_active — the ears' own published phase,
#: the same fact the deleted sweep was drawing — and by nothing else. It does
#: not idle-spin, it does not ease "so it looks alive", and when the ears stop
#: publishing, PULSE_FRESH_S stops the cage rather than leaving it turning:
#: a movement that runs while she is dead is the silent success this file
#: keeps a section on, wearing jewels.
#:
#: THE RADIUS IS A CEILING, NOT A CHOICE. The three complications reach
#: inward to 102.9 (RESERVE: r=172 less a 69.1 flange), 104 (MOONPHASE:
#: 192 less 88) and 139.5 (ROOM), and the 5712 note already records that "the
#: quiet disc it leaves is r≈103".
#:
#: 95 AND NOT 100, AND THE FOUR UNITS CAME OFF A RENDER. At 100 the drawn
#: ink — the bridge ends at TOURB_R+1 plus their shadow, which is offset and
#: blurred — reached r=102.3 against the RESERVE's 102.9, and the RESERVE
#: sits at bearing 207.9 while one of the three cocks points at 210. Six
#: tenths of a pixel between two things on the same ray is touching. At 95
#: the ink reaches 97.3: 5.6 clear of the RESERVE, 6.5 of the MOONPHASE,
#: 42 of the ROOM. Those three are the number to re-measure if any of those
#: pivots moves.
#: 2026-08-07, RE-MEASURED BECAUSE ALL THREE PIVOTS MOVED (see REG_R): the
#: three now sit on one circle at r=192 with one flange of 88, so every one
#: of them reaches inward to 104 and the ink at 97.3 clears all three by the
#: same 6.7. The tightest case above (5.6) is gone and the ceiling rose, so
#: 95 stays — it is a ceiling this radius no longer touches, and growing the
#: cage to use the extra 1.1px would be answering nobody's brief.
#: ── 2026-08-07: 95 -> 130 — THE TOURBILLON GROWS ─────────────────────────
#: Owner, by voice: "make the center tourbillon larger in radius it should
#: stand out." The ceiling above EXPIRED when the three registers moved out
#: to one circle at r=235 (amendment 2, see RES_PIVOT): measured off the
#: constants, all three pivots sit at 235.0 with a 90.0 flange, so every
#: inner edge is at 145.0. At 130 the drawn ink — chamfer at TOURB_R plus
#: the shadow's offset and blur — reaches ~132.6, leaving 12.4 of air to
#: all three flanges, against the >=12 the brief demands. The cage scales
#: with the aperture (62 -> 85, the same ratio) and the whole angle table
#: re-bakes once at startup at the new size (cages + balances measured at
#: 14.5 MB, was ~8.5); the frame loop still does one indexed paste.
#: TWO THINGS HAD TO MOVE OUT OF THE GROWN DAMAGE RECT (276px square,
#: x/y 402..678): the RANGE plate (see RANGE_XY — its figure ink sat 123.6
#: from the centre and 418 in x, inside both the ink circle and the rect)
#: and the reserve's low-credit throb ring, which now stands the rect path
#: down while it breathes (_RES_THROB, the `plain` gate's own pattern).
TOURB_R = 130                       # the opening cut in the mainplate
TOURB_CAGE_R = 85                   # the carriage inside it
#: ── 2026-08-07: THE GOLD TOURBILLON, AND IT NOW TELLS THE TIME ────────────
#:
#: Owner, by voice, holding up the Royal Oak DOUBLE BALANCE WHEEL OPENWORKED
#: in frosted gold: "why don't we have a tourbillon or something ... it should
#: be GOLD to make it look special and give our puck's face real contrast ...
#: you see straight through the dial into the moving mechanism. BUILD A GOLD
#: TOURBILLON, and make it the thing the eye goes to ... Nothing is decorative
#: here; it tells the time and it happens to be the most beautiful thing on
#: the dial."
#:
#: WHAT THIS SUPERSEDES, and the note above is left standing because its
#: argument is still the reason this complication exists at all. The cage was
#: driven by _pulse_active at ten times life and STOPPED when she was idle.
#: It is now a SECONDS DISPLAY: one turn a minute, clockwise, always. The
#: owner's words — "on a real tourbillon the cage turns ONCE PER MINUTE, so
#: the cage IS the seconds hand" — and a hand that stops when the compute is
#: idle is a broken clock, not a complication.
#:
#: SO WHERE DID "IF THE CAGE IS SPINNING SHE IS THINKING" GO? It did not
#: vanish (§1). It is the GLOW under the cage, which has ridden the burn rate
#: since the day this was written and is bright exactly when she is working —
#: the same fact, in the same aperture, one layer down. The bezel carries the
#: named state and the lock screen keeps its sweep. Nothing that had a reader
#: lost one; what changed is that the MOTION is now the seconds and the LIGHT
#: is now the compute, which is the honest division of the two.
#:
#: WHERE IT IS, and this is the one instruction NOT followed. The brief says
#: "an aperture cut in the dial at SIX O'CLOCK, sized like the other
#: complications". Six o'clock is the MOONPHASE's pivot (MOON_XY = 540,732)
#: and all three registers now sit on one circle at REG_R with 9, 3 and 6
#: taken — so putting the cage at six means evicting a showpiece the owner
#: commissioned by name, which is his call and not this session's. The
#: aperture stays at the CENTRE, where it already is: it is r=95 against the
#: registers' 88, so it IS "sized like the other complications", it is the
#: opening the same owner asked for when he asked for a skeletonised centre,
#: and the centre is where the eye goes by default. If he wants it at six,
#: that is a conversation about which register moves.
#: 2026-08-09, themes: these three ride the theme row's `accent` (the
#: fourth-pass note at _THEMES). They were never only the cage's gold — the
#: three hands' counterpoises, the reserve's F/E, the $LEDGER caption, the
#: moon hand's tail and tip and the listening ring all strike in them, which
#: is why the owner's "the gold accents becoming red" lands here and not on
#: the wordmark's metal. patek and royal-oak carry the spoken (212,175,92)
#: and its two flanks unchanged; ferrari carries Rosso Corsa.
TOURB_GOLD = _THEME["accent"]       # the owner's number, spoken
TOURB_GOLD_LIT = _THEME["accent_lit"]   # the specular edge up one flank
TOURB_GOLD_DARK = _THEME["accent_dark"]  # the shaded flank, so an arm is three
                                    # planes and not a drawn line (see below)
#: ── THE CAPTION'S THROB (2026-08-07, refile of the ledger cadence brief) ──
#: One swell per counter STEP (see LEDGER_STEP_MIN_S): 1.5s ease-in-out from
#: the strike gold toward (255,225,150) and back. TABLE-DRIVEN — these 48
#: colours are computed once here, and draw_gold_strikes indexes them by
#: elapsed/LEDGER_THROB_S; the cosine envelope is 0 at both ends, so entry
#: 47 is TOURB_GOLD again and the swell lands exactly where it left.
#: Defined HERE and not with the other LEDGER_ constants because it is
#: built from TOURB_GOLD, which this file defines at the tourbillon.
LEDGER_THROB_PEAK = (255, 225, 150)
_LEDGER_THROB_TABLE = [
    tuple(int(round(g + (p - g) * (0.5 - 0.5 * math.cos(
        2.0 * math.pi * i / 47.0))))
        for g, p in zip(TOURB_GOLD, LEDGER_THROB_PEAK))
    for i in range(48)
]
#: THE DARKNESS IS THE TRICK, and it is the owner's own diagnosis of the
#: reference watch: "under the cage, dark openworked structure, NEAR BLACK, so
#: the GOLD HAS SOMETHING TO READ AGAINST". Near black and not black — a hole
#: with nothing in it is a hole; these three luminances are a mainplate, its
#: wheels and the light catching their edges, seen a long way down.
#: SUPERSEDED 2026-08-07 by the floor/plate pairs below, and kept because the
#: paragraph above them is still the argument for this aperture being dark at
#: all. What they got wrong is measurable and is written up there: all three
#: are warm greys within 20 luminance of each other, so they were one plane
#: wearing three names, and the movement had no depth to read.
TOURB_DARK = (11, 10, 9)            # was: the floor of the movement
TOURB_DARK_PLATE = (33, 30, 25)     # was: the openworked plate above it
TOURB_DARK_LIT = (66, 59, 47)       # was: the arris on that plate
#: ── 2026-08-07: IT IS A FLYING TOURBILLON, SO ALL THE DEPTH IS BELOW ──────
#:
#: Owner, by voice: "right now it's just this black background in the circle,
#: that isn't right ... more layered colours, perceived depth", pointing at the
#: Audemars Piguet Royal Oak FLYING Tourbillon 26730TI. The decisive fact is in
#: that reference and it is not a colour: a flying tourbillon has NO BRIDGE
#: OVER THE CAGE — "an unobstructed view of the movement ... the illusion of
#: flying, suspended in the middle of the aperture". Nothing crosses over it.
#: Every plane there is, is UNDERNEATH.
#:
#: WHAT WAS ACTUALLY WRONG, and the note above is left standing because its
#: argument — near black so the gold has something to read against — is still
#: why this aperture is dark at all. We drew the cage and then drew nothing
#: below it, so a flat TOURB_DARK disc was carrying the whole floor. A flat
#: fill cannot read as a depression, for the reason the owner gave: PURE BLACK
#: HAS NO GRADIENT TO READ. The eye takes a hole from the fall-off across it,
#: not from its darkness.
#:
#: SO IT IS BUILT IN PLANES, BACK TO FRONT, and there are four:
#:   1  the floor      — a radial well, MID at the centre to RIM at the wall,
#:                       because a well is darkest where it meets its own wall.
#:                       Grey-blue, off the reference's sandblasted dial.
#:   2  the wheels     — TOURB_PLATE_DARK: the deepest structure, one step
#:                       off the floor, which is where it always sat. It had
#:                       to leave near black BECAUSE THE FLOOR TOOK IT — at
#:                       luminance 30 against a floor running 24–38, the whole
#:                       train was the same tone as the ground it stood on.
#:   3  the bridges    — TOURB_PLATE, cool titanium, bevelled, lit from the
#:                       fixed upper-left key (TOURB_KEY). Distinctly cooler
#:                       AND darker than the gold: 79 against the gold's 175,
#:                       so the cage still wins the aperture.
#:   4  the cage       — gold, flying, and NOTHING is drawn above it. The
#:                       pivot boss moved out of _tourb_static and down into
#:                       the ground for exactly this reason.
#: Plus the jewels, which are the only warm accent besides the gold and are
#: what says "mechanism" faster than any amount of grey.
#:
#: AND THE ONE THAT SELLS IT: THE CAGE CASTS A SHADOW ON THE FLOOR. A shadow
#: between two planes buys more perceived depth than any shading within one,
#: because it is the only mark that proves the two planes are apart. Offset
#: DOWN-RIGHT, away from the same upper-left key the numerals use (NUM_SPEC:
#: "the specular goes up-left and the shadow down-right"), and blurred, since
#: a hard shadow reads as a second cage.
#:
#: IT COSTS NOTHING PER FRAME. The shadow is baked into the sixty pre-rendered
#: cage angles that were already cached — built from each ROTATED cage, so its
#: shape turns with the cage while its direction stays with the light, which
#: is what a fixed key demands. The sprite grows 136 -> 166 px to hold the
#: offset and the blur, so the table goes from ~4.4 MB to ~6.6 MB, paid once
#: at startup. The frame loop still does one indexed paste.
TOURB_FLOOR_MID = (34, 42, 52)      # was: smoked grey-blue, the well's CENTRE
TOURB_FLOOR_RIM = (6, 7, 9)         # was: near black where floor meets wall
#: ── 2026-08-08: THAT PAIR WAS A MOUND, AND THE MEASUREMENT SAYS SO ────────
#: The two above are kept standing because they are the tones — grey-blue
#: metal, near black — and the range between them was right. WHICH END EACH
#: ONE WAS ON WAS BACKWARDS, and the argument that put them that way ("a well
#: is darkest where it meets its own wall") is the argument for a SAUCER, not
#: for a bore cut through a plate.
#:
#: Owner, on the live glass: "the well's centre measures L=76.5, its middle
#: L=29.0, its rim L=12.7 — the BRIGHT PART IS THE MIDDLE. That is a mound,
#: not a well." Re-measured here on _tourb_layer over WHOLE annuli (the
#: r42 verification sampled the floor on the bearings BETWEEN the bridges and
#: got the right answer for the wrong region — the eye does not sample between
#: arms, it takes the whole aperture): median L 79.3 / 30.2 / 21.7 across
#: r20-32, r60-80, r112-126. Monotonically DOWN and outward. A raised boss.
#:
#: A BORE IS DEEPEST IN THE MIDDLE AND BRIGHTEST AT ITS LIP, because the lip
#: is the part the room can still see and the middle is the part light has to
#: reach twice. So the gradient runs the other way now: DEEP at the centre,
#: LIP at the wall, and the wall's own arithmetic (TOURB_WALL_W) picks up
#: from the lip tone instead of climbing out of near black.
TOURB_FLOOR_DEEP = (5, 6, 8)        # the bottom of the bore, at its centre
TOURB_FLOOR_LIP = (46, 56, 68)      # the lit floor where it runs up to the wall
TOURB_PLATE = (74, 80, 88)          # titanium bridge at an intermediate depth
TOURB_PLATE_LIT = (128, 136, 146)   # its polished bevel, on the key side
TOURB_PLATE_DARK = (40, 44, 50)     # the flank turned away from the key
TOURB_RUBY = (146, 26, 30)          # the jewels: deep red, and small
TOURB_RUBY_LIT = (214, 96, 84)      # the light in the middle of one
#: ── 2026-08-07: THE BORE OF THE HOLE, LIT BACKWARDS ───────────────────────
#: The r42 pass built the planes and they still read as concentric FLAT
#: RINGS, and this is the missing part: the aperture's rim gets a visible
#: INNER WALL, and an interior catches the key light on the side OPPOSITE
#: everything standing on the dial — the light crosses the hole and lands on
#: the far side of the bore. Lit lower-right, dark upper-left, which is what
#: makes the eye read DOWN INTO rather than "a dark disc with a rim".
TOURB_WALL_W = 8                    # px of visible bore below the dial edge
TOURB_WALL_LIT = (66, 72, 82)       # the flank the key light lands on
TOURB_WALL_DARK = (3, 4, 6)         # the flank under the key side's overhang
#: The key, as a unit vector on the y-down panel: upper-left, the same one the
#: baked bezel and the numerals are lit by. If the aperture is lit from a
#: different direction than the metal around it the whole illusion dies, so
#: this is read from NUM_SPEC's note rather than chosen here.
TOURB_KEY = (-0.7071, -0.7071)
#: THE SHADOW IS MEASURED, NOT PICKED. First cut was alpha 165 over a 4.0
#: blur, and the render said it was not doing its job: the cage's 3px ring is
#: THIN, and a 4.0 sigma spreads a thin line until almost nothing of it is
#: left — the floor beside the cage went 20.4 -> 16.6, a 4-unit dip on a
#: ground that is already dark. A shadow you have to be told about is not
#: buying depth. 3.0 and 210 keep the same soft edge and land the dip where
#: the eye can find it. It cannot be made deeper than the floor it falls on,
#: which is the other half of why plane one stopped being pure black.
#: 7 -> 10, 2026-08-07, with the aperture (95 -> 130): the offset is what
#: states the DROP between cage and floor, so it scales with the well or the
#: bigger cage reads as floating lower. The blur does NOT scale — the note
#: above measured a 4.0 sigma spreading the 3px ring to nothing, and the
#: ring is still 3px.
TOURB_SHADOW_OFF = 10               # px down-right: away from TOURB_KEY
TOURB_SHADOW_BLUR = 3.0
TOURB_SHADOW_A = 210                # peak alpha of the cast shadow
#: ── 2026-08-08: THE DEPTH BRIEF, VERIFIED BY MEASUREMENT ──────────────────
#: The owner's refiled brief (twice killed by session limits) demanded the
#: five planes above be PROVED on the render, not asserted. Measured on
#: _tourb_ground / _tourb_cages as built, Rec.709 luminance:
#:   WELL    floor centre 38.9 -> rim 14.6, a 62.5% fall (brief: >=25%).
#:           Centre sampled r20-30 on bearings 30/150/270 — the bearings
#:           BETWEEN the bridges; on 0/60/... the arms' 15px hub half-width
#:           reaches r<30 and the "floor" reads 78.7, i.e. bridge metal.
#:   PLANES  floor 28.5 < bridges 79.3 < cage 178.9 — steps of 2.79x and
#:           2.26x against the >=1.25x asked.
#:   SHADOW  darkening centroid vs cage-ink centroid, four cage angles
#:           (idx 0/7/22/45): dx +3.8/+1.4/+6.4/+2.4, dy +18.4/+3.6/
#:           +12.4/+10.9 — down-right at every angle, as TOURB_KEY demands.
#:           (Built at +10,+10 before blur; occlusion by the cage's own ink
#:           is what moves the visible centroid off that.)
#:   CPU     cached _tourb_layer path 0.09 ms/frame; the bake is startup-
#:           only and no frame-path code changed, so the budget moved 0 pts.
#: ── 2026-08-08, later: THAT "WELL" LINE IS THE ONE THAT MISLED ────────────
#: It is left standing because the trap is in HOW it sampled, not in the
#: arithmetic. Sampling the floor on the bearings BETWEEN the bridges — and
#: saying so, and even naming what the other bearings read — got the right
#: answer for a region the eye never looks at on its own. THE EYE TAKES THE
#: WHOLE APERTURE, and over whole annuli the same render read median L 79.3
#: (r20-32) / 30.2 (r60-80) / 21.7 (r112-126): brightest in the middle, which
#: is a mound. The owner saw it immediately and the verification had passed.
#: So the well was inverted (TOURB_FLOOR_DEEP) and the hub metal taken down
#: (see _tourb_ground), and the test is now stated on WHOLE ANNULI: median L
#: must RISE outward by >=25% per step. As built, over all 20 sampled cage
#: angles, the worst case is 21.7 -> 29.4 -> 41.0, x1.36 and x1.35. The plane
#: order above is unchanged where it is read: floor 38.8 < bridges 79.3 <
#: cage 176.9. The shadow was not touched.
#: A MEASUREMENT ON A SUBSET IS A CLAIM ABOUT THAT SUBSET. If the thing being
#: proved is what the eye reads, sample what the eye reads.
#: NO ROTATION PER FRAME — the idle loop is at 8 fps for thermal reasons and
#: resampling a sprite there is the one cost this complication could easily
#: have added. The cage is pre-rendered at TOURB_STEPS angles, one per second
#: of the minute, and the frame indexes by the current second: one cached
#: paste, no resample, ever. They are small — the sprite is cut to the cage's
#: own diameter, not the aperture's, so sixty of them is about 4.4 MB.
#: 120 (half-second steps, 3 degrees) is a one-character change here and the
#: owner pre-authorised it; 60 is shipped because it doubles as the deadbeat
#: tick a seconds display is allowed to have, at half the memory on a board
#: that already runs hot.
TOURB_STEPS = 60
#: ── 2026-08-07: THE BALANCE OSCILLATES; THE CAGE STILL TURNS ──────────────
#:
#: Owner, by voice: "the tourbillon's motion is wrong — it should be a more
#: SPRINGY BACK AND FORTH rotation, not this monotonic clock movement." He is
#: right, and the reason names the part: in an openworked watch the thing the
#: eye catches is NOT the cage. The cage turns once a minute and is almost too
#: slow to see. What moves is the BALANCE WHEEL inside it, and a balance does
#: not rotate — it winds back and forth against a hairspring, forever.
#:
#: SO NOTHING WAS TAKEN AWAY. The cage keeps its one turn a minute (it is the
#: seconds hand, see above, and a seconds hand that springs is a broken one).
#: The balance came OUT of the cage sprite and became its own table, and it is
#: the part that swings. Motion and time-telling are now different parts, and
#: that is how the reference watch does it too.
#:
#: SINE, NOT SAWTOOTH, AND NOT BY TASTE. A hairspring IS a harmonic
#: oscillator, so sin() is the physics: fastest through the middle, easing to
#: a stop at each end, with no easing curve to tune by eye.
#:
#: THE FRAME RATE PICKS THE NUMBERS, and this is the part that would have
#: bitten. The idle loop is 8 fps (IDLE_FPS, thermal). A real balance beats at
#: 4 Hz, and 4 Hz sampled at 8 fps is exactly Nyquist — it would render as a
#: standing still wheel or a stutter, which is the strobing wagon wheel and
#: not a complication. So this is a STYLISED balance and the beat is chosen to
#: be honest at 8 fps:
#:   0.4 Hz  → one full back-and-forth every 2.5 s = 20 frames, 10 per swing.
#:   110 deg each way → 220 peak-to-peak. Peak step = 110*2pi*0.4/8 = 34.6 deg
#:   per frame through the middle, falling to ~5 deg at each end where the
#:   sine flattens. That gradient IS the springiness; the eye reads the pause
#:   at the ends and the dash across the middle.
#: The owner's "roughly 270 deg each way" is the real physics and is not what
#: is drawn: at 8 fps a 270 amplitude puts 85 deg between consecutive frames
#: and the wheel teleports. Raising the frame rate would fix it and the
#: thermal budget is not available, so the amplitude gives way instead.
TOURB_BAL_AMP_DEG = 110.0
TOURB_BAL_HZ = 0.4
#: SAME TRICK AS THE CAGE, WHICH IS WHY THIS COSTS NOTHING. 72 pre-rendered
#: angles over the whole circle (5 deg apart), indexed by a sine of the clock:
#: the motion is a change of INDEX, not a change of work, and there is still
#: no resample in the frame. 5 deg of quantisation against a 34.6 deg fastest
#: frame is a seventh of one step and cannot be seen. The sprite is cut to the
#: balance's own diameter (82 px), so all 72 are ~1.9 MB.
#: The full circle and not just the swept arc, because the balance is CARRIED
#: BY THE CAGE: the drawn angle is the swing PLUS the cage's own bearing, so
#: it wraps past 360 twice a minute.
TOURB_BAL_STEPS = 72
#: THE CREDITS BURNING THROUGH IT. Intensity rides the BURN RATE, in credits
#: per minute, and 500 is not a fresh guess: it is the scale home.html's face
#: arc has always used (PUCK-SHOW, 2026-08-01: "the existing face arc scale
#: (rate/500) happens to sit right for real burn rates"). So the glow under
#: the cage is bright exactly when the meter beside it is.
TOURB_BURN_FULL = 500.0
TOURB_GLOW_R = 90                   # 66, scaled with the cage 2026-08-07
TOURB_GLOW = (255, 176, 64)         # RES_AMBER: one fire, two windows on it
TOURB_GLOW_STEPS = 12
_TOURB_STATIC = None
_TOURB_GROUND = None
_TOURB_CAGES: list = []
_TOURB_BALANCES: list = []
#: "under" and "box" are the damage rect: the aperture's background and its
#: top-left, kept by draw_tourbillon so _tourb_rect_paint can repaint that
#: window alone between full frames (TOURB_RECT_FPS).
_TOURB_LAY: dict = {"key": None, "lay": None, "under": None, "box": None}


def _tourb_bar(px, py, a_deg: float, r0: float, r1: float,
               w0: float, w1: float, off=(0.0, 0.0)):
    """A tapered bar along a bearing: (r0,w0) at the hub end, (r1,w1) out.

    `off` shifts the bar SIDEWAYS across its own width — (hub, tip) in the
    same units as w0/w1. It exists for the arms' cross-section bands
    (2026-08-08): each band is a narrow bar offset to its own place across
    the beam, which is how a chamfered section gets modelled without
    per-pixel shading in a once-per-process sprite.
    """
    t = math.radians(a_deg)
    ux, uy = math.cos(t), math.sin(t)
    o0, o1 = off
    return [(px + r0 * ux - (w0 - o0) * uy, py + r0 * uy + (w0 - o0) * ux),
            (px + r1 * ux - (w1 - o1) * uy, py + r1 * uy + (w1 - o1) * ux),
            (px + r1 * ux + (w1 + o1) * uy, py + r1 * uy - (w1 + o1) * ux),
            (px + r0 * ux + (w0 + o0) * uy, py + r0 * uy - (w0 + o0) * ux)]


def _tourb_ground():
    """What you see THROUGH the hole: near-black openworked structure.

    ── 2026-08-07 ────────────────────────────────────────────────────────
    New layer, and it is the half of the reference watch the first cut of
    this complication did not have. Before today the aperture was an outline
    and the TAPISSERIE showed through it, so the cage was steel on a lit
    field and had nothing to stand against. The owner, on the frosted-gold
    Royal Oak: "under the cage, dark openworked structure, near black, so the
    gold has something to read against; THAT DARKNESS IS THE WHOLE TRICK in
    the reference watch."

    So this is opaque, and that is how "the tapisserie stops at the aperture's
    edge" gets done — two regions, two treatments, exactly as the subdials do
    it, and without touching the bake. The dial's texture and the starfield
    are both already on the frame when this is pasted over them.

    Everything here is OPENWORKED — plates with gaps between them, not a
    disc. A filled black circle is a hole; this has to read as a movement
    seen a long way down.
    """
    global _TOURB_GROUND
    if _TOURB_GROUND is None:
        r = TOURB_R + 8
        lay = Image.new("RGBA", (2 * r, 2 * r), (0, 0, 0, 0))
        px = py = float(r)
        d = ImageDraw.Draw(lay)
        rr = float(TOURB_R) - 1.0
        # Everything openworked below was drawn for the 95 aperture and
        # scales with it (2026-08-07, 95 -> 130) — wheels that kept their
        # old radii would huddle in the middle of the grown well.
        K = TOURB_R / 95.0
        # PLANE ONE, THE FLOOR: a recessed well and not a disc (2026-08-07,
        # see TOURB_FLOOR_MID). Concentric 1px bands, and the RISE outward IS
        # the depression — a flat fill cannot have it, and neither can a fall
        # outward, which is a mound (2026-08-08, see TOURB_FLOOR_DEEP).
        # Deepest and darkest at the centre, running up to the lit lip where
        # the floor meets its own wall. Exponent 1.3 keeps the middle third
        # genuinely dark and spends most of the range on the outer half,
        # which is where a bore actually catches the room.
        for i in range(int(rr), 0, -1):
            k = (i / rr) ** 1.3
            d.ellipse([px - i, py - i, px + i, py + i],
                      fill=tuple(int(round(TOURB_FLOOR_DEEP[j]
                                           + (TOURB_FLOOR_LIP[j]
                                              - TOURB_FLOOR_DEEP[j]) * k))
                                 for j in range(3)) + (255,))
        # ── THE WELL IS LIT BACKWARDS, 2026-08-08 ──────────────────────
        # The radial fall-off above is a DOME's signature: brightest in the
        # middle, dark at the edge. Measured on the live glass it gave
        # centre 76.5 / mid 29.0 / rim 12.7 and the owner read exactly what
        # that is — "still flat", a boss on a dark disc rather than a bore.
        # LATER THE SAME DAY: a directional wash alone did not settle it,
        # because it left the dome underneath. The base gradient is inverted
        # now (TOURB_FLOOR_DEEP), so this wash rides on a bore and does the
        # job it was written for — DIRECTION, not depth.
        #
        # An INTERIOR catches the key light on its FAR wall: the sky is
        # upper-left (TOURB_KEY), so the lit crescent is LOWER-RIGHT and the
        # near wall under the overhang is the dark one. That inversion is
        # the same arithmetic the subdial pockets already use
        # (_pocket_relief) and it is what makes the eye read DOWN INTO
        # rather than UP AT. Applied as a directional wash over the radial
        # base so the well keeps its depth AND gains its direction.
        _wash = Image.new("RGBA", lay.size, (0, 0, 0, 0))
        _wd = ImageDraw.Draw(_wash)
        _kx, _ky = -TOURB_KEY[0], -TOURB_KEY[1]      # toward the far wall
        for i in range(int(rr), 0, -1):
            t = i / rr                                # 0 centre .. 1 rim
            # Only the outer half of the floor is wall; the middle stays the
            # deepest, darkest part of the bore.
            if t < 0.45:
                continue
            g = (t - 0.45) / 0.55
            off = int(round(rr * 0.30 * g))
            cx2, cy2 = px + _kx * off, py + _ky * off
            a = int(round(150 * g * g))
            _wd.ellipse([cx2 - i, cy2 - i, cx2 + i, cy2 + i],
                        fill=TOURB_WALL_LIT + (a,))
        _wash = _wash.filter(ImageFilter.GaussianBlur(6.0))
        # Clipped to the bore: the wash must not spill onto the dial.
        _clip = Image.new("L", lay.size, 0)
        ImageDraw.Draw(_clip).ellipse([px - rr, py - rr, px + rr, py + rr],
                                      fill=255)
        _wash.putalpha(ImageChops.multiply(_wash.getchannel("A"), _clip))
        lay.alpha_composite(_wash)
        # And the NEAR wall's occlusion, upper-left, where the dial's own
        # edge overhangs the hole — the dark half of the same pair.
        _occ = Image.new("RGBA", lay.size, (0, 0, 0, 0))
        _od = ImageDraw.Draw(_occ)
        for i in range(int(rr), int(rr * 0.55), -1):
            t = (i - rr * 0.55) / (rr * 0.45)
            off = int(round(rr * 0.22 * t))
            cx2, cy2 = px + TOURB_KEY[0] * off, py + TOURB_KEY[1] * off
            _od.ellipse([cx2 - i, cy2 - i, cx2 + i, cy2 + i],
                        fill=(0, 0, 0, int(round(120 * t * t))))
        _occ = _occ.filter(ImageFilter.GaussianBlur(7.0))
        _occ.putalpha(ImageChops.multiply(_occ.getchannel("A"), _clip))
        lay.alpha_composite(_occ)
        # PLANE TWO, the wheel train: two rims and a barrel, sitting just off
        # the floor, which is where they have always sat. Drawn BEFORE the
        # bridges now — they are the deepest structure and the bridges cross
        # over them. Off the three arms' bearings on purpose, so the gaps
        # between the arms have something in them.
        #
        # THEY LOST THEIR NEAR-BLACK BECAUSE THE FLOOR TOOK IT. Measured on
        # this render: TOURB_DARK_PLATE is luminance 30.3 and the new floor
        # runs 24–38 across the radii these wheels sit at, so at the old
        # colour the whole train was invisible — same tone as the ground it
        # stood on. They are the dimmest titanium now, one step under the
        # bridges that cross them, which is the depth order they actually have.
        for a, rad, wr in ((30.0, 52.0, 21.0), (150.0, 46.0, 15.0),
                           (270.0, 55.0, 12.0)):
            rad, wr = rad * K, wr * K
            t = math.radians(a)
            wx, wy = px + rad * math.cos(t), py + rad * math.sin(t)
            d.ellipse([wx - wr, wy - wr, wx + wr, wy + wr],
                      outline=TOURB_PLATE_DARK + (255,), width=2)
            d.ellipse([wx - wr * 0.35, wy - wr * 0.35,
                       wx + wr * 0.35, wy + wr * 0.35],
                      outline=TOURB_PLATE + (255,), width=1)
        # PLANE ORDER IS ALSO FOCUS ORDER (2026-08-07): the floor and the
        # wheels standing on it take a slight defocus before the bridges go
        # on sharp — three planes, three focus levels, and the cage above
        # them keeps the only crisp specular. The blur softens the layer's
        # own alpha edge too, so the hole is re-punched hard at rr; the
        # bore wall below then covers the seam.
        lay = lay.filter(ImageFilter.GaussianBlur(1.1))
        mask = Image.new("L", lay.size, 0)
        ImageDraw.Draw(mask).ellipse([px - rr, py - rr, px + rr, py + rr],
                                     fill=255)
        lay.putalpha(ImageChops.multiply(lay.getchannel("A"), mask))
        d = ImageDraw.Draw(lay)
        # PLANE THREE, the bridges: three broad arms on the bearings the OLD
        # steel cocks used (90/210/330), because that arrangement was found by
        # rendering and the argument for it — two would make a V with an open
        # foot on a y-down panel — has not changed. Cool titanium since
        # 2026-08-07 rather than near black: a movement seen down a hole is
        # metal, and the eye needs a tone between the floor and the gold.
        #
        # THE BEVEL IS LIT FROM A FIXED KEY, and that is the whole reason this
        # is not the cage's rotating specular: TOURB_KEY is upper-left, like
        # the bezel and the numerals, so which flank of an arm is bright
        # depends on the arm's own bearing. dot(v, KEY) picks it. Light this
        # from anywhere else and the aperture stops belonging to the dial.
        #
        # DRAWN AT 3x AND REDUCED, for the reason the cage's own note gives:
        # ImageDraw has no antialiasing, and a 2px bevel down the flank of a
        # tapered bar is exactly where that shows — at near black it did not
        # matter, at titanium it is three staircased grey stripes. Paid once,
        # in a function that is cached for the life of the process.
        #
        # AND THEY STOP SHORT OF THE WALL (rr-11, not rr-2). Near black they
        # could run into it because nothing could see them; at this luminance
        # a bar that touches the wall reads as tape across the hole instead of
        # as a bridge standing inside it, and it fills in the dark ring that
        # is doing the work of saying "depression".
        S = 3
        sub = Image.new("RGBA", (lay.size[0] * S, lay.size[1] * S),
                        (0, 0, 0, 0))
        ds = ImageDraw.Draw(sub)
        for a in (90.0, 210.0, 330.0):
            bar = _tourb_bar(px * S, py * S, a, 6.0 * K * S,
                             (rr - 11.0 * K) * S, 11.0 * K * S, 6.5 * K * S)
            ds.polygon(bar, fill=TOURB_PLATE + (255,))
            t = math.radians(a)
            vx, vy = -math.sin(t), math.cos(t)
            key_side = (vx * TOURB_KEY[0] + vy * TOURB_KEY[1]) > 0.0
            ds.line([bar[0], bar[1]],
                    fill=(TOURB_PLATE_LIT if key_side else TOURB_PLATE_DARK)
                    + (255,), width=2 * S)
            ds.line([bar[2], bar[3]],
                    fill=(TOURB_PLATE_DARK if key_side else TOURB_PLATE_LIT)
                    + (255,), width=2 * S)
        lay.alpha_composite(sub.resize(lay.size, Image.LANCZOS))
        d = ImageDraw.Draw(lay)
        # THE JEWELS, and they are tiny on purpose (2026-08-07). Four deep-red
        # rubies at the pivots — the three wheels and the cage's own centre —
        # and they are the only warm thing in the aperture besides the gold.
        # On a real movement they say "mechanism" faster than any amount of
        # grey does, which is why four 4px dots are worth their room.
        for a, rad in ((30.0, 52.0), (150.0, 46.0), (270.0, 55.0)):
            t = math.radians(a)
            rad *= K            # the pivots follow their wheels; the rubies
            jx, jy = px + rad * math.cos(t), py + rad * math.sin(t)   # stay small
            # ── BLING, 2026-08-08 ─────────────────────────────────
            # 4px dots vanished at arm's length. The owner: "the red
            # contrast is perfect for the gold and blue behind it. but
            # they barely stick out right now. make them obnoxiously
            # blingly big." So: a gold chaton (the setting a real jewel
            # sits in), a fat ruby, and a bright specular pip upper-left
            # of centre so it reads as a polished stone catching the same
            # sky as everything else, not a red dot.
            # 11 -> 8.5, 2026-08-08: "make the rubies a tad bit smaller" —
            # the bling landed and overshot slightly.
            jr = 8.5 * K
            d.ellipse([jx - jr - 2, jy - jr - 2, jx + jr + 2, jy + jr + 2],
                      fill=TOURB_GOLD_DARK + (255,),
                      outline=TOURB_GOLD_LIT + (255,), width=2)
            d.ellipse([jx - jr, jy - jr, jx + jr, jy + jr],
                      fill=TOURB_RUBY + (255,))
            d.ellipse([jx - jr * 0.55, jy - jr * 0.55,
                       jx + jr * 0.15, jy + jr * 0.15],
                      fill=TOURB_RUBY_LIT + (255,))
            d.ellipse([jx - jr * 0.42, jy - jr * 0.42,
                       jx - jr * 0.10, jy - jr * 0.10],
                      fill=(255, 214, 196, 235))
        # The cage's pivot, WHICH USED TO BE IN _tourb_static AND ABOVE THE
        # CAGE. It is below it now, and that is the flying tourbillon's one
        # rule: nothing crosses over the carriage. Same boss, same jewel, one
        # plane down.
        bo = 9.0 * K
        d.ellipse([px - bo, py - bo, px + bo, py + bo],
                  fill=TOURB_GOLD_DARK + (255,),
                  outline=TOURB_GOLD_LIT + (255,), width=2)
        _cr = 6.5 * K                     # the centre jewel, a tad smaller
        d.ellipse([px - _cr, py - _cr, px + _cr, py + _cr],
                  fill=TOURB_RUBY + (255,))
        d.ellipse([px - _cr * 0.5, py - _cr * 0.5,
                   px + _cr * 0.1, py + _cr * 0.1],
                  fill=TOURB_RUBY_LIT + (255,))
        # ── THE HUB WAS FILLING THE CENTRE, 2026-08-08 ─────────────────
        # Half of "the bright part is the middle" is not the floor at all:
        # it is METAL. The three bridges converge here 15 px wide apiece and
        # the pivot boss is polished gold, so at r20-32 the majority of the
        # pixels the eye takes are plate at L79 and boss at L>100, sitting on
        # a floor that is supposed to be the deepest thing in the aperture.
        # The measurement had no way to say so because it sampled between the
        # arms; over the whole annulus the metal wins.
        #
        # A CAST SHADOW ALREADY PROVES THE CAGE IS ABOVE THE FLOOR. This is
        # the other half of the same claim: whatever is directly under a
        # carriage that flies is in ITS OWN shade, so the hub goes down with
        # the light it does not receive. Black, not a repaint, so every part
        # keeps its own hue and only loses value — the bridges still step
        # above the floor further out, where they are lit, and the plane
        # order (floor < bridges < cage) is untouched where it is read.
        _hub = Image.new("RGBA", lay.size, (0, 0, 0, 0))
        _hd = ImageDraw.Draw(_hub)
        _hr = rr * 0.50
        for i in range(int(_hr), 0, -1):
            t = i / _hr                              # 1 at its edge, 0 middle
            _hd.ellipse([px - i, py - i, px + i, py + i],
                        fill=(0, 0, 0, int(round(245 * (1.0 - t) ** 0.45))))
        lay.alpha_composite(_hub.filter(ImageFilter.GaussianBlur(6.0)))
        d = ImageDraw.Draw(lay)
        # The wall of the hole. A cut through a dial has a THICKNESS, and it
        # is what stops the black reading as printed ink: the last few px
        # inside the aperture fall away to true black.
        #
        # EVERY COLOUR IN THIS FUNCTION IS ALPHA 255, and the first render is
        # why. ImageDraw REPLACES the pixel rather than compositing, so a
        # ring drawn here at alpha 200 does not darken the plate — it punches
        # a 78%-transparent band in it, and the dial's tapisserie shows
        # straight back through the rim of a hole that is supposed to be
        # opaque. Measured on the first cut: the ground read (20,23,34)
        # against a (24,28,42) backdrop at r=87, i.e. the hole had no edge.
        # Darkening here is done by choosing a darker OPAQUE colour.
        # 2026-08-07: against TOURB_FLOOR_RIM rather than TOURB_DARK, so the
        # wall picks up exactly where the floor's own gradient has arrived.
        # ── 2026-08-07, later: SUPERSEDED — the rings above were a uniform
        # fall-off, the same in every direction, and a bore is not: see
        # TOURB_WALL_W. 5-degree arc segments, colour set by the dot of each
        # segment's bearing with -TOURB_KEY, so the wall is brightest at
        # lower-right — exactly opposite the dial's own lighting — with a
        # near-black seam where it meets the floor, so the lit flank stands
        # off the ground it drops to.
        wall = [px - rr, py - rr, px + rr, py + rr]
        for seg in range(72):
            a0 = seg * 5.0
            t = math.radians(a0 + 2.5)
            f = 0.5 + 0.5 * (math.cos(t) * -TOURB_KEY[0]
                             + math.sin(t) * -TOURB_KEY[1])
            col = tuple(int(round(TOURB_WALL_DARK[j]
                                  + (TOURB_WALL_LIT[j]
                                     - TOURB_WALL_DARK[j]) * f))
                        for j in range(3))
            d.arc(wall, a0 - 0.6, a0 + 5.6, fill=col + (255,),
                  width=TOURB_WALL_W)
        s = rr - TOURB_WALL_W
        d.ellipse([px - s, py - s, px + s, py + s],
                  outline=(0, 0, 0, 255), width=2)
        _TOURB_GROUND = lay
    return _TOURB_GROUND


def _tourb_static():
    """The polished chamfer of the opening. Nothing else stands above the cage.

    Built once, and composited LAST — the lip goes through _dial_metal like
    the moonphase frame, because it is the DIAL cut through and must be the
    same steel as the rest of it; the cage inside it is gold on purpose, and
    the contrast between the two is the picture.

    ── 2026-08-07 ────────────────────────────────────────────────────────
    THE JEWEL BOSS LEFT THIS LAYER. It is in _tourb_ground now, one plane
    down. This is a FLYING tourbillon (see TOURB_FLOOR_MID) and the one thing
    that makes it flying is that nothing crosses over the carriage — a 20px
    gold boss on the cage's own centre is exactly the upper bridge the
    reference watch does not have. What is left here is the chamfer, which is
    not above the cage but around it: it is the dial's own cut edge, and it is
    what makes the opening read as cut THROUGH rather than printed on.
    """
    global _TOURB_STATIC
    if _TOURB_STATIC is None:
        r = TOURB_R + 8
        lay = Image.new("RGBA", (2 * r, 2 * r), (0, 0, 0, 0))
        px = py = float(r)
        d = ImageDraw.Draw(lay)
        # The opening itself: a polished chamfer where the dial is cut
        # through, the same line home.html puts where the bezel meets the
        # dial and for the same reason — it is the edge that says "hole".
        d.ellipse([px - TOURB_R, py - TOURB_R, px + TOURB_R, py + TOURB_R],
                  outline=_dial_metal(228, 150), width=2)
        d.ellipse([px - TOURB_R + 3, py - TOURB_R + 3,
                   px + TOURB_R - 3, py + TOURB_R - 3],
                  outline=_dial_metal(24, 120), width=3)
        _TOURB_STATIC = lay
    return _TOURB_STATIC


def _tourb_cage_base():
    """The carriage at zero: a three-armed GOLD bridge, drawn once.

    Cut to the CAGE's diameter and not the aperture's — this sprite exists in
    TOURB_STEPS copies, so every px of margin is paid for sixty times. The
    ink reaches the ring at TOURB_CAGE_R plus its own 2px stroke, which is
    inside the inscribed circle of this canvas, so no rotation clips it.

    A FACET IS NOT A LIGHTER GREY, and it is now the gold's job: each arm is
    a body at TOURB_GOLD with a bright specular up one flank and a shaded
    edge down the other. The owner asked for exactly this and said why — "so
    it CATCHES LIGHT AS IT TURNS" — and because the specular is baked into
    the sprite, it turns with the arm, which is what a polished bevel does.

    DRAWN AT 3x AND REDUCED, which the moonphase's lens note argues for on
    the same face and for the same reason: ImageDraw has no antialiasing, so
    a 3px gold ring on a black ground comes out of it as a staircase, and
    this is the object the owner wants the eye to go to. One reduce, once, at
    build time — the sixty rotations are then of an already-smooth sprite.
    """
    S = 3
    r = TOURB_CAGE_R + 6
    lay = Image.new("RGBA", (2 * r * S, 2 * r * S), (0, 0, 0, 0))
    d = ImageDraw.Draw(lay)
    px = py = float(r * S)
    c = float(TOURB_CAGE_R * S)
    # The cage ring.
    d.ellipse([px - c, py - c, px + c, py + c],
              outline=TOURB_GOLD + (255,), width=3 * S)
    d.ellipse([px - c + 3 * S, py - c + 3 * S, px + c - 3 * S, py + c - 3 * S],
              outline=TOURB_GOLD_LIT + (170,), width=S)
    # THE THREE ARMS, and they are the BRIDGE now rather than a dimmer thing
    # under one: the old note had them deliberately thinner than the steel
    # cocks so the two did not read as one five-bladed fan. The cocks are
    # gone (they are the dark plate below), so the arms take their weight —
    # 8 at the hub to 5.5 out, which is the width that pass found by render.
    # ── THE ARMS GET A CROSS-SECTION, 2026-08-08 ──────────────────────
    # The owner: "the 3 gold handles in the tourbillon could use some UI
    # love, they don't have the depth they deserve... very 2d looking."
    # He is right and the cause is that a flat fill between two edge lines
    # is a RIBBON, not a bar: a real cage arm is a chamfered beam, so
    # across its width it runs dark flank -> bright crest -> mid face, and
    # WHICH flank is bright depends on where the arm points relative to the
    # sky. The old code lit the same side of every arm, so the three read
    # as one flat pinwheel however they turned.
    #
    # So each arm is drawn as a stack of narrowing polygons — the beam's
    # section, lit by the dot of its own normal with TOURB_KEY. Six bands
    # is enough for a 8px bar at S supersample and costs nothing: this is
    # the once-per-process base sprite, not the frame loop.
    _kx, _ky = TOURB_KEY
    for k in range(3):
        a = k * 120.0
        # The arm's own surface normal across its width, in the frame's
        # coordinates: perpendicular to the arm's direction.
        t = math.radians(a)
        nx, ny = -math.sin(t), math.cos(t)
        lit = (nx * _kx + ny * _ky)          # +1 flank faces the sky
        bar = _tourb_bar(px, py, a, 5.0 * S, c, 8.0 * S, 5.5 * S)
        d.polygon(bar, fill=TOURB_GOLD_DARK + (255,))
        BANDS = 6
        for i in range(BANDS):
            # u runs -1 (one flank) .. +1 (the other) across the beam
            u0 = -1.0 + 2.0 * i / BANDS
            u1 = -1.0 + 2.0 * (i + 1) / BANDS
            um = (u0 + u1) * 0.5
            # A chamfered beam: brightest where the section faces the key,
            # falling off as cos toward each flank.
            f = max(0.0, um * lit) ** 0.6 if lit else 0.0
            g = 0.35 + 0.65 * f
            col = tuple(int(round(TOURB_GOLD_DARK[j]
                                  + (TOURB_GOLD_LIT[j] - TOURB_GOLD_DARK[j])
                                  * g)) for j in range(3))
            hw0, hw1 = 8.0 * S, 5.5 * S
            sub = _tourb_bar(px, py, a, 5.0 * S, c,
                             hw0 * abs(u1 - u0) * 0.5 + 0.5,
                             hw1 * abs(u1 - u0) * 0.5 + 0.5,
                             off=(hw0 * um, hw1 * um))
            d.polygon(sub, fill=col + (255,))
        # The crest: a hairline of near-white where the beam's apex catches
        # the sky — the thing that says polished rather than painted.
        if lit:
            uc = 0.55 if lit > 0 else -0.55
            crest = _tourb_bar(px, py, a, 5.0 * S, c, 1.6, 1.2,
                               off=(8.0 * S * uc, 5.5 * S * uc))
            d.polygon(crest, fill=TOURB_GOLD_LIT + (255,))
    # The balance wheel USED TO BE DRAWN HERE and is now its own sprite
    # (_tourb_balance_base, 2026-08-07): it oscillates and the cage rotates,
    # so they cannot be one bitmap. Nothing else about this carriage changed.
    # The escape wheel, off-centre and finely toothed. KEPT, and the reason
    # is arithmetic rather than taste: three arms and a centred balance are
    # 3-fold symmetric, so a cage built only of those looks identical every
    # 20 seconds and a full turn reads as three. This is the one asymmetric
    # feature on the carriage, and it is what makes "once per minute" a
    # thing the eye can actually check.
    ex, ey, er = px + c * 0.56, py, c * 0.26
    d.ellipse([ex - er, ey - er, ex + er, ey + er],
              outline=TOURB_GOLD_LIT + (245,), width=2 * S)
    for k in range(15):
        t = math.radians(k * 24.0)
        d.line([(ex + er * 0.5 * math.cos(t), ey + er * 0.5 * math.sin(t)),
                (ex + er * math.cos(t), ey + er * math.sin(t))],
               fill=TOURB_GOLD + (215,), width=S)
    return lay.resize((2 * r, 2 * r), Image.LANCZOS)


def _tourb_cages():
    """TOURB_STEPS pre-rendered angles of the cage, EACH WITH ITS SHADOW.

    THIS IS THE WHOLE FRAME BUDGET ARGUMENT. The idle loop runs at 8 fps for
    thermal reasons; rotating this sprite per frame would put a resample in
    it forever. Sixty rotations cost one loop at startup and the steady state
    becomes a list index and a paste.

    Negative angle because PIL rotates anticlockwise and a tourbillon carries
    the escapement round CLOCKWISE — the same sign the deleted per-frame
    rotate used, kept so the direction did not quietly flip in the move.

    ── 2026-08-07: THE CAGE CASTS A SHADOW ON THE FLOOR ──────────────────
    The single mark that buys the most depth in this aperture, and the reason
    is geometric rather than aesthetic: shading WITHIN a plane is a guess the
    eye can refuse, but a shadow lands on a DIFFERENT plane and is proof the
    two are apart. See TOURB_FLOOR_MID for the full argument.

    IT IS BUILT FROM THE ROTATED CAGE, NOT ROTATED WITH IT, and that is the
    one thing that would have been wrong if it were baked into the base
    sprite. The shadow's SHAPE must turn with the carriage; its DIRECTION must
    not, because the key light does not move. Rotating a pre-offset shadow
    would swing it round the dial once a minute and the eye reads that as the
    sun going round, which is worse than no shadow at all.

    Free per frame — sixty blurs at startup, then the same one indexed paste
    the table always cost. The canvas grows by the offset plus twice the blur
    so nothing clips; alpha_composite in _tourb_layer still centres it.
    """
    global _TOURB_CAGES
    if not _TOURB_CAGES:
        base = _tourb_cage_base()
        pad = TOURB_SHADOW_OFF + int(math.ceil(2.0 * TOURB_SHADOW_BLUR))
        n = base.size[0] + 2 * pad
        _TOURB_CAGES = []
        for i in range(TOURB_STEPS):
            rot = base.rotate(-360.0 * i / TOURB_STEPS,
                              resample=Image.BILINEAR)
            # The cage's own alpha, dimmed to shadow strength, IS the shadow:
            # a silhouette of whatever the carriage happens to be at this
            # angle, so the arms and the escape wheel each cast their own.
            sil = Image.new("RGBA", rot.size, (0, 0, 0, 0))
            sil.putalpha(rot.getchannel("A").point(
                lambda v: (v * TOURB_SHADOW_A) // 255))
            lay = Image.new("RGBA", (n, n), (0, 0, 0, 0))
            lay.paste(sil, (pad + TOURB_SHADOW_OFF, pad + TOURB_SHADOW_OFF))
            lay = lay.filter(ImageFilter.GaussianBlur(TOURB_SHADOW_BLUR))
            lay.alpha_composite(rot, (pad, pad))
            _TOURB_CAGES.append(lay)
    return _TOURB_CAGES


def _tourb_balance_base():
    """The balance wheel at zero: a FINE gold annulus, drawn once.

    ── 2026-08-07 ────────────────────────────────────────────────────────
    Lifted out of _tourb_cage_base so it can swing while the cage turns —
    the full argument is at TOURB_BAL_AMP_DEG. The drawing is the same one
    that was inside the carriage: a 2px rim where the cage ring gets 3,
    because the owner's word was "a FINE gold annulus" and it has to read as
    a wheel held in the cage rather than as a second cage.

    THE ROLLER JEWEL IS NOT DECORATION. Two spokes at 180 are 2-fold
    symmetric, so a bare balance looks identical every half turn and 110
    degrees of swing would read as a 70 degree one. One bright jewel at a
    spoke end makes the wheel asymmetric over the whole circle, which is the
    same argument the escape wheel already carries for the cage — it is what
    makes the reversal something the eye can actually see.

    Drawn at 3x and reduced, like the cage: ImageDraw has no antialiasing and
    a 2px ring is exactly where that shows.
    """
    b = TOURB_CAGE_R * 0.58
    S = 3
    r = int(b) + 6
    lay = Image.new("RGBA", (2 * r * S, 2 * r * S), (0, 0, 0, 0))
    d = ImageDraw.Draw(lay)
    px = py = float(r * S)
    bb = b * S
    # ── THE BALANCE GETS ITS SECTION TOO, 2026-08-08 ──────────────────
    # The owner: "more love to the 3 parts of the balance wheel, they look
    # flat." A single-stroke ring and two single-stroke spokes are exactly
    # that — line art. A balance is a machined annulus: it has an outer
    # flank, a crest and an inner flank, and the crest catches the same sky
    # as everything else. Three concentric strokes with the light landing on
    # the middle one give the rim a section; the spokes get the same
    # treatment down their length.
    _kx, _ky = TOURB_KEY
    for off, col, wid in ((+1.4 * S, TOURB_GOLD_DARK, 1 * S),
                          (0.0, TOURB_GOLD_LIT, 2 * S),
                          (-1.4 * S, TOURB_GOLD, 1 * S)):
        rr_ = bb + off
        d.ellipse([px - rr_, py - rr_, px + rr_, py + rr_],
                  outline=col + (235,), width=max(1, int(wid)))
    # The sky's own highlight on the rim: a bright arc where the annulus
    # faces the key, so the ring reads as metal turned toward the light
    # rather than as a drawn circle.
    _ka = math.degrees(math.atan2(_ky, _kx))
    d.arc([px - bb, py - bb, px + bb, py + bb],
          _ka - 55, _ka + 55, fill=(255, 240, 214, 255), width=2 * S)
    for k in range(2):
        t = math.radians(60.0 + k * 180.0)
        ux, uy = math.cos(t), math.sin(t)
        nx, ny = -uy, ux                      # across the spoke
        # Three passes across each spoke's width: shaded flank, lit crest,
        # body — the same beam section the cage arms now carry.
        for off, col, wid in ((+1.2 * S, TOURB_GOLD_DARK, 1 * S),
                              (0.0, TOURB_GOLD_LIT, 2 * S),
                              (-1.2 * S, TOURB_GOLD, 1 * S)):
            d.line([(px - bb * ux + off * nx, py - bb * uy + off * ny),
                    (px + bb * ux + off * nx, py + bb * uy + off * ny)],
                   fill=col + (215,), width=max(1, int(wid)))
    t = math.radians(60.0)
    jx, jy = px + bb * math.cos(t), py + bb * math.sin(t)
    jr = 3.0 * S
    # The roller jewel as a domed stone: gold seat, body, specular pip.
    d.ellipse([jx - jr - S, jy - jr - S, jx + jr + S, jy + jr + S],
              fill=TOURB_GOLD_DARK + (255,))
    d.ellipse([jx - jr, jy - jr, jx + jr, jy + jr],
              fill=TOURB_GOLD_LIT + (255,))
    d.ellipse([jx - jr * 0.45, jy - jr * 0.45, jx + jr * 0.05, jy + jr * 0.05],
              fill=(255, 246, 224, 255))
    return lay.resize((2 * r, 2 * r), Image.LANCZOS)


def _tourb_balances():
    """TOURB_BAL_STEPS pre-rendered angles of the balance, built once.

    Identical trick to _tourb_cages, and for the identical reason: at 8 fps
    the frame may not resample. The swing becomes an index into this table
    and the paste costs what it always cost.

    Negative angle to match the cage's sign, so index i is i*5 degrees
    CLOCKWISE and the two tables can be added before either is indexed.
    """
    global _TOURB_BALANCES
    if not _TOURB_BALANCES:
        base = _tourb_balance_base()
        _TOURB_BALANCES = [base.rotate(-360.0 * i / TOURB_BAL_STEPS,
                                       resample=Image.BILINEAR)
                           for i in range(TOURB_BAL_STEPS)]
    return _TOURB_BALANCES


_TOURB_GLOWS: dict = {}


def _tourb_glow(step: int):
    """The mainspring's light, at one of TOURB_GLOW_STEPS intensities.

    Cached per step — twelve small tiles at most, and the burn rate holds
    still for minutes at a time, so the steady state costs a dict lookup.
    """
    if step not in _TOURB_GLOWS:
        r = TOURB_GLOW_R
        lay = Image.new("RGBA", (2 * r, 2 * r), (0, 0, 0, 0))
        d = ImageDraw.Draw(lay)
        k = step / float(TOURB_GLOW_STEPS - 1)
        # Concentric, hottest at the middle: a hole with light coming up
        # through it, not a disc laid on the dial.
        for i in range(r, 0, -3):
            f = 1.0 - i / float(r)
            a = int(150 * k * f * f)
            if a <= 1:
                continue
            d.ellipse([r - i, r - i, r + i, r + i], fill=TOURB_GLOW + (a,))
        _TOURB_GLOWS[step] = lay.filter(ImageFilter.GaussianBlur(4.0))
    return _TOURB_GLOWS[step]


#: ── THE RTX-RENDERED CENTREPIECE, 2026-08-09 ─────────────────────────────
#: Owner, on the patek: "we can just pre-render a super high quality video on
#: the RTX and play it in the middle." And on the ferrari: "make it look jaw
#: dropping and preload it ... it's the first thing that draws the eye."
#:
#: scripts/render_centre.py raymarches the movement on the workstation GPU —
#: real occlusion, soft shadows, ambient occlusion, environment reflections —
#: and drops a numbered frame table into packs/centre_<name>/. This is the
#: consumer, and it is deliberately the dumbest half of the pair: index by
#: the clock, paste, return. THE PUCK MUST NEVER RESIZE ONE OF THESE. The
#: renderer already emits them at the bore's exact size, so a paste here is
#: a memcpy and the 8fps thermal budget never notices (the argument at
#: TOURB_RECT_FPS applies unchanged).
#:
#: LOADED ONCE, EAGERLY, AT IMPORT — 72 frames of 288px RGBA is about 24 MB
#: resident, which this process can afford, and the alternative (loading on
#: first use) would put a 70-file disk read inside the frame loop exactly
#: when the face is trying to appear. Compose-loop rule 2: bake it once.
#:
#: A MISSING PACK IS NOT AN ERROR. The drawn tourbillon is still here and
#: still correct; a puck with no pack simply keeps it. That is what makes
#: this safe to ship mid-demo-prep — the fallback is the thing that already
#: worked, and it is chosen by whether a directory exists.
#: Beside dj_face.py, exactly like the bezel bakes — on a puck that is
#: ~/aura_face/packs/, and in the repo it is apps/puck_face/packs/. One
#: convention for every shipped asset, so a bundle carries them all the
#: same way.
CENTRE_PACK_DIR = (Path(__file__).resolve().parent / "packs"
                   / f"centre_{_THEME.get('centre_pack') or '_none'}")
_CENTRE: dict = {"frames": None, "loop": 9.0, "xy": (0, 0)}


def centre_pack_load() -> None:
    """Read the frame table if this theme names one. Never raises."""
    if _CENTRE["frames"] is not None or not _THEME.get("centre_pack"):
        _CENTRE["frames"] = _CENTRE["frames"] or []
        return
    try:
        man = json.loads((CENTRE_PACK_DIR / "manifest.json").read_text())
        fs = sorted(CENTRE_PACK_DIR.glob("frame_*.png"))
        if not fs:
            raise FileNotFoundError("no frames in the pack")
        # ── THE COUNT COMES FROM THE GLOB, SO STALE FILES JOIN THE LOOP ──
        # `len(ims)` below indexes the animation, and it is whatever the
        # directory happens to contain — the manifest is never consulted
        # about it. Copy a 300-frame pack over a 360-frame one and the 60
        # orphans are not replaced, they are APPENDED: the loop plays two
        # months of design decisions back to back, runs 20% long, and never
        # closes on itself. Nothing raises, nothing logs, and the symptom is
        # "the animation hitches" — which reads as a render problem and
        # sends you to the wrong file.
        #
        # The manifest already records the true count. Cross-check it and
        # refuse: the handler below turns a refusal into the drawn centre
        # plus a line saying why, which is a fallback you can see. A pack
        # assembled from two builds is not a pack.
        want = int(man.get("frames") or 0)
        if want and len(fs) != want:
            raise ValueError(f"{len(fs)} frames on disk, manifest says "
                             f"{want} — stale files in the pack")
        ims = [Image.open(p).convert("RGBA") for p in fs]
        for im in ims:
            im.load()
        side = ims[0].size[0]
        _CENTRE["frames"] = ims
        _CENTRE["loop"] = float(man.get("seconds_per_loop") or 9.0)
        _CENTRE["xy"] = (SIZE // 2 - side // 2, SIZE // 2 - side // 2)
        print(f"centre: RTX pack '{man.get('name')}' loaded — {len(ims)} "
              f"frames at {side}px, {_CENTRE['loop']:.1f}s per loop, "
              f"built {man.get('built')}", flush=True)
    except Exception as exc:                    # noqa: BLE001
        # §1: a centrepiece that quietly fell back to the drawn cage is a
        # face wearing last month's centre with nothing in the log saying so.
        _CENTRE["frames"] = []
        print(f"centre: NO RTX pack ({exc!r}) — keeping the drawn "
              f"tourbillon", flush=True)


#: ══ THE MECHANISM IS THE PROGRESS INDICATOR (2026-08-13) ═══════════════
#: Owner: "what i want is to use the ferrari gears and the tourbillon to
#: reflect aura thinking. so slower gears / slower tourbillon get sped up
#: when it's showing Aura is thinking and acknowledging your request."
#:
#: This is §13 and §10 answered with the object already on the dial rather
#: than with another overlay. The first hundred milliseconds belong to
#: acknowledgement, and a train that visibly picks up the moment she hears
#: you says "working" in a way no spinner does — it is the difference
#: between a watch and a progress bar. It also costs nothing: the frames are
#: already rendered and already being indexed every paint.
#:
#: PHASE IS ACCUMULATED, NOT SCALED. The obvious version multiplies `now`
#: by the rate, and it JUMPS: at t=100s a 2.5x rate suddenly indexes frame
#: 250 instead of 100, so the mechanism teleports every time she starts
#: thinking. Integrating rate over elapsed time instead means the speed can
#: change at any instant and the picture never moves — which is what a real
#: escapement does when it is wound harder.
#:
#: AND THE RATE ITSELF IS EASED, for the same reason. A gear train that
#: steps from 1.0x to 2.6x between two frames reads as a dropped frame, not
#: as acceleration. 0.9 per second toward the target is about a third of a
#: second to spin up, which is roughly how long a real mass takes and,
#: conveniently, about as long as the acknowledgement clip it accompanies.
#:
#: The rates are deliberately modest. This is a watch: the movement should
#: quicken, not race. 2.6x on thinking is clearly faster at a glance and
#: still reads as a mechanism rather than a fan.
CENTRE_RATE = {"idle": 1.0, "hearing": 1.7, "thinking": 2.6}
CENTRE_RATE_EASE = 0.9          # per second, toward the target
_CENTRE_PH = {"t": 0.0, "at": 0.0, "rate": 1.0}


def _centre_phase(now: float) -> float:
    """Virtual time for the pack, running fast while she is engaged."""
    want = CENTRE_RATE["idle"]
    try:
        ph = _pulse_phase(now)
        if ph in CENTRE_RATE:
            want = CENTRE_RATE[ph]
    except Exception:
        pass
    last = _CENTRE_PH["at"] or now
    dt = max(0.0, min(0.5, now - last))      # a stall must not fling it
    _CENTRE_PH["at"] = now
    k = min(1.0, CENTRE_RATE_EASE * dt)
    _CENTRE_PH["rate"] += (want - _CENTRE_PH["rate"]) * k
    _CENTRE_PH["t"] += dt * _CENTRE_PH["rate"]
    return _CENTRE_PH["t"]


# ── continuum reactive centre (2026-10-08): coalesce to a SOLID BLACK DISC +
# a SUBTLE amber that emanates and dissipates around the perimeter when Aura is
# engaged (pulse.json hearing/thinking/speaking/waiting, card0 playback, or the
# /tmp/aura_face/continuum_force debug flag). Lives in centre_pack_sprite so the
# 30fps damage-rect path gets it too. Never mutates the cached pack frame.
_CONT = {"v": 0.0, "t": None}
_CONT_PULSE = "/tmp/aura_face/pulse.json"
_CONT_PB = "/proc/asound/card0/pcm0p/sub0/status"
_CONT_FORCE = "/tmp/aura_face/continuum_force"
_CONT_PHASES = ("thinking", "speaking", "waiting")   # NOT 'hearing' (ambient)
_CONT_AMBER = (255, 186, 78)


def _continuum_engaged(now):
    try:
        if os.path.exists(_CONT_FORCE):
            return True
    except Exception:
        pass
    try:
        d = json.load(open(_CONT_PULSE))
        if now - d.get("at", 0) < 12.0 and d.get("phase") in _CONT_PHASES:
            return True
    except Exception:
        pass
    try:
        if "RUNNING" in open(_CONT_PB).read():
            return True
    except Exception:
        pass
    return False


_PART = None  # FLOWFIX_V2
_PCACHE = {"t": -1.0, "sprite": None}


def _continuum_particles(S):
    import numpy as _np, math as _m
    rng = _np.random.default_rng(7)
    SS = 2
    SR = S * SS
    c = SR / 2.0
    Np = 42000
    R_idle = SR * 0.44
    ur = (rng.uniform(0, 1, Np) ** 0.58) * R_idle
    ua = rng.uniform(0, 2 * _m.pi, Np)
    BX = (c + ur * _np.cos(ua)).astype(_np.float32)
    BY = (c - ur * _np.sin(ua)).astype(_np.float32)
    R_mid = SR * 0.40; half = SR * 0.045
    ha = rng.uniform(0, 2 * _m.pi, Np)
    hr = R_mid + rng.uniform(-half, half, Np)
    HX = (c + hr * _np.cos(ha)).astype(_np.float32)
    HY = (c - hr * _np.sin(ha)).astype(_np.float32)
    pv = rng.uniform(0.5, 1.05, Np).astype(_np.float32)
    KO = 4
    AMP = _np.array([34.0, 20.0, 11.0, 7.0], _np.float32)
    FRQ = _np.array([1.3, 2.2, 3.6, 5.7], _np.float32)
    MT = _np.array([1.0, 2.0, 3.0, 2.0], _np.float32)
    thx = rng.uniform(0, 2 * _m.pi, KO); thy = rng.uniform(0, 2 * _m.pi, KO)
    phx = rng.uniform(0, 2 * _m.pi, KO); phy = rng.uniform(0, 2 * _m.pi, KO)
    cxd = _np.cos(thx).astype(_np.float32); sxd = _np.sin(thx).astype(_np.float32)
    cyd = _np.cos(thy).astype(_np.float32); syd = _np.sin(thy).astype(_np.float32)
    nx = ((BX - c) / R_idle).astype(_np.float32)
    ny = ((BY - c) / R_idle).astype(_np.float32)
    return {"c": c, "S": S, "SR": SR, "Np": Np, "BX": BX, "BY": BY, "HX": HX,
            "HY": HY, "pv": pv, "AMP": AMP, "FRQ": FRQ, "MT": MT,
            "phx": phx, "phy": phy, "cxd": cxd, "sxd": sxd, "cyd": cyd,
            "syd": syd, "nx": nx, "ny": ny, "KO": KO}


def _continuum_overlay(im, now):
    if im is None:
        return None
    tgt = 1.0 if _continuum_engaged(now) else 0.0
    t0 = _CONT["t"]; _CONT["t"] = now
    dt = 0.0 if t0 is None else max(0.0, min(0.25, now - t0))
    rate = 1.7 if tgt > _CONT["v"] else 1.0
    _CONT["v"] += (tgt - _CONT["v"]) * (1.0 - math.exp(-rate * dt))
    e = _CONT["v"]
    if _PCACHE["sprite"] is not None and (now - _PCACHE["t"]) < 0.045:
        return _PCACHE["sprite"]
    import numpy as _np
    global _PART
    S = im.size[0]
    if _PART is None or _PART["S"] != S:
        _PART = _continuum_particles(S)
    P = _PART; SR = P["SR"]
    ci = e * e * (3.0 - 2.0 * e)
    anx = P["BX"] * (1.0 - ci) + P["HX"] * ci
    any_ = P["BY"] * (1.0 - ci) + P["HY"] * ci
    t = (now % 10000.0) * 0.09
    dx = _np.zeros(P["Np"], _np.float32); dy = _np.zeros(P["Np"], _np.float32)
    nx = P["nx"]; ny = P["ny"]
    for k in range(P["KO"]):
        dx += P["AMP"][k] * _np.cos(2 * math.pi * (P["FRQ"][k] * (P["cxd"][k] * nx + P["sxd"][k] * ny) + P["MT"][k] * t) + P["phx"][k])
        dy += P["AMP"][k] * _np.cos(2 * math.pi * (P["FRQ"][k] * (P["cyd"][k] * nx + P["syd"][k] * ny) + P["MT"][k] * t) + P["phy"][k])
    fs = (1.0 - ci) * 1.0 + ci * 0.18
    px = anx + dx * fs; py = any_ + dy * fs
    ix = _np.round(px).astype(_np.int32); iy = _np.round(py).astype(_np.int32)
    m = (ix >= 0) & (ix < SR) & (iy >= 0) & (iy < SR)
    I = _np.zeros((SR, SR), _np.float32)
    _np.add.at(I, (iy[m], ix[m]), P["pv"][m])
    sm = (Image.fromarray((_np.clip(I, 0, 1) * 255).astype("uint8"))
          .filter(ImageFilter.GaussianBlur(1.7)).resize((S, S), Image.LANCZOS))
    a = _np.asarray(sm, "uint8")
    rgb = _np.full((S, S, 3), (18, 16, 15), "uint8")
    sprite = Image.fromarray(_np.dstack([rgb, a]), "RGBA")
    _PCACHE["t"] = now; _PCACHE["sprite"] = sprite
    return sprite


def centre_pack_sprite(now: float) -> "Image.Image | None":
    """This instant's pack frame as a sprite, or None when no pack is loaded.

    Split out of centre_pack_paste for the same reason _tourb_layer was split
    out of draw_tourbillon: the damage-rect path needs these pixels without a
    frame to paste them into.
    """
    ims = _CENTRE["frames"]
    if not ims:
        return None
    i = int((_centre_phase(now) % _CENTRE["loop"]) / _CENTRE["loop"]
            * len(ims)) % len(ims)
    return _continuum_overlay(ims[i], now)


def centre_pack_paste(frame: "Image.Image", now: float) -> bool:
    """Paste this instant's frame. False if there is no pack to paste."""
    if _CENTRE["frames"] is None:
        centre_pack_load()
    im = centre_pack_sprite(now)
    if im is None:
        return False
    #: ── 2026-08-12: THE PACK WAS PLAYING AT 8 fps ─────────────────────────
    #: draw_tourbillon has stored these two since 2026-08-07 so the aperture
    #: can be repainted inside the idle gap at TOURB_RECT_FPS (30). A pack
    #: face never called draw_tourbillon — centre_pack_paste returns True and
    #: short-circuits it — so `under` stayed None, the `plain` gate was never
    #: satisfied, and the fast path simply did not exist for the three themes
    #: that actually ship a pack.
    #:
    #: MEASURED ON THE GLASS before this change, sampling the aperture off
    #: /dev/fb0 at 250 Hz for 12 s on the chopard puck: 100 distinct frames,
    #: **8.33 fps, median gap 125 ms** — IDLE_FPS exactly, against an aperture
    #: budget of 30. We were rendering 360-frame packs and showing a quarter
    #: of them.
    #:
    #: This is why the render knobs were the wrong place to look. Measured
    #: A/B on one tourbillon frame at 288px: march steps 256 -> 1024 changes
    #: the image by a mean of 0.000 levels, and SS 8 -> 16 by 0.111 levels
    #: (0.66% of pixels by more than 3) for FOUR TIMES the render cost. The
    #: spatial knobs are saturated; the panel is 288px and the marcher
    #: already resolves everything in it. The only dimension with headroom
    #: was time, and it was being thrown away here, downstream of the render,
    #: for free (PRINCIPLES §6 — measure in the environment that applies).
    box = _CENTRE["xy"]
    _TOURB_LAY["box"] = box
    _TOURB_LAY["under"] = frame.crop((box[0], box[1],
                                      box[0] + im.size[0],
                                      box[1] + im.size[1]))
    #: ── AND A MARGIN, SO THE RECT CAN BE TURNED (2026-08-13) ────────────
    #: Owner: "when i rotated my screen by touch the motion becomes way
    #: blurrier. and if i put my finger down to rotate it again it goes to
    #: the normal pacing." Measured on his puck, the same face minutes apart:
    #:     rotated:  6.0 fps to the glass (6.0 full + 0.0 rect)
    #:     square:  27.6 fps to the glass (5.9 full + 21.6 rect)
    #: The `plain` gate stood the fast path down at any rotation, so the
    #: centrepiece played at a QUARTER of its frame rate exactly when he had
    #: just touched it — and with blur-4 frames a quarter rate reads as
    #: smearing rather than as motion.
    #:
    #: Rotating the square rect about its own centre would lose its CORNERS
    #: to the fill colour, and those corners are dial, not bore. So a margin
    #: of sqrt(2)/2 is kept around it: rotate the larger square, centre-crop
    #: back, and every pixel of the result came from real dial.
    #:
    #: Captured here because here is the only moment the background exists
    #: un-covered — the same reason `under` itself is taken here.
    m = int(im.size[0] * (math.sqrt(2.0) - 1.0) / 2.0) + 2
    _TOURB_LAY["margin"] = m
    _TOURB_LAY["under_big"] = frame.crop((box[0] - m, box[1] - m,
                                          box[0] + im.size[0] + m,
                                          box[1] + im.size[1] + m))
    frame.paste(im, box, im)
    return True


#: ── THE ROTOR: A CENTREPIECE THAT IS AN INSTRUMENT (2026-08-26) ──────────
#:
#: Owner, on the carbon face: "there is still no centerpiece to the thing
#: like the pearl has the stone and the watches have their turbillon, etc.
#: you have to come up with a concept."
#:
#: A tourbillon is not decoration. It exists to SHOW THE ESCAPEMENT — the
#: living heart of the watch, cut open and put on display, and it is
#: compelling because it is the mechanism rather than a picture of one.
#: Pearl answers that with a basalt stone: geological, still, a museum
#: object on a museum wall. Correct for plaster and wrong for this part.
#:
#: This device's living heart is not a stone and it is not an escapement.
#: It is THERMAL. The shell is cut with ocean swells that are air
#: apertures; the enclosure work this month was worth 13 C at load; there
#: is a fan behind this glass turning right now. So the centrepiece is the
#: impeller, and the thing that makes it a tourbillon rather than a
#: screensaver is that IT SPINS AT THE REAL FAN SPEED. Watch it long
#: enough and you know the machine is working before any number says so.
#:
#: Ten blades, because the shell outside is cut with ten swells — the
#: glass quotes the object it lives in.
#:
#: The listening rings already leave from LISTEN_C_R0=168, outboard of
#: ROTOR_R, so they read as air leaving the rotor rather than as a second
#: unrelated animation. That was luck, but it is the right relationship
#: and it is why the rotor is sized to sit inside them.
CENTRE_PIECE = str(_THEME.get("centre") or "")
ROTOR_R = 152.0                 # tip circle
ROTOR_HUB_R = 34.0              # the machined boss
ROTOR_BLADES = 10               # = the swells cut into the shell
ROTOR_SWEEP = 34.0              # deg of curve from root to tip
ROTOR_IDLE_RPM = 26.0           # what it turns at with the fan stopped
ROTOR_MAX_RPM = 190.0           # at pwm 255
_FAN_PATHS = ("/sys/devices/platform/pwm-fan/hwmon/hwmon0/pwm1",
              "/sys/devices/platform/pwm-fan/hwmon/hwmon1/pwm1",
              "/sys/devices/platform/pwm-fan/hwmon/hwmon2/pwm1")
_FAN = {"pwm": 0.0, "at": 0.0, "path": None, "said": False}
_ROTOR = {"deg": 0.0, "t": 0.0}


def _rotor_metal(f: float, a: int = 255) -> tuple:
    """The rotor's own value ramp, black -> machined grey -> lit edge.

    NOT _dial_metal, and that is a measurement rather than a preference.
    Asked for eight values from 0.04 to 1.00, _dial_metal returns
    (12,12,13) for every one of them on this theme — it is FLAT here, so
    the first two cuts of this piece drew black blades in a black well and
    the only thing visible was the amber on the tips. Two rounds went into
    adjusting numbers that the function was discarding.
    (Left alone rather than fixed: the watch faces are built on it and it
    is correct for them; what is wrong is using it on a row whose ramp is
    declared elsewhere.)

    So the ramp is built from what the ROW actually declares — `black` and
    `mid` are both real triples on carbon — and extended past mid toward a
    lit edge for the specular flank.
    """
    lo = tuple(_THEME.get("black") or (12, 12, 13))
    md = tuple(_THEME.get("mid") or (150, 147, 141))
    hi = tuple(min(255, int(c * 1.42 + 26)) for c in md)
    f = max(0.0, min(1.0, float(f)))
    if f <= 0.5:
        t = f / 0.5
        c = tuple(lo[i] + (md[i] - lo[i]) * t for i in range(3))
    else:
        t = (f - 0.5) / 0.5
        c = tuple(md[i] + (hi[i] - md[i]) * t for i in range(3))
    return (int(c[0]), int(c[1]), int(c[2]), a)


def fan_pwm(now: float) -> float:
    """The fan's real duty, 0..255. Cached: this is a sysfs read inside a
    compositor, and the fan governor only moves it every few seconds.

    Returns 0.0 when it cannot be read — on a workstation preview there is
    no pwm-fan at all, and the rotor must still turn (at idle) rather than
    freeze or throw. Says so ONCE: a centrepiece silently stuck at idle
    would look exactly like a working one on a cool machine.
    """
    if now - _FAN["at"] < 2.0:
        return _FAN["pwm"]
    _FAN["at"] = now
    try:
        if _FAN["path"] is None:
            import glob as _g
            hits = _g.glob("/sys/devices/platform/pwm-fan/hwmon/hwmon*/pwm1")
            _FAN["path"] = hits[0] if hits else (_FAN_PATHS[0])
        with open(_FAN["path"]) as fh:
            _FAN["pwm"] = float(fh.read().strip())
    except Exception:                                   # noqa: BLE001
        _FAN["pwm"] = 0.0
        if not _FAN["said"]:
            _FAN["said"] = True
            print("rotor: no pwm-fan on this host — turning at idle rate",
                  flush=True)
    return _FAN["pwm"]


#: ── THE IRIS, EASED (2026-08-26) ─────────────────────────────────────
#: The mechanism lives in iris.py; this is only the part that knows about
#: this device — which state it should be in and how fast it may travel.
#: Kept apart because the geometry was developed while this file was being
#: refactored elsewhere, and because a centrepiece that reads pulse.json
#: is a different concern from one that draws leaves.
_IRIS = {"op": 0.10, "t": 0.0}
IRIS_REST = 0.10                # a spiral, shut
IRIS_HEAR = 0.86                # wide: she has you
IRIS_THINK = 0.60               # held open while she works
IRIS_RATE = 2.6                 # units per second; ~0.3 s to travel


def draw_disc_centre(frame: "Image.Image", now: float) -> None:
    """The turned pocket at the centre. See centre_disc.py for why the
    three attempts before it all failed the same way.

    Wrapped whole: new paint in a compositor that must never stop.
    """
    try:
        from centre_disc import draw_disc
        try:
            ph = _pulse_phase(now)
        except Exception:                               # noqa: BLE001
            ph = None
        live = 1.0 if ph in ("hearing", "thinking") else 0.0
        draw_disc(frame, now, live,
                  black=tuple(_THEME.get("black") or (12, 12, 13)),
                  mid=tuple(_THEME.get("mid") or (150, 147, 141)),
                  accent=tuple(TOURB_GOLD), size=SIZE)
    except Exception as exc:                            # noqa: BLE001
        _bez_say(f"disc:{exc!r}", f"disc: draw failed {exc!r} — the centre "
                                  f"is empty")


def draw_ingot_centre(frame: "Image.Image", now: float) -> None:
    """The cast bar at the centre, and the heat in it. See centre_ingot.py
    for why a rectangle rather than a fifth disc.

    THE COLOURS ARE NOT PASSED, THE RAMP IS (§15). draw_disc takes `black`
    and `mid` and rebuilds a three-stop ramp of its own from them, which
    was right for a row whose two anchors ARE its material. This row's
    material is a ten-stop hue turn — red below L=70, nickel above L=107 —
    and any two triples taken out of it would be a second opinion about
    the theme's colours that agrees with the first until somebody edits
    the row. So the bar is handed `_ramp_rgb` and asks for the luminances
    it wants.

    Wrapped whole: new paint in a compositor that must never stop.
    """
    try:
        from centre_ingot import draw_ingot
        try:
            ph = _pulse_phase(now)
        except Exception:                               # noqa: BLE001
            ph = None
        live = 1.0 if ph in ("hearing", "thinking") else 0.0
        #: hearing HOLDS the heat, thinking TRAVELS it — one mechanism,
        #: two speeds, which is what makes the acceleration legible
        #: without a second indicator.
        travel = 1.0 if ph == "thinking" else 0.0
        draw_ingot(frame, now, live, travel, tone=_ramp_rgb,
                   #: the shoulders are the ground's own signal red (the
                   #: stop at 0.275, read back out of the ramp rather than
                   #: written down twice) and the crest is the row's lamp
                   warm=_ramp_rgb(70), hot=tuple(TOURB_GOLD_LIT),
                   size=SIZE)
    except Exception as exc:                            # noqa: BLE001
        _bez_say(f"ingot:{exc!r}", f"ingot: draw failed {exc!r} — the centre "
                                   f"is empty")


#: ── THE SEAL, EASED (2026-08-27) ─────────────────────────────────────
#: `_pulse_phase` is a STEP — it is "hearing" or it is not — and wax does
#: not step. The disc and the bar both take that step raw, which is right
#: for a machined part (an arris either has the lamp on it or it does not);
#: it is wrong for a material whose whole state is temperature. So the
#: caller owns the easing, the same way draw_iris_centre owns the iris's,
#: and centre_seal.py stays a pure function of (live, travel).
#: Rates: LIVE reaches the top in ~0.42 s, which is inside §13's budget for
#: "something perceivable happened"; TRAVEL is slower because it is a
#: change of character rather than an acknowledgement.
_SEAL = {"live": 0.0, "travel": 0.0, "t": 0.0}
SEAL_LIVE_RATE = 2.4            # units per second
SEAL_TRAVEL_RATE = 1.3


def draw_seal_centre(frame: "Image.Image", now: float) -> None:
    """The struck wax seal at the centre, and the heat in it. See
    centre_seal.py for why a seal is allowed to be round when four
    round centrepieces were rejected.

    THE COLOURS ARE NOT PASSED, THE RAMP IS (§15) — draw_ingot_centre's
    note applies verbatim: this row's material is a ten-stop hue turn and
    any two triples lifted out of it would be a second opinion about the
    theme that agrees with the first until somebody edits the row.

    Wrapped whole: new paint in a compositor that must never stop.
    """
    try:
        from centre_seal import draw_seal
        try:
            ph = _pulse_phase(now)
        except Exception:                               # noqa: BLE001
            ph = None
        dt = 0.0 if _SEAL["t"] == 0.0 else max(0.0, min(0.25,
                                                        now - _SEAL["t"]))
        _SEAL["t"] = now
        g_live = 1.0 if ph in ("hearing", "thinking") else 0.0
        g_trav = 1.0 if ph == "thinking" else 0.0
        for k, rate in (("live", SEAL_LIVE_RATE), ("travel",
                                                   SEAL_TRAVEL_RATE)):
            goal = g_live if k == "live" else g_trav
            step = rate * dt
            _SEAL[k] += max(-step, min(step, goal - _SEAL[k]))
        draw_seal(frame, now, _SEAL["live"], _SEAL["travel"], tone=_ramp_rgb,
                  #: the satin sheen is the room's lamp on a glossy red
                  #: object, and the travelling warmth is the lit lamp —
                  #: both read out of the row rather than written here
                  gloss=tuple(TOURB_GOLD), warm_c=_ramp_rgb(76),
                  hot=tuple(TOURB_GOLD_LIT), size=SIZE)
    except Exception as exc:                            # noqa: BLE001
        _bez_say(f"seal:{exc!r}", f"seal: draw failed {exc!r} — the centre "
                                  f"is empty")


#: ── THE STONE (2026-08-30) ────────────────────────────────────────────
#: Owner: "sard's centerpiece is still something i really don't like,
#: redesign that completely." The seal is left standing — the row above
#: still works and `centre="seal"` still selects it — because a
#: centrepiece is chosen by editing one theme row and the last four
#: rejections are worth being able to walk back to (docs/PRINCIPLES.md
#: #11). centre_stone.py's header carries the argument.
#:
#: THE EASING IS THE SEAL'S, and deliberately so. The phase source is a
#: step, the material is not, and the rates were tuned on this dial: LIVE
#: reaches the top in ~0.42 s, inside §13's budget for "something
#: perceivable happened"; TRAVEL is slower because it is a change of
#: character rather than an acknowledgement. Two centrepieces on the same
#: row must not disagree about how fast the room's state arrives, so they
#: share the constants rather than each keeping a copy (§15).
_STONE = {"live": 0.0, "travel": 0.0, "t": 0.0}


def draw_stone_centre(frame: "Image.Image", now: float) -> None:
    """The cut sard at the centre. See centre_stone.py.

    THE COLOURS ARE NOT PASSED, THE RAMP IS (§15) — the bezel is metal
    because it is driven above the ramp's nickel knee, not because a
    second file has an opinion about what colour metal is.

    Wrapped whole: new paint in a compositor that must never stop.
    """
    try:
        from centre_stone import draw_stone
        try:
            ph = _pulse_phase(now)
        except Exception:                               # noqa: BLE001
            ph = None
        dt = 0.0 if _STONE["t"] == 0.0 else max(0.0, min(0.25,
                                                         now - _STONE["t"]))
        _STONE["t"] = now
        g_live = 1.0 if ph in ("hearing", "thinking") else 0.0
        g_trav = 1.0 if ph == "thinking" else 0.0
        for k, rate in (("live", SEAL_LIVE_RATE),
                        ("travel", SEAL_TRAVEL_RATE)):
            goal = g_live if k == "live" else g_trav
            step = rate * dt
            _STONE[k] += max(-step, min(step, goal - _STONE[k]))
        draw_stone(frame, now, _STONE["live"], _STONE["travel"],
                   tone=_ramp_rgb, gloss=tuple(TOURB_GOLD),
                   warm_c=_ramp_rgb(76), hot=tuple(TOURB_GOLD_LIT), size=SIZE)
    except Exception as exc:                            # noqa: BLE001
        _bez_say(f"stone:{exc!r}", f"stone: draw failed {exc!r} — the centre "
                                   f"is empty")


def draw_iris_centre(frame: "Image.Image", now: float) -> None:
    """The iris at the centre, opening on what the ears are doing.

    Wrapped whole: new paint in a compositor that must never stop.
    """
    try:
        from iris import draw_iris
        ph = None
        try:
            ph = _pulse_phase(now)
        except Exception:                               # noqa: BLE001
            ph = None
        goal = (IRIS_HEAR if ph == "hearing"
                else IRIS_THINK if ph == "thinking" else IRIS_REST)
        dt = 0.0 if _IRIS["t"] == 0.0 else max(0.0, min(0.25,
                                                        now - _IRIS["t"]))
        _IRIS["t"] = now
        step = IRIS_RATE * dt
        _IRIS["op"] += max(-step, min(step, goal - _IRIS["op"]))
        draw_iris(frame, now, _IRIS["op"],
                  black=tuple(_THEME.get("black") or (12, 12, 13)),
                  mid=tuple(_THEME.get("mid") or (150, 147, 141)),
                  accent=tuple(TOURB_GOLD), size=SIZE)
    except Exception as exc:                            # noqa: BLE001
        _bez_say(f"iris:{exc!r}", f"iris: draw failed {exc!r} — the centre "
                                  f"is empty")


def draw_rotor(frame: "Image.Image", now: float) -> None:
    """The impeller at the centre, turning at the machine's own fan rate.

    Drawn where draw_tourbillon would be — after the colourway, before the
    dial rotate — so it belongs to the dial and turns with it.

    Wrapped whole: new paint in a compositor that must never stop.
    """
    try:
        pwm = fan_pwm(now)
        rpm = ROTOR_IDLE_RPM + (ROTOR_MAX_RPM - ROTOR_IDLE_RPM) * min(
            1.0, pwm / 255.0)
        dt = 0.0 if _ROTOR["t"] == 0.0 else max(0.0, min(0.25,
                                                         now - _ROTOR["t"]))
        _ROTOR["t"] = now
        _ROTOR["deg"] = (_ROTOR["deg"] + rpm * 6.0 * dt) % 360.0
        spin = _ROTOR["deg"]

        cx = cy = SIZE / 2.0
        #: supersampled, then reduced: ten curved blades at this size show
        #: their stair-steps badly at 1:1, and the whole point of the piece
        #: is that it looks machined.
        S = 2
        n = int(ROTOR_R * 2 * S) + 8
        lay = Image.new("RGBA", (n, n), (0, 0, 0, 0))
        d = ImageDraw.Draw(lay, "RGBA")
        m = n / 2.0

        def pt(rad, deg):
            a = math.radians(deg)
            return (m + rad * S * math.cos(a), m + rad * S * math.sin(a))

        #: the well the rotor sits in — a turned recess, so the blades read
        #: as being INSIDE the part rather than printed on it
        d.ellipse([m - ROTOR_R * S, m - ROTOR_R * S,
                   m + ROTOR_R * S, m + ROTOR_R * S],
                  fill=_rotor_metal(0.04, 255))
        #: the recess wall, lit from the top-left like every chamfer on
        #: this face, so the well reads as TURNED rather than as a black
        #: circle someone drew
        for _k, _f in ((0, 0.50), (1, 0.34), (2, 0.20)):
            _rr = ROTOR_R - _k * 1.6
            d.arc([m - _rr * S, m - _rr * S, m + _rr * S, m + _rr * S],
                  170.0, 350.0, fill=_rotor_metal(_f * 0.62, 210),
                  width=int(2 * S))
            d.arc([m - _rr * S, m - _rr * S, m + _rr * S, m + _rr * S],
                  350.0, 170.0, fill=_rotor_metal(_f * 0.45, 170),
                  width=int(2 * S))

        lit = tuple(TOURB_GOLD)
        #: ── FINER, AND SPLIT (2026-08-26) ──────────────────────────────
        #: Owner: "make the blades finer they look too clunky and add some
        #: orange accent to the edges of them."
        #:
        #: Thinning them alone would leave ten slivers in a wide empty
        #: well, which is a different kind of wrong. Real centrifugal
        #: impellers solve exactly this: SPLITTER BLADES, half-length vanes
        #: sitting between the mains, added because a full blade at every
        #: station would choke the inlet. So the piece gets twenty vanes
        #: and keeps ten blades — the count that quotes the shell's ten
        #: swells is unchanged, and the fineness comes from turbomachinery
        #: rather than from an arbitrary number.
        _vanes = []
        for b in range(ROTOR_BLADES):
            _step = 360.0 / ROTOR_BLADES
            _vanes.append((spin + b * _step, 0.0))          # main
            _vanes.append((spin + (b + 0.5) * _step, 0.42))  # splitter
        for a0, start in _vanes:
            #: each vane is a swept quad: root arc, out along a curve to
            #: the tip, back along the trailing curve. Built from samples
            #: rather than an arc primitive because the sweep has to widen
            #: toward the tip the way a real impeller blade does.
            lead, trail = [], []
            for k in range(11):
                f = start + (k / 10.0) * (1.0 - start)
                rad = ROTOR_HUB_R + f * (ROTOR_R - 6.0 - ROTOR_HUB_R)
                #: chord widens with radius; sweep curves the blade back.
                #: 6.0+10.5 -> 3.0+5.0: at the old chord ten blades filled
                #: most of the disc and the piece read as a pinwheel rather
                #: than as a machined rotor — the gap between vanes is what
                #: makes it look like it moves air.
                wid = 3.0 + 5.0 * f
                ang = a0 + ROTOR_SWEEP * (f ** 1.35)
                lead.append(pt(rad, ang - wid * 0.5))
                trail.append(pt(rad, ang + wid * 0.5))
            poly = lead + trail[::-1]
            #: the blade FACE, dark composite, and a lit leading edge. Two
            #: tones only — this face has one lamp and one metal, and a
            #: third would be the mark15 engraving's mistake in pixels.
            #: MEASURED BY EYE ON THE FIRST RENDER, and the fault is the
            #: same one that has bitten this face twice: a face at 0.30
            #: against a well at 0.10 is two values a fifth apart, and
            #: through carbon's duotone both arrive nearly black — so the
            #: blades vanished and only their amber tips showed, reading as
            #: scratches on a disc. The blade is the SUBJECT; it gets the
            #: metal, and the well gets the dark.
            #: 0.46 -> 0.19. At 0.46 the blade fills at machined grey and
            #: the piece reads as a paper pinwheel — bright, flat, and
            #: shouting over a face whose whole argument is restraint.
            #: Carbon in a dark housing is nearly black WITH A LIT EDGE;
            #: the light belongs on the arris, not in the field. Same
            #: mistake as filling a wedge to prove it is there.
            d.polygon(poly, fill=_rotor_metal(0.19, 255))
            #: trailing edge first, so the leading edge overwrites it where
            #: they meet at the tip — a blade is lit on one flank only
            d.line(trail, fill=_rotor_metal(0.07, 220), width=int(2.0 * S),
                   joint="curve")
            d.line(lead, fill=_rotor_metal(0.62, 225), width=int(1.5 * S),
                   joint="curve")
            #: ── THE AMBER ON THE ARRIS ────────────────────────────────
            #: It ran along the outer 40% of the leading edge only. Owner
            #: wants it on "the edges", plural, so it now runs the WHOLE
            #: leading edge and returns along the trailing one, fading
            #: inboard on both — the lamp rakes the vane rather than
            #: tipping it. Still the one lamp this face allows: amber and
            #: nothing else, laid on the arris where the light would
            #: actually catch.
            #: 2026-08-26, second pass: "still can't notice the orange,
            #: make it bolder". It was 40..215 alpha on a 1.7px pen, which
            #: on a 152px rotor viewed across a room is a hairline — and a
            #: hairline of accent on a near-black field is the hearing
            #: bloom's mistake again, present in the frame and under the
            #: threshold of sight. Alpha now runs to full and the pen is
            #: half again as wide; the trailing arris keeps half rather
            #: than a third, so the vane is legible as a SOLID even where
            #: it is turning away.
            for _i in range(len(lead) - 1):
                _f = _i / float(len(lead) - 1)
                _a = int(110 + 145 * (_f ** 0.7))
                d.line([lead[_i], lead[_i + 1]], fill=lit + (min(255, _a),),
                       width=int(2.6 * S))
                d.line([trail[_i], trail[_i + 1]],
                       fill=lit + (int(_a * 0.5),), width=int(1.8 * S))
            #: and the tip itself takes a hot cap — the brightest point on
            #: the vane is where it meets the well, which is where a real
            #: rim light would blow out
            d.line(lead[-3:], fill=(255, 214, 150, 255), width=int(2.8 * S),
                   joint="curve")

        #: the hub: a machined boss with the one lamp at its centre
        d.ellipse([m - ROTOR_HUB_R * S, m - ROTOR_HUB_R * S,
                   m + ROTOR_HUB_R * S, m + ROTOR_HUB_R * S],
                  fill=_rotor_metal(0.20, 255),
                  outline=_rotor_metal(0.58, 235), width=int(2.5 * S))
        #: a turned step inside the boss — one ring, not three: the piece
        #: already carries ten blades and does not need more incident
        _sr = ROTOR_HUB_R * 0.70
        d.ellipse([m - _sr * S, m - _sr * S, m + _sr * S, m + _sr * S],
                  outline=_rotor_metal(0.42, 200), width=int(1.5 * S))
        _lr = ROTOR_HUB_R * 0.42
        d.ellipse([m - _lr * S, m - _lr * S, m + _lr * S, m + _lr * S],
                  fill=lit + (int(150 + 60 * math.sin(now * 1.7)),))

        lay = lay.resize((int(ROTOR_R * 2) + 4,) * 2, Image.LANCZOS)
        frame.paste(lay, (int(cx - lay.size[0] / 2.0),
                          int(cy - lay.size[1] / 2.0)), lay)
    except Exception as exc:                            # noqa: BLE001
        _bez_say(f"rotor:{exc!r}", f"rotor: draw failed {exc!r} — the "
                                   f"centre is empty")


def draw_tourbillon(frame: "Image.Image", now: float) -> None:
    """The open-worked centre. AFTER the colourway, BEFORE the dial rotate.

    After, with the moonphase and for its reason: the lip goes through
    _dial_metal by hand so it matches the two complications beside it, the
    credit glow is amber on purpose, and since 2026-08-07 the CAGE IS GOLD —
    gold against near black is a contrast between two hues and a duotone has
    one, which is the same argument that put the moonphase on this side of
    desertify. Before the rotate because it belongs to the dial and turns
    with it.

    The ground is OPAQUE inside the aperture, which is how the tapisserie and
    the starfield stop at its edge: the hole is cut here, at paste time, not
    in the bake.

    Wrapped whole: new paint in a compositor that must never stop.
    """
    try:
        lay = _tourb_layer(now)
        r = lay.size[0] // 2
        box = (SIZE // 2 - r, SIZE // 2 - r)
        # THE DAMAGE RECT (2026-08-07, see TOURB_RECT_FPS). What is under the
        # aperture is kept BEFORE the movement is pasted over it, so the idle
        # loop can repaint this one window between full frames without
        # recomposing the face. Stored here rather than derived later because
        # here is the only moment the background exists un-covered.
        _TOURB_LAY["box"] = box
        _TOURB_LAY["under"] = frame.crop((box[0], box[1],
                                          box[0] + lay.size[0],
                                          box[1] + lay.size[1]))
        #: The DRAWN centre keeps no margin, so the turned-rect path must not
        #: find a stale one left by a pack that was loaded earlier in this
        #: process. Cleared rather than filled: this path is the fallback for
        #: a device with no pack, and it can take the full-frame rate.
        _TOURB_LAY["under_big"] = None
        frame.paste(lay, box, lay)
    except Exception as e:                      # noqa: BLE001
        _TOURB_LAY["under"] = None              # a stale background is worse
        _bez_say(f"tourb:{e!r}", f"tourbillon: draw failed {e!r} — "
                                 f"the centre is empty")


def _tourb_layer(now: float) -> "Image.Image":
    """The movement at this instant, as one RGBA sprite the size of the
    aperture. Lifted out of draw_tourbillon so the rect path can build the
    same pixels without a frame to paste them into."""
    # ...OR THE REV COUNTER, on a theme whose row asks for one (REV_ON, and
    # the doctrine argument is there). One branch and no second call site:
    # the aperture, the damage rect and the `plain` gate belong to the HOLE,
    # not to what is in it, and every clearance measured for the cage holds
    # for anything that fits the same opening.
    if REV_ON:
        return _rev_layer(now)
    # THE CAGE IS THE SECONDS HAND (2026-08-07, see TOURB_GOLD). One turn
    # a minute off the wall clock, so it agrees with draw_clock rather
    # than free-running from process start; indexed straight into the
    # pre-rendered sprites, so there is no angle to integrate, nothing to
    # drift, and no resample in the frame.
    cstep = int((now % 60.0) / 60.0 * TOURB_STEPS) % TOURB_STEPS
    # THE BALANCE IS THE THING THAT SPRINGS (2026-08-07, see
    # TOURB_BAL_AMP_DEG). A sine of the wall clock IS the hairspring, so
    # the easing at each end of the travel comes out of the physics
    # rather than being tuned; the cage's own bearing is added because
    # the balance is carried by it. Modulo the period first — the phase
    # is what matters and now is ~1.7e9, where the double loses precision
    # it does not have to lose.
    bal_deg = (TOURB_BAL_AMP_DEG
               * math.sin((now % (1.0 / TOURB_BAL_HZ))
                          * TOURB_BAL_HZ * 2.0 * math.pi)
               + 360.0 * cstep / TOURB_STEPS)
    bstep = int(round(bal_deg * TOURB_BAL_STEPS / 360.0)) % TOURB_BAL_STEPS
    led = _ledger_now(now)
    burn = 0.0 if led is None else max(0.0, led["rate_real"])
    gstep = int(round(min(1.0, burn / TOURB_BURN_FULL)
                      * (TOURB_GLOW_STEPS - 1)))
    key = (cstep, gstep)
    if _TOURB_LAY["key"] != key or _TOURB_LAY["lay"] is None:
        lay = _tourb_ground().copy()
        if gstep > 0:
            g = _tourb_glow(gstep)
            off = (lay.size[0] - g.size[0]) // 2
            lay.alpha_composite(g, (off, off))
        cage = _tourb_cages()[cstep]
        coff = (lay.size[0] - cage.size[0]) // 2
        lay.alpha_composite(cage, (coff, coff))
        _TOURB_LAY["key"], _TOURB_LAY["lay"] = key, lay
    # The cached layer above changes once a second; the balance moves
    # every frame, so it and the two static parts go on a COPY of it.
    # That is one 276px copy and two composites per frame — no resample,
    # and the expensive half (ground, glow, cage) stays cached.
    lay = _TOURB_LAY["lay"].copy()
    bal = _tourb_balances()[bstep]
    boff = (lay.size[0] - bal.size[0]) // 2
    lay.alpha_composite(bal, (boff, boff))
    # The lip of the hole and the jewel go on TOP of the movement: the
    # dial is cut through ABOVE it, and the cage turns on a pivot that
    # does not.
    lay.alpha_composite(_tourb_static())
    return lay


#: ── THE AURORA FACE GETS A DAMAGE RECT (2026-08-19) ──────────────────────
#: Every pace sample this face has ever produced reads `(N full + 0.0 rect)`.
#: The painter exists — blit_rect, 0.76 ms for a 200x200 — and has served the
#: watch dials' tourbillon aperture since 08-07; the aurora face repaints all
#: 1080 rows to move a waveform.
#:
#: WHAT MOVES ON THIS FACE, and it is only two things: the iris in the middle
#: (c:core, 19-25 ms — by far the most expensive phase, and NOT something a
#: rect can help with, because redrawing it IS the cost) and the ribbon in the
#: pane gap (t:ribbon, 2.9 ms). The panes themselves are still. So the ribbon
#: is the one object on this face whose motion can be bought cheaply, and this
#: is the path that buys it.
#:
#: THE GROUND IS THE FRAME WITH THE RING ON IT AND THE TRACE NOT YET DRAWN.
#: Same discipline as _tourb_rect_paint: composite over clean pixels every
#: time, never over the previous paint, or the trace smears a trail along the
#: arc at whatever rate this runs.
#:
#: IT STANDS DOWN WITH THE DIAL OFF HOME, AND SAYS SO. The ribbon is drawn in
#: unrotated panel coordinates and turns because the WHOLE COMPOSED FRAME is
#: rotated once afterwards (see the long note in draw_aurora_ribbon — adding
#: rot_deg here as well is a documented bug that walked the trace across the
#: buttons at twice the dial rate). A rect cannot use that rotate: it would
#: have to reproduce it, which means a second piece of geometry that can
#: disagree with the first. The drawn tourbillon already made this call for
#: the same reason. What is NOT acceptable is doing it silently — a face that
#: quietly stops being fast looks identical to one that was never fast — so
#: the stand-down is logged once and the pace line goes on reporting 0.0 rect,
#: which is the honest reading.
_AUR_RIB_LAY: dict = {"under": None, "box": None, "said": set()}


def _aur_rect_stash(frame: "Image.Image", deg: float) -> None:
    """Keep the ribbon's ground. Called from the compose, between the ring
    and the trace — the ONE moment the frame is in that state."""
    try:
        if not _AUR_UI["vis"]:
            #: the ring is down, so the stash is a picture of a face that no
            #: longer exists. Cleared rather than left: a stale ground is
            #: exactly the smear this whole path is arranged to avoid.
            _AUR_RIB_LAY["under"] = None
            return
        box = _aur_ribbon_box()
        if box is None:
            _AUR_RIB_LAY["under"] = None
            return
        if box != _AUR_RIB_LAY.get("box"):
            _AUR_RIB_LAY["box"] = box
            print(f"aurora: ribbon damage rect {box[2] - box[0]}x"
                  f"{box[3] - box[1]} at ({box[0]},{box[1]}) — "
                  f"{100.0 * (box[2] - box[0]) * (box[3] - box[1]) / (SIZE * SIZE):.1f}% "
                  f"of the glass", flush=True)
        _AUR_RIB_LAY["under"] = frame.crop(box)
    except Exception as exc:                            # noqa: BLE001
        _AUR_RIB_LAY["under"] = None
        if "stash" not in _AUR_RIB_LAY["said"]:
            _AUR_RIB_LAY["said"].add("stash")
            print(f"aurora: ribbon ground not kept {exc!r} — full frames "
                  f"only", flush=True)


def _aur_rect_paint(now: float, deg: float = 0.0) -> None:
    """Repaint ONLY the pane gap, straight to the panel."""
    under, box = _AUR_RIB_LAY.get("under"), _AUR_RIB_LAY.get("box")
    if under is None or box is None:
        #: RAISES rather than returning quietly: the caller's gate has
        #: already decided this path is armed, so arriving here with no
        #: ground means the two disagree, and the loop's except turns that
        #: into a printed line and a fall back to full frames (§1).
        raise RuntimeError("aurora rect armed with no ground kept")
    if abs(deg) > 0.05:
        raise RuntimeError(f"aurora rect cannot turn (dial at {deg:.1f} deg)")
    reg = under.copy()
    draw_aurora_ribbon(reg, now, rot_deg=0.0, off=(box[0], box[1]))
    blit_rect(reg, box[0], box[1])


def _tourb_rect_paint(now: float, deg: float = 0.0) -> None:
    """Repaint ONLY the aperture, straight to the panel — the damage rect.

    The background is the frame as it stood just before the last full paste,
    so this composites the movement over clean pixels every time rather than
    over its own previous frame; nothing accumulates at the sprite's soft
    edge. Everything outside the rect is left exactly as the full frame left
    it, which is why the caller must be sure nothing else has been painted
    over the centre since (see the `plain` gate in main).
    """
    under, box = _TOURB_LAY.get("under"), _TOURB_LAY.get("box")
    if under is None or box is None:
        return
    reg = under.copy()
    #: THE PACK OWNS THE HOLE WHEN THERE IS ONE, and the aperture, the rect
    #: and the `plain` gate belong to the HOLE rather than to what is in it —
    #: the rev-counter note above makes the same argument for its own branch.
    #: Whichever filled the aperture on the last full frame is what refills it
    #: here, or the rect would repaint a live tourbillon over a pack.
    lay = centre_pack_sprite(now)
    if lay is None:
        lay = _tourb_layer(now)
    #: ── THE TURNED CASE, WHICH IS THE ONE HE NOTICED ────────────────────
    #: Compose in UNROTATED coordinates exactly as the full frame does, then
    #: apply the same rotation the full frame applies, then crop back. The
    #: box itself never moves: it is concentric with the panel and PIL
    #: rotates about the image centre, so a rotation about the dial centre
    #: leaves the aperture where it was and only turns what is inside it.
    #:
    #: NEAREST, matching the full path's own resample for the dial rotate —
    #: a rect that filtered differently from the frame it sits in would show
    #: a seam at the aperture edge every time the two met.
    if abs(deg) > 0.05 and _TOURB_LAY.get("under_big") is not None:
        m = _TOURB_LAY["margin"]
        big = _TOURB_LAY["under_big"].copy()
        big.paste(lay, (m, m), lay)
        draw_chopard_hands(big, now, off=(box[0] - m, box[1] - m))
        big = big.rotate(deg, resample=Image.NEAREST)
        reg = big.crop((m, m, m + reg.size[0], m + reg.size[1]))
        blit_rect(reg, box[0], box[1])
        return
    if abs(deg) > 0.05:
        #: DRAWN centre, dial turned (2026-08-16, the spun royal-oak):
        #: the drawn path keeps no margin (see draw_tourbillon), so there
        #: is nothing here that knows how to turn — and an UNROTATED rect
        #: against ROTATED full frames flickered the cage between two
        #: orientations 38 times a second ("the tourbillon just goes out
        #: of control" the moment the dial rests off home). Stand down and
        #: let the 8 fps full frames own the aperture — exactly what the
        #: pre-08-13 gate did for every face, now only for the one path
        #: that cannot do better.
        return
    reg.paste(lay, (0, 0), lay)
    # Whatever sweeps OVER the aperture has to be re-applied here or the
    # rect erases it 30 times a second — see the note at draw_chopard_hands.
    draw_chopard_hands(reg, now, off=box)
    blit_rect(reg, box[0], box[1])


#: ── 2026-08-09: ON THE FERRARI THE CENTRE IS A REV COUNTER ────────────────
#:
#: Owner, commissioning the theme: "not a tourbillon: a TACHYMETER-style
#: centre. The middle of the dial becomes a rev-counter arc sweeping from
#: black through amber to red — driven by something real, and the honest
#: choice is the credit burn rate (the rate/MIN the ledger already
#: publishes), so the needle climbs when the puck is working hard. A REDLINE
#: ZONE at the top of the arc in bright red says 'burning fast' at a glance.
#: That is a genuine instrument, not decoration."
#:
#: THE DOCTRINE IS WHY THIS EXISTS AT ALL (docs/PREMIUM.md, 2026-08-08:
#: "themes must not share centerpieces"). Three sellable faces cannot all
#: open a hole in the middle of the dial and put the same gold cage in it.
#: The APERTURE is shared and stays shared — same TOURB_R, same chamfer from
#: _tourb_static, so every clearance measured for the cage (12.4px to all
#: three register flanges) holds without being re-derived, and the damage
#: rect, the `plain` gate and _tourb_rect_paint keep working unchanged. What
#: changes is what is INSIDE the hole.
#:
#: IT READS A REAL NUMBER, and that is the same test the cage had to pass:
#: "an animation that reports a real state is a complication; one that just
#: moves is a screensaver." The needle is _ledger_now()["rate_real"] — the
#: honest burn, the one the reserve integrates, not the shown one — against
#: TOURB_BURN_FULL, deliberately the SAME 500 credits/min full scale the
#: tourbillon's glow has always used. Two windows on one fire; a face that
#: metered the burn on a different scale from the meter beside it would be
#: two instruments disagreeing in public.
#:
#: WHEN THERE IS NO READING THE NEEDLE PARKS AT ZERO AND SAYS SO, once, on
#: stdout. §2: "I cannot tell" is not "no" — a needle resting at zero is a
#: legitimate reading of an idle puck, so the only way to tell the two apart
#: is a log line, and the alternative (a needle that hides) is the silent
#: failure this file keeps a section on.
#:
#: WHERE THE REDLINE IS. The owner asked for it "at the top of the arc" and
#: that is what decided the geometry rather than symmetry: the scale opens at
#: seven o'clock (REV_A0 = 120 in the panel's cos/sin frame, so the needle
#: rests pointing lower-left the way a car's does) and sweeps 185 degrees
#: clockwise to about one o'clock. The last 24% is therefore the band
#: straddling twelve — the top. A SYMMETRIC arc would have been prettier and
#: would have put full scale on the right flank, which is not what was asked.
#: The open 175 degrees at the bottom is not waste: it is where the caption
#: goes, and it keeps the aperture's lower half quiet under the moon
#: register's own block.
REV_ON = _THEME.get("centre") == "rev"
REV_A0 = 120.0                      # zero, at seven o'clock
REV_SWEEP = 185.0                   # ...clockwise to about one
REV_RED_AT = 0.76                   # where the redline zone opens, as a
                                    # fraction of full scale: 380 of 500
                                    # credits/min. "Burning fast" wants to be
                                    # rare enough to mean something.
#: ── 2026-08-09: THE GAUGE MOVES INTO A STEERING WHEEL'S HUB ───────────────
#: Owner: "perhaps the center looks more like the steering wheel that becomes
#: the volume indicator as you speak?" — which SUPERSEDES the plain rev-counter
#: centre in the block above while keeping everything else in it (the scale,
#: the redline, the reading, the eased needle, the engine under it). The block
#: above stands with its date; only these radii changed.
#:
#: EVERY RADIUS BELOW IS THE OLD ONE SCALED BY 0.717, AND THAT NUMBER IS
#: GEOMETRY RATHER THAN TASTE. The wheel has to fit the aperture it inherits
#: (TOURB_R=130, less POCKET_WALL_W=7 of bore wall = 121 of usable radius), it
#: is flat-topped and flat-bottomed like an F1 wheel, and the tach face has to
#: fit the opening those flats leave. WHEEL_R=119 with a 13px rim puts the
#: rim's INNER flats at |y|=88, so the largest circular face that clears them
#: is 86 — against the 120 the scale channel used to reach. 86/120 = 0.717,
#: and everything from the channel to the crank boss is that factor.
REV_FACE_R = 86                     # the yellow dial face, inside the hub
REV_BAND_R0, REV_BAND_R1 = 72, 86    # the scale channel, cut in that face
REV_TICK_MINOR, REV_TICK_MAJOR = 66, 59   # graduations hang inward from R0
REV_NUM_R = 48                      # the numerals' own circle
REV_DIVS, REV_MINOR = 5, 4          # 0..5 hundred credits/min, 4 minors each
REV_NEEDLE_TIP = 68                 # stops short of the channel: a needle
REV_NEEDLE_TAIL = 18                # that touches its own scale hides it
REV_NEEDLE_W = 4.0                  # half-width at the hub, tapering to 1.2
REV_HUB_R = 11
REV_STEPS = 96                      # angle table, ~1.9 degrees a step
REV_CACHE_MAX = 32                  # ...built LAZILY and capped; see below
#: The bore. Same physics as the tourbillon's (deep at the centre, lit at the
#: lip — the corrected arithmetic at TOURB_FLOOR_DEEP), in carbon rather than
#: in the AP's grey-blue, because the hole is cut through a carbon dial. It is
#: now what the WHEEL sits in rather than what the gauge is painted on.
REV_FLOOR_DEEP = (4, 4, 5)
REV_FLOOR_LIP = (40, 40, 44)
#: ── THE DIAL FACE IS GIALLO MODENA, AND THE NUMERALS ARE BLACK ────────────
#: Owner: "the rev gauge's dial face goes yellow with black numerals — that
#: single move makes the centre read Ferrari from across a room, and it is the
#: one place yellow belongs most."
#:
#: THE FACE IS SHADED, NOT FLAT, for the same reason every other recess here
#: is: a flat fill on a dial where everything else is lit from POCKET_KEY
#: reads as a sticker. Lit at the upper-left lip, a shade deeper at the
#: opposite edge — one radial ramp, baked once with the rest of the ground.
#:
#: THE GRADUATIONS AND THE UNIT CAPTION GO BLACK WITH THE NUMERALS. They were
#: _dial_metal(228) — a near-white that had 4.5:1 against carbon and has 1.2:1
#: against Giallo. Black on this yellow is 10.9:1, which is the contrast the
#: owner means by "the contrast is the point".
REV_FACE = _THEME.get("yellow", (250, 200, 20))
REV_FACE_LIP = tuple(min(255, int(c * 1.10)) for c in REV_FACE)
REV_FACE_DEEP = tuple(int(c * 0.72) for c in REV_FACE)
REV_FACE_SHADE_OFF = 16             # how far the sky's disc is pushed...
REV_FACE_SHADE_BLUR = 11.0          # ...and how soft the crescent it leaves
REV_FACE_SHADE_A = 132              # peak alpha of that shade
REV_INK = (14, 12, 6)               # the black the numerals are painted in
#: The arc's ramp: black -> amber -> red, then the redline zone in a brighter
#: red so it separates from the red the scale has already reached.
#: IT STAYS AS IT WAS on a yellow face, and that is a decision rather than an
#: oversight: the ramp is painted INSIDE the channel, whose walls are struck
#: at REV_CHANNEL (source L 30, near-black through this ramp) and stand either
#: side of it — so the amber never touches the Giallo, and the redline zone
#: keeps the bright red the brief asks to be preserved against the yellow.
REV_COLD = (16, 16, 18)
REV_AMBER = (232, 146, 42)
REV_REDLINE = (255, 62, 52)
REV_CHANNEL = 30                    # the unlit floor of the channel, source L
#: ── 2026-08-09: THE NEEDLE SWEEPS, IT NO LONGER JUMPS ─────────────────────
#: Owner: "make the movement visible and eased, not a jump." The gauge read
#: the right number from the first render and showed it by TELEPORTING — the
#: rate is sampled once per bake, so a 40-credit change moved the needle 15
#: degrees between two frames and the eye saw a new position rather than a
#: movement. A first-order lag on the DISPLAYED fraction is the whole fix:
#: the needle chases the reading with a 0.45 s time constant, so it settles
#: in ~1.4 s and every frame in between is on the way there. The number it
#: is chasing is untouched — this eases the POINTER, never the reading.
REV_EASE_TAU = 0.45
_REV = {"ground": None, "needles": {}, "key": None, "lay": None,
        "said": False, "t": None, "disp": 0.0, "phase": 0.0,
        "over": False, "flash": -99.0, "hzq": None,
        # the shift-light strip's own state (see SHIFT_LEDS)
        "lvl": 0.0, "lit": -1, "src": None, "deaf": False}


def _rev_frac(now: float):
    """(fraction of full scale, the rate it came from) or (0.0, None).

    None is the third answer §2 asks for: no ledger reading at all, as
    against a real reading of zero."""
    led = _ledger_now(now)
    if led is None:
        if not _REV["said"]:
            _REV["said"] = True
            print("rev: no $LEDGER reading — the needle parks at zero",
                  flush=True)
        return 0.0, None
    if _REV["said"]:
        _REV["said"] = False
        print("rev: $LEDGER reading is live again", flush=True)
    rate = max(0.0, led["rate_real"])
    return min(1.0, rate / TOURB_BURN_FULL), rate


def _rev_ang(frac: float) -> float:
    return REV_A0 + REV_SWEEP * max(0.0, min(1.0, frac))


def _rev_band_col(frac: float) -> tuple:
    """The channel's colour at this point of the scale: black -> amber -> red,
    and BRIGHT red past REV_RED_AT. Two straight ramps rather than one curve —
    the amber has to land where the eye reads 'working', which is the middle
    of the scale, and a single interpolation from black to red never passes
    through amber at all."""
    if frac >= REV_RED_AT:
        return REV_REDLINE
    if frac < 0.55:
        k = frac / 0.55
        a, b = REV_COLD, REV_AMBER
    else:
        k = (frac - 0.55) / (REV_RED_AT - 0.55)
        a, b = REV_AMBER, TOURB_GOLD          # the theme's accent: Rosso Corsa
    return tuple(int(round(a[i] + (b[i] - a[i]) * k)) for i in range(3))


def _rev_ground():
    """The instrument, everything but the needle, baked once per process.

    Built like every other recessed thing on this dial: the bore's floor and
    wall come from _pocket_relief (one upper-left sky, interior lit
    backwards), the scale channel is CUT into that floor and its graduations
    are struck in the dial's own metal, and the ramp is laid segment by
    segment so the colour is a property of the SCALE rather than of the
    needle's position — a gauge whose markings change colour as the needle
    passes is a light show, not an instrument.
    """
    if _REV["ground"] is None:
        r = TOURB_R + 8
        lay = Image.new("RGBA", (2 * r, 2 * r), (0, 0, 0, 0))
        px = py = float(r)
        d = ImageDraw.Draw(lay)
        rr = float(TOURB_R) - 1.0
        # PLANE ONE, THE BORE: deep in the middle, lit at the lip. Concentric
        # 1px bands, opaque — this is what cuts the weave off at the
        # aperture's edge without touching the bake.
        steps = int(rr)
        for i in range(steps, 0, -1):
            k = i / float(steps)
            col = tuple(int(round(REV_FLOOR_DEEP[j]
                                  + (REV_FLOOR_LIP[j] - REV_FLOOR_DEEP[j]) * k))
                        for j in range(3))
            d.ellipse([px - i, py - i, px + i, py + i], fill=col + (255,))
        # PLANE ONE AND A HALF, THE YELLOW FACE (see REV_FACE). Giallo Modena,
        # lit at the upper-left lip and a shade deeper across from it, laid as
        # concentric bands like everything else recessed here. It stops at
        # REV_FACE_R so the bore's carbon floor still shows all round it —
        # that dark ring is what the steering wheel is mounted in.
        for i in range(REV_FACE_R, 0, -1):
            k = i / float(REV_FACE_R)
            col = tuple(int(round(REV_FACE[j]
                                  + (REV_FACE_LIP[j] - REV_FACE[j]) * k))
                        for j in range(3))
            d.ellipse([px - i, py - i, px + i, py + i], fill=col + (255,))
        # ...and the shaded flank, so the face is a lit disc rather than a
        # flat yellow sticker: the disc MINUS the same disc pushed toward
        # POCKET_KEY is a crescent on the side turned away from the sky, and
        # blurring it is what makes it a shadow instead of an edge.
        #
        # BUILT AS A MASK, NOT AS ARCS, and that is a measured correction: a
        # stack of alpha arcs was tried first and came out as a DOTTED ring on
        # the render — ImageDraw has no antialiasing and REPLACES pixels
        # rather than compositing them, so an alpha in a fill= punches holes
        # in the face instead of shading it. Masks composite; arcs do not.
        disc = Image.new("L", lay.size, 0)
        ImageDraw.Draw(disc).ellipse([px - REV_FACE_R, py - REV_FACE_R,
                                      px + REV_FACE_R, py + REV_FACE_R],
                                     fill=255)
        ox, oy = POCKET_KEY[0] * REV_FACE_SHADE_OFF, \
            POCKET_KEY[1] * REV_FACE_SHADE_OFF
        lit = Image.new("L", lay.size, 0)
        ImageDraw.Draw(lit).ellipse([px - REV_FACE_R + ox,
                                     py - REV_FACE_R + oy,
                                     px + REV_FACE_R + ox,
                                     py + REV_FACE_R + oy], fill=255)
        cres = ImageChops.multiply(
            ImageChops.subtract(disc, lit).filter(
                ImageFilter.GaussianBlur(REV_FACE_SHADE_BLUR)), disc)
        sh = Image.new("RGBA", lay.size, REV_FACE_DEEP + (0,))
        sh.putalpha(cres.point(
            lambda p: p * REV_FACE_SHADE_A // 255))
        lay.alpha_composite(sh)
        # PLANE TWO, THE CHANNEL the scale is engraved in: a darker annulus,
        # so the coloured ramp sits IN the floor rather than on it.
        #
        # ONE THICK OUTLINE, NOT A STACK OF 1px ONES, and that is a measured
        # correction from this pass rather than tidying. The stack left GAPS
        # between successive radii — invisible while the floor under it was
        # carbon, and on the yellow face a DOTTED ring of Giallo showing
        # through the groove, which is the first thing the eye found on the
        # render. PIL draws a width= outline inward from the box, so one call
        # covers the annulus solidly.
        d.ellipse([px - REV_BAND_R1, py - REV_BAND_R1,
                   px + REV_BAND_R1, py + REV_BAND_R1],
                  outline=_dial_metal(REV_CHANNEL, 255),
                  width=REV_BAND_R1 - REV_BAND_R0 + 1)
        # THE RAMP, one degree at a time. Inset 3px inside the channel so the
        # colour band leaves the channel's own walls visible either side —
        # that gap is what says the paint is IN a groove.
        # THE BOX IS THE OUTER WALL LESS 3, NOT THE CHANNEL'S MIDLINE: PIL
        # draws a width= stroke INWARD from the box rather than centred on it,
        # so the midline put the whole band against the inner wall and left
        # all six px of gap on the outside. MEASURED on the render at bearing
        # 200: paint 72..79 of a 72..86 channel. This lands it 75..83.
        cw = (REV_BAND_R1 - REV_BAND_R0) - 6
        cr = float(REV_BAND_R1 - 3)
        box = [px - cr, py - cr, px + cr, py + cr]
        n = int(REV_SWEEP)
        for i in range(n):
            f0 = i / float(n)
            d.arc(box, REV_A0 + REV_SWEEP * f0 - 0.6,
                  REV_A0 + REV_SWEEP * (i + 1) / float(n) + 0.6,
                  fill=_rev_band_col(f0) + (255,), width=cw)
        # THE GRADUATIONS, struck BLACK now that the face is Giallo — see the
        # contrast arithmetic at REV_INK. The redline zone's own marks stay
        # red, which is the one thing the brief asked to be preserved through
        # the yellow. Numerals scaled 15 -> 11 with the rest of the gauge.
        f_num = face("label-b", 11)
        for i in range(REV_DIVS * REV_MINOR + 1):
            f = i / float(REV_DIVS * REV_MINOR)
            major = i % REV_MINOR == 0
            t = math.radians(_rev_ang(f))
            r1 = REV_BAND_R0 - 1
            r0 = REV_TICK_MAJOR if major else REV_TICK_MINOR
            red = f >= REV_RED_AT
            ink = REV_REDLINE + (255,) if red else REV_INK + (255,)
            d.line([(px + r0 * math.cos(t), py + r0 * math.sin(t)),
                    (px + r1 * math.cos(t), py + r1 * math.sin(t))],
                   fill=ink, width=3 if major else 1)
            if major:
                s = str(i // REV_MINOR)
                bb = d.textbbox((0, 0), s, font=f_num)
                d.text((px + REV_NUM_R * math.cos(t) - (bb[2] - bb[0]) / 2.0,
                        py + REV_NUM_R * math.sin(t) - (bb[3] - bb[1]) / 2.0
                        - bb[1]), s, font=f_num, fill=ink)
        # WHAT IT READS, said on the dial. A gauge with no unit is a
        # decoration with a needle: x100 credits per minute, which is the
        # figure the $LEDGER block publishes three inches away.
        #
        # THE SIZE IS MEASURED, NOT CHOSEN, and that supersedes the old "y+78,
        # corners reach r=100 against the bore's 129" — the caption used to
        # live on the bore floor below the scale and now lives ON the yellow
        # face, whose usable width at the caption's row is a good deal less.
        # §6: the constant is only meaningful against the thing it competes
        # with, so the size is picked by measuring the string until its own
        # corners clear the channel's inner wall, and WHICH size won is
        # printed once (§1) — a caption silently shrunk to nothing looks
        # exactly like a caption that failed to draw.
        cap = "x100 CR/MIN"
        cap_y = py + 52
        for pt in (11, 10, 9, 8, 7):
            f_cap = face("label", pt)
            bb = d.textbbox((0, 0), cap, font=f_cap)
            w, h = bb[2] - bb[0], bb[3] - bb[1]
            if math.hypot(w / 2.0, cap_y - py + h) <= REV_BAND_R0 - 3:
                break
        print(f"rev: unit caption {cap!r} set at {pt}pt — corners reach "
              f"r={math.hypot(w / 2.0, cap_y - py + h):.0f} of the "
              f"{REV_BAND_R0 - 3} the yellow face allows", flush=True)
        d.text((px - w / 2.0 - bb[0], cap_y), cap, font=f_cap,
               fill=REV_INK + (255,))
        # THE BORE'S WALL AND ITS RIM PAIR, from the pockets — the same
        # arithmetic the three registers wear, so the centre is lit by the
        # same sky as everything round it.
        _pocket_relief(lay, px, py, rr, _dial_metal)
        _REV["ground"] = lay
    return _REV["ground"]


def _rev_needle(step: int):
    """One needle angle, cut to its own square. Cached LAZILY and CAPPED.

    The tourbillon builds its sixty cages at startup because the cage turns
    every second and will visit all sixty within the minute. A rev needle
    does not: the burn rate holds still for minutes at a time, so building
    all REV_STEPS up front would pay 14 MB and a few seconds of startup for
    angles this process may never draw. The cap is the other half of that —
    a rate that wanders across the whole scale must not grow the table
    without bound, so past REV_CACHE_MAX the dict is dropped and refills.
    """
    lay = _REV["needles"].get(step)
    if lay is not None:
        return lay
    if len(_REV["needles"]) >= REV_CACHE_MAX:
        _REV["needles"].clear()
    n = 2 * (REV_NEEDLE_TIP + 4)
    c = n / 2.0
    lay = Image.new("RGBA", (n, n), (0, 0, 0, 0))
    t = math.radians(_rev_ang(step / float(REV_STEPS)))
    ux, uy = math.cos(t), math.sin(t)
    px_, py_ = -uy, ux                       # across the needle
    w0, w1 = REV_NEEDLE_W, 1.2
    body = [(c - REV_NEEDLE_TAIL * ux - w0 * 0.8 * px_,
             c - REV_NEEDLE_TAIL * uy - w0 * 0.8 * py_),
            (c + REV_NEEDLE_TIP * ux - w1 * px_,
             c + REV_NEEDLE_TIP * uy - w1 * py_),
            (c + REV_NEEDLE_TIP * ux + w1 * px_,
             c + REV_NEEDLE_TIP * uy + w1 * py_),
            (c - REV_NEEDLE_TAIL * ux + w0 * 0.8 * px_,
             c - REV_NEEDLE_TAIL * uy + w0 * 0.8 * py_)]
    # THE SHADOW FIRST, down-right away from TOURB_KEY and blurred — the one
    # mark that proves the needle and the floor are at different heights, and
    # the same offset/blur the cage's shadow was measured at.
    sh = Image.new("RGBA", (n, n), (0, 0, 0, 0))
    o = TOURB_SHADOW_OFF * 0.6
    ImageDraw.Draw(sh).polygon([(x + o, y + o) for x, y in body],
                               fill=(0, 0, 0, TOURB_SHADOW_A))
    lay.alpha_composite(sh.filter(ImageFilter.GaussianBlur(TOURB_SHADOW_BLUR)))
    d = ImageDraw.Draw(lay)
    d.polygon(body, fill=TOURB_GOLD + (255,))
    # The relief pair on a needle is its two flanks: the one turned up-left
    # into the sky is the specular, the other is the shaded side. Drawn as
    # the body's own edges rather than as a second polygon, so the needle
    # keeps its measured width.
    d.line([body[0], body[1]], fill=TOURB_GOLD_LIT + (255,), width=1)
    d.line([body[3], body[2]], fill=TOURB_GOLD_DARK + (255,), width=1)
    # THE HUB, and it is the one warm metal: a machined aluminium boss with
    # the standard raised pair, so the red needle reads as paint turning on
    # metal — the owner's own argument for keeping a metal at all.
    d.ellipse([c - REV_HUB_R, c - REV_HUB_R, c + REV_HUB_R, c + REV_HUB_R],
              fill=_dial_metal(150, 255), outline=_dial_metal(232, 255),
              width=2)
    d.arc([c - REV_HUB_R, c - REV_HUB_R, c + REV_HUB_R, c + REV_HUB_R],
          20.0, 160.0, fill=_dial_metal(24, 220), width=2)
    d.ellipse([c - 4, c - 4, c + 4, c + 4], fill=TOURB_GOLD + (255,))
    _REV["needles"][step] = lay
    return lay


#: ── 2026-08-09: THE ENGINE RUNS UNDER THE GAUGE ───────────────────────────
#:
#: Owner: "THE ENGINE MUST OUT-DRAMA THE CHASSIS. The rev counter is a good
#: instrument and a static one ... add a RUNNING ENGINE at the centre — some
#: unique engine style animation in the middle. It should idle slowly when
#: the puck is quiet and RUN FASTER WHEN THE BURN RATE CLIMBS — the machine
#: visibly working is the whole metaphor, and it is honest because the speed
#: is a real number."
#:
#: IT IS THE SAME COMPLICATION TEST THE CAGE HAD TO PASS ("an animation that
#: reports a real state is a complication; one that just moves is a
#: screensaver"), and it passes it TWICE: the needle says what the burn rate
#: IS and the crank says how hard the thing is working, off the one number.
#: Nothing here free-runs — ENG_IDLE_HZ is what a parked engine turns at and
#: every revolution above it was bought with credits.
#:
#: BUILT LIKE THE CAGE, DELIBERATELY: ENG_STEPS frames of the assembly at
#: fixed angles, rendered once and indexed per frame, so a frame costs one
#: cached paste and never a resample or a rotate. The 8 fps thermal cap
#: (IDLE_FPS, and FAILURES 2026-08-04 for what happens when it is overspent)
#: is not a budget this may borrow against.
#:
#: WHY THE SPEEDS ARE LOW, AND IT IS AN ALIASING NUMBER RATHER THAN A TASTE
#: ONE. The aperture repaints at ~24 updates a second (the arithmetic is at
#: TOURB_RECT_FPS: 8 full frames plus 16 rect paints). A rotor with ENG_VANES
#: vanes has a 360/ENG_VANES = 45 degree pattern, so at 24 fps anything past
#: 1.5 rev/s advances more than half a pitch per frame and the wheel starts
#: to read as stopped or as turning backwards — the stroboscope every film
#: of a wheel has. ENG_FULL_HZ is 1.10: 16.5 degrees a frame at the top of
#: the scale, comfortably inside half a pitch, and still 5.5x the idle, which
#: is what "visibly working" has to mean.
#:
#: THE FLAT-PLANE CRANK IS WHY IT READS AS AN ENGINE AND NOT AS A FAN. Two
#: counterweights at 180 degrees (which is what a flat-plane crank IS — the
#: Ferrari V8's own layout) in Rosso, swinging round against the aluminium
#: vanes. A symmetric rotor at speed is a disc; two heavy lobes give the eye
#: something to follow, so the SPEED is legible and not just the motion.
#:
#: WHAT IT COSTS, MEASURED — and the honest comparison is the TOURBILLON,
#: not the gauge as it stood. The old rev counter cached its whole layer and
#: handed it back untouched while the needle held still, so an idle frame
#: cost 0.002 ms: nothing moved, so nothing was composited. A centre that
#: RUNS cannot do that. Per aperture repaint, 400 frames, workstation:
#:   rev + engine (this pass)   0.181 ms median, 0.290 p95
#:   tourbillon (royal-oak)     0.097 ms median, 0.181 p95
#:   rev, before this pass      0.002 ms median  — a still picture
#: So a running centre here costs what the running centre on the other face
#: has always cost, within a factor of two, and the table itself is built
#: ONCE (17 ms at startup, logged with its frame count). §6 applies to every
#: number above: this is the workstation, the SoC is several times slower,
#: and the budget it fits in is the 1.24 ms an end-to-end rect paint was
#: MEASURED at on the puck — RE-TIME IT THERE before believing it.
ENG_ON = REV_ON
ENG_STEPS = 60                      # the angle table, 6 degrees a frame
#: 2026-08-09, THE WHEEL PASS: every radius here is the same 0.717 the gauge
#: took when it moved into the hub (see REV_FACE_R). The clearance sentence
#: below is re-derived rather than scaled, because it is the one that decides
#: whether the crank eats the numerals: they ride at REV_NUM_R=48 and their
#: ink starts at ~42 at 11pt, so ENG_R=37 clears them by 5px.
ENG_R = 37                          # outer radius — the numerals ride at
                                    # REV_NUM_R=48 and their ink starts at
                                    # ~42, so this clears them by 5px
ENG_HUB_R = 14                      # the crank boss, under the needle's own
ENG_VANES = 8
ENG_VANE_R0, ENG_VANE_R1 = 16, 34
ENG_CW_R0, ENG_CW_R1 = 18, 33       # the two counterweights...
ENG_CW_HALF = 21.0                  # ...and their half-width, degrees
ENG_IDLE_HZ = 0.20                  # a parked engine
ENG_FULL_HZ = 1.10                  # ...and one at the top of the scale
#: The redline flash. Owner: "A REDLINE FLASH when the rate crosses the top
#: of the arc, brief and bright, is the moment that sells the theme." On the
#: CROSSING, not while over — a lamp that is permanently on is not a moment,
#: and a rate parked in the redline would otherwise strobe the centre of the
#: dial for as long as it stayed there.
ENG_FLASH_S = 0.55
ENG_FLASH_STEPS = 6
ENG_FLASH_A = 150                   # peak alpha at the bore's lip
_ENG = {"frames": None, "flash": None}


def _eng_frames() -> list:
    """The assembly at ENG_STEPS angles, built ONCE and held.

    No blur and no resample anywhere in here: this is the table the per-frame
    cost is paid out of, and every effect on it is a polygon or an ellipse.
    """
    if _ENG["frames"] is not None:
        return _ENG["frames"]
    t0 = time.time()
    n = 2 * (ENG_R + 2)
    c = n / 2.0
    out = []

    def arc_poly(a0: float, a1: float, r0: float, r1: float) -> list:
        pts = []
        k = max(2, int((a1 - a0) / 4.0))
        for i in range(k + 1):
            t = math.radians(a0 + (a1 - a0) * i / k)
            pts.append((c + r1 * math.cos(t), c + r1 * math.sin(t)))
        for i in range(k + 1):
            t = math.radians(a1 - (a1 - a0) * i / k)
            pts.append((c + r0 * math.cos(t), c + r0 * math.sin(t)))
        return pts

    for s in range(ENG_STEPS):
        a = 360.0 * s / ENG_STEPS
        lay = Image.new("RGBA", (n, n), (0, 0, 0, 0))
        d = ImageDraw.Draw(lay)
        # THE CRANKCASE: a machined pocket set into the gauge floor, lit by
        # the one sky every other recess on this dial is lit by, so the
        # engine sits IN the instrument rather than on top of it.
        d.ellipse([c - ENG_R, c - ENG_R, c + ENG_R, c + ENG_R],
                  fill=_dial_metal(14, 255))
        d.arc([c - ENG_R, c - ENG_R, c + ENG_R, c + ENG_R], 180.0, 360.0,
              fill=_dial_metal(96, 210), width=2)
        d.arc([c - ENG_R, c - ENG_R, c + ENG_R, c + ENG_R], 0.0, 180.0,
              fill=_dial_metal(46, 210), width=2)
        # THE VANES, in the aluminium the theme keeps for contrast. Skewed
        # back from the radius by a fixed angle so the wheel has a direction
        # even in a still — a radial spoke is a wheel that could be turning
        # either way.
        for k in range(ENG_VANES):
            va = a + 360.0 * k / ENG_VANES
            body = arc_poly(va - 2.0, va + 2.0, ENG_VANE_R0, ENG_VANE_R1)
            skew = arc_poly(va + 2.0, va + 11.0, ENG_VANE_R0, ENG_VANE_R1)
            d.polygon(skew, fill=_dial_metal(64, 255))
            d.polygon(body, fill=_dial_metal(178, 255))
            # the lit leading edge: the vane is metal turning in a light
            lt = math.radians(va - 2.0)
            d.line([(c + ENG_VANE_R0 * math.cos(lt),
                     c + ENG_VANE_R0 * math.sin(lt)),
                    (c + ENG_VANE_R1 * math.cos(lt),
                     c + ENG_VANE_R1 * math.sin(lt))],
                   fill=_dial_metal(228, 255), width=1)
        # THE TWO COUNTERWEIGHTS, 180 apart — the flat-plane crank, and the
        # only Rosso in the assembly.
        for lobe in (a, a + 180.0):
            d.polygon(arc_poly(lobe - ENG_CW_HALF, lobe + ENG_CW_HALF,
                               ENG_CW_R0, ENG_CW_R1),
                      fill=TOURB_GOLD + (255,))
            d.polygon(arc_poly(lobe - ENG_CW_HALF, lobe - ENG_CW_HALF + 4.0,
                               ENG_CW_R0, ENG_CW_R1),
                      fill=TOURB_GOLD_LIT + (255,))
            d.polygon(arc_poly(lobe + ENG_CW_HALF - 4.0, lobe + ENG_CW_HALF,
                               ENG_CW_R0, ENG_CW_R1),
                      fill=TOURB_GOLD_DARK + (255,))
        # THE CRANK BOSS. The needle's own hub (REV_HUB_R=15) lands on top of
        # this, so what shows is a 4px collar of turned metal round it.
        d.ellipse([c - ENG_HUB_R, c - ENG_HUB_R, c + ENG_HUB_R,
                   c + ENG_HUB_R], fill=_dial_metal(112, 255),
                  outline=_dial_metal(212, 255), width=2)
        out.append(lay)
    _ENG["frames"] = out
    print(f"engine: {ENG_STEPS}-frame angle table built once in "
          f"{(time.time() - t0) * 1000:.0f} ms "
          f"({n}x{n} each, {ENG_VANES} vanes, flat-plane crank) — "
          f"{ENG_IDLE_HZ:.2f} rev/s idle to {ENG_FULL_HZ:.2f} at full scale",
          flush=True)
    return out


def _eng_flash(level: int):
    """The redline bloom at one of ENG_FLASH_STEPS brightnesses, baked once.

    Rim-weighted: the redline zone is at the OUTSIDE of the scale, so the
    flash is brightest where the needle has just arrived and fades to nothing
    over the crank, which would otherwise be washed out at the moment the
    owner most wants to see it running.
    """
    if _ENG["flash"] is None:
        rr = TOURB_R - 1
        tab = []
        for i in range(ENG_FLASH_STEPS):
            k = (i + 1) / float(ENG_FLASH_STEPS)
            lay = Image.new("RGBA", (2 * (TOURB_R + 8),) * 2, (0, 0, 0, 0))
            dd = ImageDraw.Draw(lay)
            pc = lay.size[0] / 2.0
            for r in range(rr, 0, -1):
                a = int(round(ENG_FLASH_A * k * (r / float(rr)) ** 2))
                if a <= 1:
                    continue
                dd.ellipse([pc - r, pc - r, pc + r, pc + r],
                           fill=REV_REDLINE + (a,))
            tab.append(lay)
        _ENG["flash"] = tab
    return _ENG["flash"][max(0, min(ENG_FLASH_STEPS - 1, level))]


def _eng_hz(frac: float) -> float:
    """Revolutions a second at this point of the scale. Linear, so the log
    line below is checkable by hand against the published rate."""
    return ENG_IDLE_HZ + (ENG_FULL_HZ - ENG_IDLE_HZ) * max(0.0, min(1.0, frac))


#: ── 2026-08-09: THE CENTRE BECOMES A FERRARI STEERING WHEEL ───────────────
#:
#: Owner, pointing at the 488 Spider's dashboard: "perhaps the center looks
#: more like the steering wheel that becomes the volume indicator as you
#: speak?" — flat-topped and flat-bottomed, carbon rim with red stitching, and
#: the tach face living inside its hub. This SUPERSEDES the plain rev-counter
#: centre commissioned at REV_ON and keeps everything else in that brief: the
#: same reading, the same redline, the same eased needle, the same engine
#: turning under it. Only the radii moved (see REV_FACE_R).
#:
#: WHAT MAKES IT OURS RATHER THAN A PICTURE OF A CAR PART, and it is the
#: owner's own answer: the LED SHIFT-LIGHT STRIP across the top of the rim.
#: On an F1-derived wheel that strip runs GREEN -> YELLOW -> RED as the revs
#: climb. Here it is driven by the ROOM: it lights progressively with the live
#: mic level while somebody is speaking, and it doubles as the volume
#: indicator while volume is being set. That is honest — both are real numbers
#: this device already publishes (puck_ears' ROOM_FILE energy, which the ROOM
#: sub-dial reads three inches away; and _VOL's own level) — and it is the
#: same complication test the cage and the gauge had to pass: an animation
#: that reports a real state is a complication, one that just moves is a
#: screensaver.
#:
#: THE STRIP'S RESOLUTION IS THE FEED'S, NOT THE FRAME'S (§6 — measure in the
#: units that will actually apply). puck_ears republishes the array's speech
#: energy every DOA_PERIOD_S = 0.6 s, so a "live" strip repainted at 24 Hz is
#: still stepping at 1.7 Hz underneath. The ballistics are the ROOM needle's
#: own (ROOM_RISE_S / ROOM_FALL_S, fast up and slow down) so the two
#: instruments cannot disagree in public, and the decay is what makes the
#: strip look continuous between publishes rather than the paint rate.
#:
#: THE WHEEL TURNS WITH THE DIRECTION OF ARRIVAL, a few degrees and eased, so
#: the car steers toward whoever is talking. It reads the bearing the wordmark
#: already turns to — see _wheel_bearing for why it READS that eased value
#: instead of calling _doa_angle, which would advance the easing four times
#: per full frame and desynchronise the wheel from the text.
#:
#: WHAT IT COSTS, AND THE 8 FPS THERMAL CAP IS LAW (IDLE_FPS, and FAILURES
#: 2026-08-04 for what happens when it is overspent). Everything is a table,
#: exactly like the tourbillon cage: WHEEL_ROT_STEPS rim sprites built once,
#: and the lit LEDs as small cropped strips built LAZILY per (rotation, count)
#: and capped — the needle's own idiom at REV_CACHE_MAX, and for the same
#: reason: a room that only ever gets loud enough for four LEDs must not pay
#: for eleven. Per aperture repaint that is two more cached pastes and no
#: drawing, no resample and no rotate. MEASURED over 400 repaints with the
#: strip moving, against the same harness the figures above were taken on:
#:   rev + engine + wheel (this pass)  0.266 ms median, 0.299 p95
#:   rev + engine (previous pass)      0.181 ms median, 0.290 p95
#:   tourbillon (royal-oak)            0.097 ms median, 0.181 p95
#: The rim table costs 20 ms once at startup and eight lit-strip sprites of
#: the forty-slot cache covered a full speak-and-decay cycle. RE-TIME IT ON
#: THE PUCK before believing any figure quoted off the workstation (§6): that
#: box is several times slower and the budget is 71.4 ms of which 64.5 was
#: already spent.
#:
#: VERIFIED ON THE LIVE RENDER (/tmp/ferrari_render.py, which replays main()'s
#: compose order over the shipped profile bake), the four things the brief
#: asked to be checked rather than asserted:
#:   YELLOW  1.75% of the dial, redness/yellowness weighted the same way the
#:           red figure is — 1.63 of it inside the aperture, the rest the
#:           amber that was already on the dial. Single digit, and rare.
#:   RED     13.97%, still inside the 10-14 the livery pass asked for
#:           (WGLASS_WASH_A). The gauge shrinking by 0.717 is what bought the
#:           headroom for the redline to stay as loud as it is.
#:   STRIP   driven by the published mic level, logged together: energy 40k ->
#:           38% of scale -> 4 lamps; 220k -> 69% -> 7; 600k -> 87% -> 9;
#:           1.19M -> 100% -> 10, then the ROOM needle's own decay back down.
#:   IDENTITY the other three faces open the same hole and put a gold cage in
#:           it. This one is a yellow-faced tachometer inside a flat-topped
#:           wheel. Nobody is going to confuse the two across a room.
WHEEL_ON = REV_ON
WHEEL_R = 119                       # the rim's outer edge. TOURB_R=130 less
                                    # POCKET_WALL_W=7 of bore wall is 121 of
                                    # usable radius; 119 leaves the chamfer
                                    # from _tourb_static its own 2px.
WHEEL_FLAT = 101                    # |y| of the flat top and flat bottom
WHEEL_RIM_W = 13                    # ...so the inner flats land at 88, and
                                    # the largest face that clears them is 86
WHEEL_ROT_DEG = 6.0                 # full deflection. "Subtle, a few degrees"
WHEEL_ROT_STEPS = 7                 # odd, so dead ahead IS a step
WHEEL_CACHE_MAX = 40                # lit-strip sprites held; see above
WHEEL_STITCH_R = WHEEL_R - WHEEL_RIM_W + 4      # the seam, along the grips
WHEEL_GRIP_HALF = 40.0              # how much of each side is grip, degrees
WHEEL_BADGE_Y = 100                 # the shield, on the bottom of the rim
WHEEL_BADGE_W, WHEEL_BADGE_H = 13, 12           # half-sizes
#: The rim's carbon and its two arrises, through the theme's own ramp so the
#: wheel is the same material as the dial it is cut into.
#: 56, NOT THE 20 THE FIRST CUT USED, and it is a separation measurement
#: rather than a taste one (§6: an absolute number is meaningless without the
#: floor it competes against). L=20 renders at (28,26,26) through this ramp,
#: against a bore floor that reaches (33,33,36) at its lip — the rim came out
#: DARKER than the hole it sits in and the wheel simply was not visible on the
#: render; only the stitching showed where it was. L=56 lands at (69,67,67),
#: which is twice the floor and still unmistakably carbon.
WHEEL_CARBON = 56                   # source L of the rim body
WHEEL_EDGE_LIT = 128                # the outer arris, turned into POCKET_KEY
WHEEL_EDGE_DARK = 6                 # the inner one, turned away from it
#: ── THE SHIFT-LIGHT STRIP ─────────────────────────────────────────────────
#: Ten lamps across the top flat. The colour ladder is the real one — green
#: while there is room to rev, yellow as it runs out, red at the top — and the
#: yellow is the theme's own Giallo, which is the ONE other place the third
#: colour appears (REV_FACE is the other; the shield badge is the third and
#: last).
SHIFT_LEDS = 10
SHIFT_GREEN, SHIFT_YELLOW = 4, 3    # ...and the remaining three are red
SHIFT_GREEN_COL = (46, 214, 96)
SHIFT_SPAN = 52                     # the row runs x -52..+52 on the flat...
SHIFT_W, SHIFT_H = 4, 3             # ...and each lamp is this half-size
#: The crop the lit strip is baked into: wide enough for the row plus its
#: halo at full deflection (a lamp at x=52,y=-94.5 swings to x=62 at 6 deg),
#: and nothing more — this sprite exists once per (rotation, count) pair.
SHIFT_CROP_W, SHIFT_CROP_TOP, SHIFT_CROP_H = 72, 110, 32
SHIFT_LOG_S = 0.3                   # ...and the evidence line's rate limit
_WHEEL: dict = {"frames": None, "lit": {}, "said": 0.0}


def _wrot(x: float, y: float, ct: float, st: float):
    """One point of the wheel, turned toward the talker. y-down frame, so a
    positive angle is CLOCKWISE — the same sense draw_wordmark turns in."""
    return (x * ct - y * st, x * st + y * ct)


def _wheel_step_deg(step: int) -> float:
    """Rotation of one step of the table, degrees."""
    if WHEEL_ROT_STEPS <= 1:
        return 0.0
    return (-WHEEL_ROT_DEG
            + 2.0 * WHEEL_ROT_DEG * step / (WHEEL_ROT_STEPS - 1))


def _wheel_bearing() -> float:
    """The eased bearing draw_wordmark already maintains — READ here, never
    advanced. _doa_angle() integrates its own easing on every call, and the
    aperture repaints ~24 times a second against the wordmark's 8, so calling
    it from here would ease three times as fast and the wheel would arrive
    somewhere the text is still travelling toward. Zero when this unit has no
    measured bearing calibration, which is the same gate the wordmark uses."""
    return _DOA["now"] if _DOA_CAL.get("on") else 0.0


def _wheel_step(now: float) -> int:
    """Which rotation step the room's bearing lands on. The sine keeps the
    deflection bounded and wrapping-safe without a special case at 180: a
    talker dead ahead or dead behind gives zero, one at either side gives the
    full WHEEL_ROT_DEG, and everything between eases in."""
    if WHEEL_ROT_STEPS <= 1:
        return 0
    deg = WHEEL_ROT_DEG * math.sin(math.radians(_wheel_bearing()))
    k = (deg + WHEEL_ROT_DEG) / (2.0 * WHEEL_ROT_DEG)
    return max(0, min(WHEEL_ROT_STEPS - 1,
                      int(round(k * (WHEEL_ROT_STEPS - 1)))))


def _wheel_d_poly(r: float, flat: float, ct: float, st: float) -> list:
    """The flat-topped, flat-bottomed silhouette, as a closed polygon.

    CLAMPING y IS THE CHORD, not an approximation of one: where the circle
    would go past the flat, y holds at the flat while x goes on as r*cos(a),
    which traces exactly the straight line between the two points where the
    circle meets it. So one expression gives the D and there is no seam to
    get wrong at the join."""
    pts = []
    for a in range(360):
        t = math.radians(a)
        pts.append(_wrot(r * math.cos(t),
                         max(-flat, min(flat, r * math.sin(t))), ct, st))
    return pts


def _shift_xy(i: int):
    """Lamp i's centre in the wheel's own frame, before rotation."""
    x = -SHIFT_SPAN + 2.0 * SHIFT_SPAN * i / (SHIFT_LEDS - 1)
    return x, -(WHEEL_FLAT - WHEEL_RIM_W / 2.0)


def _shift_col(i: int) -> tuple:
    if i < SHIFT_GREEN:
        return SHIFT_GREEN_COL
    if i < SHIFT_GREEN + SHIFT_YELLOW:
        return REV_FACE                     # Giallo, the third colour
    return REV_REDLINE


def _wheel_frames() -> list:
    """The rim at WHEEL_ROT_STEPS bearings, built ONCE and held.

    No blur and no resample: the D-ring is a polygon mask minus a polygon
    mask, and every mark on it is a line, an arc or an ellipse. The unlit
    lamps are baked in here — only the lit ones are a per-frame paste.
    """
    if _WHEEL["frames"] is not None:
        return _WHEEL["frames"]
    t0 = time.time()
    n = 2 * (WHEEL_R + 4)
    c = n / 2.0
    f_badge = face("label-b", 18)
    out = []
    for s in range(WHEEL_ROT_STEPS):
        a = _wheel_step_deg(s)
        ct, st = math.cos(math.radians(a)), math.sin(math.radians(a))
        outer = [(c + x, c + y)
                 for x, y in _wheel_d_poly(WHEEL_R, WHEEL_FLAT, ct, st)]
        inner = [(c + x, c + y)
                 for x, y in _wheel_d_poly(WHEEL_R - WHEEL_RIM_W,
                                           WHEEL_FLAT - WHEEL_RIM_W, ct, st)]
        mo = Image.new("L", (n, n), 0)
        ImageDraw.Draw(mo).polygon(outer, fill=255)
        mi = Image.new("L", (n, n), 0)
        ImageDraw.Draw(mi).polygon(inner, fill=255)
        lay = Image.new("RGBA", (n, n), _dial_metal(WHEEL_CARBON, 255))
        lay.putalpha(ImageChops.subtract(mo, mi))
        d = ImageDraw.Draw(lay)
        # THE TWO ARRISES: the outer edge is turned up into POCKET_KEY and the
        # inner one away from it, which is the relief pair every raised thing
        # on this dial wears. Drawn as the silhouettes themselves so the rim
        # keeps its measured width.
        d.line(outer + outer[:1], fill=_dial_metal(WHEEL_EDGE_LIT, 255),
               width=2)
        d.line(inner + inner[:1], fill=_dial_metal(WHEEL_EDGE_DARK, 255),
               width=2)
        # THE RED STITCHING along the seam of each grip. On a circle about the
        # wheel's own centre, so the rotation is a shift of its angles and
        # nothing else — PIL's arc is the exact shape either way.
        box = [c - WHEEL_STITCH_R, c - WHEEL_STITCH_R,
               c + WHEEL_STITCH_R, c + WHEEL_STITCH_R]
        dth = math.degrees(5.0 / WHEEL_STITCH_R)        # ~5px of thread
        for grip in (0.0, 180.0):
            k = 0
            while k * dth < WHEEL_GRIP_HALF:
                for sgn in (1.0, -1.0):
                    a0 = grip + a + sgn * k * dth
                    d.arc(box, a0 - dth * 0.34, a0 + dth * 0.34,
                          fill=TOURB_GOLD + (255,), width=2)
                k += 1
        # THE LAMP WELLS, dark and baked in: an unlit shift light is a hole in
        # the rim, not an absence. §1 in its smallest possible form — the
        # strip is visibly a strip even when the room is silent.
        for i in range(SHIFT_LEDS):
            wx, wy = _wrot(*_shift_xy(i), ct=ct, st=st)
            d.ellipse([c + wx - SHIFT_W - 1, c + wy - SHIFT_H - 1,
                       c + wx + SHIFT_W + 1, c + wy + SHIFT_H + 1],
                      fill=_dial_metal(4, 255),
                      outline=_dial_metal(56, 255), width=1)
        # THE SHIELD, on the bottom of the rim where a wheel carries its
        # maker's badge. Owner: "a yellow shield-shaped mark can carry the
        # AURA monogram IF IT CAN BE DONE TASTEFULLY" — so it is the initial
        # and not the word: a 26px badge cannot hold four letters at any size
        # a person could read, and four illegible ones is the untasteful
        # outcome the condition is guarding against. Flat top tapering to a
        # point, which is the shield shape the reference actually uses.
        bx, by = _wrot(0.0, float(WHEEL_BADGE_Y), ct, st)
        w2, h2 = float(WHEEL_BADGE_W), float(WHEEL_BADGE_H)
        d.polygon([(c + bx - w2, c + by - h2), (c + bx + w2, c + by - h2),
                   (c + bx + w2, c + by + h2 * 0.15), (c + bx, c + by + h2),
                   (c + bx - w2, c + by + h2 * 0.15)],
                  fill=REV_FACE + (255,), outline=_dial_metal(2, 255))
        # The letter stays UPRIGHT through the deflection: six degrees is not
        # enough tilt to read as styling and a rotate here would cost a
        # resample per step for it.
        bb = d.textbbox((0, 0), "A", font=f_badge)
        d.text((c + bx - (bb[2] - bb[0]) / 2.0 - bb[0],
                c + by - (bb[3] - bb[1]) / 2.0 - bb[1] - 1),
               "A", font=f_badge, fill=REV_INK + (255,))
        out.append(lay)
    _WHEEL["frames"] = out
    print(f"wheel: {WHEEL_ROT_STEPS}-step rim table built once in "
          f"{(time.time() - t0) * 1000:.0f} ms ({n}x{n} each, flat top and "
          f"bottom, +/-{WHEEL_ROT_DEG:.0f} deg of steer, {SHIFT_LEDS} shift "
          f"lamps)", flush=True)
    return out


def _shift_lit(step: int, lit: int):
    """The lit lamps at one (rotation, count), cropped to the strip's own box.

    Cached LAZILY and CAPPED, the needle's idiom at REV_CACHE_MAX: the pair
    space is WHEEL_ROT_STEPS x (SHIFT_LEDS + 1) and a given room visits a
    small corner of it.
    """
    key = (step, lit)
    lay = _WHEEL["lit"].get(key)
    if lay is not None:
        return lay
    if len(_WHEEL["lit"]) >= WHEEL_CACHE_MAX:
        _WHEEL["lit"].clear()
    lay = Image.new("RGBA", (2 * SHIFT_CROP_W, SHIFT_CROP_H), (0, 0, 0, 0))
    d = ImageDraw.Draw(lay)
    a = _wheel_step_deg(step)
    ct, st = math.cos(math.radians(a)), math.sin(math.radians(a))
    for i in range(lit):
        lx, ly = _wrot(*_shift_xy(i), ct=ct, st=st)
        cx, cy = lx + SHIFT_CROP_W, ly + SHIFT_CROP_TOP
        col = _shift_col(i)
        d.ellipse([cx - SHIFT_W - 2, cy - SHIFT_H - 2,
                   cx + SHIFT_W + 2, cy + SHIFT_H + 2], fill=col + (64,))
        d.ellipse([cx - SHIFT_W, cy - SHIFT_H, cx + SHIFT_W, cy + SHIFT_H],
                  fill=col + (255,))
    _WHEEL["lit"][key] = lay
    return lay


def _shift_level(now: float):
    """(0..1, source) for the strip, or (None, source) for 'I cannot tell'.

    §2: a silent room and a dead microphone both produce zero, so the two must
    not arrive here as the same float — _room_frac already refuses to collapse
    them and this passes the refusal straight through.

    VOLUME WINS WHILE IT IS BEING SET, and that is not a conflict: the volume
    overlay owns the whole glass while it is up (it dims the dial to 0.42 and
    draws over it), so during those seconds the strip is the only thing in the
    aperture anyone is looking at, and it is showing the number the finger is
    moving. The moment DONE is pressed it is a mic meter again.
    """
    if _VOL["open"]:
        return max(0.0, min(1.0, _VOL["level"] / 100.0)), "volume"
    d0 = _room_now(now)
    return _room_frac(d0.get("energy") if d0 else None), "mic"


def _shift_state(now: float, dt: float, over: bool) -> int:
    """How many lamps are lit, and the evidence line that proves why.

    THE LOG IS THE VERIFICATION THE BRIEF ASKED FOR — level and lit count on
    ONE line, so the claim that the strip is driven by the published mic level
    is checkable from the log alone rather than from the eye that wants it to
    be true (§4: do not grade your own tests). Rate-limited, because the decay
    ramp would otherwise print a line per lamp per utterance forever.
    """
    raw, src = _shift_level(now)
    if raw is None:
        _REV["lvl"] = 0.0
        if not _REV["deaf"]:
            _REV["deaf"] = True
            print("shift: no room feed — the strip is dark (the ROOM dial "
                  "says NO EARS beside it)", flush=True)
    else:
        if _REV["deaf"]:
            _REV["deaf"] = False
            print("shift: room feed is live again", flush=True)
        if src == "volume":
            _REV["lvl"] = raw               # a finger's number does not decay
        elif dt > 0.0:
            tau = ROOM_RISE_S if raw > _REV["lvl"] else ROOM_FALL_S
            _REV["lvl"] += (raw - _REV["lvl"]) * (1.0 - math.exp(-dt / tau))
    lit = int(round(_REV["lvl"] * SHIFT_LEDS))
    if over:
        # The burn is in the redline. The strip's top lamps are the red ones,
        # so lighting the whole row IS the warning, and it is the same event
        # the flash fires on rather than a second opinion about the room.
        lit = SHIFT_LEDS
    if ((lit, src) != (_REV["lit"], _REV["src"])
            and now - _WHEEL["said"] >= SHIFT_LOG_S):
        _WHEEL["said"] = now
        _REV["lit"], _REV["src"] = lit, src
        print(f"shift: {src} level {_REV['lvl'] * 100:.0f}% of scale "
              f"(raw {0.0 if raw is None else raw * 100:.0f}%) -> "
              f"{lit}/{SHIFT_LEDS} lamps lit"
              + ("  [redline]" if over else ""), flush=True)
    return lit


def _rev_layer(now: float) -> "Image.Image":
    """The rev counter at this instant, as one sprite the size of the
    aperture — _tourb_layer's contract exactly, so everything downstream
    (the damage rect, the paste, the `plain` gate) is untouched.

    SIX PASTES, NO DRAWING (four until the wheel pass, 2026-08-09). Ground
    (baked once), engine (one frame of the table), needle (its own angle,
    cached), wheel rim (one step of its table), lit lamps (one small cropped
    strip), lip. The order is the order light puts them in and it is the
    reason the engine cannot be folded into the needle's cache: the crank
    turns UNDER the pointer that reads it, and both sit inside the hub the
    wheel is a rim around.
    """
    target, rate = _rev_frac(now)
    # dt is CLAMPED: a frame the compose stalled on must not spin the crank
    # half a turn, and the first frame of the process has no previous one.
    dt = 0.0 if _REV["t"] is None else max(0.0, min(0.5, now - _REV["t"]))
    _REV["t"] = now
    # THE POINTER EASES, THE READING DOES NOT (see REV_EASE_TAU).
    if dt > 0.0:
        _REV["disp"] += (target - _REV["disp"]) * (
            1.0 - math.exp(-dt / REV_EASE_TAU))
    frac = _REV["disp"]
    step = int(round(frac * REV_STEPS))
    # THE CRANK'S SPEED IS THE READING, not the eased pointer: the engine
    # answers the burn rate the moment it lands, and the needle catches up.
    hz = _eng_hz(target)
    _REV["phase"] = (_REV["phase"] + hz * dt) % 1.0
    # THE REDLINE FLASH FIRES ON THE CROSSING (see ENG_FLASH_S).
    over = target >= REV_RED_AT
    if over and not _REV["over"]:
        _REV["flash"] = now
        print(f"rev: REDLINE — {rate:.0f} credits/min crossed "
              f"{REV_RED_AT * TOURB_BURN_FULL:.0f}, flash fired", flush=True)
    _REV["over"] = over
    # THE GAUGE SAYS WHAT IT IS READING AND WHAT IT CHOSE TO DO ABOUT IT —
    # the rate and the speed on ONE line, so the claim that the animation is
    # tied to the published burn rate is checkable from the log alone
    # (§4: do not grade your own tests).
    #
    # KEYED ON THE READING, NOT ON THE POINTER, and that supersedes the old
    # line's "a needle that walks prints a line per 1.9 degrees": with the
    # easing above the needle now walks on EVERY rate change, so keying the
    # log on its step would print forty lines per bake — two a second, on a
    # log that is appended to forever. One line per reading is the event
    # anyone is actually looking for, and it states where the needle is going
    # rather than where it has got to.
    tstep = int(round(target * REV_STEPS))
    hzq = round(hz, 2)
    if (_REV["key"] != tstep or _REV["hzq"] != hzq) and rate is not None:
        print(f"rev: {rate:.0f} credits/min of {TOURB_BURN_FULL:.0f} "
              f"= {target * 100:.0f}% -> needle sweeps to "
              f"{_rev_ang(target):.1f} deg, engine {hzq:.2f} rev/s"
              + ("  [REDLINE]" if over else ""), flush=True)
    _REV["key"], _REV["hzq"] = tstep, hzq
    lay = _rev_ground().copy()
    if ENG_ON:
        eng = _eng_frames()[int(_REV["phase"] * ENG_STEPS) % ENG_STEPS]
        off = (lay.size[0] - eng.size[0]) // 2
        lay.alpha_composite(eng, (off, off))
    nee = _rev_needle(step)
    off = (lay.size[0] - nee.size[0]) // 2
    lay.alpha_composite(nee, (off, off))
    # THE WHEEL AROUND THE HUB, and its shift lights. Above the gauge because
    # the rim stands proud of the face the tach is printed on, and clear of it
    # either way: the rim's inner edge is at 106 and the needle's tip at 68.
    if WHEEL_ON:
        wstep = _wheel_step(now)
        whl = _wheel_frames()[wstep]
        off = (lay.size[0] - whl.size[0]) // 2
        lay.alpha_composite(whl, (off, off))
        n_lit = _shift_state(now, dt, over)
        if n_lit > 0:
            lay.alpha_composite(_shift_lit(wstep, n_lit),
                                (lay.size[0] // 2 - SHIFT_CROP_W,
                                 lay.size[1] // 2 - SHIFT_CROP_TOP))
    # The lip of the hole goes on top, as it does over the cage: the dial
    # is cut through ABOVE the instrument.
    lay.alpha_composite(_tourb_static())
    fu = (now - _REV["flash"]) / ENG_FLASH_S
    if 0.0 <= fu < 1.0:
        lay.alpha_composite(_eng_flash(
            int(round((1.0 - fu) ** 2 * (ENG_FLASH_STEPS - 1)))))
    _REV["lay"] = lay
    return lay


#: ── THE CHAPTER RING: TWELVE ROMAN NUMERALS, 2026-08-07 ───────────────────
#:
#: Owner, by voice, naming the reference: "let's have some interesting numerals
#: around the circumference of the circle", pointing at the Patek Philippe
#: Grand Complications Celestial, ref 6102P — the platinum one with the night
#: sky on the dial. That reference is chosen well and it is worth saying why:
#: its dial IS a star chart, and this one already carries a starfield
#: (dial_sky) and a moonphase (MOON_XY). We are closer to that watch than to
#: anything else this face has quoted, and the numerals are the third thing it
#: has that we did not.
#:
#: "Roman numerals, not Arabic ... on a celestial dial the Roman forms are what
#: a grand complication wears", and "small and confident, not large and shouty:
#: the circumference is a big circle and twelve small marks around it reads as
#: expensive, whereas twelve big ones read as a clock radio."
#:
#: UPRIGHT, NOT ROTATED TO THE RADIUS — the owner's instruction and Patek's own
#: practice: "rotated numerals are upside down at the bottom of the dial". They
#: are drawn before the dial rotate, like everything else that belongs to the
#: dial, so a spun face carries them round together; upright is the rest
#: position, not a per-frame correction.
#:
#: THE RADIUS IS A MEASUREMENT, NOT A TASTE. Taken off today's base.png by
#: radial profile rather than derived: every baked wedge fill runs 317..397
#: display px on all five sectors, and the annulus from there out to the steel
#: ring's inner edge — 516 px, bake_bezel.py's R_VERT less RING, since the
#: octagon was retired for the circle — is empty ground, peak luminance 82
#: against this gold's 176. NUM_R = 468 puts the widest numeral's furthest
#: corner at 502 (14 px inboard of the steel) and its nearest edge at 434
#: (37 px clear of the wedges), which is what "just inboard of the steel ring"
#: has room to mean.
#:
#: THE GOLD IS THE ACCENT ALREADY AGREED, TOURB_GOLD — the owner's spoken
#: 212,175,92 — and the numerals are APPLIED, not printed, by the same
#: three-tone trick the tourbillon's arms use: a bright specular down the
#: light side, a shaded flank down the other, the body between them. Light on
#: this face comes from above (the baked bezel runs 192 at the top flat to 53
#: at the bottom), so the specular goes up-left and the shadow down-right.
NUM_R = 468.0                       # centre of each numeral, display px
NUM_PT = 38                         # Nimbus Sans; cap height 28 px, measured
NUM_TRACK = 2.0                     # I, V and X set solid read as one glyph
NUM_SPEC = 1.5                      # specular / shadow offset, px
NUM_PAD = 8.0                       # clearance a numeral demands of a wedge
ROMAN = ("XII", "I", "II", "III", "IV", "V",
         "VI", "VII", "VIII", "IX", "X", "XI")
#: WHERE A TILE IS, THERE IS NO NUMERAL. Owner: "BRIEFING, STERLING, LOCK,
#: VOLUME and SETTINGS already occupy an arc of that circumference, so where a
#: numeral would land under a tile, let the tile win and drop that numeral
#: rather than drawing both. A missing numeral behind a tile is invisible; a
#: numeral colliding with one is the first thing the eye finds."
#:
#: SO THE TEST IS GEOMETRIC, NOT A HAND-WRITTEN LIST OF HOURS, and that is the
#: standing DIAL_K contract again: that band has moved twice this week (336 ->
#: 368 viewBox, then the whole dial by 0.80), and a list of dropped hours would
#: go on being confidently right about a ring that had moved. Overlap is tested
#: ANGULARLY AND RADIALLY, against WEDGE_R0/WEDGE_R1 — the same two constants
#: the tap hit-test uses, so the paint and the target cannot disagree.
#:
#: On today's geometry the two bands do not meet (434 against 397 + pad), so
#: all twelve are drawn; if the ring ever grows outward the numerals under it
#: drop on their own. WHAT WAS DROPPED, OR THAT NOTHING WAS, IS PRINTED ONCE
#: (§1): a chapter ring that quietly came out with five numerals on it is
#: indistinguishable from one that failed to draw.
_NUMERALS = None


def _ang_hit(a: float, half: float, a0: float, a1: float) -> bool:
    """Does [a-half, a+half] meet [a0, a1]? Degrees, wrapping at 360."""
    mid = (a0 + a1) / 2.0
    gap = abs((a - mid + 180.0) % 360.0 - 180.0)
    return gap <= half + (a1 - a0) / 2.0


def _numerals():
    """The twelve numerals as small sprites with their paste boxes, built once.

    Static ink on a dial that turns as a whole: nothing in here changes from
    frame to frame, so nothing in here is computed from frame to frame. Twelve
    boxes of about 70x40 cost a fraction of what one more full-frame paste
    would on a puck already at 64.5 ms of a 71.4 ms budget.
    """
    global _NUMERALS
    if _NUMERALS is not None:
        return _NUMERALS
    font = face("text", NUM_PT)
    probe = ImageDraw.Draw(Image.new("RGB", (1, 1)))
    out, dropped = [], []
    for h, text in enumerate(ROMAN):
        deg = h * 30.0 - 90.0               # XII at twelve, y-down like WEDGES
        a = math.radians(deg)
        bb = probe.textbbox((0, 0), text, font=font)
        w = (sum(probe.textlength(ch, font=font) for ch in text)
             + NUM_TRACK * (len(text) - 1))
        ht = bb[3] - bb[1]
        cx, cy = SIZE / 2 + NUM_R * math.cos(a), SIZE / 2 + NUM_R * math.sin(a)
        # The ink box, in radius and in bearing, from the dial's centre. Both
        # bounds are the conservative ones: furthest corner out, nearest
        # possible point in, and the half-angle the box's own diagonal
        # subtends — a numeral that is merely CLOSE to a tile should drop too.
        diag = math.hypot(w / 2.0, ht / 2.0)
        r_far = math.hypot(abs(NUM_R * math.cos(a)) + w / 2.0,
                           abs(NUM_R * math.sin(a)) + ht / 2.0)
        r_near = NUM_R - diag
        half = math.degrees(math.atan2(diag, max(1.0, r_near)))
        under = next((k for k, (a0, a1, _c) in zip(WEDGE_KEYS, WEDGES)
                      if _ang_hit(deg, half, a0, a1)
                      and r_far + NUM_PAD >= WEDGE_R0
                      and r_near - NUM_PAD <= WEDGE_R1), None)
        if under is not None:
            dropped.append(f"{text}/{under}")
            continue
        p = int(math.ceil(NUM_SPEC)) + 3
        spr = Image.new("RGBA", (int(math.ceil(w)) + 2 * p, ht + 2 * p),
                        (0, 0, 0, 0))
        d = ImageDraw.Draw(spr)
        sx, sy = spr.size[0] / 2.0, p - bb[1]
        # Shaded flank first, specular over it, body on top: the two fringes
        # survive only where the body does not cover them, which is what makes
        # the mark read as a piece of metal laid on the dial rather than
        # printed on it.
        draw_tracked(d, sx + NUM_SPEC, sy + NUM_SPEC, text, font,
                     TOURB_GOLD_DARK + (255,), track=NUM_TRACK)
        draw_tracked(d, sx - NUM_SPEC, sy - NUM_SPEC, text, font,
                     TOURB_GOLD_LIT + (255,), track=NUM_TRACK)
        draw_tracked(d, sx, sy, text, font, TOURB_GOLD + (255,),
                     track=NUM_TRACK)
        out.append((spr, (int(round(cx - spr.size[0] / 2.0)),
                          int(round(cy - spr.size[1] / 2.0)))))
    print(f"numerals: {len(out)} drawn at r={NUM_R:.0f}"
          + (f", dropped under a wedge: {', '.join(dropped)}" if dropped
             else ", none under a wedge"), flush=True)
    _NUMERALS = out
    return _NUMERALS


def draw_numerals(frame: "Image.Image") -> None:
    """The chapter ring. In place, AFTER the colourway and BEFORE the rotate.

    After the colourway because the gold is a COLOUR THAT MEANS SOMETHING —
    the same exemption the tourbillon cage and the moonphase take, and for the
    same reason: desertify() opens with convert("L") and would hand this ring
    back in the dial's own blue. Before the rotate because these are marks ON
    the dial and a spun face has to carry them with it.

    Wrapped whole: new paint in a compositor that must never stop.
    """
    try:
        for spr, box in _numerals():
            frame.paste(spr, box, spr)
    except Exception as e:                      # noqa: BLE001
        _bez_say(f"numerals:{e!r}", f"numerals: draw failed {e!r} — "
                                    f"the chapter ring is bare")


def render_countdown(backdrop: Image.Image, remaining: int,
                     beat: float) -> Image.Image:
    """Backdrop + MM:SS in big glowing digits + a heartbeat ring."""
    frame = backdrop.copy()
    d = ImageDraw.Draw(frame)
    # heartbeat ring under the digits: radius/alpha follow a 1 Hz pulse
    k = math.exp(-3.0 * beat)                    # sharp attack, soft decay
    r = 210 + 26 * (1 - k)
    v = int(70 * k) + 12
    d.ellipse([540 - r, 570 - r, 540 + r, 570 + r],
              outline=(int(v * 0.3), int(v * 0.85), v), width=4)
    mm, ss = divmod(max(0, remaining), 60)
    text = f"{mm:02d}:{ss:02d}"
    font = face("text", 220)
    tw = d.textlength(text, font=font)
    pos = ((SIZE - tw) / 2, 452)
    layer = Image.new("RGB", (SIZE, SIZE), 0)
    ld = ImageDraw.Draw(layer)
    ld.text(pos, text, font=font, fill=(120, 205, 255))
    glow = layer.filter(ImageFilter.GaussianBlur(14))
    frame = ImageChops.screen(frame, glow)
    d = ImageDraw.Draw(frame)
    d.text(pos, text, font=font, fill=(238, 246, 255))
    return frame


#: `find_touch` used to live here and raise SystemExit. It is now next to
#: `blit`, with the retry state and the notice it paints — see the block
#: above the Framebuffer section.


# ---------------------------------------------------------------------------
# Ambient
# ---------------------------------------------------------------------------

def make_sweep() -> Image.Image:
    """A faint comet-tail arc, screen-blended and rotated over briefing
    scenes so they read as alive rather than as a slideshow (owner:
    "make it sexier, like animated graphics"). Deliberately dim — it
    decorates the data, it must never compete with it."""
    im = Image.new("RGB", (SIZE, SIZE), 0)
    d = ImageDraw.Draw(im)
    for i in range(26):
        v = 30 - i
        col = (int(v * 0.25), int(v * 0.8), v)
        d.pieslice([60, 60, SIZE - 60, SIZE - 60],
                   start=i * 3, end=i * 3 + 3.4, fill=col)
    return im


SWEEP_DPS = 24.0


def bolt_gain(t: float) -> float:
    """0.6..1.0 slow breath, with a rare bright spike — alive, not epileptic.

    HALVED 2026-08-04. The resting bolt was the brightest thing on the face
    at all times, which spends the one gesture the design has for emphasis
    on doing nothing. The owner: "lower the lumens on the main lightning
    thing at the start, it's really bright, just use it for emphasis as we
    discussed when people are doing consequential actions".

    So the BREATH comes down and the SURGE does not: the tap-ack flare
    (BOLT_SURGE_GAIN) multiplies whatever this returns, so a quieter resting
    state makes the acknowledgement land harder, not softer. Emphasis is a
    ratio, and it was being paid for out of the baseline.
    """
    g = 0.40 + 0.06 * math.sin(t * 0.9) + 0.04 * math.sin(t * 2.23 + 1.3)
    if math.sin(t * 0.41 + 2.0) > 0.995:
        g = 0.62                      # the rare spike, still a spike
    return max(0.28, min(0.62, g))


#: Tap-ack surge (round 2, owner: the bolt "grows really really bright, i
#: think that would be cool"). handle_tap stamps the time on ANY wedge
#: tap; the compose path adds a hard flare that decays over ~0.6s on top
#: of the ordinary breath/flicker. It is the instant "yes, I felt that"
#: that buys the mode's spool time (PRINCIPLES §10) — from a layer
#: already in memory, so it costs nothing at the moment it matters.
_BOLT_SURGE = [0.0]
BOLT_SURGE_S = 0.6
#: 2.8 -> 4.2. The surge now has 0.42s of clear screen to happen on
#: (WEDGE_OPEN_DELAY_S), where before the overlay covered it within a frame.
#: It can afford to be dramatic — it is the single most-liked thing on the
#: device ("that is just magically gratifying to the human view") and it
#: multiplies a resting gain that was halved earlier today, so the RATIO is
#: what grew, not the baseline.
BOLT_SURGE_GAIN = 4.2


#: THE HOME FACE IS DESERT BEIGE (owner, by voice, 2026-08-05: "a little bit
#: more beige, you know, almost like a desert kind of theme"). It was bright
#: green before that, and red before that — same duotone, same reasoning, only
#: the three anchor colours moved; the green and red values are in git history
#: if either is ever asked for back. Applied as a
#: duotone over the finished ambient
#: composite rather than by re-colouring a dozen constants, because most of
#: the home face's blue arrives as PIXELS — base/rings/bolt are stills the
#: RTX renders from home.html — and a constant edit here would leave those
#: stubbornly blue while the live-drawn parts turned red.
#:
#: LUMINANCE IS PRESERVED, which is the whole reason this is a colorize on
#: L rather than a channel swap or a multiply by the hue. The AURAVISION
#: comment records why the wordmark is cyan-leaning: the owner reads this
#: panel "45% askew" and hue alone does not survive that angle — lightness
#: contrast does. Mapping black -> black, mid -> sand, white -> warm white
#: keeps every element at the L it was designed with, so AURA still reads
#: near-white against a sand VISION and nothing goes muddy off-axis. A
#: multiply by beige would have dropped the blues to near-black, which is the
#: same screen with the content missing.
#:
#: The sand mid is held at roughly the luminance the green mid had (L≈158 vs
#: 146), so the face keeps the brightness it was tuned to and only the hue
#: moves. Beige is a DESATURATED colour by nature, so the mid is kept warm but
#: unsaturated rather than pushed to orange — a saturated tan reads as amber
#: warning light on this panel, not as desert.
#:
#: 2026-08-05, later, by voice: "make it more feel like 1970s hi-fi — warm
#: amber, chunky". That CONTRADICTS the paragraph above, deliberately: the
#: saturated warm mid it warned against is now the brief. The warning stands
#: as written and was correct for "desert"; a 1970s receiver dial is exactly
#: an amber indicator lamp, so the thing that was a failure mode there is the
#: target here. Only the mid moved far — black stays a warm near-black and
#: white stays a warm cream, so LUMINANCE IS STILL PRESERVED (mid L=145,
#: measured, between the sand's 158 and the green's 146) and the 45%-
#: askew reading argument above is untouched.
#: 2026-08-06, by voice with the translation: "change my entire home screen
#: into Dutch and make the color scheme appropriately". So the colourway is
#: ORANJE — the one colour a Dutch room reads as its own — over a near-black
#: carrying the flag's blue, with the flag's white at the top end. Same three
#: anchors, same duotone, same reason it lives here rather than in a dozen
#: constants: most of this face arrives as PIXELS from home.html, and only
#: the pass that touches every pixel can recolour those too.
#:
#: LUMINANCE IS STILL PRESERVED, which is the whole argument the paragraphs
#: above make and the reason the owner's 45%-askew reading survives a hue
#: change. Measured on the Rec.601 weights this duotone maps on:
#:
#:     mid    amber (214,132,30) L=144.9  ->  oranje (255,121,0)  L=147.3
#:     white  cream (255,238,198) L=238.5 ->  flag   (236,240,248) L=239.8
#:     black  warm  (10,4,0)      L=5.3   ->  blue   (3,6,16)      L=6.2
#:
#: The white turns COOL where the amber scheme wanted it warm, and that is
#: deliberate rather than an oversight: against a warm cream the orange mid
#: reads as more amber — the colourway it is replacing. The flag's own white
#: is what makes the orange look chosen.
#:
#: 2026-08-06, later, by voice with the Māori pass: "change the homepage to be
#: a New Zealand theme". So the colourway is POUNAMU AND THE SILVER FERN —
#: greenstone green over a bush near-black, with the fern's cool silver-white
#: at the top end. Not the NZ flag: its blue-and-red is the Union Jack half of
#: the argument and would land within a few degrees of the Persian face this
#: puck already wore, while pounamu and the fern are what the room means when
#: it says New Zealand in te reo. Same three anchors, same duotone, same
#: reason it lives here rather than in a dozen constants.
#:
#: LUMINANCE IS STILL PRESERVED — the argument every paragraph above makes,
#: and the reason the owner's 45%-askew reading survives another hue change.
#: Measured on the Rec.601 weights this duotone maps on:
#:
#:     mid    oranje (255,121,0)   L=147.3  ->  pounamu (30,208,140) L=147.0
#:     white  flag   (236,240,248) L=239.8  ->  fern    (236,242,238) L=239.8
#:     black  blue   (3,6,16)      L=6.2    ->  bush    (3,8,6)       L=6.3
#:
#: Three L's inside half a point of the scheme they replace, so nothing on
#: the face changes weight — only its hue. The mid is held saturated for the
#: reason the 1970s note gives: a desaturated jade at this L reads as grey
#: haze on this panel, and pounamu is not a grey stone.
#: 2026-08-06, evening, by voice with the return to English: "redesign the
#: overall GUI to look like a Patek Philippe watch". So the colourway is
#: GRAND FEU BLUE AND ROSE GOLD.
#:
#: WHICH PATEK, AND WHY NOT THE OBVIOUS ONE. A Calatrava is an opaline WHITE
#: dial with dark hands, and this face is bright ink on a dark ground
#: everywhere — every glow, every ring, the bolt itself. Inverting the ground
#: means re-tuning the luminance of every element on the panel at once, which
#: is precisely the thing the paragraphs above have refused to do three
#: colourways running. The Nautilus reading — a deep blue dial, rose gold
#: furniture, opaline highlights — is the Patek this face's existing L-map can
#: actually wear. Same three anchors, same duotone.
#:
#: LUMINANCE IS STILL PRESERVED, to within half a point, as every note above
#: requires. Measured on the Rec.601 weights this duotone maps on:
#:
#:     mid    pounamu (30,208,140)  L=147.0 -> rose gold (210,127,88) L=147.4
#:     white  fern    (236,242,238) L=239.8 -> opaline   (250,238,222) L=239.8
#:     black  bush    (3,8,6)       L=6.3   -> grand feu (2,7,14)      L=6.3
#:
#: WHAT MAKES THE MID READ AS METAL RATHER THAN AS THE 1970s AMBER IT SITS
#: BESIDE IN THIS FILE'S HISTORY IS ITS BLUE CHANNEL. Amber was (214,132,30)
#: at almost the same L and has no blue in it at all; 88 of blue under this
#: red and green is the difference between an indicator lamp and a warm metal.
#: A lighter, yellower gold is not on offer here — L is pinned at 147 by the
#: 45%-askew argument above, and gold gets lighter by getting brighter.
#: 2026-08-06, night, by voice at the puck: "revamp the face as an Audemars
#: Piguet Royal Oak ... the Royal Oak is a STEEL SPORTS WATCH, bold and
#: architectural, not a delicate dress piece. Move off the rose gold to
#: brushed steel and a deep blue dial." So the colourway is BLEU NUIT AND
#: BRUSHED STEEL, and the Patek block above it stands with its date.
#:
#: THE DUOTONE IS WHAT MAKES THIS ONE FREE, and it is worth saying why: a
#: Royal Oak is a blue dial with steel furniture, which is exactly the shape
#: of this ramp — a dark blue BLACK anchor, a neutral-cool MID, a cool white.
#: The Patek pass had to argue itself out of an opaline dial; this watch is
#: already the dark-ground instrument this face has always been.
#:
#: LUMINANCE IS PRESERVED to within a quarter of a point, as every colourway
#: note here has required since the beige pass — so nothing on the face
#: changes WEIGHT, only hue, and the owner's 45-degree reading survives:
#:
#:     mid    rose gold (210,127,88)  L=147.4 -> steel  (143,148,154) L=147.2
#:     white  opaline   (250,238,222) L=239.8 -> polish (233,241,250) L=239.6
#:     black  grand feu (2,7,14)      L=6.3   -> bleu   (0,2,45)      L=6.3
#:
#: THE BLACK ANCHOR IS WHERE THE BLUE ACTUALLY LIVES, and it is spent right
#: to the edge of its budget. Most of this dial's area sits at L=6 — the
#: ground under the tapisserie — so the ground IS the black anchor, pixel for
#: pixel. At L=6.3 the brightest blue available is (0,2,45): red and green
#: cost 0.299 and 0.587 of luminance per unit against blue's 0.114, so every
#: unit spent on them is four to five units of blue given up. A "nicer",
#: less saturated navy at this L is a darker navy, and this dial has to read
#: as blue at a glance across a room.
#:
#: AND THE MID IS DELIBERATELY NEUTRAL, which is the opposite of the note
#: above it. Rose gold needed 88 of blue to stop reading as a lamp; brushed
#: steel needs the three channels within eleven of each other, because any
#: cast at all turns steel into either pewter or aluminium. (143,148,154) is
#: a hair cool — the direction a brushed 316L bezel actually goes under
#: room light.
#:
#: ── 2026-08-06, night, later: THE NAVY IS BLEU NUIT, NUAGE 50 ─────────────
#: Owner, by voice at the puck: "the blue has to be the RIGHT blue ... a deep
#: midnight navy, not a bright or royal blue ... around RGB 27,42,74 in
#: shadow lifting to about 36,54,94 where the light catches it. If it looks
#: cheerful it is wrong." The STRUCTURE above is confirmed unchanged — navy
#: at the BLACK end, steel MID, cool white — and the owner said why in the
#: same breath: the navy is the dial's GROUND, not its ink, and putting it
#: at the mid would darken every element pinned to L=147 and spend exactly
#: the 45-degree legibility the whole ramp above exists to protect.
#:
#: WHAT CHANGES IS THE ANCHOR'S BUDGET, and this contradicts the paragraph
#: above it, which stands with its date. That note spent the black anchor to
#: the edge of L=6.3 and got (0,2,45) — the bluest triple available at that
#: luminance, but a near-black with a hint of blue in it, and channel-starved
#: (2 of green) in a way no dial lacquer is. AP's Bleu Nuit is not a blue at
#: L=6; it is a navy at L≈41 that only READS dark because everything around
#: it is steel and white. So the anchor is unpinned from 6.3 and set where
#: the colour actually lives. The MID IS UNTOUCHED at L=147.2 — that is the
#: constraint every colourway note here has been protecting, and it is the
#: one the owner named explicitly.
#:
#: THE ANCHOR IS SET FROM THE RECESSES, NOT FROM ITSELF, because L=0 is not
#: a colour anyone sees on this face — the dial's darkest large area is the
#: tapisserie's grooves at source L≈8.5. Through this ramp that lands at
#: (27,42,74), which is the shadow triple the owner quoted, to within a
#: quarter of a unit on every channel. The raised square tops (source
#: L≈35 after the wash was widened — see home.html's TAPISSERIE note of the
#: same date) land at (53,66,92) against the quoted (36,54,94): brighter and
#: less blue than the number, on purpose. The ramp runs toward a NEUTRAL
#: steel mid, so blue climbs 85 over the same span red climbs 124, and any
#: triple further up it is greyer by construction. The owner ranked that
#: trade in advance — "that contrast is where a real Royal Oak dial gets its
#: shimmer, and it is worth more than the exact hue" — so the texture keeps
#: the separation and the tops pay for it in saturation.
#:
#: ── 2026-08-06, night, later: THE PANEL HAS A BLUE CAST, SO THE METAL IS
#:    WARM IN THE FILE ─────────────────────────────────────────────────────
#: Owner, measured at the puck today: "this panel renders neutral grey with a
#: strong blue cast — a pure white photographs at roughly 172,245,255, red
#: about eighty counts below blue. So a steel drawn as a true neutral will
#: LOOK blue-grey and will never read as steel against the blue dial."
#:
#: THIS IS THE ONLY PLACE THE BEZEL'S HUE CAN BE SET, which is why the change
#: is here and not in home.html where the octagon is drawn. desertify() opens
#: with im.convert("L"): every hex on that page is thrown away and only its
#: LUMINANCE survives. Warming #steel there would have been a perfect silent
#: success (§1) — a real edit, plausible in the source, reviewable, and with
#: no effect whatsoever on the glass. The bezel's colour is these three
#: triples and nothing else.
#:
#: THE CORRECTION IS THE MEASUREMENT INVERTED, per channel. The panel's gains
#: are R 172/255 = 0.675, G 245/255 = 0.961, B 1.000, so a triple appears
#: neutral when 0.675R = 0.961G = 1.000B. At the MID that is affordable in
#: full and it is spent in full: (187,131,126) displays as (126,126,126) —
#: dead neutral — at the SAME source luminance of 147.2 that every colourway
#: note above has pinned itself to since the beige pass, so no element on the
#: face changes weight. It looks like terracotta in this file. It is grey on
#: the puck, and that is the entire point of the paragraph.
#:
#: AT THE WHITE THE GAMUT RUNS OUT, and that is stated rather than hidden:
#: full neutrality at L=239.6 needs red at 304. Red pins at 255 and the rest
#: of the budget holds the luminance, so (255,235,223) displays as
#: (172,226,223) — a third of the cast (233,241,250) had, not none of it.
#: Buying the remainder would mean taking the brightest polish on the dial
#: down to L=200, and weight is worth more than the last of the hue: the
#: highlights stay bright and slightly cool, the metal's body reads neutral.
#:
#: THE BLACK ANCHOR IS DELIBERATELY NOT CORRECTED. It is the dial's Bleu
#: Nuit, and a navy that displays as neutral is not a navy — it is meant to
#: read blue, and this panel's cast is helping it.
#:
#: IF IT OVERSHOOTS ON THE GLASS, the photograph is the suspect and not the
#: arithmetic: a camera's own white balance rides on that 172,245,255. Back
#: the MID off toward (143,148,154) along the same line. The cast is encoded
#: in these two triples and PAT_COL, nowhere else.
#:
#: ── 2026-08-06, night, later: TRUE BLACK OUTSIDE THE BEZEL ────────────────
#: Owner, at the glass: "the ground outside the bezel must be TRUE BLACK,
#: 0,0,0 ... everything nominally black is painted midnight blue, and the
#: panel's own blue cast doubles it. The result is a blue halo around the
#: whole face ... the BLUE BELONGS TO THE DIAL, not to the surround: paint
#: the dial face inside the bezel Bleu Nuit, and paint everything outside the
#: bezel pure black. I gave you the navy as the duotone's black end and that
#: was my error, because it painted the surround as well as the dial."
#:
#: HE IS DESCRIBING A REAL MEASUREMENT. home.html's case shoulder is #0b0c10,
#: L=12.2, and through this ramp that lands at (35,44,74) — L=44.7, which is
#: BRIGHTER than the dial's own deepest ground at (27,42,74), L=41.2. The
#: surround is not a dark edge the dial sits in; it is a slightly brighter
#: navy mat around it, and the cast makes it worse on the glass than it is in
#: this file — the note above corrects the MID and the WHITE for the panel's
#: blue and deliberately does not correct this anchor.
#:
#: THE ANCHOR CANNOT BE THE FIX, and that is why this is geometry and not a
#: triple. desertify() opens with convert("L"): the duotone is a function of
#: LUMINANCE ALONE, so it cannot tell a case shoulder at L=12 from a dial
#: ground at L=12 — one anchor paints both, which is exactly the mechanism
#: the owner has just diagnosed. Setting DESERT_BLACK to (0,0,0) obeys the
#: letter of the instruction and takes the dial's Bleu Nuit with it: the
#: tapisserie's grooves (source L 8.5) and its raised tops (L 35) get their
#: navy from this anchor pixel for pixel, and against a true-black anchor
#: they land at (12,9,8) and (51,36,34) — a warm charcoal with no blue in it
#: at all, because the ramp above it now runs to the warm-corrected mid from
#: zero. The dial would lose the colourway to fix the surround.
#:
#: SO THE ANCHOR STAYS AND ITS JOB NARROWS. It is the DIAL's Bleu Nuit and
#: nothing else; the surround is painted (0,0,0) afterwards, by the one thing
#: the duotone has no access to — where on the face a pixel is. Inside the
#: octagon, Bleu Nuit; outside it, the ground the display's own black border
#: and the shell continue.
#:
#: EIGHT POLYGONS RATHER THAN A CACHED MASK, and it is a thermal choice with
#: a measurement under it (§6). Measured on the dev box, per 1080 frame:
#: paste((0,0,0), mask) with a supersampled octagon mask is 5.6 ms; drawing
#: the eight outward quadrilaterals is 0.19 ms. desertify() is 5.5 ms of a
#: 64.5 ms composite against a 71.4 ms budget — the mask would have been a
#: tenth of the frame budget spent on a shape that never changes.
#: WHAT THE CHEAP ONE COSTS is antialiasing: a filled polygon has a hard
#: edge. It is spent where it does not show — the cut is at the OUTER edge of
#: the bezel's own arris stroke, so the bright silhouette line survives whole
#: and the 1 px staircase lands on the dim blend outside it. Four of the
#: eight flats are axis-aligned and have no staircase at all.
#:
#: IT ALSO FIXES THE SPIN, which was a second symptom of the same cause: the
#: whole home frame rotates by rot.deg with fillcolor=(0,0,0), so a navy
#: surround turning under a true-black fill showed a seam. Both are black now.
#: TRUE BLACK, and it must stay that way. This is the SURROUND, not the
#: dial: the Bleu Nuit belongs inside the bezel, and painting the black
#: end of the duotone navy painted the whole margin blue as well —
#: 'the background beyond the bezel but still part of the display is
#: slightly blue' (owner, at the glass). Two requests were asked to fix
#: this and both reported done without changing it, so it is set here by
#: hand. screen-blend never darkens, so any floor above zero survives
#: everything drawn on top of it.
#:
#: ── 2026-08-07: THE RAMP IS COOLED. THIS SUPERSEDES THE BLUE-CAST NOTE ─────
#: Owner, at the glass, having measured the anchors himself: "the dial has no
#: blue in it and the reason is not the ocean — it is the duotone underneath.
#: MEASURED: all three anchors are WARM ... every colour home.html specifies,
#: including the Bleu Nuit dial ground, is destroyed and repainted rose before
#: the ocean ever arrives ... The red channel is already at 187 and no screen
#: pass can ever pull it down. Adding blue light to a rose surface does not
#: make it blue; it makes it grey. So the blue has to come from the RAMP, not
#: the overlay."
#:
#: HE IS RIGHT, AND THE ARITHMETIC IS HIS. Blue-minus-red at the two anchors
#: was MID -61 and WHITE -32; the dial ground (source L about 38) came off
#: this ramp at (55,39,37), a rose, and nothing composited afterwards can
#: subtract red.
#:
#: ONE CORRECTION TO HIS MECHANISM, AND IT MAKES THE CASE STRONGER RATHER
#: THAN WEAKER. ocean_overlay is screened BEFORE this pass, not after it:
#: convert("L") throws the swell's blue away entirely and keeps only its
#: brightness. So the overlay was not "cancelling" the dial, it never reached
#: it. The conclusion is unchanged and the fix is the same one — the only
#: place a hue can enter this face is these three triples.
#:
#: LUMINANCE HELD, HUE INVERTED, which is the constraint every colourway note
#: above has pinned itself to since the beige pass, so no element on the face
#: changes weight. Rec.601 luma, computed rather than eyeballed:
#:   MID   (187,131,126) L 147.2  ->  (100,154,230) L 146.5, B-R -61 -> +130
#:   WHITE (255,235,223) L 239.6  ->  (232,240,255) L 239.3, B-R -32 -> +23
#: SAMPLED THROUGH THIS FUNCTION, not predicted from it, on a frame carrying
#: home.html's own source greys: the dial ground goes (55,39,37) B-R -18 ->
#: (29,46,68) B-R +39. The ocean's added light now reinforces that instead of
#: greying it.
#:
#: WHAT THIS SUPERSEDES, EXPLICITLY: the BLUE CAST note above corrected these
#: two anchors WARM to cancel a panel measured at 172,245,255 for a pure
#: white. That note stands as written and its measurement was real; what it
#: could not know is that spending the whole correction at the MID left the
#: dial with no hue of its own to be cast. The cast now works FOR the dial
#: rather than against the steel — which is the arrangement the TRUE BLACK
#: note already relies on for the Bleu Nuit. If the blue overshoots on the
#: glass, back the MID toward (126,150,205) along the same luma line rather
#: than reinstating the rose.
#:
#: THE BLACK ANCHOR IS UNCHANGED at (0,0,0) — measured, correct, and the
#: subject of the two notes above.
#:
#: ── 2026-08-08, by voice: BACK TO THE PATEK ("change my GUI interface to
#: the Padre Philippe mode" — Whisper for Patek Philippe). The anchors
#: return to the GRAND FEU AND ROSE GOLD triples of the 2026-08-06 evening
#: note above, which holds the arguments and the L measurements; every note
#: since stands with its date. What does NOT revert is structure rather than
#: hue: the surround cut, the bezel exemption and the baked steel band are
#: untouched, so this is rose gold against neutral steel. DESERT_BLACK goes
#: to grand feu (2,7,14) rather than staying (0,0,0) because the TRUE BLACK
#: note's job — a black ground beyond the bezel — is done by the surround
#: polygons now, so the anchor is free to be the dial's own again.
#:
#: ── 2026-08-08, later, by voice: BACK TO THE ROYAL OAK ("change my theme
#: from my home screen to the Adam R. P. Gay theme" — Whisper for Audemars
#: Piguet, the mangling puck_conduct's alias table already anticipates).
#: The anchors return to the BLEU NUIT AND BRUSHED STEEL triples in their
#: final 2026-08-07 cooled-ramp form, whose arguments and measurements are
#: in the notes above; every note since stands with its date. As with the
#: Patek return, only hue moves — the surround cut, the bezel exemption and
#: the baked steel band are structure and stay untouched. PAT_COL moves in
#: the same commit, as its own notes promise.
#:
#: ── 2026-08-08, latest: THE COLOURWAY IS A THEME ROW ──────────────────────
#: Owner, wearing the frozen patek bundle: "the patek color scheme is
#: gorgeous, but the power reserve overlaps with AURAVISION in the center."
#: The pivot recorded in docs/PREMIUM.md lands here: the anchors now come
#: from the theme table at the top of this file (_THEMES), one row per
#: sellable face, so every dated argument above is the provenance of a ROW
#: rather than of a hand edit. The patek row is the GRAND FEU AND ROSE GOLD
#: triples of the 2026-08-06 evening note verbatim — e13215b's dial, byte-
#: equal to the frozen bundle's anchors — and the royal-oak row is the
#: cooled-ramp values that stood on these three lines at r180. As the
#: Patek-return note above requires, patek's black anchor is grand feu
#: (2,7,14), not (0,0,0): the surround polygons own true black now, so the
#: anchor is free to be the dial's own.
DESERT_BLACK = _THEME["black"]
DESERT_MID = _THEME["mid"]
DESERT_WHITE = _THEME["white"]
#: CHUNKY, and it lives here for the same reason the colour does: most of the
#: home face arrives as PIXELS from home.html, so the only place that can
#: coarsen ALL of it is the pass that already touches every pixel. Quantising
#: L before the colorize turns the smooth glows into stepped bands — the look
#: of a segment display rather than a screen. 4 bits is 16 steps: visible
#: banding in the big gradients, still enough levels left on antialiased text
#: edges that the wordmark does not go ragged.
#:
#: Not to be confused with the sleep-mode breath, which was the OPPOSITE
#: complaint ("the fade is halting") — that was 13 steps over TIME. This is
#: steps over SPACE, in one frame, on purpose.
#:
#: 4 -> 8, i.e. OFF, with the Patek pass (2026-08-06 evening). The note above
#: stands and still describes accurately what the posterize does; it is simply
#: the opposite of the brief now. Banding is the tell of a cheap display, and
#: a fine dial is smooth at every magnification — that is most of what makes
#: a watch dial read as expensive. 8 bits is every level the L channel has, so
#: desertify() SKIPS the pass rather than paying 0.4 ms of a 64.5 ms frame
#: budget to compute an identity on a puck already measured at 96C.
DIAL_STEP_BITS = 8

#: THE OCTAGON, IN THIS FILE'S PIXELS — the boundary the note above splits the
#: colourway on. It is home.html's BEZ_OUT (461.94 viewBox: the inradius that
#: puts the eight corners exactly on r=500, the edge of the world) plus the
#: outer half of its 1.6-unit arris stroke, x VB_PX like every other geometry
#: this file borrows from that page.
#:
#: PINNED TO BEZ_OUT, NOT TO BEZ_BAND, which is what makes this a safe
#: two-file constant rather than another one to re-derive: the band has been
#: 11.5, 65, 40 and now 28 units, and BEZ_OUT has not moved through any of it.
#: The bezel thins inward. Its silhouette is the same octagon it has been
#: since the corners came back onto the panel.
#: ── 2026-08-06, late night: THE BOUNDARY IS THE CIRCLE, NOT THE OCTAGON ───
#: Owner, at the glass, having measured this surround himself: "the surround
#: is already exactly 0,0,0 — every corner, every edge ... There is no
#: charcoal left to audit. What the owner can see is the DIAL ENDING ...
#: between the octagon's corners there are wedges of true black INSIDE the
#: round glass ... Make the bezel's OUTER boundary the CIRCLE at r=500."
#:
#: THE NOTE ABOVE IS NOT WRONG, IT IS FINISHED. Its job was to keep the navy
#: out of the ground beyond the bezel, and it did; what it could not know is
#: that "beyond the bezel" would stop being an octagon. home.html now carries
#: its metal out to the circle at r=500 (see THE OUTER BOUNDARY IS THE CIRCLE
#: there, same commit), so an octagonal cut here would repaint eight segments
#: of that new metal true black — the exact wedges the owner is looking at,
#: reinstated by the file that is supposed to have removed them. The line at
#: 536 of that page saying SURROUND_IR "needed no second half" is dated and
#: stands; this IS the second half, and the pinning it describes is why there
#: was only ever one number to move.
#:
#: FOUR PIECES, NOT EIGHT, and the shape is the reason: r=500 viewBox is
#: 540 px, exactly half of 1080, so the circle is inscribed in the frame and
#: touches it at the four edge midpoints. What is left outside is the four
#: CORNERS of the square, meeting at a point on each axis. MEASURED here, both
#: cuts on a 1080 frame in the same run rather than compared against the note
#: above's number from another box: 251,174 px filled in 0.169 ms, against the
#: octagon's 340,340 px in 0.251 ms. Four polygons of 26 points are cheaper
#: than eight of four, because the area is what this costs and there is less
#: of it — a circle inside the square leaves less over than an octagon does.
#: THE ARC IS CIRCUMSCRIBED, NOT INSCRIBED. 24 chords over a quadrant is
#: 3.75 degrees each, whose sagitta at r=540 is 0.29 px; pushing every vertex
#: out by 1/cos(half the step) puts the whole polygon OUTSIDE the true circle,
#: so the hard edge this cut has always had can bite into the panel's last
#: fraction of a pixel and never into the metal. That is the same trade the
#: note above makes — spend the antialiasing where it does not show — moved
#: onto a boundary that is now under the physical bezel entirely.
SURROUND_R = 500.0 * VB_PX                    # 540 px: the panel edge itself


def _surround_quads():
    """Everything outside the panel's own circle, as four corner polygons.

    One per quadrant: the arc from one axis to the next, then straight out to
    a point well past the square's corner (1600 px), so each piece covers its
    whole corner of the frame and adjacent pieces meet at the axis exactly."""
    n, out = 24, 1600.0
    c = SIZE / 2.0
    step = math.radians(90.0 / n)
    r = SURROUND_R / math.cos(step / 2.0)         # circumscribed, not inscribed
    quads = []
    for q in range(4):
        a0 = math.radians(90.0 * q)
        pts = [(c + r * math.cos(a0 + i * step), c + r * math.sin(a0 + i * step))
               for i in range(n + 1)]
        d = math.radians(45.0 + 90.0 * q)
        pts.append((c + out * math.cos(d), c + out * math.sin(d)))
        quads.append(pts)
    return quads


SURROUND = _surround_quads()


#: ── 2026-08-07: THE BEZEL IS EXEMPT FROM THE DUOTONE ───────────────────────
#: Owner, at the glass, in the same breath as the cooled ramp above: "the blue
#: should be A CONTRAST. If the duotone is applied to the whole frame then the
#: steel goes blue too and nothing is gained — the face is uniformly blue
#: instead of uniformly grey, and it still reads flat. A Royal Oak is TWO
#: MATERIALS. So exempt the bezel ring from desertify and let it stay neutral
#: polished steel, so the blue has something to be blue AGAINST."
#:
#: THE RING IS PUT BACK, NOT RE-COLOURED, and that is the cheap half of it:
#: home.html already draws this band in true greys (BEZ_CHAM_L / BEZ_FLAT_L /
#: BEZ_BEV_L are all rgb(v,v,v)), so "neutral polished steel" is exactly the
#: pixels that arrived. Pasting the pre-duotone frame back through this mask
#: also preserves whatever was screened onto the band before the colourway —
#: the rings, the bolt, the ocean's own lift — rather than inventing a second
#: ramp that would have to be kept in step with the first.
#:
#: THE TWO BOUNDARIES ARE THE ONES ALREADY ON THE FACE, borrowed and not
#: re-guessed, so the exemption cannot drift off the metal it is exempting.
#: OUTER: SURROUND_R, the panel's own circle — the same edge the black cut
#: below uses, since home.html carried the bezel out to it (THE OUTER
#: BOUNDARY IS THE CIRCLE, that page). INNER: home.html's bezIn, the octagon
#: at BEZ_OUT - BEZ_BAND, solved corner by corner through _bez_oct exactly as
#: draw_bezel_state solves the brushed tops. Both are on the standing DIAL_K
#: contract; if that page moves them, this moves in the same commit.
#:
#: SUPERSAMPLED, UNLIKE THE SURROUND, and the difference is deliberate. That
#: cut spends its aliasing on a dim blend outside a bright arris and can
#: afford a hard edge. This one is now a HUE boundary — grey metal against a
#: blue dial, all the way round — and a 1 px staircase on a colour change is
#: the sort of thing that reads as a cheap render. 4x, built once: measured
#: here at 24 ms of startup, which is paid where nobody is looking.
#:
#: MEASURED, because a full-frame paste is exactly the kind of cost the
#: surround note above rejected (§6). Dev box, same run, this function with
#: and without the paste: 3.58 ms -> 4.51 ms. The exemption costs 0.93 ms of
#: a 71.4 ms frame — an eighth of what a general 1080 paste costs, because
#: the mask is zero over the whole dial and only the band is blended. That
#: is cheap enough that the alternative was not built: there is no bounding
#: box on an annulus, and the four-strip cover that would fit round one is
#: still 62% of the frame.
#:
#: AND THE RESULT IS SAMPLED, not looked at, because the owner asked for it
#: that way and because looking is what would miss it. Through this function,
#: on a frame carrying home.html's own source greys:
#:   dial ground     (29,46,68)    blue-minus-red  +39
#:   bezel flat      (168,168,168) blue-minus-red    0   (was -51)
#:   bezel crease    (236,236,236) blue-minus-red    0
#: Strongly positive on the dial, exactly zero on the band. If both ever come
#: back near zero again, the duotone is eating the dial and this paste is not
#: the thing that broke.
_BEZEL_MASK = None


#: ONLY THE STEEL, not the chapter zone. RING alone from
#: scripts/bake_bezel.py (13.6, +1 for the seam) — NOT RING + CHAPTER.
#: 2026-08-08: at 36 the mask preserved un-colourwayed pixels across the
#: whole bezel including the chapter band, which is mostly TRANSPARENT
#: between its ticks — so the AP blue showed straight through the gaps and
#: the owner saw "the blue ap dial circle still survives", measured alive
#: at r=508..538. The chapter band's gaps are DIAL and must take the
#: colourway; only the polished ring itself is the other material.
BEZEL_RING_W = 14.6


def _bezel_mask() -> Image.Image:
    """The bezel band as an alpha mask: the panel's circle, less the dial's
    octagon. Built once — the bezel is baked and cannot move."""
    global _BEZEL_MASK
    if _BEZEL_MASK is None:
        ss = 4
        n = SIZE * ss
        m = Image.new("L", (n, n), 0)
        d = ImageDraw.Draw(m)
        c, r = n / 2.0, SURROUND_R * ss
        d.ellipse([c - r, c - r, c + r, c + r], fill=255)
        # ── THE MASK WENT CIRCULAR WITH THE BEZEL, 2026-08-08 ──────────
        # This cut an OCTAGON out of the panel circle — the shape of the
        # bezel that was retired weeks ago. Everything between that ghost
        # octagon and the glass kept its ORIGINAL, un-colourwayed pixels,
        # so on the patek theme the owner saw "the color scheme boxed in
        # the octagon and filled with the blue AP background", with the
        # octagon's edge reading as an inexplicable circle through the
        # wedges. The bezel is a RING now: keep the steel of the ring
        # itself and let the colourway own every pixel inboard of it.
        ri = (SURROUND_R - BEZEL_RING_W) * ss
        d.ellipse([c - ri, c - ri, c + ri, c + ri], fill=0)
        _BEZEL_MASK = m.resize((SIZE, SIZE), Image.BOX)
    return _BEZEL_MASK


#: ── THE BEZEL IS BAKED STEEL NOW, NOT A DRAWN ONE, 2026-08-07 ────────────
#:
#: Owner, by voice: "the face looks almost like a cartoon", and it "should
#: reflect the light hitting the sides in different ways". scripts/bake_bezel.py
#: answers that — anisotropic GGX over a per-facet brush direction reflecting a
#: studio environment, supersampled 4x — and writes packs/bezel_steel.png:
#: 1080x1080 RGBA, transparent everywhere except the band. 0.6 s to regenerate,
#: any time.
#:
#: THE GPU IS NOT IN THE PUCK'S PATH. It ran ONCE, on a workstation. What ships
#: is a PNG and the device composites it, exactly like the overnight content
#: packs. The standing rule — a puck hears, speaks, unlocks and recovers with
#: the RTX off — is untouched, and must stay that way if this asset is ever
#: rebuilt differently.
#:
#: NEVER RESCALE IT. It is authored at this panel's native 1080 and pasted at
#: (0, 0). Resampling puts back exactly the aliasing the 4x supersample exists
#: to remove, and the grain is a sub-pixel structure, so it is the first thing
#: a resize destroys. A wrong-sized file is therefore a REFUSAL below, not a
#: resize.
#:
#: AND IT MUST NOT GO THROUGH desertify(). That function opens with
#: convert("L") and repaints the result on ONE ramp: it would greyscale eight
#: differently-lit facets and hand them back a single gradient, which destroys
#: the per-facet variation that is the entire point of the asset. It is the
#: same argument the dial's blue makes about the moonphase. So the paste sits
#: AFTER the colourway in the loop — and still before draw_bezel_state, which
#: lights this metal, and before the rotate, so the band turns with the face
#: as the drawn one did.
#:
#: WHY IT LOOKS DIFFERENT, so nobody tunes it back toward the old one: the
#: owner measured the drawn bezel at 1.21:1 in luminance across all eight
#: flats — effectively uniform, which is the whole cartoon effect — against
#: 3.38:1 for this one, 53 at the bottom flat to 192 at the top. Bright at the
#: top, dark at the bottom, mid on the sides, polished chamfers at the corners
#: against brushed flats. That alternation of brushed and polished on adjacent
#: surfaces is the Royal Oak's whole argument, and a single gradient sweeping
#: a ring cannot produce it. (Measured here on the shipped file a different
#: way — the MEAN over each whole 45° sector, chamfers and screw heads
#: included — the eight come out 105..194, a 1.85:1 spread. Sector means are
#: not flat centres; both numbers are recorded so a future session does not
#: read one as contradicting the other and go looking for a bug.)
#:
#: THE DRAWN BEZEL IN home.html IS STILL THERE, DELIBERATELY. This band ends
#: at r=500 px; the panel's own circle is SURROUND_R = 540, and the old
#: octagon's corners are what fill that last 40 px. Deleting the vector bezel
#: today would leave a black ring at the glass edge, and it would need a fresh
#: base.png bake on the RTX besides — the puck only ever sees frozen
#: screenshots of that page, and home.html is not in the deployer's table.
#: Everything inboard of 500 px is this PNG; what survives of the drawn one is
#: the outer rim, under the physical shell.
#: ── 2026-08-08: THE BEZEL IS THEMED ──────────────────────────────────────
#: The ring is composited after desertify() and therefore cannot be recoloured
#: by a colourway (the paragraph at _THEMES says why), so a warm theme needs a
#: warm BAKE: scripts/bake_bezel.py --gold, packs/bezel_gold.png. The theme row
#: names the file; a row that names none gets the steel one.
#:
#: THE STEEL NAME IS ALWAYS THE LAST CANDIDATE, and that is what lets a bundle
#: switch without teaching the switcher a second filename: a profile carrying
#: its own ring installs it into ~/aura_face/ under whichever name it was
#: captured as, and if only `bezel_steel.png` is there it is used whatever the
#: theme asked for. Preferring the themed name FIRST means the repo mirror
#: (packs/, which holds both) still gets the right metal.
BEZEL_STEEL_NAME = "bezel_steel.png"
_BEZEL_STEEL = None
_BEZEL_STEEL_TRIED = False


def bezel_steel():
    """The baked bezel this theme wears, loaded once and held. None if it
    never landed.

    Two candidate homes because dj_face.py has two on a puck: the unit runs
    ~/aura_face/dj_face.py, where the deployer drops this beside it, and
    ~/aura-next/ is the repo mirror, where it keeps its packs/ path. A miss on
    both SAYS SO, once, on stdout (PRINCIPLES §1) — a face that quietly shows
    the old bezel is an hour spent wondering why the deploy did nothing.
    """
    global _BEZEL_STEEL, _BEZEL_STEEL_TRIED
    if _BEZEL_STEEL_TRIED:
        return _BEZEL_STEEL
    _BEZEL_STEEL_TRIED = True
    here = Path(__file__).resolve().parent
    # Themed name first, in both homes, then the steel one in both — dict
    # rather than a set so a theme naming the steel file is not tried twice.
    # THE LAST CANDIDATE IS THE NEUTRAL BAKE AND MUST STAY THAT WAY: a row
    # with no `bezel` key, or one naming a file this device was never sent,
    # falls back to steel — never to another row's warm ring. Adding a warm
    # name to this list is how the ferrari came to wear rose gold once.
    names = list(dict.fromkeys(
        [n for n in (_THEME.get("bezel"), BEZEL_STEEL_NAME) if n]))
    for p in [d / n for n in names for d in (here, here / "packs")]:
        if not p.exists():
            continue
        try:
            im = Image.open(p)
            im.load()
            im = im.convert("RGBA")
        except Exception as e:                  # noqa: BLE001
            print(f"bezel: {p} is unreadable {e!r}", flush=True)
            continue
        if im.size != (SIZE, SIZE):
            # NOT RESIZED — see the note above. A wrong-sized asset is a bake
            # that no longer matches this panel, and the answer is to re-bake
            # it, not to resample the grain away here.
            print(f"bezel: {p} is {im.size[0]}x{im.size[1]}, not {SIZE}x{SIZE}"
                  f" — NOT pasted; re-run scripts/bake_bezel.py", flush=True)
            continue
        _BEZEL_STEEL = im
        # Which FILE, not just "loaded": on a themed face the interesting
        # failure is landing on the fallback, and it looks identical in a
        # log that only says the load worked.
        print(f"bezel: {FACE_THEME} wears {p.name}, loaded from {p}",
              flush=True)
        break
    if _BEZEL_STEEL is None:
        print(f"bezel: none of {', '.join(names)} beside dj_face.py or under "
              f"packs/ — the face is wearing the drawn bezel", flush=True)
    return _BEZEL_STEEL


def _ramp_lut(stops):
    """Three 256-entry LUTs from (position 0-1, (r,g,b)) stops, interpolated.

    Linear in sRGB on purpose. The stops are chosen by eye against the glass,
    so interpolating in the space they were picked in is what makes the
    midpoints land where the eye expects — a "correct" linear-light blend
    puts the gold band somewhere nobody asked for.
    """
    stops = sorted(stops)
    out = ([0] * 256, [0] * 256, [0] * 256)
    for v in range(256):
        f = v / 255.0
        hi = next((i for i, (pos, _) in enumerate(stops) if pos >= f),
                  len(stops) - 1)
        lo = max(0, hi - 1)
        p0, c0 = stops[lo]
        p1, c1 = stops[hi]
        t = 0.0 if p1 <= p0 else (f - p0) / (p1 - p0)
        for ch in range(3):
            out[ch][v] = int(round(c0[ch] + (c1[ch] - c0[ch]) * t))
    return out


#: The theme's own ramp, or None for the three-stop colorize every other row
#: has always used. See the note inside desertify().
_RAMP_LUT = _ramp_lut(_THEME["ramp"]) if _THEME.get("ramp") else None


def _ramp_rgb(lum) -> tuple:
    """A SOURCE luminance 0..255 through this row's colour authority.

    ── 2026-08-27, AND THE UNITS ARE THE WHOLE POINT ────────────────────
    `_dial_metal()` does the same job for the three-anchor rows and takes
    the same 0..255. It was handed 0.04..1.00 during the centrepiece work
    and returned the black anchor for every input from ankle to ceiling —
    a value ramp that had collapsed to one colour, with nothing in any log
    to say so, on a row (carbon) where black is (12,12,13) and the fault
    therefore looked like a design choice. Take the argument in the units
    the LUT is indexed by, and clamp rather than wrap so an out-of-range
    caller gets the ceiling instead of the floor.

    Anything composited AFTER desertify() that wants to be made of the
    dial's material asks HERE rather than keeping its own copy of two
    triples (§15): the ramp moves, the mark moves with it.
    """
    v = int(round(max(0.0, min(255.0, float(lum)))))
    if _RAMP_LUT is not None:
        return (_RAMP_LUT[0][v], _RAMP_LUT[1][v], _RAMP_LUT[2][v])
    return _dial_metal(v)[:3]


def _colourway(im: Image.Image) -> Image.Image:
    """Luminance -> this theme's colours. The colour half of desertify(),
    with none of its framing.

    ── ONE PLACE STATES THE RAMP (2026-08-26, §15) ──────────────────────
    Split out because a SECOND caller appeared: the relief panes sample
    home.html's baked type and re-draw it as a raised surface, and the
    colour that type arrives in on the glass is not the bake's own ink —
    it is the bake's LUMINANCE put through this ramp, because desertify()
    opens with convert("L") and throws the hue away. A private copy of
    these five lines beside the sprite would be a second opinion about
    the theme's colours that agrees with this one until someone edits a
    row, which is the drift §15 exists to make impossible.

    desertify() is unchanged in behaviour: it is this, plus the SURROUND
    cut that only makes sense on a whole frame.
    """
    lum = im.convert("L")
    if DIAL_STEP_BITS < 8:
        lum = ImageOps.posterize(lum, DIAL_STEP_BITS)
    if _RAMP_LUT is not None:
        return Image.merge("RGB", tuple(lum.point(t) for t in _RAMP_LUT))
    return ImageOps.colorize(lum, DESERT_BLACK, DESERT_WHITE, mid=DESERT_MID)


def desertify(im: Image.Image) -> Image.Image:
    """The home face's colourway — grand feu blue and rose gold since
    2026-08-06 evening, pounamu and warm amber before it. Measured on the dev
    box: the colorize is 2.1 ms on a 1080 frame, the surround 0.19 ms, and the
    posterize (now off) added ~0.4 ms."""
    #: ── 2026-08-12: WHY THE CHOPARD DIAL IS MONOCHROME, STRUCTURALLY ──────
    #: Owner: "it needs more detail and interesting colors." The obvious move
    #: is to paint colour into home_chopard.html, and it CANNOT WORK: this
    #: function throws the frame's colour away. `im.convert("L")` is the first
    #: line, and everything after it is a re-colouring of luminance.
    #:
    #: Demonstrated rather than asserted — six saturated, wildly different
    #: hues put through the shipped ramp:
    #:   (255,120,120) (120,255,120) (120,120,255) ... all six arrive as
    #:   (209,156,158) (226,191,190) (199,135,138) ... six shades of one rose.
    #:
    #: That is the whole reason the face reads as one hue. It is not the
    #: palette and it is not the bake; a three-stop ramp has ONE hue family in
    #: it by construction, so a dial drawn through it can only ever be
    #: monochrome. Everything with real colour on this face — the rubies, the
    #: bezel, the anodised caps, the moonphase — is composited AFTER this
    #: function for exactly that reason.
    #:
    #: A ROW MAY BRING ITS OWN RAMP. With more than three stops, luminance
    #: bands become HUE bands: bake mother-of-pearl shelves as light and dark
    #: in home_chopard.html, and the ramp turns them into pink, cream, gold
    #: and a glance of pale blue. Same architecture, same 2 ms, and the bake
    #: still says WHERE the shelves are while the theme says what colour they
    #: come out.
    #:
    #: A ROW WITHOUT THE KEY TAKES THE OLD PATH UNCHANGED — not an equivalent
    #: LUT, the actual ImageOps.colorize call, so patek, ferrari and royal-oak
    #: cannot move by a level.
    #: ── AND THE RAMP MOVED ONE FUNCTION UP (2026-08-26) ───────────────────
    #: Same arithmetic, same call, same bytes on every row — see _colourway,
    #: which the relief panes' type sampler also reads so the raised label
    #: cannot come out a different colour from the dial it is cut into.
    out = _colourway(im)
    # ── THE PASTE-BACK IS RETIRED, 2026-08-08 ────────────────────────
    # This re-pasted the ORIGINAL pixels over the bezel band so the steel
    # would survive the duotone. It is redundant and has been since the
    # bezel became a baked PNG: bezel_steel() is composited AFTER this
    # function returns ("on top of the colourway and never through it"),
    # so the steel already keeps its own material without help. All the
    # paste-back did was preserve un-colourwayed pixels wherever the PNG
    # is transparent or feathered — the chapter ring's gaps and the ring's
    # own anti-aliased rim — which on the patek theme left a blue hoop the
    # owner chased three times, measured last at r=526..538. The colourway
    # now owns every pixel of the dial; the steel is pasted over it.
    # The dial keeps the anchor's Bleu Nuit; the ground outside the PANEL'S
    # OWN CIRCLE is true black, which no luminance the duotone can be handed
    # will produce. Outside the bezel until 2026-08-06 late night — the bezel
    # reaches the circle now, so this cut no longer lands on the glass at all.
    d = ImageDraw.Draw(out)
    for q in SURROUND:
        d.polygon(q, fill=(0, 0, 0))
    return out


def main() -> None:
    # Pidfile so a deployer can kill THIS instance by number — never
    # pkill/pgrep -f, which matches the invoking shell's own command line
    # (the trap is in the house rules for a reason).
    Path("/tmp/aura_face").mkdir(parents=True, exist_ok=True)
    #: ── ONE RENDERER PER FRAMEBUFFER (2026-08-19) ──────────────────────
    #: Owner: "there is a noticeable drop in rendering quality, it's really
    #: slow and laggy." Two compositors were running — an afternoon
    #: session's manual relaunch (pid 129636, 3h old) and the systemd unit
    #: I started on top of it without checking. Both writing full frames to
    #: /dev/fb0, so the panel showed an interleaving of two independent
    #: renderer states: tearing and judder, from a device that was
    #: otherwise healthy.
    #:
    #: IT WAS INVISIBLE, and the pidfile is why. It was written and never
    #: READ, so the second instance simply overwrote it — after which the
    #: file names the newcomer and the older process cannot be killed by
    #: number at all. Both also append to the same dj_face.log, so the
    #: `pace:` lines interleave and each reports a healthy ~25 fps of ITS
    #: OWN frames. Every instrument on the device said fine.
    #:
    #: So: refuse, and say so. Same rule as sterling_up.sh — "two instances
    #: fight over the microphone and the GPU, and both half-work, which is
    #: far harder to diagnose than either one being plainly down."
    #:
    #: EXIT ZERO, deliberately. The unit is Restart=on-failure/RestartSec=3,
    #: so a non-zero exit would spin this message every three seconds
    #: forever. A clean exit leaves the unit inactive with one renderer
    #: still on the glass, which is the correct end state.
    #:
    #: The cmdline check is what stops a stale pidfile whose number has
    #: been recycled by an unrelated process from blanking the screen.
    _pidf = Path("/tmp/aura_face/dj_face.pid")
    try:
        _old = int(_pidf.read_text().strip())
    except Exception:                                       # noqa: BLE001
        _old = 0
    if _old and _old != os.getpid():
        try:
            _cmd = Path(f"/proc/{_old}/cmdline").read_bytes().decode(
                "utf-8", "ignore")
        except Exception:                                   # noqa: BLE001
            _cmd = ""
        if "dj_face.py" in _cmd:
            print(f"face: ALREADY RUNNING as pid {_old} — refusing to start "
                  f"a second compositor on /dev/fb0. Two renderers on one "
                  f"panel read as tearing and lag with nothing in any log. "
                  f"Kill {_old} first if you meant to replace it.",
                  flush=True)
            raise SystemExit(0)
    _pidf.write_text(str(os.getpid()))
    # A desk flag surviving a crash would leave the conductor filing the
    # room's conversation as feature requests with no card on screen. The
    # face owns the mode, so the face clears it on the way up.
    if CONCIERGE_OPEN.exists():
        CONCIERGE_OPEN.unlink(missing_ok=True)
        print("sterling: cleared a stale desk flag from a previous run",
              flush=True)
    #: ARMED, so the glass says when the panel is absent — and armed BEFORE
    #: the first look, so a puck that boots with no touchscreen wears the
    #: notice on its very first frame rather than after the first outage.
    #: Off-device harnesses never reach this line, which is why a preview
    #: does not render the banner over everything it draws.
    _TOUCH["armed"] = True
    touch_acquire(time.time())          # prints either the panel or the miss
    layers = Layers()
    rot = Rotation()

    x = y = 0.0
    down = False
    scale = SIZE / 4096.0
    last = time.time()
    last_gain_q = None
    bolt_lit = None             # the bolt already scaled to last_gain_q
    was_locked = False          # arms the wedge entrance on the unlock tick
    wedge_t0 = None
    scene_mtime = None
    scene_img = scene_base = scene_data = prev_composite = None
    scene_born = 0.0
    pre_backdrop, target = None, 0.0
    lock_img = None
    stars = make_stars()
    _make_click()               # the volume detent's voice, ready on disk
    #: and the three UI sounds, for the same reason: generating a wav is
    #: ~50 ms of Python, and the ONE tap that must never be slow is the
    #: first one (§13). Lazily is how the first touch of a fresh boot ends
    #: up being the one that feels unacknowledged.
    _make_ui_sounds()
    sweep = make_sweep()
    #: The watcher starts with the compositor and never stops, because the
    #: state it is watching for is precisely the one where nobody opens the
    #: settings book — see the block at HEALTH_REFRESH_S. It is a daemon
    #: thread and every poll is wrapped, so it can never hold the glass.
    health_start()

    while True:
        # The ceremony is not twistable (owner, 2026-08-02 morning). One
        # stat per frame, hoisted out of the event loop below so the
        # check is not paid per touch sample. Rotation gestures are
        # dropped outright while the scan is up — see the rot.move gate.
        login_up = LOGIN.exists()
        if login_up and not _LOGIN_SNAP["seen"]:
            # First frame of the ceremony: orient ONCE toward whoever
            # just spoke, so "WELCOME BACK, PAUL" faces the person it
            # names. A snap, never a glide — the DoA block below is
            # disabled during login precisely because chasing utterances
            # made the ceremony "very very twisty", and this is the one
            # orientation decision the ceremony gets. Same sign/offset
            # math as that block, deliberately: one calibration, two
            # call sites.
            _LOGIN_SNAP["seen"] = True
            try:
                #: 2026-08-25: HONOUR THE CALIBRATION FLAG HERE TOO. The
                #: comment above says "one calibration, two call sites"
                #: and that was the intent, but only the wordmark ever
                #: checked doa_cal.json's `enabled`. On this unit it is
                #: false — the array reads one near-constant bearing from
                #: every position — so the ceremony snapped the dial to
                #: the same meaningless angle on every unlock. Harmless
                #: while every theme DREW its labels (they re-rendered at
                #: the new angle); visible the moment gallery shipped a
                #: BAKED base PNG, because the bake rotates with the dial
                #: and its labels went with it. Owner, live: "the
                #: orientation of every wedge is not correct ... it's
                #: supposed to be a color / skin change." It was; this
                #: was a latent bug the skin made visible.
                if not _doa_cal(time.time())["on"]:
                    print("login: bearing not calibrated on this unit "
                          "— no snap, dial holds", flush=True)
                elif FACE_DOA.exists():
                    dj = json.loads(FACE_DOA.read_text())
                    age = time.time() - float(dj.get("at", 0))
                    if age < LOGIN_SNAP_FRESH_S:
                        _sign = float(dj.get("sign", DOA_SIGN))
                        _off = float(dj.get("offset", DOA_OFFSET))
                        rot.deg = (_sign * float(dj["deg"]) + _off) % 360.0
                        rot.vel, rot.inertia = 0.0, False
                        print(f"login: snapped to speaker "
                              f"raw={float(dj['deg']):.0f} -> "
                              f"face={rot.deg:.0f} (age {age:.1f}s)",
                              flush=True)
                    else:
                        # PRINCIPLES §1: a bearing declined for staleness
                        # says so, or the next "it didn't turn" report
                        # has nothing behind it.
                        print(f"login: DoA stale ({age:.0f}s) — no snap",
                              flush=True)
                else:
                    print("login: no DoA on disk — no snap", flush=True)
            except Exception as e:
                print(f"login: snap skipped {e!r}", flush=True)
        elif not login_up and _LOGIN_SNAP["seen"]:
            _LOGIN_SNAP["seen"] = False      # re-arm for the next ceremony

        # -- input (non-blocking) ----------------------------------------
        #: THE PANEL MAY NOT BE THERE. It may never have enumerated, and it
        #: may vanish under a running compositor when USB re-enumerates —
        #: both used to end the process (SystemExit at start, an unguarded
        #: OSError here). Neither does now: the frame below still paints,
        #: and the retry runs from this same pass.
        touch_acquire(time.time())
        touch = _TOUCH["dev"]
        while touch is not None:
            try:
                if not select.select([touch.fd], [], [], 0)[0]:
                    break
                #: LIST, not the bare generator: evdev raises while it is
                #: being iterated, so consuming it inside the try is the
                #: difference between catching the re-enumeration and
                #: catching nothing.
                evs = list(touch.read())
            except BlockingIOError:
                break                   # select lied about a readable fd
            except (OSError, ValueError) as exc:
                touch_lost(exc)
                break
            for ev in evs:
                if ev.type == evdev.ecodes.EV_ABS:
                    if ev.code in (evdev.ecodes.ABS_MT_POSITION_X, evdev.ecodes.ABS_X):
                        x = ev.value * scale
                    elif ev.code in (evdev.ecodes.ABS_MT_POSITION_Y, evdev.ecodes.ABS_Y):
                        y = ev.value * scale
                elif ev.type == evdev.ecodes.EV_KEY \
                        and ev.code == evdev.ecodes.BTN_TOUCH:
                    if ev.value and not down:
                        down = True
                        rot.press(x, y)
                    elif not ev.value and down:
                        down = False
                        tap = rot.release()
                        if tap is not None:
                            handle_tap(tap, rot)
                        elif _SET["open"]:
                            # A drag released while the settings book is
                            # open is a page turn, not a spin — the dial
                            # is pinned for the whole mode. Round 2: rim
                            # drags are the book's ORIENTATION gesture
                            # and must not also turn a page; and the
                            # swipe vector is mapped into the book's
                            # rotated frame so "left" is the READER's
                            # left whichever way the book faces.
                            pr = math.hypot(rot.press_xy[0] - SIZE / 2,
                                            rot.press_xy[1] - SIZE / 2)
                            if pr < SET_ORIENT_R:
                                _settings_swipe(*_rot_vec(
                                    x - rot.press_xy[0],
                                    y - rot.press_xy[1],
                                    _SET["view_deg"]))
                elif ev.type == evdev.ecodes.EV_SYN and down \
                        and rot.dragging:
                    # The finger is SOVEREIGN on every screen (owner,
                    # 09:0x: "capturing waveform screen i can't rotate...
                    # morning briefing screen i also can't rotate" — the
                    # morning's rotation lock read his 07:25 remark
                    # backwards). The DoA snap still orients the ceremony
                    # initially; a hand can always override it.
                    # ...EXCEPT while the power slide is up. The finger
                    # cannot do two jobs at once: the owner, 2026-08-04 —
                    # "the power slide is bad because as i try to slide it is
                    # taking it as a rotation command as well so the screen
                    # starts rotating as i am trying to slide it
                    # horizontally". The volume mode already solved this with
                    # drag_role ("one finger never does both jobs mid-
                    # gesture"); the power overlay simply never claimed its
                    # finger. It does now — the slide is a takeover, and a
                    # takeover owns the gesture.
                    if _POWER["until"] > time.time():
                        rot.finger_xy = (x, y)      # slide still tracks it
                    else:
                        rot.move(x, y)

        now = time.time()
        dt, last = now - last, now
        # Heavier dial on the waiting/briefing screens; the home face keeps
        # its approved feel. Flicks also cap slower outside the home face.
        rot.friction = 3.2 if (COUNT.exists() or SCENE_DATA.exists()
                               or SCENE.exists()) else FRICTION
        rot.tick(dt)
        # Face the speaker: glide toward the last heard bearing — but a
        # finger always outranks a voice, and stale bearings are ignored.
        # HOME FACE ONLY: during the lock screen, login theatre and
        # enrollment the user is talking constantly, and chasing every
        # utterance made those screens "very very twisty" (owner, live) —
        # a ceremony holds still.
        # DISABLED 2026-08-02 by measurement, not opinion: a 15-sample
        # walk covering 330deg of real movement moved the array's reported
        # bearing by 38deg total (it sat at 162-200 from every position),
        # and the beam probe found beam 3 dead and beam 4 duplicating the
        # louder of 1/2 — two usable beams cannot resolve a circle. The
        # face was swinging 287deg on a number that means nothing. Honour
        # the 'enabled' flag in doa_cal.json; re-enable when the ears live
        # in the puck (docs/PUCK-STANDALONE.md) or the array is replaced.
        #: 2026-08-25: _DOA_ENABLED is a hardcoded True and the flag this
        #: comment block promises to honour was never actually read here
        #: — see the login-snap note. Read it.
        if _DOA_ENABLED and _doa_cal(time.time())["on"] \
                and not rot.moving and FACE_DOA.exists() \
                and not LOCKED.exists() and not LOGIN.exists():
            try:
                dj = json.loads(FACE_DOA.read_text())
                if time.time() - float(dj.get("at", 0)) < DOA_FRESH_S:
                    _sign = float(dj.get("sign", DOA_SIGN))
                    _off = float(dj.get("offset", DOA_OFFSET))
                    cand = (_sign * float(dj["deg"]) + _off) % 360.0
                    # COARSE MODE: the free-running beam tracks honestly
                    # but noisily (RMS 39deg over a measured walk — same
                    # spot read 89 and 358 on two visits). Snapping to
                    # the nearest quadrant turns a 39deg error into "the
                    # text faces your side of the room", which is the
                    # whole point; precision can come when the ears live
                    # in the puck and utterances are longer.
                    _q = float(dj.get("coarse", 0) or 0)
                    if _q > 0:
                        cand = (round(cand / _q) * _q) % 360.0
                    # Retarget only on a genuinely NEW bearing that moved
                    # >20° — chasing per-utterance jitter made the dial
                    # "weirdly twitchy" (owner, live). One speaker talking
                    # from one spot now produces one settled orientation.
                    if dj.get("at") != _DOA_STATE["at"]:
                        _DOA_STATE["at"] = dj.get("at")
                        if _DOA_STATE["tgt"] is None or abs(
                                (cand - _DOA_STATE["tgt"] + 540.0)
                                % 360.0 - 180.0) > 20.0:
                            _DOA_STATE["tgt"] = cand
                            # Two field reports, two blind cal guesses.
                            # No third: log raw vs applied so the next
                            # "still inverted" comes with numbers.
                            print(f"doa: raw={dj['deg']:.0f} sign={_sign:+.0f} "
                                  f"off={_off:.0f} -> face={cand:.0f}",
                                  flush=True)
                    if _DOA_STATE["tgt"] is not None:
                        diff = (_DOA_STATE["tgt"] - rot.deg + 540.0) \
                            % 360.0 - 180.0
                        if abs(diff) > 1.5:
                            step_deg = max(-DOA_GLIDE_DPS * dt,
                                           min(DOA_GLIDE_DPS * dt, diff))
                            rot.deg = (rot.deg + step_deg) % 360.0
            except Exception:
                pass                          # half-written; next tick

        # Settings, volume and the Sterling screen are HOME-FACE modes.
        # Any takeover screen — sleep, brick, login, lock, countdown,
        # briefing — closes them, LOUDLY: an invisible mode that kept
        # eating taps underneath a briefing would be the same
        # silent-success trap volume mode fell into (PRINCIPLES §1).
        # This is also the ONLY exit besides DONE any of them has
        # (round 2: the volume inactivity expiry is gone). Only paid
        # while a mode is open.
        # ── the desk, asked for by voice ──────────────────────────────
        #
        # Consumed whether or not they are acted on: a request left on disk
        # would fire again on the next frame, and "open" arriving while the
        # screen is locked must be a refusal that is OVER, not one that
        # retries ten times a second.
        if CONCIERGE_OPEN_REQ.exists():
            CONCIERGE_OPEN_REQ.unlink(missing_ok=True)
            # _REQ_CARD belongs in this list for the reason the whole list
            # exists: a voice-opened desk on top of the queue card would be
            # two modes at once, and the first tap would close the one
            # UNDERNEATH — the exact stacked-screens bug the modal law was
            # written for.
            blocked = (login_up or SLEEPING.exists() or deaf_now()
                       or LOCKED.exists() or COUNT.exists() or SCENE.exists()
                       or SCENE_DATA.exists() or _SET["open"] or _VOL["open"]
                       or _REQ_CARD["open"] or _PAT_CARD["open"])
            if _STERLING["open"]:
                pass                      # already at the desk
            elif blocked:
                print("sterling: asked for by voice but another screen owns "
                      "the glass — not opening", flush=True)
            else:
                _STERLING.update(view_deg=0.0, view_prev_ang=None,
                                 grab_deg=0.0)
                _sterling_set(True, "asked for by voice")
        if CONCIERGE_CLOSE_REQ.exists():
            CONCIERGE_CLOSE_REQ.unlink(missing_ok=True)
            if _STERLING["open"]:
                _sterling_set(False, "finished by voice")

        if (_SET["open"] or _VOL["open"] or _STERLING["open"]
                or _REQ_CARD["open"] or _PAT_CARD["open"]) \
                and (login_up or SLEEPING.exists() or deaf_now()
                     or LOCKED.exists()
                     or COUNT.exists() or SCENE.exists()
                     or SCENE_DATA.exists()):
            _settings_close("pre-empted by another screen")
            if _VOL["open"]:
                _VOL["open"] = False
                print("volume: closed (pre-empted by another screen)",
                      flush=True)
            if _STERLING["open"]:
                _sterling_set(False, "pre-empted by another screen")
            if _REQ_CARD["open"]:
                _requests_card_set(False, "pre-empted by another screen")
            if _PAT_CARD["open"]:
                _patients_card_set(False, "pre-empted by another screen")

        # SLEEP outranks everything, the brick included. The screen shows
        # the EMBER at the same ~2 fps it used to show black at — the ears
        # live on the RTX, not here, so the only jobs are watching for the
        # file to vanish (the conductor removes it remotely when someone
        # talks to Aura) and for a finger (the input pass ABOVE this
        # branch feeds handle_tap, which removes it). Both wake paths are
        # untouched by the ember and still land within ~0.5s.
        #
        # The cadence WAS 0.5s and this comment used to forbid raising it.
        # It is now EMBER_FRAME_S — see the constant for the measurement and
        # the trade. Short version: 13 frames per breath is arithmetically
        # a fade and visually a slideshow, and the owner saw the steps.
        if SLEEPING.exists():
            if not _SLEEP["asleep"]:
                _SLEEP["asleep"], _SLEEP["tap_woke"] = True, False
                # INHERIT THE FACE'S ORIENTATION. Going dark must not
                # silently re-zero the room's idea of which way is up.
                _SLEEP["view_deg"] = rot.deg % 360.0
                _SLEEP["view_prev_ang"] = None
                _EMBER["minute"] = None       # force a clock rebuild
                _EMBER["warned"] = False
                # The number here is MEASURED and has been wrong before: it
                # still read "L=11" through two deliberate raises, so the
                # log was quoting a brightness the screen had not used since
                # the day he first said he could not see it.
                print("sleep: ember on (amber core L=109 -> indigo rim, "
                      "trough L=60, 0.15Hz breath)", flush=True)
            # THE DJ SPIN, ON THE EMBER. Same call every other mode makes.
            if rot.dragging:
                _orient_drag(_SLEEP, rot)
            else:
                _SLEEP["view_prev_ang"] = None
            try:
                blit(_apply_view(_ember_frame(now), _SLEEP["view_deg"]))
            except Exception as e:
                # Falling back to black is the OLD behaviour, so it must
                # announce itself or it reads as "the ember never shipped"
                # — once per sleep, not 2/s for eight hours.
                if not _EMBER["warned"]:
                    _EMBER["warned"] = True
                    print(f"sleep: ember failed {e!r} — black", flush=True)
                try:
                    blit(Image.new("RGB", (SIZE, SIZE), 0))
                except Exception as e2:
                    print(f"blit: {e2!r}", flush=True)
            # A BREATH IS SLOW; A FINGER IS NOT. EMBER_FRAME_S is sized for
            # the 0.15Hz fade, and tracking a drag at 6.7fps feels broken
            # even when the arithmetic is right — the same "visually a
            # slideshow" the constant's own note warns about, one gesture
            # later. While a finger is down the loop runs at the active
            # rate and drops back the moment it lifts.
            time.sleep(1.0 / ACTIVE_FPS if rot.dragging else EMBER_FRAME_S)
            continue
        if _SLEEP["asleep"]:
            _SLEEP["asleep"] = False
            if not _SLEEP["tap_woke"]:
                print("sleep: woken remotely", flush=True)
            _SLEEP["tap_woke"] = False

        # Instant chime flag — checked every frame, on every screen.
        if CHIME_FLAG.exists():
            try:
                CHIME_FLAG.unlink()
                # pw-play mixes: the chime rides OVER whatever is playing
                # instead of fighting it for an exclusive device.
                _spawn_player(
                    ["pw-play", CHIME_WAV], env=_PW_ENV,
                    stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                print("chime: local, instant", flush=True)
            except Exception:
                pass
        audio_tick()
        _settings_reload_if_dictated()
        # THE DEAF FACE outranks every other screen: a red, deaf puck does
        # nothing else until a finger wakes it (handle_tap → lock screen).
        # The voice mute IS the same deafness — one state, one red face.
        if deaf_now():
            k = 0.5 + 0.5 * math.sin(now * math.tau / 3.4)
            try:
                #: ── AND IT TURNS (2026-08-17) ────────────────────────────
                #: Owner: "the mute screen still does not rotate when i try
                #: rotate it." It could not: this branch blits the brick
                #: frame straight to the panel and never applied rot.deg —
                #: the ONE screen on the device with no rotate in its path.
                #: Not the lock screen's fault (that one rotated and had
                #: nothing with an orientation to show for it); this is the
                #: simpler thing, a missing transform.
                #:
                #: Same expression as everywhere else — `-rot.deg if INVERT`
                #: — because a screen that turns the other way from the rest
                #: of the device is worse than one that does not turn.
                _bf = _brick_frame(k)
                if rot.deg > 0.05:
                    _bd = -rot.deg if INVERT else rot.deg
                    _bf = _bf.rotate(_bd, resample=Image.NEAREST,
                                     fillcolor=(0, 0, 0))
                blit(_bf)
            except Exception:
                pass
            time.sleep(1.0 / 8.0)
            continue

        # Login sequence: the voice-print theatre, above everything else —
        # it is short and the conductor removes the file when done.
        if LOGIN.exists():
            try:
                spec = json.loads(LOGIN.read_text())
                # Mid-unlock the scan belongs over the starfield, not the
                # home face the user hasn't earned yet.
                backdrop = (lock_img if (LOCKED.exists() and lock_img is not None)
                            else layers.base if layers.base is not None
                            else Image.new("RGB", (SIZE, SIZE), (5, 6, 12)))
                frame = render_login(backdrop, spec, now)
                a = (now * SWEEP_DPS) % 360.0
                frame = ImageChops.screen(
                    frame, sweep.rotate(-a, resample=Image.NEAREST))
                # The gesture was unlocked this morning but the CANVAS
                # never turned — rot.deg moved while the ceremony drew
                # upright ("still cannot rotate the authentication part",
                # owner, 10:03, second report). Paint follows the dial —
                # with the INVERT convention every other screen uses, or
                # the ceremony turns against the finger.
                if rot.deg > 0.05:
                    _dg = -rot.deg if INVERT else rot.deg
                    frame = frame.rotate(_dg, resample=Image.BILINEAR,
                                         fillcolor=(0, 0, 0))
                blit(frame)
            except Exception:
                pass                      # half-written; next tick
            time.sleep(1.0 / 12.0)
            continue

        # Lock screen: deep space, her name, twinkling. Below login/scenes/
        # countdown in priority — those are all things a locked system may
        # legitimately be doing mid-unlock.
        if LOCKED.exists() and not (SCENE_DATA.exists() or SCENE.exists()
                                    or COUNT.exists()):
            if lock_img is None and LOCK_IMG.exists():
                try:
                    lock_img = (Image.open(LOCK_IMG).convert("RGB")
                                .resize((SIZE, SIZE)))
                except Exception:
                    lock_img = None
            was_locked = True   # the unlock that follows earns the entrance
            if AURORA_BLOB:
                #: ── THE DOOR IS THE SAME OBJECT (2026-08-17) ─────────────
                #: The lock screen wore a baked bitmap starfield from
                #: another face — and it is the FIRST thing anyone sees, at
                #: every demo, before a word is spoken. So it gets the same
                #: sky, the same bezel and the same corona as the unlocked
                #: face, only quieter: the eye is dimmed to a coal and the
                #: HUD never appears. Unlocking should feel like the room
                #: coming up, not like a different program starting.
                frame = _aurora_ground(now).copy()
                #: 0.24, not 0.42: at 0.42 the corona was brighter than the
                #: wordmark laid over it and AURAVISION stopped being
                #: readable — the one thing this screen must do.
                draw_aurora_core(frame, now, rot_deg=rot.deg, dim=0.24)
            elif LOCK_FACE:
                #: ── THE DOOR IS THE SAME OBJECT, FOR EVERY FACE ────────
                #: (2026-08-26) Owner, on the pearl puck: "create a pearl
                #: specific unlock screen, right now it's the same old
                #: black one that doesn't jive with the new face. they
                #: should be consistent."
                #:
                #: The 2026-08-17 note two branches up already made this
                #: argument and made it only for aurora: the lock screen is
                #: the FIRST thing anyone sees, at every demo, before a
                #: word is spoken, and unlocking should feel like the room
                #: coming up rather than like a different program starting.
                #: gallery never got it, so a plaster dial was sitting
                #: behind a deep-space starfield from another face.
                #:
                #: So the door is the dial: the theme's own baked ground,
                #: quieted. No wedges, no HUD, nothing live — the same
                #: object, asleep.
                #:
                #: refresh() HERE, not only below: layers.refresh() is
                #: called further down in the unlocked path, which this
                #: branch never reaches (it ends in `continue`). Without
                #: this the first locked frame after a restart has no base
                #: at all — which is the state the puck boots into.
                layers.refresh()
                _lb = getattr(layers, "base", None)
                if _lb is None:
                    base_l = lock_img if lock_img is not None \
                        else Image.new("RGB", (SIZE, SIZE), (4, 5, 12))
                    frame = render_lock(base_l, stars, now)
                else:
                    frame = _lb.convert("RGB")
                    #: a slow breath on the dim so the face is ASLEEP
                    #: rather than switched off — 12 s, well under the eye's
                    #: threshold for noticing a cycle, which is the point.
                    #: ASLEEP IS NOT "TURNED DOWN". A straight multiply
                    #: took the plaster to a muddy grey — the dial did not
                    #: look at rest, it looked badly exposed. A face goes
                    #: quiet by losing CONTRAST, not brightness: flatten
                    #: toward the dial's own mid tone so the marks recede
                    #: while the ground stays the colour it is, then settle
                    #: it a little. On a dark row the same two numbers do
                    #: the right thing from the other side.
                    _st = frame.resize((1, 1)).getpixel((0, 0))
                    _flat = Image.new("RGB", frame.size, _st)
                    frame = Image.blend(frame, _flat, LOCK_FACE_FLAT)
                    _k = LOCK_FACE_DIM + LOCK_FACE_BREATH * (
                        0.5 + 0.5 * math.sin(now * math.tau / 12.0))
                    frame = frame.point(lambda v, _k=_k: int(v * _k))
            else:
                base_l = lock_img if lock_img is not None \
                    else Image.new("RGB", (SIZE, SIZE), (4, 5, 12))
                frame = render_lock(base_l, stars, now)
            if ENROLL_CATS.exists():
                frame = draw_cats(frame, now)
            # THE WORDMARK LIVES ON THIS SCREEN TOO, and for the same
            # reason the caption below does: the locked branch ends in
            # `continue`, so the home-face compose — where draw_wordmark is
            # called — is never reached. The owner looked at a locked puck
            # and reported "i still don't see the VISION on my lock screen",
            # which was exactly right: render_lock draws a backdrop and
            # stars and nothing else, and never has.
            #
            #: ── AND IT TURNS NOW (2026-08-17) ────────────────────────────
            #: It used to be drawn AFTER the rotate, so it stayed level
            #: whatever the dial did. That reads as a bug from the chair:
            #: the sky and the corona are very nearly rotationally
            #: symmetric, so the wordmark was the ONLY thing on this screen
            #: with an orientation, and holding it level meant turning the
            #: dial changed nothing anyone could see. Owner: "the lock
            #: screen itself doesn't rotate. there was always this
            #: invariant we had put into the design principles that every
            #: screen must allow rotation."
            #:
            #: So it moved above the rotate. The trade is real and is the
            #: right way round: a lock screen is not a reading surface, it
            #: is the FACE of the object, and turning the object should
            #: turn its face toward whoever you turned it for.
            draw_comets(frame, now)
            draw_wordmark(frame, now)
            #: ── THE SENTENCES TURN WITH THE CIRCLE (2026-08-18) ─────────
            #: Owner, twice: "the rotation for the unlock screen is still
            #: off the circle moves but the sentences do not move in
            #: tandem. i thought we made this an invariant."
            #:
            #: He is right, and the invariant is the one quoted eight lines
            #: above — every screen must allow rotation. The wordmark was
            #: moved above the rotate to satisfy it and the hints were left
            #: below, so the object turned and its captions stayed nailed
            #: to the glass. Half a screen rotating is worse than none: it
            #: reads as a bug rather than as a decision, because the two
            #: halves visibly disagree.
            #:
            #: The old reasoning was "an instruction upside down is worse
            #: than none", and it is a real cost he is now choosing to pay.
            #: It is also smaller than it sounds — the dial rests near
            #: level and these lines sit with the circle they belong to.
            #: Same call, above the rotate.
            draw_lock_hint(frame, now)
            #: ...and, when something is actually wrong, one more line under
            #: them. This is the screen a puck that nobody has unlocked sits
            #: on all day — Bob's spent twelve hours here while deaf — so it
            #: is the single most important place on the device for this to
            #: appear. Turns with the hints, for their reason: half a screen
            #: rotating reads as a bug. No SETTINGS pointer behind a locked
            #: door; see draw_health_mark.
            draw_health_mark(frame, now, where="lock")
            if rot.deg > 0.05:
                _dgl = -rot.deg if INVERT else rot.deg
                frame = frame.rotate(_dgl, resample=Image.NEAREST,
                                     fillcolor=(0, 0, 0))

            # Enrollment runs over the starfield, so the stage caption
            # has to live on THIS screen too — the home-face copy below
            # would never be reached. After the rotate, so the words
            # stay level whatever the dial is doing.
            stage = _enroll_stage()
            if stage:
                frame = draw_enroll_caption(frame, stage, now)
            # The ceremony happens HERE, at the lock screen, to somebody the
            # device has never met — so the progress ring has to be on this
            # branch or a retail user never sees it at all.
            #: _enroll_ring_state, not _enroll_state: the ring now covers the
            #: whole ceremony including the seconds before the first sample,
            #: which on this screen is most of what a stranger ever sees.
            _est = _enroll_ring_state(now)
            if _est:
                draw_enroll_ring(frame, _est, now)
            # The acknowledgement outranks the gauge: while she is actually
            # working on what you just said, that is the more urgent fact.
            if _pulse_active(now):
                draw_thinking_sweep(frame, now)
            blit(frame)
            spare = 1.0 / 10.0 - (time.time() - now)
            if spare > 0:
                time.sleep(spare)
            continue
        lock_img = lock_img if LOCKED.exists() else None

        # Pre-show countdown: the unveil. Runs beneath scene mode in
        # priority so the handover (countdown removed, scenes pushed) is
        # seamless. Digits + heartbeat render locally at ~8 fps; the same
        # drag physics rotate it toward whoever is watching.
        if not SCENE_DATA.exists() and not SCENE.exists() and COUNT.exists():
            try:
                m = COUNT.stat().st_mtime
                if scene_mtime != ("count", m):
                    target = float(json.loads(COUNT.read_text())["target"])
                    pre_backdrop = (Image.open(PRESHOW_BASE).convert("RGB")
                                    .resize((SIZE, SIZE))
                                    if PRESHOW_BASE.exists()
                                    else Image.new("RGB", (SIZE, SIZE), (5, 6, 12)))
                    scene_mtime = ("count", m)
            except Exception:
                time.sleep(0.3)
                continue
            remaining = int(max(0.0, target - now))
            frame = render_countdown(pre_backdrop, remaining, now % 1.0)
            a = (now * SWEEP_DPS) % 360.0
            frame = ImageChops.screen(
                frame, sweep.rotate(-a, resample=Image.NEAREST))
            if rot.deg > 0.05:
                dg = -rot.deg if INVERT else rot.deg
                frame = frame.rotate(dg, resample=Image.NEAREST,
                                     fillcolor=(0, 0, 0))
            blit(frame)
            budget = 1.0 / (ACTIVE_FPS if rot.moving else 8.0)
            spare = budget - (time.time() - now)
            if spare > 0:
                time.sleep(spare)
            continue

        # Briefing scene mode — the movie path. While the conductor keeps
        # scene layers on disk it owns the screen: new scenes crossfade in,
        # the data marks wipe into existence, the whole slide drifts on a
        # slow zoom and the sweep orbits. The SAME touch physics apply, so
        # a viewer drags the slide to face wherever they stand around the
        # puck (owner ask, live). Taps abort (see handle_tap).
        if SCENE_DATA.exists() or SCENE.exists():
            try:
                src = SCENE_DATA if SCENE_DATA.exists() else SCENE
                m = src.stat().st_mtime
                if scene_mtime != m:
                    if src is SCENE_DATA:
                        nb = (Image.open(SCENE_BASE).convert("RGB")
                              .resize((SIZE, SIZE)))
                        nd = (Image.open(SCENE_DATA).convert("RGB")
                              .resize((SIZE, SIZE)))
                    else:
                        nb = (Image.open(SCENE).convert("RGB")
                              .resize((SIZE, SIZE)))
                        nd = None
                    prev_composite = scene_img   # for the crossfade
                    scene_base, scene_data = nb, nd
                    scene_born = now
                    scene_mtime = m
            except Exception:
                pass                      # half-written; next tick
            if scene_base is not None:
                age = now - scene_born
                frame = scene_base
                # Ken Burns drift: a slow zoom-out over the scene's life.
                k = min(1.0, age / DRIFT_S)
                pad = int(DRIFT_SPAN * (1.0 - k))
                if pad > 0:
                    frame = (frame.crop((pad, pad, SIZE - pad, SIZE - pad))
                             .resize((SIZE, SIZE)))
                if scene_data is not None:
                    r = min(1.0, age / REVEAL_S)
                    r = 1.0 - (1.0 - r) ** 3          # ease-out
                    w = int(SIZE * r)
                    d = scene_data
                    # breath after the reveal completes
                    if r >= 1.0:
                        g = 0.86 + 0.14 * math.sin(age * 1.6)
                        d = d.point(lambda p, kk=g: int(p * kk))
                    if w < SIZE:
                        mask = Image.new("L", (SIZE, SIZE), 0)
                        mask.paste(255, (0, 0, w, SIZE))
                        d = Image.composite(d, Image.new("RGB", (SIZE, SIZE), 0), mask)
                    frame = ImageChops.screen(frame, d)
                # Named-director pulse: a warm ring breathing around the
                # portrait she is talking about right now.
                if HIGHLIGHT.exists():
                    try:
                        hl = json.loads(HIGHLIGHT.read_text())
                        # Preferred: a timed schedule — ONE director at a
                        # time, the ring handing over as she reaches each
                        # name (owner: "the first one disappears and then
                        # the pulsing circle goes to the next one").
                        # Legacy {"names","until"} still honoured.
                        active = []
                        for e in hl.get("schedule", []):
                            if float(e["from"]) <= now < float(e["to"]):
                                active.append(e["name"])
                        if not active and now < float(hl.get("until", 0)):
                            active = hl.get("names", [])
                        if active:
                            d2 = ImageDraw.Draw(frame)
                            # slower breath — 0.6 Hz, calm not frantic
                            ph = 0.5 + 0.5 * math.sin(now * math.tau * 0.6)
                            pr = 92 + 10 * ph
                            v = int(140 + 100 * ph)
                            for nm in active:
                                pos = DIRECTOR_POS.get(nm)
                                if pos:
                                    d2.ellipse([pos[0] - pr, pos[1] - pr,
                                                pos[0] + pr, pos[1] + pr],
                                               outline=(v, int(v * 0.75),
                                                        int(v * 0.2)),
                                               width=6)
                    except Exception:
                        pass
                a = (now * SWEEP_DPS) % 360.0
                frame = ImageChops.screen(
                    frame, sweep.rotate(-a, resample=Image.NEAREST))
                # NO extra rotate here: the INVERT-aware rotate a few
                # lines down already turns the scene, and a second one
                # added this morning spun the OPPOSITE way — they
                # cancelled exactly, freezing the slide under the finger
                # ("world briefing slide, i cannot rotate it", 10:05).
                if prev_composite is not None and age < XFADE_S:
                    frame = Image.blend(prev_composite, frame, age / XFADE_S)
                # BEFORE the rotate: the verbs belong to the SLIDE's frame
                # — drawn after, they sat screen-level while the slide
                # faced the asker, reading as "strangely diagonal to the
                # ask me anything text" (owner, 12:58, mid-question).
                frame = draw_thinking(frame, now)
                # THE EXIT PROMPT, after a first tap (see SCENE_EXIT_HINT).
                # Drawn BEFORE the rotate so it turns with everything else,
                # and it expires on the same 1.2s the double-tap allows —
                # so the prompt is on screen exactly while a second tap
                # would still count, and never a moment longer.
                try:
                    _h = SCENE_EXIT_HINT.stat().st_mtime
                    if time.time() - _h <= SCENE_EXIT_HINT_S:
                        _hd = ImageDraw.Draw(frame, "RGBA")
                        _hf = face("label", 26)
                        _ht = "TAP AGAIN TO EXIT"
                        _hw = track_len(_hd, _ht, _hf, 6.0)
                        _hd.rounded_rectangle(
                            [SIZE / 2 - _hw / 2 - 26, 904,
                             SIZE / 2 + _hw / 2 + 26, 966],
                            radius=31, fill=(6, 8, 14, 214),
                            outline=(226, 234, 248, 150), width=2)
                        track_text(_hd, (SIZE / 2 - _hw / 2, 922), _ht,
                                   _hf, (235, 241, 252), 6.0)
                except OSError:
                    pass
                if rot.deg > 0.05:
                    dg = -rot.deg if INVERT else rot.deg
                    frame = frame.rotate(dg, resample=Image.NEAREST,
                                         fillcolor=(0, 0, 0))
                scene_img = frame if age >= XFADE_S else scene_img
                blit(frame)
            budget = 1.0 / (ACTIVE_FPS if rot.moving else SCENE_FPS)
            spare = budget - (time.time() - now)
            if spare > 0:
                time.sleep(spare)
            continue
        if scene_mtime is not None:
            scene_mtime = None            # scene ended: force a face repaint
            scene_img = scene_base = scene_data = prev_composite = None
            layers.mtimes.clear()

        # The frame clock starts here, not in _ph: the previous frame
        # ended with a sleep and a segment that swallowed it would be
        # the biggest number in the report and mean nothing.
        _PH["t"] = time.time()
        layers.refresh()
        if layers.base is None:
            time.sleep(0.25)
            continue
        # ── A FINISHED BAKE TAKES NO STAMPS (2026-08-22) ─────────────────
        # BAKE_FINAL's note has the argument: every pass in this block
        # samples the bake for bright ink, and a light theme-shipped base
        # is bright ink wall to wall. One gate, here, so the next stamp
        # added to this block inherits it instead of re-learning the
        # chopard's night.
        if BAKE_FINAL:
            if not _BAKE_FINAL_SAID:
                _BAKE_FINAL_SAID.append(True)
                print(f"bake: {FACE_THEME} base is theme-shipped and final "
                      f"— all bake stamps stand down", flush=True)
        # THE GROUND, first of the stamps and only on a theme that asks for
        # one: the tapisserie is re-surfaced as a carbon weave before anything
        # samples or covers it (see _carbon_weave_sync for the ordering).
        if not BAKE_FINAL:
            _carbon_weave_sync(layers)
        # ...and the RM ghost train, on a row that asks for one. Beside the
        # weave and for the same reasons: both re-surface the GROUND, both
        # must land before anything samples or covers it, and the two are
        # mutually exclusive in practice (carbon is the ferrari's ground,
        # gears are the patek's) though nothing here enforces that — a row
        # asking for both would simply get a weave with gears behind it.
        _gear_train_sync(layers)
        # ...and the wedge captions get their relief. AFTER the two ground
        # passes: both re-surface the field the captions sit on, and a
        # relief pair stamped before them would be re-surfaced away.
        if not BAKE_FINAL:
            _wedge_type_sync(layers)
            # The $LEDGER figures ride in the corner of the still they
            # belong to, so they are read when the still lands and never
            # again — and the numeral's cover is sampled from that same
            # picture (see _ledger_sync).
            _ledger_sync(layers.base,
                         layers.mtimes.get("base")
                         or layers.mtimes.get("legacy"))
            # The RESERVE's pocket depth rides the same fresh bake — after
            # _ledger_sync on purpose; see the note at _RES_DEPTH.
            _pocket_depth_sync(layers)
            # The machined SLEEP/POWER caps ride it too, and sample their
            # engraving stencil off the pristine disc ink before covering it.
            _btn_machine_sync(layers)
        # ── AND THE TRAIN TURNS LAST OF ALL ──────────────────────────────
        # Dead last on purpose. The tick repaints six boxes of GROUND, so
        # it must run after every pass that stamps something into them or
        # it spends four ticks a second erasing their work — which is
        # exactly what it did to the machined SLEEP and POWER caps for the
        # twelve minutes this was live in the wrong place. The 23-tooth
        # wheel's box is 180px at (232,690), and that is where they live.
        _gear_train_tick(layers, now)

        # The deferred wedge open: a tap asked for a mode, the bolt got its
        # moment, now the mode arrives. Checked every frame, before compose,
        # so the very next painted frame is the new screen.
        open_pending(rot)

        # -- compose ------------------------------------------------------
        #
        # THE COMPOSE-LOOP RULES — 2026-08-07, permanent. Touch is serviced
        # once per frame, so a saturated loop is mushy fingers: dj_face hit
        # 98.7% CPU at idle and five of six gdb stack samples landed in
        # ImagingFill2 — full 1080x1080 layers allocated and cleared every
        # frame. Twelve passes had each added one "cheap" full-size
        # Image.new; together they were the whole budget.
        #   1. NO Image.new OF FRAME SIZE inside this loop or anything it
        #      calls per frame. Scratch layers are allocated ONCE and
        #      reused, or an effect draws into a small per-effect bounding
        #      box — never a full canvas.
        #   2. ANYTHING STATIC GETS BAKED ONCE — rendered at startup (or
        #      RTX-baked) and pasted per frame, never re-rendered live.
        #      The embossed AURA (_aura_embossed) is the worked example.
        _ph("bakesync")
        frame = layers.base
        if AURORA_BLOB:
            #: the aurora face owns its ground whole: no bake, no ocean —
            #: the drifting field and the core are the only light on it.
            frame = _aurora_ground(now).copy()
        else:
            # The ocean lives under everything: swell first, marks on top.
            frame = ImageChops.screen(frame, ocean_overlay(now))
        # ── ONE FRESH CANVAS, NOT TWO (2026-08-12) ───────────────────────
        # The requirement below is real and unchanged: layers.base is the
        # cached still, and everything under this line — ledger, comets,
        # rings, the rotated wordmark — paints LIVE. Anything burnt into
        # layers.base is one frame's state, forever.
        #
        # But an unconditional `frame = frame.copy()` used to follow the
        # screen above, and ImageChops.screen ALREADY returns a new image.
        # So the copy duplicated 1080x1080 RGBA to protect a buffer we were
        # no longer holding — measured at roughly 10 ms of a 61 ms frame,
        # every frame, since the ocean went in.
        #
        # Written as an identity test rather than deleted, because the
        # premise is exactly the kind that stops being true quietly: make
        # the ocean skippable the way rings and bolt now are, and `frame` is
        # layers.base again. Then this line notices and copies, instead of
        # corrupting the cached still one frame's colour at a time (§1 — the
        # silent version of this bug is unrecoverable and invisible).
        if frame is layers.base:
            frame = frame.copy()
        # THE DIAL'S SKY, under everything live-drawn and over the baked
        # dial. Screened from its own cached tile inside its own box, so it
        # costs one 712px crop-and-screen a frame and nothing else — see
        # dial_sky() for why it is baked and why it stops at the wedge ring.
        _ph("ocean+copy", frame)
        if not _THEME.get("no_sky"):
            _sky_tile, _sky_box = dial_sky()
            frame.paste(ImageChops.screen(frame.crop(_sky_box), _sky_tile),
                        _sky_box[:2])
        # draw_clock lived here until 2026-08-07 — retired with its pill
        # (the headstone is at CLOCK_BOX). The time is drawn inside the
        # moonphase register now, by _moon_register, so draw_moonphase
        # below carries it.
        # The counter, over its own baked figure — the clock's arrangement,
        # one complication down the dial. BEFORE desertify, so it wears the
        # colourway's rose gold like every other ambient element; its reserve
        # LIGHT is drawn after, where meaning is allowed its own colour.
        # 2026-08-08 premium pass: this call is the COVER and the step
        # machinery only — the figure itself is applied blue-steel now and
        # is laid by draw_ledger_figure on the far side of the colourway,
        # beside the gold strikes (the split note is on draw_ledger).
        _ph("sky", frame)
        if not AURORA_BLOB:
            draw_ledger(frame, now)
        #: ── 2026-08-12: A SHOOTING STAR IS A BLACK SCRATCH ON AN OPALINE ──
        #: The fourth theme-polarity bug of the night, and the one that took
        #: longest to catch because it is TRANSIENT — it was in the 02:29
        #: capture and gone from the 02:36 one, so every static measurement
        #: said "nothing there" while the owner would have seen a scratch
        #: crossing his mother's dial roughly every 26 seconds (PRINCIPLES §5:
        #: the instrumentation was incomplete, not the observation wrong).
        #:
        #: COMET_HEAD (236,246,255) and COMET_TAIL (90,150,235) are painted
        #: OPAQUE, not screened, and they were chosen against a near-black
        #: dial. The tail's luminance is 158 against an opaline ground of 239,
        #: so on her face the comet is DARKER than the sky it crosses, and the
        #: duotone then renders it as a near-black taper. It is a shooting
        #: star everywhere else and a hairline scratch here.
        #:
        #: SUPPRESSED, not recoloured. MINIMAL's whole argument is that a
        #: theme system which can only change colours will always hand this
        #: dial somebody else's furniture — and a comet across a ladies'
        #: Happy Sport is exactly that, at any brightness.
        if not MINIMAL and not _THEME.get("no_comets"):
            draw_comets(frame, now)
        # draw_wordmark(brand=True) lived here until 2026-08-07 amendment 2
        # — the wordmark is APPLIED GOLD now (see AURA_INK) and gold on this
        # side of desertify() arrives as the dial's blue, so the call moved
        # below the colourway, beside the moonphase and the tourbillon.
        # Also on the home face: a second person can enrol while the puck is
        # already unlocked for someone else, and that ceremony deserves the
        # same evidence the first one gets.
        _est = _enroll_ring_state(now)
        if _est:
            draw_enroll_ring(frame, _est, now)
        # ── 2026-08-06: THE SWEEP IS OFF THE ROYAL OAK FACE ────────────────
        # Owner, by voice: "DELETE THE INDICATOR RING. The thin circle with
        # the travelling dot around the circumference — the live gauge band —
        # costs a whole annulus to say something the BEZEL can say for free
        # ... it removes a rotating element nobody reads."
        #
        # The call is gone from THIS branch only. "She is working" is not
        # deleted, it MOVES: the tourbillon cage at the centre turns while
        # _pulse_active and rests when it is not, which is the same fact in
        # the place the owner asked for it ("if the cage is spinning she is
        # thinking, and if it is still she is not"). The LOCK screen keeps
        # its sweep — that screen is a starfield with no bezel and no cage on
        # it, so deleting it there would delete the signal outright with
        # nothing to carry it (§1), and the brief was about this face.
        # ══ A SCRIM THAT THREE COMPLICATIONS ARE PAINTED OVER (2026-08-11)
        # Owner, looking at a briefing on the glass: "the complications
        # still overshadow the briefing ... it's unreadable."
        #
        # draw_briefing has laid a scrim disc over the dial since it was
        # written, and it works. What it cannot do is defend itself from
        # everything drawn AFTER it — and draw_room, draw_moonphase and the
        # centrepiece all are, several hundred lines below. On the frame he
        # snapshotted: the tourbillon sat on the Ukraine headline, the
        # moonphase on the Mangione one, ROOM/PAUL on the Trump one, and the
        # rings' copper arcs crossed all five.
        #
        # A scrim is only as good as the LAST thing painted, so the fix is
        # not a darker scrim — it is that a face showing a briefing stops
        # drawing the instruments it is covering. They come straight back
        # when the card goes.
        _ph("ledger", frame)
        _card = _briefing_card(now)
        if _card:
            frame = draw_briefing(frame, _card, now)
        _ph("card", frame)
        #: ── THE BAKED LAYERS BELONG TO THE WATCH FACES (2026-08-17) ──
        #: Owner: "after expanding the eye did the perceived frame rate go
        #: down it seems halting again". It had: compose went 31 -> 48 ms of
        #: a 56 ms budget, and the new cost was not the eye at all — the
        #: `centre` timer was unchanged at ~19 ms. It was `rings`, which had
        #: read 0.0 for weeks because /tmp/aura_face/rings.png was empty,
        #: and gained ink when a profile copy landed at 11:52. A full-frame
        #: rotate-and-screen is 11-17 ms, every frame, for a layer the
        #: aurora face does not use: it draws its own steel, its own centre
        #: and its own menu.
        #:
        #: With the budget that tight, the pack's 18 fps and the compositor's
        #: 17.8 beat against each other and the playback judders — which is
        #: what he saw. Headroom is the fix, and free headroom is the best
        #: kind: base, rings and bolt are all skipped on this face now.
        #: `no_rings` (2026-08-22): the rings layer is a SCREENED overlay,
        #: light by construction, so on a light theme a stale
        #: /tmp/aura_face/rings.png from a previously worn face would ride
        #: over the plaster invisibly-in-the-log — the polarity family
        #: again, one layer up.
        if layers.rings is not None and not _card \
                and not layers.rings_empty and not AURORA_BLOB \
                and not _THEME.get("no_rings"):
            a = (now * RINGS_DPS) % 360.0
            # NOT CROPPED, AND THE ATTEMPT IS WORTH RECORDING. Screening
            # only the rings' ink box would save ~8.9 ms and it is NOT
            # equivalent: rotating a centred crop about its own centre came
            # out up to 62 levels different from rotating the full frame and
            # cropping, at every angle that is not a multiple of 180. The
            # argument that it must be identical — same centre, ink inside
            # the inscribed circle — is wrong somewhere, and a rendering
            # difference of 62 is not a rounding artefact. Measured, not
            # assumed; see the bolt below, where the same idea IS exact
            # because nothing rotates.
            frame = ImageChops.screen(
                frame, layers.rings.rotate(-a, resample=Image.NEAREST))
        _ph("rings", frame)
        if layers.bolt is not None and not layers.bolt_empty \
                and not _THEME.get("no_bolt") and not AURORA_BLOB:
            g = bolt_gain(now)
            # Tap-ack surge (round 2): a wedge tap flares the bolt to
            # several times its breath and it decays over ~0.6s — the
            # acknowledgment that buys spool time. The ordinary flicker
            # continues underneath, untouched.
            st = (now - _BOLT_SURGE[0]) / BOLT_SURGE_S
            if 0.0 <= st < 1.0:
                g += BOLT_SURGE_GAIN * (1.0 - st) ** 2
            # The quantisation was here and was doing nothing: `gq` was
            # computed, compared, and assigned, and then the point() ran
            # unconditionally anyway. A memoisation somebody started and
            # never wired up — measured at 3.0 ms of every frame on the
            # panel, thrown away (2026-08-06).
            #
            # Scaling by gq/24 rather than by g is what makes the cache
            # honest: the pixels must correspond to the key they are filed
            # under, or a held frame is a fraction of a step stale. At 24
            # steps that difference is below the panel's own quantisation.
            gq = round(g * 24)
            if gq != last_gain_q or bolt_lit is None:
                last_gain_q = gq
                src = layers.bolt_ink if layers.bolt_box else layers.bolt
                bolt_lit = src.point(
                    lambda p, k=gq / 24.0: min(255, int(p * k)))
            # The bolt is the narrowest layer on the face — 22% of the
            # canvas — so this is where cropping pays most: the point() and
            # the screen both shrink with it.
            if layers.bolt_box is not None:
                bx = layers.bolt_box
                frame.paste(
                    ImageChops.screen(frame.crop(bx), bolt_lit), bx[:2])
            else:
                frame = ImageChops.screen(frame, bolt_lit)
        # THE ROOM, the third of the three. Beside the moonphase and before
        # the colourway for the same reason it is: it is an instrument in the
        # dial's own steel, and nothing on it carries meaning in its colour.
        _ph("bolt", frame)
        if not _card and not MINIMAL:
            draw_room(frame, now)
        # THE COLOURWAY (amber, since 2026-08-05; beige before it). Here and
        # not later: everything above is the ambient face and
        # takes the colourway; everything below carries MEANING in its colour
        # — the REQUESTS wedge's green done and red failed most of all, and
        # the palette note in PUCK-SHOW.md says outcomes are exempt from any
        # house family. A duotone applied over them would repaint a finished
        # job in the colour of a failed one.
        _ph("predial", frame)
        if not AURORA_BLOB:
            frame = desertify(frame)
        # THE ANODISED CAPS, on the colourway side because the duotone would
        # otherwise turn them grey (the whole argument is at BTN_ANODISE).
        # Two cached pastes, before the rotate so they turn with the dial.
        for _bxy, _btile in _BTN_RED:
            frame.paste(_btile, _bxy, _btile)
        # THE CASE PUSHERS — same side of the colourway for the same metal
        # reason, before the rotate so they sit in their bezel band.
        if CASE_PUSHERS:
            draw_case_pushers(frame, now)
        # THE SPRINKLED GOLD that had to wait for the duotone — the ROOM and
        # RESERVE counterpoises and the reserve's F/E, on the steel that is
        # already there (amendment 2; see draw_gold_strikes).
        if not MINIMAL:
            draw_gold_strikes(frame, now)
        # ...and the $LEDGER figure, which had to wait for the same reason
        # in the other metal: applied blue-steel (VISION's) laid before the
        # duotone would arrive as the dial's blue. Its cover and machinery
        # ran with draw_ledger above, on the colourway side.
        if not MINIMAL:
            draw_ledger_figure(frame, now)
        # THE BAKED STEEL BEZEL, on top of the colourway and never through it
        # — the whole argument is at bezel_steel(). Native 1080, pasted at
        # (0, 0), never resampled; transparent everywhere but the band, so it
        # touches nothing on the dial. Here rather than lower down because
        # draw_bezel_state lights this metal and has to land on it, and above
        # the rotate so the band turns with the face like the drawn one did.
        _ph("duotone", frame)
        _steel = None if AURORA_BLOB else bezel_steel()
        if _steel is not None:
            frame.paste(_steel, (0, 0), _steel)
        # THE MOONPHASE, and it is on THIS side of the colourway since the
        # showpiece pass — the full argument, and what it supersedes, is at
        # MOON_XY. Short version: aventurine and gold is a contrast between
        # two hues and a duotone has one. Still after the bolt (an applied
        # aperture is metal laid on the dial and the fracture is light behind
        # it) and still before the dial rotate, so it turns with the face.
        # ...and a theme may decline the moon outright (2026-08-22): the
        # gallery is not a watch, and a complication on a museum wall is
        # somebody else's furniture — the MINIMAL argument, per-theme.
        if not _card and not AURORA_BLOB and not _THEME.get("no_moon"):
            draw_moonphase(frame, now)
        # THE OPEN-WORKED CENTRE, beside the moonphase and on its side of the
        # colourway for its reasons: the aperture's lip is put through
        # _dial_metal by hand so it is the same steel as the two
        # complications either side of it, and the gold cage and the credit
        # glow are both colours that mean something. Since 2026-08-07 the
        # cage turns once a minute — it is the seconds display, and the only
        # thing on this face that moves continuously.
        # ...UNLESS AN RTX-RENDERED PACK IS INSTALLED, in which case the
        # centrepiece is a frame table and this call is skipped entirely —
        # drawing both would put a hand-drawn cage under a raymarched one.
        # HER HANDS GO ON AFTER THE CENTRE, for the reason in the note at
        # draw_chopard_hands: the stones are the chamber and the hands sweep
        # over it, as they do on the watch.
        if AURORA_BLOB:
            if not _card:
                #: the eye recedes while a briefing plays, and eases back
                #: when it ends — the transition is the point, so it is a
                #: ramp and not a switch
                _shw0 = _show_now(now)
                #: ONE call per frame, here, because this is already the
                #: place that asks whether a briefing is on the glass —
                #: two places asking would be two answers (§15).
                _show_open(now, 1.0 if _shw0 is not None else 0.0)
                _wantdim = 0.30 if _shw0 is not None else 1.0
                #: ── THE DETONATION IS EXEMPT ─────────────────────────────
                #: The show dims the eye so the diagrams can be read — and
                #: that was dimming the BIG BANG too, which is the one
                #: moment the whole face is supposed to be the brightest
                #: thing in the room. The ignition overrides the dimmer
                #: for as long as its front is crossing the glass.
                _bk1 = _AUR["bang"].get("k", 0.0)
                if _bk1 > 0.0:
                    _wantdim = max(_wantdim,
                                   0.35 + 2.6 * _bk1 * (1.0 - _bk1))
                _dp = _AUR["dimph"]
                _ddt = max(0.0, min(0.5, now - (_dp["at"] or now)))
                _dp["at"] = now
                _dp["v"] += (_wantdim - _dp["v"]) * min(1.0, 1.9 * _ddt)
                #: ── SPLIT THE BIGGEST BUCKET (2026-08-19) ───────────────
                #: Owner: "people are complaining about my test videos of
                #: the puck being laggy." The pace counter said where the
                #: time goes only to the nearest 108-line block:
                #:
                #:     centre 19.2-33.8 ms   tail 7.8-18.4 ms
                #:     everything else, all twelve phases, under 2.5 ms
                #:
                #: Two coarse buckets holding all the time is not a
                #: measurement, it is a place to start guessing — and the
                #: last three optimisation attempts on this project went
                #: wrong by taking the biggest number and assuming what was
                #: inside it. Markers are free (one time.time() per frame
                #: per phase) and they turn "centre is expensive" into a
                #: line of code.
                _ph("c:pre", frame)
                draw_aurora_core(frame, now, rot_deg=rot.deg, dim=_dp["v"])
                _ph("c:core", frame)
                #: ── THE SHOW TAKES THE GLASS (2026-08-16) ────────────────
                #: A briefing beat draws OVER the core, and its first beat
                #: fires the detonation — the owner's "explodes into the
                #: briefing". The core stays underneath throughout, so the
                #: scenes read as things happening INSIDE her rather than
                #: as slides replacing her.
                _shw = _show_now(now)
                if _shw is not None:
                    if _AUR.get("show_i") != (_shw.get("i"), _shw.get("at")):
                        _AUR["show_i"] = (_shw.get("i"), _shw.get("at"))
                        if int(_shw.get("i", 0)) == 0:
                            _AUR["bang"]["t0"] = now      # ignite the show
                            print("aurora: SHOW — ignition", flush=True)
                    draw_aurora_show(frame, now, _shw, rot_deg=rot.deg)
                #: the shockwave crosses the WHOLE glass, so it is drawn on
                #: the frame rather than inside the core's own box
                draw_aurora_bang(frame, now, _AUR["bang"].get("k", 0.0))
        elif not _card and not centre_pack_paste(frame, now):
            #: a theme may name its own centrepiece; the watch faces keep
            #: the tourbillon, which is theirs and is why it was drawn.
            if CENTRE_PIECE == "disc":
                draw_disc_centre(frame, now)
            elif CENTRE_PIECE == "iris":
                draw_iris_centre(frame, now)
            elif CENTRE_PIECE == "rotor":
                draw_rotor(frame, now)
            elif CENTRE_PIECE == "ingot":     # 2026-08-27, the lacquer row
                draw_ingot_centre(frame, now)
            elif CENTRE_PIECE == "seal":      # 2026-08-27, lacquer, after
                draw_seal_centre(frame, now)  # "it's just a rectangle"
            elif CENTRE_PIECE == "stone":     # 2026-08-30, lacquer, after
                draw_stone_centre(frame, now)  # "redesign that completely"
            else:
                draw_tourbillon(frame, now)
        if not AURORA_BLOB and not _card:
            #: ── A BRIEFING TAKES THE GLASS ON ANY FACE (2026-08-17) ──────
            #: The show block above lives inside `if AURORA_BLOB`, because
            #: that is the face it was built on. Bob's puck wears FERRARI —
            #: he asked for it, on 08-16 — so the crypto briefing would
            #: have played him three and a half minutes of narration over a
            #: watch dial with no diagrams at all, which is precisely the
            #: half the owner commissioned ("can we have more graphics for
            #: a crypto related brief... push this to bob's puck").
            #:
            #: A briefing is not a property of a watch face. It is a
            #: full-screen takeover with its own art, and it belongs to
            #: whichever face happens to be worn. The ignition is aurora's
            #: own flourish and stays there; the scenes draw everywhere.
            _shw2 = _show_now(now)
            #: the aperture opens on a watch face too. There is no eye to
            #: expand there, but the SCENES still get the whole glass —
            #: which is the half of the ask that is about screen space
            #: rather than about the iris.
            _show_open(now, 1.0 if _shw2 is not None else 0.0)
            if _shw2 is not None:
                draw_aurora_show(frame, now, _shw2, rot_deg=rot.deg)
        # THE DIAL LAYOUT of the wordmark — small, under twelve, the ONE
        # call that passes brand=True (the lock screen's own call above
        # stays as it was). HERE since amendment 2: the letters are applied
        # gold (draw_numerals' shadow/face/top-facet rendering — see
        # _draw_wordmark_flat), which only survives on this side of
        # desertify(). Still before the dial rotate, so it turns with the
        # face exactly as it did from its old slot.
        if not MINIMAL:
            draw_wordmark(frame, now, brand=True)
        # THE FIVE WEDGES AS SMOKED GLASS — the pane, the red pair, the
        # sweep and the contact shadow, on an INSTR row only (the whole
        # argument, including why it cannot live in home.html or in a base
        # stamp, is at WGLASS_FILL_A). Here for the standing reason: the red
        # carries meaning so it must be on this side of the colourway, and
        # it belongs to the ring so it must be on this side of the rotate.
        # BEFORE the entrance below, so a covered wedge stays covered.
        _ph("centre", frame)
        draw_chopard_hands(frame, now)
        # Her upper-left caption. AFTER the hands only because it is never
        # under them (see CH_PROV_R), and before the wedge glass so the two
        # keep the order they have on the dial.
        draw_proverb(frame, now)
        #: ── THE SUMMONED RING (2026-08-16) ───────────────────────────────
        #: On aurora every hand-driven element — the five glass panes, the
        #: wedge tenants, the bezel state — is raised by a touch, held
        #: while it is worked, and faded back into the void after. Computed
        #: HERE because the glass is the first of them: `_aur_under` is the
        #: face without any of it, and the blend at the end of the block
        #: brings the whole ring in and out as light rather than snapping.
        #: the patek furniture never returns on this face — its own menu
        #: takes the sectors instead (draw_aurora_menu), so `_tenants` is
        #: simply false here and the aurora HUD is drawn from its own
        #: per-wedge alphas (the clockwise reveal).
        _tenants = not AURORA_BLOB
        #: aurora's HUD is drawn AFTER the dial rotate (below), because it
        #: is pinned to the screen — see the note in handle_tap. Nothing
        #: is drawn here for it.
        if _tenants:
            draw_wedge_glass(frame)
        # THE ROMAN NUMERALS ARE RETIRED — 2026-08-07, the owner, twice in
        # ten minutes: "forget the roman numerals they look tacky. get rid
        # of them" and then "gaudy gold roman numbers". They lasted under an
        # hour on the glass. draw_numerals() is kept below, unreferenced,
        # because the applied-numeral rendering (shadow, face, top facet) is
        # the only worked example of applied type on this dial and the next
        # marker design will want it. The chapter ring's engraved ticks live
        # in bezel_steel.png and stay — his words: "keep the ticks".
        if FLASH.exists():
            frame = ImageChops.screen(frame, flash_overlay(now))
        # The entrance: first home frame after an unlock starts the wedge
        # reveal. Applied AFTER the flash so a covered wedge stays covered
        # until its cue, whatever else wants to glow there.
        if was_locked and not LOCKED.exists():
            was_locked = False
            #: ── TWO ENTRANCES RAN, AND ONE OF THEM WAS THE OTHER FACE'S
            #: (2026-08-20) Owner, after the arrival flash was removed and
            #: he still saw it: "it wasn't killed, i still see the annoying
            #: INTRO WEDGES ON TOP. it needs to fade in as gracefully as
            #: normal operations do it."
            #:
            #: "On top" was the word that mattered and it took seven rounds
            #: to hear it. Everything before this was tuning
            #: draw_aurora_menu — the ring's own arrival, the thing that
            #: DOES behave in normal operation. But an unlock also started
            #: `wedge_intro`, which is the BAKED face's entrance: five
            #: black covers lifting and a border glow SCREENED over each
            #: one, throbbing at 2.6 Hz for 1.5 s (WEDGE_THROB_S). On the
            #: aurora face that is a different ring's choreography, in a
            #: different geometry, composited on top of a seven-pane ring
            #: that was already arriving underneath it.
            #:
            #: So no amount of work on the arris or the halo could have
            #: fixed it, and six reports of "the highlights are wrong" were
            #: describing a throb this code adds after the fact. The panes
            #: he was pointing at were not the panes I was measuring.
            #:
            #: On aurora the entrance is aurora_ui_show and nothing else.
            #: The baked faces keep wedge_intro exactly as it was — it is
            #: right for the ring it was written for.
            #: `no_intro` (2026-08-22): wedge_intro lifts five BLACK covers
            #: with a screened glow — dark-dial choreography that inverts
            #: on a light ground (five black sectors flashing on plaster).
            #: A theme that asks skips the entrance and simply arrives.
            if not AURORA_BLOB and not _THEME.get("no_intro"):
                wedge_t0 = now
                #: the unlock reveals them; the idle timer takes them away
                #: again. Without this the veil would still be at 1.0 and
                #: the entrance would play underneath an opaque cover.
                baked_ui_show(now)
            #: THE UNLOCK INTRODUCES THE DEVICE (2026-08-16). On aurora the
            #: ring is normally absent, so the one moment it MUST appear
            #: unasked is the moment the face opens: the wedges arrive one
            #: by one, clockwise, and then leave on the idle timer. It is
            #: the only time the controls announce themselves.
            if AURORA_BLOB:
                aurora_ui_show(now)
        if wedge_t0 is not None:
            frame, _wdone = wedge_intro(frame, now - wedge_t0)
            if _wdone:
                wedge_t0 = None
        #: the persistent veil: the entrance is a one-shot, this is the
        #: state the wedges live in afterwards. Painted AFTER the entrance
        #: so the two never fight over the same sectors on the unlock frame.
        frame = baked_ui_veil(frame, now)
        # The REQUESTS wedge. BEFORE the dial rotate, because it belongs to
        # the ring and the ring turns (docs/PUCK-STANDALONE.md §12.1); AFTER
        # the entrance, because a sixth sector arriving in the middle of the
        # five-wedge reveal steps on the choreography — it holds at zero
        # while the entrance runs and fades in afterwards on its own.
        # rot.deg goes in because OVERFLOW LIVES ON THE DIAL: the ring
        # policy uses it to decide which claimant holds the one free arc,
        # so spinning pages the slot instead of needing a new affordance.
        _ph("glass", frame)
        _ring_log(now, rot.deg)
        #: ── AURORA CLEARS THE GLASS (2026-08-16) ─────────────────────────
        #: Owner: "push functionality to voice as much as possible to clear
        #: the screen and have a clean look." The five wedge tenants — news,
        #: clinic, requests, Iran, Sterling's status — are the busiest thing
        #: on the dial and every one of them can be ASKED FOR instead. So on
        #: this face they do not paint at rest. Nothing is lost: the wedges
        #: still hit-test, the desk still opens by name, the briefing still
        #: plays when asked. What goes is the standing furniture.
        if _tenants:
            draw_requests_wedge(frame, now, hold=wedge_t0 is not None,
                                rot_deg=rot.deg)
        # The CLINIC LIST, in the same slot and strictly after it: its alpha
        # is the complement of the requests fade, so the upper left carries
        # whichever of the two is live and never both.
        if _tenants:
            draw_patients_wedge(frame, now, hold=wedge_t0 is not None,
                                rot_deg=rot.deg)
        # THE WORLD BRIEF, third in the same slot and strictly after the
        # other two: its alpha carries the complement of both their fades.
        if _tenants:
            draw_world_wedge(frame, now, hold=wedge_t0 is not None,
                             rot_deg=rot.deg)
        # THE IRAN WATCH, fourth and last in that slot: its alpha carries
        # the complement of all three, so the arc paints exactly one of
        # them and never two at once.
        if _tenants:
            draw_iran_wedge(frame, now, hold=wedge_t0 is not None,
                            rot_deg=rot.deg)
        # STERLING'S LIVE OVERLAY — his status on the wedge's own sector,
        # never a box (the owner's third ask; see STER_WEDGE_A0). After
        # desertify because the concierge gold carries meaning; before the
        # rotate so it turns with the baked tile it lights; held through
        # the entrance like the other live wedges.
        if _tenants:
            draw_sterling_wedge(frame, now, hold=wedge_t0 is not None)
        # THE CONCIERGE BREATHES — the STERLING tile's border swells gold on
        # the precomputed table (see STER_GLOW_TABLE), the only idle motion
        # among the five, holding bright while the desk is open or a request
        # runs. Before the rotate so it turns with its tile; held through
        # the entrance like the wedge overlays.
        if _tenants:
            draw_sterling_glow(frame, now, hold=wedge_t0 is not None)
        # The fuel gauge's other half: the RANGE plate and the reserve light.
        # Here rather than beside draw_ledger because a warning lamp carries
        # its meaning in its colour and must not be duotoned into the metal
        # it is warning about — the same line this file draws for the
        # REQUESTS wedge's green and red. Still BEFORE the dial rotate: it
        # belongs to the baked sub-dial and has to turn with it.
        if not MINIMAL:
            draw_reserve(frame, now)
        # THE BEZEL AS THE INSTRUMENT — what the deleted live gauge band
        # used to say, said by a progress arc on the steel ring (the eight
        # flats before it; see the dated note at BEZ_RING_R). Here for the
        # same two reasons the line above is: it carries meaning in its
        # colour (the concierge gold ladder, and green/done and red/failed
        # which the palette note exempts from any family), and it lights
        # baked metal, so it has to be painted before the frame turns or
        # the lit arc slides off its own steel.
        _ph("wedges", frame)
        if AURORA_BLOB:
            #: the clean look: no standing arcs, no baked-band furniture.
            #: The modes still open by tap and by voice; the CORE carries
            #: the listening/thinking light that the band used to.
            pass
        else:
            draw_bezel_state(frame, now)
        # THE BEZEL IS ALSO THE LISTENING INDICATOR — hearing bloom at the
        # talker's bearing, thinking comet, one gold done pulse. After the
        # standing state (a live utterance is the transient and rides over
        # it), before the rotate like everything on the baked band, and
        # handed rot.deg so a spun dial cannot point the bloom at nobody.
        if not AURORA_BLOB:
            draw_listening_ring(frame, now, rot_deg=rot.deg)
        # WHO IS IN THE ROOM — the multi-person roster, from the diarizer.
        # Default OFF (AURA_ROSTER_FACE=1 to show): built for the owner to
        # enable and direct placement at the glass, never an unreviewed
        # element on his dial (the caret lesson, FAILURES 2026-08-15).
        if _ROSTER_FACE:
            draw_room_roster(frame, now)
        # First-timer tour: the conductor names a wedge while Olga describes
        # it; its border breathes until she moves on.
        if WEDGE_TOUR.exists():
            try:
                tk = json.loads(WEDGE_TOUR.read_text()).get("key")
                ti = WEDGE_KEYS.index(tk)
                k = 0.45 + 0.4 * (0.5 + 0.5 * math.sin(now * 2 * math.pi * 1.2))
                frame = ImageChops.screen(
                    frame, _WEDGE_GLOWS[ti].point(lambda p, kk=k: int(p * kk)))
            except Exception:
                pass                          # half-written; next tick
        # Tap acknowledgment: an expanding ring from the fingertip and a
        # flare on the BRIEFING wedge, gone in under a second.
        rip_t = now - _RIPPLE[0]
        if 0.0 <= rip_t < 0.9:
            k = rip_t / 0.9
            d_r = ImageDraw.Draw(frame)
            rr = 30 + 160 * k
            v = int(210 * (1.0 - k))
            d_r.ellipse([_RIPPLE[1] - rr, _RIPPLE[2] - rr,
                         _RIPPLE[1] + rr, _RIPPLE[2] + rr],
                        outline=(int(v * 0.3), int(v * 0.85), v),
                        width=max(2, int(8 * (1.0 - k))))
            frame = ImageChops.screen(
                frame, _WEDGE_GLOWS[0].point(
                    lambda p, kk=(1.0 - k): int(p * kk)))
        # Volume mode: the drag sets the level instead of spinning the
        # dial; every detent crossing clicks. Round 2: no more activity
        # timer — the mode stays until DONE or a takeover. Each drag is
        # locked to ONE role by where it pressed: the detent ring
        # (r>=300) adjusts volume, anywhere inside orients the overlay.
        vol_up = _VOL["open"]
        set_up = _SET["open"]
        ster_up = _STERLING["open"]
        req_up = _REQ_CARD["open"]
        pat_up = _PAT_CARD["open"]
        top_up = _TOPUP["open"]
        if vol_up:
            # The dial is PINNED for the whole mode, not just mid-drag
            # (2026-08-02): a flick that ended in volume mode used to
            # hand its momentum to the face and the ring drifted away
            # from the finger that set it.
            rot.deg = _VOL["grab_deg"]
            rot.vel, rot.inertia = 0.0, False
            if rot.dragging and rot.moved >= TAP_MAX_PX:
                if _VOL["drag_role"] is None:
                    pr = math.hypot(rot.press_xy[0] - SIZE / 2,
                                    rot.press_xy[1] - SIZE / 2)
                    #: ── TURN IT FROM OUTSIDE THE RING TOO (2026-08-17) ──
                    #: Owner: "i can't rotate it. it has to accept rotation
                    #: touches past the lines otherwise it looks upside
                    #: down and you can't change it."
                    #:
                    #: The detents are drawn at r=430 and the level band
                    #: began at 300, so EVERY drag from the outer half of
                    #: the glass set the volume and only the small hub
                    #: could turn the screen. That is backwards for a
                    #: round device you pick up: the rim is where a hand
                    #: naturally lands, and turning something by its rim is
                    #: the gesture the hardware already teaches.
                    #:
                    #: Three bands now: hub orients, the detent band sets,
                    #: and PAST THE LINES orients again. The level band
                    #: keeps the whole width of the drawn ring, so nothing
                    #: that used to set the volume stops doing so.
                    #: ── A SMEARED TAP IS NOT A ROTATION (2026-08-17) ──
                    #: This is the trap he fell into, and the log drew it:
                    #:   view=-135.7 ... view=259.5 ... view=290.1
                    #: three taps, three different orientations, none of
                    #: them asked for. Reaching for DONE with a finger that
                    #: moves 30 px counted as an orient drag, the screen
                    #: turned, DONE went somewhere else, and he reached
                    #: again — "i'm trapped right now i can't even press
                    #: the wrongly oriented done button".
                    #:
                    #: TAP_MAX_PX (24) is the right threshold for "was that
                    #: a tap", and the wrong one for "did he mean to rotate
                    #: the whole screen". Turning a screen is a deliberate
                    #: sweep; 90 px of travel is still an easy gesture and
                    #: is nothing like a press that slid.
                    _VOL["drag_role"] = (
                        "ring" if VOL_SET_R0 <= pr < VOL_RIM_R
                        else ("orient" if rot.moved >= VOL_ORIENT_MIN_PX
                              else None))
                if _VOL["drag_role"] is None:
                    pass                        # still deciding: touch nothing
                #: ── THE GESTURE IS DECIDED AT TOUCH-DOWN ──────────────
                #: This used to re-check `rot.finger_r >= VOL_SET_R0` on
                #: EVERY frame of the drag, so a thumb that drifted a few
                #: pixels inward mid-sweep stopped crossing detents — no
                #: click, no volume change, and nothing said. A drag whose
                #: meaning is re-litigated per sample is not a drag, it is
                #: a sequence of unrelated touches; every other capture in
                #: this file decides once and holds (see rot's own
                #: `moved`, and the tap gate). Once the finger has taken
                #: the ring, it keeps it until it lifts.
                if _VOL["drag_role"] == "ring":
                    # Finger angle mapped into the OVERLAY's frame (its
                    # view rotation undone) — the overlay is composited
                    # after the rotate below, so no rot.deg term belongs
                    # here; the missing frame compensation was the
                    # offset the owner felt this morning.
                    raw = _detent_from_angle(
                        rot.finger_ang + _VOL["view_deg"])
                    prev = _VOL["detent"]
                    # HARD STOP at the seam (owner, round 2: "we had a
                    # hard block when you rotated clockwise at 100" —
                    # asking for one). A continuous drag only ever hops
                    # top-end<->bottom-end by crossing 12 o'clock, so
                    # that hop clamps at the end instead of wrapping
                    # 100 -> 0 (or 0 -> 100). Reversing back across the
                    # top re-engages normally.
                    if prev is not None and prev >= 10 and raw <= 2:
                        raw = 12
                    elif prev is not None and prev <= 2 and raw >= 10:
                        raw = 0
                    if raw != prev:
                        _VOL["detent"] = raw
                        _VOL["level"] = detent_pct(raw)
                        _set_volume(_VOL["level"])
                        _click()
                elif _VOL["drag_role"] == "orient":
                    # "i can't do the spin of the volume screen so it's
                    # not oriented to me" — inside the ring, the drag
                    # turns the whole overlay toward the user.
                    _orient_drag(_VOL, rot)
            else:
                _VOL["drag_role"] = None
                _VOL["view_prev_ang"] = None
        elif set_up:
            # Volume mode's pin, same reason: the settings book is
            # painted and hit-tested in raw screen coords, so a dial
            # coasting underneath would shear every target away from
            # its paint. The book itself is drawn after the rotate.
            # Round 2: rim drags (press radius >= SET_ORIENT_R) turn
            # the book toward the reader; inner drags stay page swipes
            # (handled on release, up in the event loop).
            rot.deg = _SET["grab_deg"]
            rot.vel, rot.inertia = 0.0, False
            if rot.dragging and rot.moved >= TAP_MAX_PX \
                    and math.hypot(rot.press_xy[0] - SIZE / 2,
                                   rot.press_xy[1] - SIZE / 2) \
                    >= SET_ORIENT_R:
                _orient_drag(_SET, rot)
            else:
                _SET["view_prev_ang"] = None
        elif ster_up:
            # The concierge screen: same pin, and ANY drag orients it —
            # it has no drag-driven controls of its own to collide with.
            rot.deg = _STERLING["grab_deg"]
            rot.vel, rot.inertia = 0.0, False
            if rot.dragging and rot.moved >= TAP_MAX_PX:
                _orient_drag(_STERLING, rot)
            else:
                _STERLING["view_prev_ang"] = None
        elif req_up:
            # The queue card: same pin, same orientation gesture. It has no
            # drag-driven controls of its own, so any drag turns it toward
            # whoever is reading it.
            rot.deg = _REQ_CARD["grab_deg"]
            rot.vel, rot.inertia = 0.0, False
            if rot.dragging and rot.moved >= TAP_MAX_PX:
                _orient_drag(_REQ_CARD, rot)
            else:
                _REQ_CARD["view_prev_ang"] = None
        elif pat_up:
            # The clinic card: identical treatment to the queue card. It is
            # a page you read across a desk, so any drag turns it toward
            # whoever is reading it, and the dial stays where it was left.
            rot.deg = _PAT_CARD["grab_deg"]
            rot.vel, rot.inertia = 0.0, False
            if rot.dragging and rot.moved >= TAP_MAX_PX:
                _orient_drag(_PAT_CARD, rot)
            else:
                _PAT_CARD["view_prev_ang"] = None
        elif top_up:
            # The $LEDGER offer. PINNED like the cards above, and this one has
            # to be: its slide is hit-tested in raw screen coordinates, so a
            # dial coasting underneath would shear the track away from the
            # finger dragging it — the failure volume mode's own pin was added
            # for. No orient drag: every drag on this card belongs to either
            # the slide or the tier selector below.
            rot.deg = _TOPUP["grab_deg"]
            rot.vel, rot.inertia = 0.0, False
            # TURNING THE DIAL MOVES BETWEEN TIERS (owner: "which is the
            # gesture this face already uses everywhere"). The dial stays
            # PINNED — nothing under the card may shear — so the turn is read
            # off the finger's angular travel with the same radial gain the
            # dial itself uses, and spent one TOPUP_TIER_DEG at a time.
            #
            # ONE DRAG, ONE ROLE, decided by where it PRESSED — volume mode's
            # rule, and here it is what keeps the two gestures apart: a drag
            # that started on the slide track is a slide and never a turn,
            # even when the finger arcs. The accumulator resets whenever no
            # drag owns it, so a released turn cannot bank credit toward the
            # next one.
            if rot.dragging and rot.moved >= TAP_MAX_PX \
                    and not (rot.press_xy[0] <= SLIDE_X0 + 3 * SLIDE_KNOB_R
                             and abs(rot.press_xy[1] - SLIDE_Y) <= SLIDE_H):
                _prev = _TOPUP["turn_prev_ang"]
                if _prev is not None:
                    _da = (rot.finger_ang - _prev + 540.0) % 360.0 - 180.0
                    _TOPUP["turn_acc"] += _da * Rotation._gain(rot.finger_r)
                    while abs(_TOPUP["turn_acc"]) >= TOPUP_TIER_DEG:
                        _st = 1 if _TOPUP["turn_acc"] > 0 else -1
                        _TOPUP["turn_acc"] -= _st * TOPUP_TIER_DEG
                        _topup_step(_st)
                    # AT A STOP, TRAVEL IS SPENT, NOT BANKED. Kept, it becomes
                    # a dead zone on the way back: turn hard past $100 for a
                    # second and the first degrees of coming off it would do
                    # nothing, which feels like a stuck dial rather than an
                    # end. The end must be felt going in and released at once
                    # coming out.
                    if (_TOPUP["turn_acc"] > 0
                            and _TOPUP["tier"] >= len(TOPUP_TIERS) - 1) \
                            or (_TOPUP["turn_acc"] < 0
                                and _TOPUP["tier"] <= 0):
                        _TOPUP["turn_acc"] = 0.0
                _TOPUP["turn_prev_ang"] = rot.finger_ang
            else:
                _TOPUP["turn_prev_ang"] = None
                _TOPUP["turn_acc"] = 0.0
        # -- slide-to-top-up: the power slide's twin -----------------------
        # Same track, same rule about where the gesture must START, same
        # logged outcomes. The only difference is what waits at the end of it
        # (see the TOPUP note): this one writes a request file and says so.
        if _TOPUP["open"]:
            if down and rot.press_xy[0] <= SLIDE_X0 + 3 * SLIDE_KNOB_R \
                    and abs(rot.press_xy[1] - SLIDE_Y) <= SLIDE_H:
                fx = rot.finger_xy[0]
                span = float(SLIDE_X1 - SLIDE_X0 - 2 * SLIDE_KNOB_R)
                _TOPUP["slide"] = max(0.0, min(
                    1.0, (fx - (SLIDE_X0 + SLIDE_KNOB_R)) / max(span, 1.0)))
            elif not down:
                if _TOPUP["slide"] >= SLIDE_DONE:
                    print(f"ledger: top-up slide completed "
                          f"({_TOPUP['slide']:.2f})", flush=True)
                    _TOPUP["open"] = False
                    _TOPUP["slide"] = 0.0
                    _topup_file(now)
                elif _TOPUP["slide"] > 0.02:
                    print(f"ledger: top-up slide released short "
                          f"({_TOPUP['slide']:.2f}) — cancelled", flush=True)
                    _TOPUP["slide"] = 0.0
        # Power confirm rides ON TOP of whatever card was up. Its 5s
        # expiry is a LOGGED cancel — an overlay that silently evaporates
        # leaves the user unsure what, if anything, was decided
        # (PRINCIPLES §1).
        # -- slide-to-power-off: follow the finger ----------------------
        # Runs every frame while the overlay is up. Progress is the finger's
        # x along the track, but ONLY if the gesture STARTED on the knob —
        # otherwise a tap anywhere on the right of the screen would read as a
        # completed slide, which is precisely the accident the gesture exists
        # to prevent.
        if _POWER["until"] > now:
            if down and rot.press_xy[0] <= SLIDE_X0 + 3 * SLIDE_KNOB_R \
                    and abs(rot.press_xy[1] - SLIDE_Y) <= SLIDE_H:
                fx = rot.finger_xy[0]
                span = float(SLIDE_X1 - SLIDE_X0 - 2 * SLIDE_KNOB_R)
                _POWER["slide"] = max(0.0, min(
                    1.0, (fx - (SLIDE_X0 + SLIDE_KNOB_R)) / max(span, 1.0)))
            elif not down:
                if _POWER["slide"] >= SLIDE_DONE:
                    print(f"power: slide completed "
                          f"({_POWER['slide']:.2f}) — powering down",
                          flush=True)
                    _POWER["until"] = 0.0
                    _POWER["slide"] = 0.0
                    _power_down()
                elif _POWER["slide"] > 0.02:
                    # Released short: snap back, stay armed. A half-slide is
                    # someone changing their mind, not someone failing.
                    print(f"power: slide released short "
                          f"({_POWER['slide']:.2f}) — cancelled", flush=True)
                    _POWER["slide"] = 0.0

        if _POWER["until"] and now >= _POWER["until"]:
            _POWER["until"] = 0.0
            print("power: confirm expired — cancelled", flush=True)
        if _POWER["until"] > now:
            frame = draw_power_confirm(frame, _POWER["until"] - now)
        elif _POWER["error_until"] > now:
            frame = draw_power_error(frame)
        #: ── AURORA'S RING TURNS WITH THE DIAL (2026-08-17) ───────────────
        #: It used to be painted AFTER the rotate, pinned to the screen, on
        #: the argument that a HUD of icons should never arrive upside down.
        #: Owner, at the glass: "the wedges have to rotate when i rotate the
        #: screen, right now they are fixed." His device, his dial — and he
        #: is right that a ring which ignores the rotation reads as painted
        #: ON the glass rather than part of the instrument.
        #:
        #: So it moves BEFORE the rotate, which carries it round with the
        #: bezel and everything else. THE HIT TEST MOVED IN THE SAME COMMIT
        #: — handle_tap's aurora branch now works in the logical frame
        #: instead of the screen frame. That pairing is the whole ballgame:
        #: the last time paint and hit-test disagreed about the rotation the
        #: owner reported "the touch mappings are wrong", measured at a
        #: 172-degree spin. Change one of these and you must change both.
        if AURORA_BLOB:
            if _show_now(now) is not None:
                #: quiet: the briefing's own entrance is the event here
                aurora_ui_hide(now, quiet=True)
            #: ── AND WHEN THE HOME FACE IS NOT ON SCREEN AT ALL ──────
            #: Owner: "fade in after my login just now still is disabled,
            #: the buttons are just there, they don't fade in. this is the
            #: 100th regression of this simple feature."
            #:
            #: The fade was never disabled. aurora_ui_show seeds `from_a`
            #: from the CURRENT alphas — correct, and the reason a second
            #: tap on an arrived ring does not replay the gesture. But
            #: nothing hid the ring when the screen locked, so it sat
            #: vis=True at alpha 1.0 through the whole login ceremony and
            #: came back with from_a all 1.0. There was nothing left to
            #: fade FROM. Every element of the animation ran perfectly over
            #: a distance of zero.
            #:
            #: That is why this keeps coming back: the bug is never in the
            #: animation, it is in the state it inherits, and each fix has
            #: been aimed at the fade. The briefing got a hide here on
            #: 08-17 for exactly this reason and lock/login/sleep never
            #: did — one more screen added to a list nobody remembered was
            #: a list.
            #:
            #: DERIVED, NOT ENUMERATED, for the same reason the glass-owner
            #: registry exists: these are the states where the home face is
            #: not on the glass, so the ring cannot be "up" on it. An
            #: overlay that merely sits OVER the home face (volume,
            #: settings) is deliberately not here — the ring is still
            #: underneath it and should not re-arrive when it closes.
            #: deaf_now(), not BRICKED alone: this said `BRICKED.exists()`
            #: and a VOICE mute paints the same red face, so the ring hung
            #: about over a screen it cannot belong to. One state, one
            #: answer — that asymmetry is the reason for the collapse.
            elif (LOCKED.exists() or LOGIN.exists()
                  or SLEEPING.exists() or deaf_now()):
                aurora_ui_hide(now, quiet=True)
            #: a spoken summon is read BEFORE the tick, so the ring it
            #: raises advances on this very frame rather than the next
            aurora_menu_voice(now)
            #: ALL state advances here, once, before anything reads it
            aurora_ui_tick(now, rot.moving)
            #: ── THE CARD GOES BACK, WHATEVER CLOSED THE DIALOG ──────
            #: _click_open holds an aplay on the speaker for the life of
            #: the volume overlay, and a standing plughw grab makes the
            #: pipewire sink unavailable — so a stream left open does not
            #: cost a tick, it costs her VOICE. The overlay has four ways
            #: out (DONE, the unrotated escape hatch, a tap elsewhere, the
            #: idle timeout) and wiring a close into each is the shape of
            #: bug the glass-owner registry exists to prevent: the list is
            #: what gets forgotten. So the state is DERIVED once a frame —
            #: if the dialog is not up, the card is not held.
            if _CLICK_STREAM["p"] is not None and not _VOL["open"]:
                _click_close()
            #: ── COUNT THE PANES THE FACE ACTUALLY HAS (2026-08-17) ──
            #: This was `len(WEDGES)` — the five BAKED panes — while the
            #: painter and the hit-test had moved to `wedges()`, which is
            #: seven on this face. So SLEEP and POWER were tappable (the
            #: owner: "the power down and sleeping buttons seem to respond
            #: to touch") and never drawn, because draw_aurora_menu asks
            #: this list for an alpha and gets 0.0 past its end.
            #: One list, one length, everywhere (§15).
            _aur_alphas = [_aurora_ui_alpha(now, _i)
                           for _i in range(len(wedges()))]
            draw_aurora_menu(frame, now, _aur_alphas, rot_deg=rot.deg)
            _ph("t:menu", frame)
            #: -- THE WORDMARK IS RETIRED (2026-08-17) --------------------
            #: Owner, after five cuts: "abandon the aura vision on the
            #: perimeter it just doesn't work either way."
            #:
            #: Five is enough to say what the problem actually was, and it
            #: was not the typography. A wordmark is a thing you read once
            #: and then never again; this face is looked at continuously,
            #: at arm's length, from wherever someone happens to be sitting.
            #: The gap was asking for something that rewards a SECOND look,
            #: and a brand name has nothing to give one. Radial, horizontal,
            #: upright, north-south, south-north, two weights, lit metal --
            #: every one of those was a better answer to the wrong question.
            #:
            #: What goes there instead is the one thing this device does
            #: that nothing else on the glass shows: it listens. See
            #: draw_aurora_ribbon. The code above it is left in place and
            #: uncalled rather than deleted, the same way the constellation
            #: was, because the next idea for this space may well want the
            #: arc-layout machinery and it took four cuts to get right.
            aurora_ribbon_sample(now)
            #: the damage rect's ground is the frame in EXACTLY this state:
            #: ring on, trace not yet drawn. See _aur_rect_stash.
            _aur_rect_stash(frame, rot.deg)
            draw_aurora_ribbon(frame, now, rot_deg=rot.deg)
            _ph("t:ribbon", frame)
        if rot.deg > 0.05:
            d = -rot.deg if INVERT else rot.deg
            frame = frame.rotate(d, resample=Image.NEAREST, fillcolor=(0, 0, 0))
        #: ── THE RESTING FACE SAYS WHEN SHE IS UNWELL (2026-08-20) ──────
        #: After the rotate, with the volume captions and the enrol caption
        #: and for their reason: it is a READING SURFACE, and a sentence
        #: tilted 135 degrees by whatever the dial happens to be doing is
        #: not one. (The lock screen's copy is deliberately the other way —
        #: it sits in a column with two hints that were moved above the
        #: rotate on 08-18, and half a screen turning reads as a bug.)
        #:
        #: RESTING means resting: any modal that owns the glass draws over
        #: this in the block below, and a briefing owns it outright. The
        #: mark is for the face nobody is touching, which is the state the
        #: device spends its life in and the one where a fault goes unseen.
        if not (vol_up or set_up or ster_up or req_up or pat_up or top_up
                or _card is not None or _show_now(now) is not None):
            draw_health_mark(frame, now)
        #: The constellation stays SCREEN-PINNED, deliberately: it marks a
        #: seat, seats are captured from a finger in screen coordinates
        #: (see the seat block in handle_tap), and rotating it here would
        #: walk the greeting away from the chair it belongs to. After the
        #: menu in z-order too, so a summoned ring sits over it — and never
        #: during a briefing, which owns the glass alone.
        if AURORA_BLOB and _show_now(now) is None:
            #: ── THE CONSTELLATION IS RETIRED (2026-08-17) ────────────
            #: Owner: "get rid of that weird constellation thing that keeps
            #: coming up." It traced a named voice's own stars at their
            #: seat when they arrived after a quiet spell — a nice idea that
            #: reads, on the glass, as unexplained shapes appearing. The
            #: drawing code and aurora_seat_write stay: the seat data is
            #: still captured and still useful, and deleting a subsystem
            #: because its one visible use was disliked is how the next
            #: session re-derives it.
            pass
        # AFTER the rotate, deliberately (2026-08-02). Volume mode's ring
        # and its DONE button are hit-tested in raw screen coordinates,
        # so they must be PAINTED in raw screen coordinates too. Drawn
        # before the rotate they were displaced by rot.deg — the detent
        # under the finger lit somewhere else, and DONE was not where it
        # looked. Round 2 adds ONE more transform on top: the per-mode
        # view rotation (_apply_view), whose exact inverse every overlay
        # hit-test applies via _unrotate_pt — orientable AND honest.
        # The enroll caption follows for the same reason as ever: it is
        # a reading surface, and text that has to be read should not be
        # tilted by whatever the dial happens to be doing.
        #: Round 3 (2026-08-17): the view now carries the DIAL as well —
        #: see _overlay_view. Every one of these paints through the same
        #: expression its hit-test undoes, which is the only property that
        #: has ever mattered here.
        #: ── AN OVERLAY IS A READING SURFACE (2026-08-17, round 3) ────
        #: This briefly carried the dial's angle as well, because the owner
        #: asked for the volume screen to "match the rotation of the
        #: screen". Rendered at his actual dial angle and LOOKED AT, that
        #: turned out to mean this: at -135.7 degrees the word DONE, the
        #: percentage and both captions are upside down. His next message
        #: was "it looks upside down and you can't change it".
        #:
        #: So the answer to "it does not match" was never to tilt the text
        #: — it is to let him TURN it, which is what `view_deg` and the
        #: orient drag have always been for. The overlay comes up upright,
        #: and a drag turns it to face wherever he is sitting.
        #:
        #: The publish-what-you-painted mechanism below stays, because it
        #: is right regardless: one writer, one reader, and the hit-test
        #: can never disagree with the paint about an angle again.
        if vol_up:
            frame = draw_volume(frame, now)
            _VIEW_PAINTED["vol"] = float(_VOL["view_deg"])
            frame = _apply_view(frame, _VIEW_PAINTED["vol"])
            #: ── THE EXIT RING IS GONE (2026-08-17) ──────────────────────
            #: Owner: "it still has this EXIT button that gets revealed when
            #: you rotate the screen. just find where that exit button is
            #: rendered and remove it forever, i have no idea how it was
            #: left there."
            #:
            #: It was left there on purpose, and the purpose has expired.
            #: DONE used to be painted BEFORE the view rotation and
            #: hit-tested after it, so on a turned screen the button and its
            #: target were in different places — four rounds of "done still
            #: does not work". The EXIT ring marked where the target
            #: actually was.
            #:
            #: DONE is painted inside the rotated frame now, so it travels
            #: with the screen and `_d_rot` tests exactly where it appears.
            #: A second ring is redundant, and a redundant escape hatch
            #: reads as a design that does not trust itself.
            #:
            #: The raw-position fallback in handle_tap STAYS, silent and
            #: undrawn: it costs nothing, it can fire nothing else, and it
            #: is what makes being locked inside this modal impossible.
        elif set_up:
            frame = draw_settings(frame, now)
            _VIEW_PAINTED["set"] = float(_SET["view_deg"])
            frame = _apply_view(frame, _VIEW_PAINTED["set"])
        elif ster_up:
            frame = draw_sterling(frame, now)
            _VIEW_PAINTED["ster"] = float(_STERLING["view_deg"])
            frame = _apply_view(frame, _VIEW_PAINTED["ster"])
        elif req_up:
            frame = draw_requests_card(frame, now)
            _VIEW_PAINTED["req"] = float(_REQ_CARD["view_deg"])
            frame = _apply_view(frame, _VIEW_PAINTED["req"])
        elif pat_up:
            frame = draw_patients_card(frame, now)
            _VIEW_PAINTED["pat"] = float(_PAT_CARD["view_deg"])
            frame = _apply_view(frame, _VIEW_PAINTED["pat"])
        # The $LEDGER offer and its outcome. AFTER the rotate, with the cards
        # above, and for their reason: the slide is hit-tested in raw screen
        # coordinates, so it has to be PAINTED in them. No _apply_view — this
        # card has no orient gesture to undo.
        if _TOPUP["open"]:
            frame = draw_topup_card(frame, now)
        elif _TOPUP["filed_until"] > now:
            frame = draw_topup_notice(frame, True)
        elif _TOPUP["error_until"] > now:
            frame = draw_topup_notice(frame, False)
        stage = _enroll_stage()
        if stage:
            frame = draw_enroll_caption(frame, stage, now)

        try:
            blit(frame)
        except Exception as e:
            print(f"blit: {e!r}", flush=True)
            time.sleep(1)

        # -- pace ---------------------------------------------------------
        # THE COMPOSE ENDS HERE, and the first version of the pace counter
        # got this wrong: it timed from the frame's start to AFTER the rect
        # loop and its sleeps, then printed the total under the label
        # "compose". The number was ~105 ms either way, which is exactly why
        # it survived a reading — a mislabelled metric that happens to look
        # plausible is worse than a missing one, because the next person
        # compares it against the 54 ms in the TOURB_RECT_FPS note and draws
        # a conclusion about the wrong quantity.
        _ph("tail", frame)
        if _PH.get("dump"):
            _PH["dump"] = False
            print("phdump: frames written to /tmp/aura_face/ph_*.png",
                  flush=True)
        elif PHDUMP.exists():
            PHDUMP.unlink(missing_ok=True)
            _PH["dump"] = True
        t_compose = time.time() - now
        # Volume mode no longer forces ACTIVE_FPS for its whole (now
        # unbounded) life: rot.moving covers its drags, IDLE_FPS carries
        # its static overlay, and the bolt surge buys fast frames only
        # for its ~0.6s flare.
        #: ── AND WHILE THE RING IS ACTUALLY MOVING (2026-08-20) ─────────
        #: The idle rate drops to the pack's own rate below, so anything
        #: that animates FASTER than the pack has to say so here or it will
        #: be sampled at 16 fps. The ring's arrival and its dissolve are
        #: the only such things on this face: `wedge_t0` covers a TAP that
        #: raised it, not a summon by voice, and not the exit at all.
        _ring_moving = bool(_AUR_UI.get("hide_t0")) or (
            _AUR_UI.get("vis")
            and (now - (_AUR_UI.get("show_t0") or 0.0)) < AUR_UI_ARRIVE_S + 0.3)
        busy = rot.moving or wedge_t0 is not None or _ring_moving \
            or _show_now(now) is not None \
            or (now - _BOLT_SURGE[0]) < BOLT_SURGE_S + 0.1
        # See PACK_IDLE_FPS: a pack-fed aperture trades full frames for
        # rect paints, a live-drawn one keeps the rate it was tuned at.
        #: The aurora face reads AUR_RECT_IDLE_FPS instead once its own rect
        #: path has a ground to paint over — same trade, its own constant,
        #: because a face whose full frames carry an IRIS is not buying the
        #: same thing a face whose full frames carry a still bezel is.
        idle = (((AUR_RECT_IDLE_FPS if _AUR_RIB_LAY.get("under") is not None
                  else AUR_IDLE_FPS)) if AURORA_BLOB
                else PACK_IDLE_FPS if _CENTRE["frames"] else IDLE_FPS)
        #: ── A LOCKED FACE IS NOT BEING WATCHED (2026-08-21) ──────────
        #: Owner: "the fan is just going bonkers fast right now what the
        #: hell is taking up so much compute." Measured on his puck the
        #: same minute: the compositor at 81% of a core, 18m55s of CPU,
        #: die at 88.1C with the fan pinned at 255/255. It is the largest
        #: consumer on the device by an order of magnitude.
        #:
        #: And it spends most of the day painting a LOCK SCREEN at 22 fps.
        #: Full frames, every one of them — `rect 0.0` in six windows of
        #: six — because the aurora animates continuously so every frame
        #: is dirty. c:core alone is 19 ms of a 45 ms budget, and it runs
        #: whether or not anybody is in the room.
        #:
        #: Locked is the one state where nobody is looking BY DEFINITION:
        #: the face is sealed, the wordmark is still, and the thing a
        #: person does next is speak or touch — both of which clear the
        #: lock and restore the full rate on the very next frame. `busy`
        #: above already covers every animation that must stay smooth, so
        #: this cannot slow a ceremony, a menu or an answer.
        #:
        #: 8 fps, not 1: the starfield still drifts and the iris still
        #: breathes, so it reads as a device that is awake and waiting
        #: rather than one that has crashed with a picture on it. That
        #: distinction is the whole reason the lock screen animates at all.
        #: ── REVERTED THE SAME HOUR IT SHIPPED (2026-08-21) ──────────
        #: It bought NOTHING and is implicated in a live GUI fault.
        #:
        #: Measured after deploying it: compositor 93.8% of a core (up
        #: from 81.2), die 90.5C (up from 88.1). The lock screen is not
        #: where this device spends its time when somebody is using it,
        #: which is exactly when he was complaining about the fan — so it
        #: throttled the one state that was not the problem.
        #:
        #: AND THE WEDGES STOPPED ARRIVING. From his log, minutes later:
        #:
        #:   tap: aurora ring summoned [arrived=0 age=58.8s
        #:                              a=[1.0,1.0,1.0,0.91,0.78,0.67,0.57]]
        #:   tap: pane 4 still arriving (alpha=0.99) — ignored
        #:
        #: The ring's arrival is FRAME-STEPPED with a per-frame dt cap
        #: (_aur_ui_dt_cap), so at 8 fps each frame advances it by less
        #: than the 125 ms that actually elapsed and the animation falls
        #: permanently behind the clock. Panes never reach 1.0, `arrived`
        #: never goes true, and every tap re-summons a ring that is
        #: already up — which from the chair is the glass ignoring you,
        #: the exact complaint this face has a whole guard for
        #: (test_ring_pressable.py).
        #:
        #: A frame-rate dial is not a free knob on a face whose animations
        #: are stepped per frame rather than by wall clock. Anything that
        #: lowers the rate has to fix the stepping first, and that is the
        #: real work — not this.
        #:
        #: AUR_LOCK_IDLE_FPS stays defined and unused, with this note, so
        #: the next person to reach for the obvious lever finds the
        #: measurement instead of repeating it.
        budget = 1.0 / (ACTIVE_FPS if busy else idle)
        deadline = now + budget
        # THE APERTURE KEEPS MOVING INSIDE THE GAP (2026-08-07,
        # TOURB_RECT_FPS). The full-frame cap is untouched; what changes is
        # that the idle gap is no longer spent entirely asleep — the
        # tourbillon's own ~276px window is repainted in it, at a cost
        # measured proportional to its pixel count.
        #
        # ONLY WHEN THE FACE IS PLAIN. The stored background is the frame as
        # it was immediately before the movement was pasted, so anything
        # drawn over the centre AFTER that — a card, the power overlay, a
        # ripple, a flash, a spun dial — would be rubbed out by a rect
        # paint. Rather than teach the rect path about each of them, the
        # fast path stands down whenever one is up and the face is exactly
        # as it was: 8 fps, whole panel.
        #: ── ROTATION NO LONGER STANDS THE FAST PATH DOWN (2026-08-13) ──
        #: `rot.deg <= 0.05` used to be the first term here, and it cost the
        #: centrepiece three quarters of its frame rate whenever the dial was
        #: turned — see the note at _TOURB_LAY["under_big"]. The rect knows
        #: how to turn now, so the gate only has to ask what it was always
        #: really asking: is anything painted OVER the centre that a rect
        #: repaint would rub out.
        #: ── ONE GATE, TWO RECTS (2026-08-19) ─────────────────────────────
        #: Everything above the last line asks the same question for both
        #: faces — "is anything painted OVER the region a rect would repaint"
        #: — so it is asked once. Only the last term differs: which ground
        #: was actually kept this frame. Splitting the shared half into two
        #: copies is how the tourbillon's gate and the aurora's would drift,
        #: and a rect firing over a card is a smear nobody can explain.
        plain_base = (not busy
                      and not (vol_up or set_up or ster_up or req_up or pat_up
                               or top_up)
                      and _card is None and not stage
                      and _POWER["until"] <= now
                      and _POWER["error_until"] <= now
                      and _TOPUP["filed_until"] <= now
                      and _TOPUP["error_until"] <= now
                      and not (0.0 <= now - _RIPPLE[0] < 0.9)
                      and not FLASH.exists() and not WEDGE_TOUR.exists()
                      and not _RES_THROB["up"])
        plain = plain_base and _TOURB_LAY["under"] is not None
        #: The aurora ribbon's rect. Turned off by the dial rather than by
        #: the gate above — see the note on _aur_rect_paint — and it says so
        #: once, because "the pace line reads 0.0 rect" is not an answer a
        #: person can act on unless something names the reason.
        aur_rect = (plain_base and AURORA_BLOB
                    and _AUR_RIB_LAY.get("under") is not None)
        if aur_rect and abs(rot.deg) > 0.05:
            aur_rect = False
            if "turned" not in _AUR_RIB_LAY["said"]:
                _AUR_RIB_LAY["said"].add("turned")
                print(f"aurora: ribbon rect STANDS DOWN — the dial is at "
                      f"{rot.deg:.1f} deg and the trace is painted in "
                      f"unrotated coordinates. Full frames own the gap "
                      f"until the dial returns home.", flush=True)
        elif aur_rect and "turned" in _AUR_RIB_LAY["said"]:
            _AUR_RIB_LAY["said"].discard("turned")
            print("aurora: ribbon rect back — dial home", flush=True)
        # Anchored to the frame's own start and stepped on a fixed grid, so
        # the aperture keeps one cadence instead of drifting with whatever
        # the compose happened to cost; slots the compose has already eaten
        # are SKIPPED rather than fired back-to-back, which would burst.
        # How many are left is exactly the gap the full frame did not use —
        # never fewer than nothing, never past the next frame's deadline.
        #: Whichever ground was kept this frame owns the gap. Never both —
        #: two painters writing overlapping rows in one gap would be a
        #: tearing bug that only appears on a face carrying both, which is
        #: no face today and is exactly the kind of latent thing this file
        #: keeps notes about.
        rect_paint = _aur_rect_paint if aur_rect else _tourb_rect_paint
        step = 1.0 / (AUR_RECT_FPS if aur_rect else TOURB_RECT_FPS)
        running = aur_rect or plain
        #: ── A RECT THAT DOES NOT FIT IS NOT FREE (2026-08-19) ────────────
        #: The loop only ever asked whether the SLOT was before the
        #: deadline, never whether the PAINT would be — which was fine for
        #: the tourbillon aperture at 0.76 ms and is not fine for the
        #: ribbon's 412x614 at ~7. Started 2 ms before the deadline, a 7 ms
        #: paint delivers the next full frame 5 ms late, every time, and the
        #: pace line reports the mean and hides it. That is exactly the
        #: p95-versus-mean problem the next priority is about: 26 fps of
        #: even frames and 26 fps of ragged ones are the same number.
        #:
        #: So the cost is MEASURED — per painter, because the two differ by
        #: an order of magnitude — and a slot is only taken if the paint can
        #: finish inside the budget. 1.3x because the first paint after a
        #: cache miss is dearer than the steady state, and being one slot
        #: conservative costs a rect where being one slot optimistic costs a
        #: late full frame.
        _rk = rect_paint.__name__
        _rcost = _RECT_COST.get(_rk, 0.0)
        nxt = now + step
        rects = 0
        while running:
            t = time.time()
            while nxt <= t:
                nxt += step
            if nxt + _rcost * 1.3 >= deadline:
                break
            time.sleep(nxt - t)
            try:
                _rt0 = time.time()
                rect_paint(_rt0, -rot.deg if INVERT else rot.deg)
                _rcost = max(time.time() - _rt0, _rcost * 0.9)
                _RECT_COST[_rk] = _rcost
                rects += 1
            except Exception as e:
                # Say it and fall back to full frames for this gap — a
                # damage rect that quietly stops is a face that has simply
                # gone still, with nothing to say why (PRINCIPLES §1).
                print(f"rect: {e!r}", flush=True)
                running = False
        #: ── ARMED AND FIRING NOTHING IS A STATE, SO IT SAYS SO ───────────
        #: The pace line reports `0.0 rect` either way — when the path is
        #: absent, when the dial has stood it down, and when it is working
        #: perfectly and there is simply no room in the budget. Three very
        #: different situations behind one number is how "the damage rect
        #: does not work on this face" gets believed for a week. The first
        #: paint always runs (the cost starts unknown), so this line quotes
        #: a MEASURED price against a measured gap.
        if aur_rect and _RECT_COST.get("_aur_rect_paint"):
            _fits = rects > 0
            if not _fits and "nogap" not in _AUR_RIB_LAY["said"]:
                _AUR_RIB_LAY["said"].add("nogap")
                print(f"aurora: ribbon rect ARMED AND IDLE — a paint costs "
                      f"{1000.0 * _RECT_COST['_aur_rect_paint']:.1f} ms and "
                      f"the budget leaves {1000.0 * (budget - t_compose):.1f}"
                      f" ms after a {1000.0 * t_compose:.0f} ms compose. "
                      f"Lower AUR_RECT_IDLE_FPS to trade full frames for it "
                      f"(measured: 12 fps buys 23.7 rect/s and costs the "
                      f"iris half its rate).", flush=True)
            elif _fits and "nogap" in _AUR_RIB_LAY["said"]:
                _AUR_RIB_LAY["said"].discard("nogap")
                print(f"aurora: ribbon rect firing again — {rects} in this "
                      f"gap", flush=True)
        #: ── 2026-08-12: THE FACE COULD NOT TELL YOU ITS OWN FRAME RATE ────
        #: The note at TOURB_RECT_FPS does the arithmetic — "the compose
        #: costs 54 ms, so ~71 ms of the 125 ms budget is free and two 33 ms
        #: slots fit in it: 8 full frames plus 16 rect paints" — and that
        #: 24 fps has never been checked on a running device. It does not
        #: hold. Sampling the aperture off /dev/fb0 at 250 Hz: the chopard
        #: puck manages 12.9 fps, the patek 21.4. The compose is eating the
        #: gap the rects were supposed to live in, and which face you are
        #: wearing decides how much (a 1080px jewelled bezel composites for
        #: longer than a steel one).
        #:
        #: So the loop reports it. Once every 30 s, never per frame, and the
        #: numbers are the two that matter: what the compose actually cost
        #: and how many rect slots survived it. A performance budget nobody
        #: measures is a comment, not a budget.
        _PACE["frames"] += 1
        _PACE["compose"] += t_compose
        _PACE["rects"] += rects
        _ft_note(now, budget)
        #: The window opens on the first frame, not at the epoch. Without
        #: this the first report divides by time.time() and announces
        #: "0.0 fps over 1786521134s", which is the shape of every uninitialised
        #: rate counter ever written — and it is worth the two lines because a
        #: number that absurd still gets read as a number.
        if _PACE["said"] == 0.0:
            _PACE.update(said=now, frames=0, rects=0, compose=0.0)
        elif now - _PACE["said"] >= 30.0:
            el = now - _PACE["said"]
            fps = (_PACE["frames"] + _PACE["rects"]) / el
            n = max(1, _PACE['frames'])
            print(f"pace: {fps:.1f} fps to the glass over {el:.0f}s "
                  f"({_PACE['frames'] / el:.1f} full + "
                  f"{_PACE['rects'] / el:.1f} rect); compose "
                  f"{1000.0 * _PACE['compose'] / n:.0f}"
                  f" ms of a {1000.0 * budget:.0f} ms budget", flush=True)
            #: the histogram, and the number the complaint is actually
            #: about: how many frames the glass held for longer than the
            #: budget. See _FT_EDGES.
            _tot = sum(_PACE["ft"])
            if _tot:
                #: EXACT, counted at measurement time against the frame's
                #: own budget. Derived from the buckets it was wrong by
                #: construction — see the note at _FT_EDGES.
                _over = _PACE["over"]
                _mean = _PACE["ftsum"] / max(1, _PACE["ftn"])
                _hist = "  ".join(
                    f"<{e:.0f}:{c}" for e, c in zip(_FT_EDGES, _PACE["ft"])
                    if c) + (f"  >={_FT_EDGES[-1]:.0f}:{_PACE['ft'][-1]}"
                             if _PACE["ft"][-1] else "")
                #: MEAN first, and the percentiles marked "<" because they
                #: are bucket upper edges and therefore over-estimates. The
                #: first version printed the upper edge as if it were the
                #: value and put a boundary on the budget itself.
                print(f"pace:   frametime mean {_mean:.1f} "
                      f"p50<{_ft_pct(0.50):.0f} p95<{_ft_pct(0.95):.0f} "
                      f"worst {_PACE['ftmax']:.0f} "
                      f"ms; {_over} of {_tot} over the "
                      f"{1000.0 * budget:.0f} ms budget "
                      f"({100.0 * _over / _tot:.1f}%)  |  {_hist}",
                      flush=True)
            _PACE["ft"] = [0] * (len(_FT_EDGES) + 1)
            _PACE["ftmax"] = 0.0
            _PACE["over"] = 0
            _PACE["ftsum"] = 0.0
            _PACE["ftn"] = 0
            parts = sorted(_PH["acc"].items(), key=lambda kv: -kv[1])
            print("pace:   " + "  ".join(
                f"{k} {1000.0 * v / n:.1f}" for k, v in parts if v > 0),
                flush=True)
            #: ...and the menu's own split, per RING-BEARING FRAME (see
            #: _MPH). Printed only when the ring actually drew, so a quiet
            #: window says nothing rather than printing a row of zeroes
            #: that would read as "the menu is free".
            if _MPH["acc"] and _MPH["n"]:
                mn = float(_MPH["n"])
                mparts = sorted(_MPH["acc"].items(), key=lambda kv: -kv[1])
                print(f"pace:   menu/{_MPH['n']}f  " + "  ".join(
                    f"{k} {1000.0 * v / mn:.2f}"
                    for k, v in mparts if v > 0), flush=True)
            _MPH["acc"] = {}
            _MPH["n"] = 0
            #: the eye's own breakdown, same shape and the same rule —
            #: silent when it did not draw, rather than a row of zeroes
            if _CPH["acc"] and _CPH["n"]:
                cn = float(_CPH["n"])
                cparts = sorted(_CPH["acc"].items(), key=lambda kv: -kv[1])
                print(f"pace:   core/{_CPH['n']}f  " + "  ".join(
                    f"{k} {1000.0 * v / cn:.2f}"
                    for k, v in cparts if v > 0), flush=True)
            _CPH["acc"] = {}
            _CPH["n"] = 0
            _PACE.update(said=now, frames=0, rects=0, compose=0.0)
            _PH["acc"] = {}
        spare = deadline - time.time()
        if spare > 0:
            time.sleep(spare)


if __name__ == "__main__":
    main()
