#!/usr/bin/env python3
"""UI Stack regression probe: every check is named after the audit defect it guards (Д-001…Д-008).
Run: python3 eunomia/tests/ui_stack_check.py [--out REPORT.json]
Needs a running Eunomia at EUNOMIA_URL (default http://127.0.0.1:18765), Python Playwright with Chromium
and axe-core: AXE_CORE or eunomia/frontend/node_modules/axe-core/axe.min.js (npm ci in eunomia/frontend).
Exit code 1 on any failed check. A crashed section is a failed check, not silence.
"""
import argparse
import json
import os
import re
import time
import urllib.request
from pathlib import Path
from urllib.parse import parse_qs, urlsplit
from playwright.sync_api import sync_playwright
from chromium import executable
BASE = os.environ.get('EUNOMIA_URL', 'http://127.0.0.1:18765').rstrip('/')
ROOT = Path(__file__).resolve().parents[1]
AXE = Path(os.environ.get('AXE_CORE') or ROOT / 'frontend/node_modules/axe-core/axe.min.js')
RESEARCH = ROOT / 'frontend/src/pantheon/Research.tsx'
HOME = str(Path.home())
SCREENS = {
'главная': ('/', '.p-stone'),
'поиск': ('/#view=search&q=395', '.p-result, .p-empty-scene'),
'читатель': ('/#doc=legal-corpus%3Acode%3Atk-rf&fragment=doc%3Alegal-corpus%3Acode%3Atk-rf_article_395', 'main h1'),
'граф': ('/#view=graph', '.p-force-canvas canvas'),
'служба': ('/#view=updates', '.p-job'),
}
LANDMARK = ('nav, aside, main, header, footer, [role=navigation], [role=complementary], [role=main], '
'[role=banner], [role=contentinfo], [role=region][aria-label], section[aria-label], form[aria-label]')
# Roles that accept an accessible name from aria-label (ARIA 1.2); generic
/ do not.
NAMED_ROLES = {'region', 'group', 'img', 'figure', 'application', 'navigation', 'complementary', 'main', 'form', 'search'}
# Colour maths as in the fixed WCAG-143 block of qa/ui-stack-2026-09-22/scripts/audit.py:
# color(srgb r g b / a) is 0..1 per channel, translucent layers are composited down to the first opaque one.
CONTRAST = """() => {
const parse = s => {const m=s.match(/^color\\(srgb ([\\d.]+) ([\\d.]+) ([\\d.]+)(?: \\/ ([\\d.]+))?\\)/);
if(m) return [m[1]*255, m[2]*255, m[3]*255, m[4]===undefined?1:+m[4]];
const n=s.match(/[\\d.]+/g).map(Number); return [n[0], n[1], n[2], n.length>3?n[3]:1]};
const over = (top, under) => [0,1,2].map(i => top[i]*top[3] + under[i]*(1-top[3])).concat(1);
const bgOf = el => {const layers=[]; for(let e=el; e; e=e.parentElement){const c=parse(getComputedStyle(e).backgroundColor); if(c[3]>0){layers.push(c); if(c[3]>=1) break}}
return layers.reverse().reduce((bg, layer) => over(layer, bg), [255,255,255,1])};
const lum = c => {const [r,g,b]=c.slice(0,3).map(v=>{v/=255;return v<=0.03928?v/12.92:Math.pow((v+0.055)/1.055,2.4)}); return 0.2126*r+0.7152*g+0.0722*b};
const ratioOf = (fg, bg) => {const L1=lum(over(fg, bg)), L2=lum(bg); return (Math.max(L1,L2)+0.05)/(Math.min(L1,L2)+0.05)};
const measure = el => {const cs=getComputedStyle(el); const px=parseFloat(cs.fontSize), w=parseInt(cs.fontWeight)||400;
const need=(px>=24 || (px>=18.66 && w>=700)) ? 3 : 4.5; const ratio=ratioOf(parse(cs.color), bgOf(el));
return {color: cs.color, px, ratio: +ratio.toFixed(2), need, pass: ratio >= need}};
const rows = [];
for (const s of ['.p-hero-copy > p:not(.p-eyebrow)','.p-stone-face span','.p-stone-face small','.p-catalog-total','.p-local-note','.p-tabs a:not([aria-current])','.p-sidebar-note','.p-brand small','.p-eyebrow','.p-tabs span']) {
const el = document.querySelector(s); if (el) rows.push({sel: s, ...measure(el)})}
const selfcheck = +ratioOf(parse('rgb(88, 101, 121)'), over(parse('color(srgb 1 1 1 / 0.97)'), [255,255,255,1])).toFixed(2);
const probe = document.createElement('span'); probe.textContent = 'контроль';
probe.style.cssText = 'color: rgb(150, 150, 150); font-size: 12px';
(document.querySelector('.p-topbar') || document.body).appendChild(probe);
const control = measure(probe); probe.remove();
return {rows, selfcheck, control}
}"""
def state_labels():
"""Human labels of the queue states, read from the component itself so the probe cannot drift from it."""
text = RESEARCH.read_text(encoding='utf-8')
block = re.search(r'const states[^=]*=\s*\{([^}]*)\}', text)
if not block:
raise RuntimeError('в Research.tsx не найден словарь states: проба не знает подписей состояний')
return dict(re.findall(r"(\w+)\s*:\s*'([^']*)'", block.group(1)))
def status_fixture(real):
"""440 jobs in every state, shaped like the live /api/status answer; one failed job carries a home-path error."""
template = {'resource_hash': '0' * 64, 'state': 'current', 'priority': 0, 'attempts': 1, 'available_at': None,
'lease_until': None, 'progress': {'done': 0, 'pending_count': 0, 'total': 0}, 'detail': None,
'freshness': 'unknown', 'availability': 'unknown', 'created_at': 0, 'updated_at': 0, 'started_at': None,
'finished_at': None, 'last_checked': None, 'last_updated': None, 'pending_resource_hash': None,
'id': 'legal-corpus:code:gk-rf', 'local_file_present': True}
live = [job for job in real.get('jobs') or [] if isinstance(job, dict)]
cycle = ['deferred', 'blocked', 'failed', 'current', 'updated', 'queued', 'running']
jobs = []
for i in range(440):
job = dict(live[i % len(live)] if live else template)
job.update(id=f"{job.get('id') or 'probe'}#probe-{i}", resource_hash=f'{i:064x}', state=cycle[i % len(cycle)])
jobs.append(job)
missing = Path(HOME, 'Проекты', 'themiz', '.agent', 'maintenance', 'background', 'jobs', '829828fc-probe', 'original.body')
jobs[2]['detail'] = f"[Errno 2] No such file or directory: '{missing}'"
return {**real, 'jobs': jobs}, bool(live)
class Check:
def __init__(self, browser):
self.results, self.errors = [], []
self.context = browser.new_context(viewport={'width': 1440, 'height': 900})
# CDP init script bypasses the app's CSP script-src 'self' without weakening it.
self.context.add_init_script(AXE.read_text(encoding='utf-8'))
self.page = self.context.new_page()
self.page.set_default_timeout(30000)
self.page.on('pageerror', lambda error: self.errors.append(f'pageerror: {error}'))
self.page.on('console', lambda message: self.errors.append(f'console: {message.text}') if message.type == 'error' else None)
for path in ('**/api/update', '**/api/graph/rebuild', '**/api/practice/refresh'):
self.page.route(path, lambda route: route.fulfill(status=200, content_type='application/json', body='{"detail":"mock"}'))
def check(self, name, ok, detail=''):
self.results.append({'name': name, 'ok': bool(ok), 'detail': detail})
def info(self, name, detail):
self.results.append({'name': name, 'ok': True, 'info': True, 'detail': detail})
def section(self, name, run):
try:
run()
except Exception as error: # a crash is a red check with its cause, never silence
self.check(f'{name}: раздел выполнен до конца', False, f'{type(error).__name__}: {str(error)[:400]}')
def open(self, route, ready, wait=700):
self.page.goto(BASE + route, wait_until='domcontentloaded')
self.page.wait_for_selector(ready)
self.page.wait_for_timeout(wait)
def fragment(self):
return parse_qs(urlsplit(self.page.url).fragment)
def axe(self, rules=None):
options = {'resultTypes': ['violations']}
if rules:
options['runOnly'] = {'type': 'rule', 'values': rules}
return self.page.evaluate("""async options => (await axe.run(document, options)).violations
.map(v => ({id: v.id, impact: v.impact, nodes: v.nodes.length, target: v.nodes[0] && v.nodes[0].target}))""", options)
def use_status_fixture(self):
real = self.page.request.get(BASE + '/api/status').json()
fixture, live = status_fixture(real)
if not live:
self.info('Д-003 фикстура очереди', 'живых заданий нет: шаблон задания взят из кода пробы, а не из ответа сервера')
body = json.dumps(fixture, ensure_ascii=False)
self.page.route('**/api/status*', lambda route: route.fulfill(status=200, content_type='application/json', body=body))
def screens(self):
self.use_status_fixture()
for name, (route, ready) in SCREENS.items():
self.open(route, ready, 3000 if name == 'граф' else 900)
dangling = self.page.evaluate("""() => [...document.querySelectorAll('[aria-controls]')].flatMap(el =>
el.getAttribute('aria-controls').split(/\\s+/).filter(id => id && !document.getElementById(id))
.map(id => ({id, el: el.outerHTML.slice(0, 120)})))""")
self.check(f'Д-001 aria-controls ведёт на существующий узел: {name}', not dangling, dangling[:3])
violations = self.axe()
region = [v for v in violations if v['id'] == 'region']
self.check(f'Д-007 всё содержимое внутри landmark (axe region): {name}', not region, region)
self.check(f'общее: ноль нарушений axe: {name}', not violations, violations)
if name == 'главная':
outside = self.page.evaluate(f"""() => [...document.querySelectorAll('[data-sidebar="header"]')]
.filter(el => !el.closest({json.dumps(LANDMARK)})).length""")
self.check('Д-007 шапка сайдбара лежит в landmark', outside == 0, f'вне landmark: {outside}')
if name == 'граф':
prohibited = [v for v in violations if v['id'] == 'aria-prohibited-attr']
self.check('Д-006 aria-label без допустимой роли (axe aria-prohibited-attr): граф', not prohibited, prohibited)
canvas = self.page.evaluate("""() => {const el = document.querySelector('.p-force-canvas');
return el && {role: el.getAttribute('role'), label: el.getAttribute('aria-label')}}""")
self.check('Д-006 поверхность графа названа через роль, которая принимает имя',
bool(canvas and canvas['role'] in NAMED_ROLES and (canvas['label'] or '').strip()), canvas)
if name == 'читатель':
self.page.wait_for_selector('.p-context', timeout=20000)
self.page.wait_for_timeout(800)
bare = self.page.evaluate("""() => [...document.querySelectorAll('aside *, .p-context *')]
.filter(e => e.children.length === 0 && /^\\d+$/.test((e.textContent || '').trim())
&& !(e.getAttribute('aria-label') || e.getAttribute('title')))
.slice(0, 4).map(e => ({tag: e.tagName, cls: String(e.className).slice(0, 30), text: e.textContent.trim()}))""")
self.check('Д-008 в панели контекста нет голых чисел без имени', not bare, bare)
self.page.unroute('**/api/status*')
def search_box(self):
self.open('/', '.p-stone')
self.page.keyboard.press('Tab')
skip = self.page.evaluate("() => String(document.activeElement.className)")
self.check('сохранено: первый Tab ведёт на skip-link', 'p-skip' in skip, skip)
self.page.keyboard.press('Escape')
search_label = "() => document.activeElement.getAttribute('aria-label') || ''"
self.page.keyboard.press('Meta+k')
self.page.wait_for_timeout(200)
if 'Поиск' not in self.page.evaluate(search_label):
self.page.keyboard.press('Control+k')
self.page.wait_for_timeout(200)
self.check('сохранено: Cmd/Ctrl+K фокусирует поиск', 'Поиск' in self.page.evaluate(search_label))
self.page.keyboard.type('395')
self.page.wait_for_selector('.p-suggestions [cmdk-item]', timeout=15000)
state = """() => {const el = document.activeElement; const ids = (el.getAttribute('aria-controls') || '').split(/\\s+/).filter(Boolean);
return {label: el.getAttribute('aria-label') || '', expanded: el.getAttribute('aria-expanded'), ids,
missing: ids.filter(id => !document.getElementById(id)), lists: document.querySelectorAll('.p-suggestions').length}}"""
opened = self.page.evaluate(state)
self.check('Д-001 открытый список: aria-controls указывает на живой список',
opened['ids'] and not opened['missing'] and opened['expanded'] == 'true', opened)
self.page.keyboard.press('Escape')
self.page.wait_for_timeout(200)
closed = self.page.evaluate(state)
self.check('Д-001 Escape закрывает подсказки и держит фокус в поле', closed['lists'] == 0 and 'Поиск' in closed['label'], closed)
self.check('Д-001 закрытый список: aria-controls не висит в пустоте', not closed['missing'], closed)
self.page.keyboard.press('Enter')
self.page.wait_for_timeout(1200)
self.check('сохранено: Enter в поиске даёт q= в URL', self.fragment().get('q') == ['395'], self.page.url)
def pagination_label(self):
return self.page.locator('.p-pagination span').first.inner_text()
def first_row(self):
return self.page.locator('.p-document-row').first.inner_text()
def catalog_pages(self):
self.open('/#view=category&kind=plenum', '.p-pagination')
self.page.locator('.p-pagination-actions button', has_text='Следующая').click()
self.page.wait_for_timeout(500)
label, second = self.pagination_label(), self.first_row()
self.check('Д-002 «Следующая» пишет страницу в URL', self.fragment().get('page') == ['2'] and 'страница 2' in label,
{'url': self.page.url, 'label': label})
self.page.reload(wait_until='domcontentloaded')
self.page.wait_for_selector('.p-pagination')
self.page.wait_for_timeout(700)
self.check('Д-002 перезагрузка держит страницу 2', 'страница 2' in self.pagination_label() and self.first_row() == second,
self.pagination_label())
self.page.go_back(wait_until='domcontentloaded')
self.page.wait_for_timeout(900)
back = self.page.locator('.p-pagination').count() and self.pagination_label()
self.check('Д-002 Back возвращает страницу 1 того же каталога',
self.fragment().get('kind') == ['plenum'] and bool(back) and 'страница 1' in back, {'url': self.page.url, 'label': back})
def catalog_filters(self):
self.open('/#view=category&kind=plenum', '.p-topic')
before = self.page.url
self.page.locator('.p-topic').first.click()
self.page.wait_for_timeout(500)
row = self.first_row()
self.check('Д-002 тема пишется в URL', self.page.url != before and 'topic' in self.fragment(), self.page.url)
self.page.reload(wait_until='domcontentloaded')
self.page.wait_for_selector('.p-document-row')
self.page.wait_for_timeout(700)
self.check('Д-002 перезагрузка держит тему', self.first_row() == row, self.page.url)
self.open('/#view=category&kind=plenum', '.p-pagination')
selects = self.page.locator('main select')
selects.nth(0).select_option('old')
self.page.wait_for_timeout(400)
self.check('Д-002 сортировка пишется в URL', self.fragment().get('sort') == ['old'], self.page.url)
# Year options carry no value attribute (): pick by index, read select.value.
selects.nth(1).select_option(index=1)
self.page.wait_for_timeout(400)
year = selects.nth(1).evaluate('select => select.value')
self.check('Д-002 год пишется в URL', bool(year) and self.fragment().get('year') == [year], self.page.url)
def document_list(self):
# Live corpus has at most 5 documents per non-plenum kind, so DocumentList never pages on real data:
# the bootstrap answer is inflated to 30 federal laws built from the live ones.
real = self.page.request.get(BASE + '/api/bootstrap').json()
laws = [d for d in real.get('documents', []) if d.get('kind') == 'federal-law']
if not laws:
self.info('Д-002 DocumentList', 'в корпусе нет федеральных законов: пагинацию списка проверить не на чем')
return
extra = [{**laws[i % len(laws)], 'id': f"{laws[i % len(laws)]['id']}#probe-{i}"} for i in range(30)]
body = json.dumps({**real, 'documents': [d for d in real['documents'] if d.get('kind') != 'federal-law'] + extra}, ensure_ascii=False)
self.page.route('**/api/bootstrap*', lambda route: route.fulfill(status=200, content_type='application/json', body=body))
try:
self.page.goto('about:blank') # a hash-only goto keeps the loaded bootstrap; force a real load
self.open('/#view=category&kind=federal-law', '.p-pagination')
self.page.locator('.p-pagination-actions button', has_text='Следующая').click()
self.page.wait_for_timeout(500)
self.check('Д-002 DocumentList: страница в URL', self.fragment().get('page') == ['2'], self.page.url)
self.page.reload(wait_until='domcontentloaded')
self.page.wait_for_selector('.p-pagination')
self.page.wait_for_timeout(600)
self.check('Д-002 DocumentList: перезагрузка держит страницу', 'страница 2' in self.pagination_label(), self.pagination_label())
finally:
self.page.unroute('**/api/bootstrap*')
self.page.goto('about:blank')
def rows(self):
return self.page.locator('.p-job').all_inner_texts()
def pick_state(self, label):
"""Choose a queue state through whatever control the queue offers: