Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

quickshell/nuguland/ui-test.mjs

Raw
import assert from 'node:assert/strict';
import { spawn, spawnSync } from 'node:child_process';
import { appendFileSync, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { homedir, tmpdir } from 'node:os';
import { basename, dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { stripVTControlCharacters } from 'node:util';
import { setTimeout as delay } from 'node:timers/promises';
import runControls from './test-fixtures/ui/controls.mjs';
import runPopups from './test-fixtures/ui/popups.mjs';
import runPrivilege from './test-fixtures/ui/privilege.mjs';
import { nativeFeatures, prepareNiriIntegration, runNiriIntegration } from './test-fixtures/ui/niri-integration.mjs';
import { barSelection, barOverlayFixtures, barEntryFixture, runBar } from './test-fixtures/ui/bar.mjs';
import { featureDoubles, featureSuites, registryEntries, rootEntry } from './test-fixtures/sources.js';

const project = dirname(fileURLToPath(import.meta.url));
const Human = createRequire(import.meta.url)('./human.js');
// Suites on the shared Bar fixture: the full Bar flow and every feature-local
// suite (`features/<name>/fixtures/suite.mjs`).
const barSuites = [barSelection, ...featureSuites(project)];

export function childEnvironment(runtime, display, socket) {
    const directory = realpathSync(runtime);
    for (const path of [display, socket]) {
        assert.equal(dirname(realpathSync(path)), directory, 'refusing non-child socket');
        assert(lstatSync(path).isSocket(), 'child endpoint must be a socket');
    }
    assert.match(basename(display), /^wayland-\d+$/);
    assert.match(basename(socket), /^niri\..*\.sock$/);
    return { ...process.env, WAYLAND_DISPLAY: display, NIRI_SOCKET: socket, XDG_RUNTIME_DIR: directory };
}

export function assertCleanLog(text) {
    assert(!/\b(?:WARN(?:ING)?|ERROR)\b|Error parsing|binding loop|ReferenceError|TypeError|deprecated|Could not|failed/i.test(text), text);
}

// QTBUG-146211 workaround, owner-approved. Qt 6.12.0 QWaylandInputContext::setFocusObject
// enables without releasing, releases the new window instead of the current one, and clears
// the current window without releasing it when focus moves between windows. Fixed upstream
// by qtbase e26d5a8eee + b4dd527686 (6.12 branch). Raw logs stay intact; every occurrence
// is counted in evidence. ui-test.test.mjs fails once installed Qt differs from brokenQt:
// then delete this constant, unwrap assertFixtureLog, and `git grep QTBUG-146211` the rest.
export const qtTextInputWorkaround = {
    brokenQt: '6.12.0',
    warnings: [
        /^\s*(?:WARN|warning) qt\.qpa\.wayland\.textinput: virtual void QtWaylandClient::QWaylandTextInputv3::disableSurface\(wl_surface\*\) Trying to disable 0x[0-9a-f]+ but 0x[0-9a-f]+ is focused$/,
        /^\s*(?:WARN|warning) qt\.qpa\.wayland\.textinput: virtual void QtWaylandClient::QWaylandTextInputv3::enableSurface\(wl_surface\*\) Trying to enable 0x[0-9a-f]+ but 0x[0-9a-f]+ has focus$/,
    ],
};

export function assertFixtureLog(text) {
    let occurrences = 0;
    for (const line of text.split(/\r?\n/)) {
        if (qtTextInputWorkaround.warnings.some(warning => warning.test(line))) occurrences++;
        else assertCleanLog(line);
    }
    return occurrences;
}

// Owner-approved sandbox exception only. Preserve raw logs and fail every
// other diagnostic, including this same message at another level or source.
export function assertNiriLog(text) {
    const fallback = 'failed building default dmabuf feedback, falling back to v3: error getting EGL device render node\n\nCaused by:\n    None of the following EGL extensions is supported by the underlying EGL implementation, at least one is required: ["EGL_EXT_device_drm"]';
    const result = { softwareFallbacks: 0 };
    const records = stripVTControlCharacters(text).split(/(?=^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d+Z\s+(?:TRACE|DEBUG|INFO|WARN|ERROR)\s)/m);
    for (const record of records) {
        const match = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d+Z\s+(TRACE|DEBUG|INFO|WARN|ERROR)\s+(\S+): ([\s\S]*?)\s*$/.exec(record);
        const [, level, source, message] = match || [];
        if (level === 'DEBUG' && source === 'niri::backend::winit' && message === fallback)
            assert(++result.softwareFallbacks <= 1, 'duplicate software fallback');
        else assertCleanLog(record);
    }
    return result;
}

// Every rendered label a suite can see: chip and bar-control words, tooltips and
// accessible names, and each feature's visible texts, control names, texts and
// tooltips, each with the surface's `userTexts`, the parts a person or app wrote.
function* renderedLabels(state) {
    for (const [name, chip] of Object.entries(state?.chips || {}))
        for (const key of ['label', 'badge', 'title', 'accessibleName', 'tooltip']) yield [`chip ${name} ${key}`, chip[key], []];
    for (const [name, control] of Object.entries(state?.barControls || {}))
        for (const key of ['label', 'tooltip']) yield [`bar control ${name} ${key}`, control[key], []];
    for (const [name, feature] of Object.entries(state?.features || {})) {
        for (const surface of [feature, feature.focusOverlay].filter(Boolean)) {
            const written = surface.userTexts || [];
            for (const text of surface.texts || []) yield [`${name} text`, text, written];
            for (const [accessibleName, control] of Object.entries(surface.controls || {})) {
                yield [`${name} control name`, accessibleName, written];
                yield [`${name} control ${accessibleName}`, control.text, written];
                yield [`${name} control ${accessibleName} tooltip`, control.tooltipText, written];
            }
            for (const [objectName, item] of Object.entries(surface.items || {})) {
                yield [`${name} item ${objectName}`, item.text, written];
                yield [`${name} item ${objectName} tooltip`, item.tooltipText, written];
            }
        }
    }
}

export function machineLabels(state) {
    const found = [];
    for (const [where, value] of renderedLabels(state)) {
        const identifier = typeof value === 'string' ? Human.findMachineIdentifier(value) : '';
        if (identifier) found.push(`${where}: ${JSON.stringify(value)} shows ${JSON.stringify(identifier)}`);
    }
    return found;
}

// A label never shows a machine identifier (human.js), whatever the data.
export function assertHumanLabels(state) {
    const found = machineLabels(state);
    assert.equal(found.length, 0, `machine identifiers in rendered labels:\n${found.join('\n')}`);
}

// Narration: a line telling what the interface cannot do or why a control is
// off, instead of showing what works (zen rule 4). A control the source can
// never perform is absent; a passing state names itself in a short tooltip.
const narration = [
    /\bnot\s+supported\b/,
    /\b(?:is|are|was|were)n['’]t\s+supported\b/,
    /\bunsupported\s+(?:by|for|on|in|with)\b/,
    /\b(?:does|do)(?:n['’]t|\s+not)\s+support\b/,
    /\bonly\s+supports?\b/,
    /\b(?:unavailable|not\s+available)\s+(?:for|on|in|with|by)\s+(?:this|the|your)\b/,
    /\bcan(?:not|['’]t|\s+not)\s+be\s+(?:controlled|used|changed|adjusted|selected|opened|played|paused|skipped|seeked)\b/,
    /\bthis\s+[a-z]+\s+(?:can(?:not|['’]t|\s+not)|does(?:n['’]t|\s+not)\s+(?:support|allow|offer|provide|let)|has\s+no)\b/,
    /\b(?:disabled|unavailable|gr[ae]yed\s+out)\b[^.;]*\b(?:because|since|unless)\b/,
    // Two or more things and what they lack: "shuffle and repeat unavailable".
    /\b[a-z]+(?: [a-z]+)?(?:, [a-z]+(?: [a-z]+)?)*,? (?:and|or) [a-z]+(?: [a-z]+)? (?:(?:are|is) )?(?:not |no longer )?(?:supported|unsupported|available|unavailable|disabled|controllable|possible|allowed)\b/,
];

// Labels narrating the interface. Text a person or an app wrote (`userText`,
// e.g. a notification body or a clip) is data: it is cut out before matching.
export function narrationLabels(state) {
    const found = [];
    for (const [where, value, written] of renderedLabels(state)) {
        if (typeof value !== 'string' || value.length === 0) continue;
        let text = value.toLowerCase();
        for (const part of [...written].sort((a, b) => b.length - a.length))
            if (part) text = text.split(part.toLowerCase()).join(' · ');
        if (narration.some(pattern => pattern.test(text))) found.push(`${where}: ${JSON.stringify(value)}`);
    }
    return found;
}

// A label never narrates what the interface cannot do or explains it.
export function assertPlainLabels(state) {
    const found = narrationLabels(state);
    assert.equal(found.length, 0, `labels narrate the interface; show what works, hide what never can:\n${found.join('\n')}`);
}

export function assertPureService(text) {
    assert.match(text, /^import QtQuick\s+Item\s*\{/);
    assert.equal((text.match(/\bimport\b/g) || []).length, 1, 'mock imports must be QtQuick only');
    assert.deepEqual(text.match(/\b[A-Z]\w*\s*\{/g), ['Item {'], 'mock must contain only Item state/functions');
    assert(!/\b(?:Qt|Quickshell|Process|FileView|XMLHttpRequest|WebSocket|WorkerScript|PolkitAgent|PamContext|fetch|eval|Function)\b/.test(text), 'privileged or dynamic mock API');
}

export async function stopChild(child) {
    if (!child.pid || child.exitCode !== null || child.signalCode !== null) return;
    const closed = new Promise(resolve => child.once('close', resolve));
    child.kill('SIGTERM');
    const force = setTimeout(() => child.kill('SIGKILL'), 2000);
    try { await closed; } finally { clearTimeout(force); }
}

export function replayRequest(args) {
    const fixture = args[0] ?? 'all';
    const size = args[1];
    const fixtures = ['all', 'shell', 'controls', 'popups', 'privilege', 'niri', 'qt-focus', 'qt-focus-editor', ...barSuites];
    assert(args.length <= 2 && fixtures.includes(fixture)
        && (size === undefined || barSuites.includes(fixture) && ['1366x768', '2560x1440'].includes(size)),
        `usage: just ui-test [${fixtures.join('|')}] [${barSuites.join('/')}: 1366x768|2560x1440]`);
    return { version: 1, fixture, command: `just ui-test ${fixture}${size ? ` ${size}` : ''}`, ...(size ? { size } : {}) };
}

export function assertSafeCapture(snapshot) {
    assert(snapshot, 'snapshot unavailable for safe screenshot');
    if (snapshot.auth?.visible) {
        assert(snapshot.auth.hasInput === false || snapshot.auth.inputMasked === true, 'refusing screenshot of unmasked input');
    }
}

export async function captureUiFailure(error, { evidence, fixture, phase, snapshot, screenshot, write = writeFileSync }) {
    const record = { version: 1, fixture, phase, error: error.stack || String(error), snapshot, screenshot: null, captureErrors: [] };
    try { record.screenshot = await screenshot('failure'); }
    catch (captureError) { record.captureErrors.push(captureError.stack || String(captureError)); }
    write(join(evidence, 'failure.json'), JSON.stringify(record, null, 2));
    return record;
}

export async function finishUiRun(failure, { children, checkLogs, capture, stop = stopChild, report = error => console.error(error.stack || String(error)) }) {
    let captured = false;
    async function retainFailure() {
        if (!failure || captured) return;
        captured = true;
        try { await capture(failure); } catch (error) { report(error); }
    }
    // The first gate runs while niri is alive so infrastructure failures have pixels too.
    try { checkLogs(); } catch (error) { failure ||= error; }
    await retainFailure();
    for (const child of [...children].reverse()) {
        try { await stop(child); }
        catch (error) { if (failure) report(error); else failure = error; }
    }
    // Retain the original complete-log gate, including diagnostics emitted on shutdown.
    try { checkLogs(); } catch (error) { failure ||= error; }
    await retainFailure();
    if (failure) throw failure;
}

const evidencePrefix = 'nuguland-ui-test-';

// Concurrent runs create and remove evidence while another run prunes: a path that
// vanished between listing and reading is gone, not an error.
function gone(error) {
    if (error?.code !== 'ENOENT') throw error;
    return null;
}

export function treeBytes(path) {
    let info;
    try { info = lstatSync(path); } catch (error) { return gone(error) ?? 0; }
    if (!info.isDirectory()) return info.size;
    let names;
    try { names = readdirSync(path); } catch (error) { return gone(error) ?? 0; }
    return names.reduce((sum, name) => sum + treeBytes(join(path, name)), 0);
}

export function lastWrite(path) {
    try {
        return Math.max(lstatSync(path).mtimeMs, ...readdirSync(path).map(name => {
            try { return lstatSync(join(path, name)).mtimeMs; } catch (error) { return gone(error) ?? 0; }
        }));
    } catch (error) {
        return gone(error);
    }
}

// Run evidence is scratch: keep the newest runs per fixture and skip runs written
// recently, which may still be in progress. Durable evidence is copied into a spec.
export function pruneEvidence(root = tmpdir(), { keep = 3, quietMs = 15 * 60_000, now = Date.now() } = {}) {
    const runs = readdirSync(root, { withFileTypes: true })
        .filter(entry => entry.isDirectory() && entry.name.startsWith(evidencePrefix))
        .map(entry => {
            const path = join(root, entry.name);
            const modified = lastWrite(path);
            if (modified === null) return null;
            // A broken scratch run must never block the gate; it groups as unnamed instead.
            let fixture = '?';
            try { fixture = JSON.parse(readFileSync(join(path, 'replay.json'), 'utf8')).fixture ?? '?'; } catch { /* missing or partial replay.json */ }
            return { path, modified, fixture };
        })
        .filter(run => run !== null)
        .sort((a, b) => b.modified - a.modified);
    const kept = new Map();
    const removed = [];
    for (const run of runs) {
        const count = kept.get(run.fixture) ?? 0;
        if (count < keep || now - run.modified < quietMs) {
            kept.set(run.fixture, count + 1);
            continue;
        }
        removed.push({ ...run, bytes: treeBytes(run.path) });
        rmSync(run.path, { recursive: true, force: true });
    }
    return removed;
}

// One process-level SIGINT/SIGTERM handler interrupts every live sandbox.
const sandboxInterrupts = new Set();
const interruptSandboxes = () => { for (const interrupt of sandboxInterrupts) interrupt(); };
function onSignal(interrupt) {
    if (sandboxInterrupts.size === 0) {
        process.on('SIGINT', interruptSandboxes);
        process.on('SIGTERM', interruptSandboxes);
    }
    sandboxInterrupts.add(interrupt);
}
function offSignal(interrupt) {
    sandboxInterrupts.delete(interrupt);
    if (sandboxInterrupts.size > 0) return;
    process.off('SIGINT', interruptSandboxes);
    process.off('SIGTERM', interruptSandboxes);
}

async function outer(replay, { echo = true } = {}) {
    const evidence = mkdtempSync(join(tmpdir(), evidencePrefix));
    const runtime = mkdtempSync(join(tmpdir(), 'nuguland-ui-runtime-'));
    writeFileSync(join(runtime, 'passwd'), `test:x:${process.getuid()}:${process.getgid()}:test:/home/test:/bin/sh\n`);
    const args = [
        '--unshare-all', '--die-with-parent', '--new-session',
        '--ro-bind', '/usr', '/usr', '--symlink', 'usr/bin', '/bin',
        '--symlink', 'usr/lib', '/lib', '--symlink', 'usr/lib', '/lib64',
        '--proc', '/proc', '--dev', '/dev', '--tmpfs', '/tmp',
        '--ro-bind', '/etc/fonts', '/etc/fonts',
        '--ro-bind', '/etc/ld.so.cache', '/etc/ld.so.cache',
        '--ro-bind', '/etc/machine-id', '/etc/machine-id',
        '--ro-bind', join(runtime, 'passwd'), '/etc/passwd',
        '--dir', '/home/test', '--dir', '/run/user',
        '--overlay-src', project, '--tmp-overlay', '/project', '--bind', evidence, '/evidence',
        '--ro-bind', resolve(project, '../../niri/themes'), '/home/test/.config/niri/themes',
        '--ro-bind', resolve(project, '../../aerc/stylesets'), '/home/test/.config/aerc/stylesets',
        '--ro-bind', resolve(project, '../../aerc/aerc.conf'), '/aerc.conf',
        '--ro-bind', resolve(project, '../../aerc/binds.conf'), '/aerc-binds.conf',
        '--ro-bind', resolve(project, '../../wezterm/bugabinga'), '/wezterm/bugabinga',
        '--ro-bind', resolve(project, '../../neovim/colors'), '/nvim-theme/colors',
        '--ro-bind', resolve(project, '../../neovim/lua/bugabinga/nugu'), '/nvim-theme/lua/bugabinga/nugu',
        '--bind', runtime, '/run/user/1000',
        '--chdir', '/project', '--clearenv',
        '--setenv', 'PATH', '/usr/bin', '--setenv', 'HOME', '/home/test',
        '--setenv', 'LC_ALL', 'C.UTF-8',
        '--setenv', 'XDG_RUNTIME_DIR', '/run/user/1000',
        '--setenv', 'XDG_CONFIG_HOME', '/home/test/.config',
        '--setenv', 'XDG_CACHE_HOME', '/home/test/.cache',
        '--setenv', 'XDG_DATA_HOME', '/home/test/.local/share',
        '--setenv', 'XDG_STATE_HOME', '/home/test/.local/state',
        '--setenv', 'QT_QPA_PLATFORM', 'wayland',
        '--setenv', 'LIBGL_ALWAYS_SOFTWARE', '1',
        '--setenv', 'NUGULAND_UI_SANDBOX', '1',
        // The host home, so the sandbox can prove it cannot see it.
        '--setenv', 'NUGULAND_HOST_HOME', homedir(),
        'dbus-run-session', '--', 'node', '/project/ui-test.mjs', '--inside', replay.fixture, ...(replay.size ? [replay.size] : [])
    ];
    if (echo) console.log(`evidence: ${evidence}`);
    writeFileSync(join(evidence, 'replay.json'), JSON.stringify({ ...replay, phase: 'startup' }, null, 2));
    writeFileSync(join(evidence, 'command.json'), JSON.stringify({ cwd: project, command: ['bwrap', ...args] }, null, 2));
    const child = spawn('bwrap', args, { stdio: ['ignore', 'pipe', 'pipe'] });
    for (const stream of [child.stdout, child.stderr]) stream.on('data', data => {
        appendFileSync(join(evidence, 'runner.log'), data);
        if (echo) process.stdout.write(data);
    });
    let interrupted = false;
    const interrupt = () => {
        if (interrupted) return;
        interrupted = true;
        void stopChild(child);
    };
    onSignal(interrupt);
    const timeout = setTimeout(interrupt, 300_000);
    try {
        const code = await new Promise((resolve, reject) => {
            child.once('error', reject);
            child.once('close', (code, signal) => resolve(signal ? -1 : code));
        });
        assert(!interrupted, `nested UI test interrupted; full logs: ${evidence}`);
        assert.equal(code, 0, `nested UI test failed; full logs: ${evidence}`);
    } catch (error) {
        // An inner failure already owns its evidence; never replace it with bwrap's exit code.
        if (!existsSync(join(evidence, 'failure.json'))) {
            try {
                const { phase } = JSON.parse(readFileSync(join(evidence, 'replay.json'), 'utf8'));
                await captureUiFailure(error, {
                    evidence, fixture: replay.fixture, phase, snapshot: null,
                    screenshot: async () => { throw new Error('sandbox unavailable for capture'); }
                });
            } catch (captureError) { console.error(captureError.stack); }
        }
        if (error && typeof error === 'object') error.evidence = evidence;
        throw error;
    } finally {
        clearTimeout(timeout);
        offSignal(interrupt);
        await stopChild(child);
        rmSync(runtime, { recursive: true });
        assert(!existsSync(runtime), 'owned runtime was not removed');
    }
    return evidence;
}

// Each suite owns one sandbox; together they cover every phase. Keep software
// rendering bounded: unbounded compositor fan-out starves unrelated startup I/O.
export const allSuites = ['shell', 'controls', 'popups', 'privilege', ...barSuites, 'niri'];

async function outerAll() {
    const started = Date.now();
    const seconds = since => ((Date.now() - since) / 1000).toFixed(1);
    const results = new Array(allSuites.length);
    let next = 0;
    let interrupted = false;
    const interrupt = () => { interrupted = true; };
    onSignal(interrupt);
    try {
        await Promise.all(Array.from({ length: 2 }, async () => {
            while (next < allSuites.length) {
                const index = next++;
                const fixture = allSuites[index];
                const begun = Date.now();
                try {
                    assert(!interrupted, 'nested UI test interrupted; queued suite not run');
                    results[index] = { fixture, evidence: await outer(replayRequest([fixture]), { echo: false }), seconds: seconds(begun) };
                } catch (error) {
                    results[index] = { fixture, error, seconds: seconds(begun) };
                }
            }
        }));
    } finally {
        offSignal(interrupt);
    }
    for (const { fixture, evidence, error, seconds } of results) {
        if (!error) {
            console.log(`pass suite ${fixture} (${seconds}s): ${evidence}`);
            continue;
        }
        // Lead with the failing check from the suite's own record, then where to look.
        const record = error.evidence && join(error.evidence, 'failure.json');
        const cause = record && existsSync(record) ? JSON.parse(readFileSync(record, 'utf8')).error : String(error.stack || error);
        console.log(`FAIL suite ${fixture} (${seconds}s): ${String(cause).split('\n')[0]}\n  evidence: ${error.evidence ?? 'none'}`);
    }
    const failed = results.filter(result => result.error).map(result => result.fixture);
    console.log(`all: ${results.length - failed.length}/${results.length} suites passed in ${seconds(started)}s`);
    assert.equal(failed.length, 0, `failed suites: ${failed.join(', ')}; rerun one with just ui-test <suite>`);
}

async function inside(replay) {
    assert.equal(process.env.NUGULAND_UI_SANDBOX, '1', 'internal mode requires sandbox');
    assert.equal(process.env.HOME, '/home/test');
    assert.equal(process.env.WAYLAND_DISPLAY, undefined, 'parent Wayland connection must not be inherited');
    assert.equal(process.env.DISPLAY, undefined, 'parent X11 connection must not be inherited');
    assert(!existsSync('/run/dbus/system_bus_socket'), 'host system bus must be inaccessible');
    assert(process.env.NUGULAND_HOST_HOME && process.env.NUGULAND_HOST_HOME !== '/home/test', 'host HOME is named');
    assert(!existsSync(process.env.NUGULAND_HOST_HOME), 'host HOME must be inaccessible');
    assert(process.env.DBUS_SESSION_BUS_ADDRESS, 'private session bus required');
    const evidence = '/evidence';
    const children = [];
    const runtimeLogs = [];
    const qtFixtureLogs = new Set();
    let fixtureLog = '';
    let phase = 'startup';
    let latestSnapshot = null;
    let fixtureProcess = null;
    let snapshot = () => { throw new Error('fixture snapshot not ready'); };
    let failureScreenshot = async () => { throw new Error('child compositor not ready'); };
    assert.notEqual(replay.fixture, 'all', 'all runs one sandbox per suite');
    const controls = replay.fixture === 'controls';
    const bar = barSuites.includes(replay.fixture);
    const lifecycle = ['popups', 'privilege'].includes(replay.fixture);
    const integration = replay.fixture === 'niri';
    const nativeNiri = readFileSync('/project/Niri.qml', 'utf8');
    // A feature suite may end with a production proof, `fixtures/production.mjs`. It
    // runs against the feature's production sources, captured before doubles replace them.
    const productionProof = bar && existsSync(`/project/features/${replay.fixture}/fixtures/production.mjs`)
        ? featureDoubles('/project', replay.fixture).map(({ target }) => ({ target, text: readFileSync(`/project/${target}`, 'utf8') }))
        : null;
    const [outputWidth, outputHeight] = (replay.size || '1280x720').split('x').map(Number);
    function prepareBar() {
        for (const { source, target } of barOverlayFixtures) {
            const text = readFileSync(`/project/${source}`, 'utf8');
            assertPureService(text);
            writeFileSync(`/project/${target}`, text);
        }
        writeFileSync(`/project/${barEntryFixture.target}`, rootEntry(readFileSync(`/project/${barEntryFixture.source}`, 'utf8'), 2));
    }
    function enterPhase(name) {
        phase = name;
        writeFileSync(join(evidence, 'replay.json'), JSON.stringify({ ...replay, phase }, null, 2));
        console.log(`phase: ${name} (fixture: ${replay.fixture})`);
    }
    // Compositor system-bus watchers use the private bus, never the host bus.
    let env = { ...process.env, DBUS_SYSTEM_BUS_ADDRESS: process.env.DBUS_SESSION_BUS_ADDRESS };
    function run(command, args = []) {
        const started = Date.now();
        const result = spawnSync(command, args, { env, encoding: 'utf8', timeout: 30_000 });
        appendFileSync(join(evidence, 'commands.log'), `${new Date(started).toISOString()} ${JSON.stringify([command, ...args])}\n${result.stdout || ''}${result.stderr || ''}exit: ${result.status} ${Date.now() - started}ms\n`);
        if (result.error) throw result.error;
        assert.equal(result.status, 0, `${command}: ${result.stdout}${result.stderr}`);
        return result.stdout.trim();
    }
    function start(command, args, name, childEnv = env) {
        appendFileSync(join(evidence, 'commands.log'), `${new Date().toISOString()} start: ${JSON.stringify([command, ...args])}\n`);
        const child = spawn(command, args, { env: childEnv, stdio: ['ignore', 'pipe', 'pipe'] });
        const log = join(evidence, `${name}.log`);
        writeFileSync(log, '');
        runtimeLogs.push(log);
        if (command === 'qs' || command === '/usr/lib/qt6/bin/qml') qtFixtureLogs.add(log);
        for (const stream of [child.stdout, child.stderr]) stream.on('data', data => appendFileSync(log, data));
        child.on('error', error => { child.failure = error; });
        children.push(child);
        return child;
    }
    async function waitFor(label, predicate) {
        const deadline = Date.now() + 30_000;
        while (Date.now() < deadline) {
            for (const child of children) {
                if (child.failure) throw child.failure;
                assert.equal(child.exitCode, null, `child exited during ${label}; inspect logs`);
                assert.equal(child.signalCode, null, `child signalled during ${label}; inspect logs`);
            }
            if (fixtureLog) assertFixtureLog(readFileSync(fixtureLog, 'utf8'));
            const value = predicate();
            if (value) return value;
            await delay(50);
        }
        throw new Error(`timeout: ${label}`);
    }
    let failure = null;
    try {
        enterPhase('startup');
        // Drop a host-generated symlink only in the disposable overlay.
        rmSync('/project/.qmlls.ini', { force: true });
        writeFileSync('/project/.qmlls.ini', '');
        writeFileSync(join(evidence, 'versions.txt'), [run('weston', ['--version']), run('niri', ['--version']), run('qs', ['--version']), run('wdotool', ['--version']), run('/usr/lib/qt6/bin/qmllint', ['--version'])].join('\n') + '\n');
        const runtime = process.env.XDG_RUNTIME_DIR;
        const busFlags = run('pkg-config', ['--cflags', '--libs', 'libsystemd']).split(/\s+/);
        run('cc', ['-std=c17', '-Wall', '-Wextra', '-Werror', '/project/test-fixtures/ui/session-bus.c', ...busFlags, '-o', '/tmp/nuguland-session-bus']);
        start('/tmp/nuguland-session-bus', [], 'session-bus');
        await waitFor('private login/locale fixtures', () => readFileSync(join(evidence, 'session-bus.log'), 'utf8').includes('session fixtures ready'));
        const westonSocket = join(runtime, 'weston-headless');
        const westonModules = [];
        if (integration) {
            const flags = run('pkg-config', ['--cflags', '--libs', 'libweston-15', 'wayland-server', 'xkbcommon']).split(/\s+/);
            run('cc', ['-std=gnu17', '-Wall', '-Wextra', '-Werror', '-shared', '-fPIC', '/project/test-fixtures/ui/niri-integration-keyboard.c', ...flags, '-o', '/tmp/niri-integration-keyboard.so']);
            run('mkfifo', [join(runtime, 'niri-integration-keyboard.fifo')]);
            westonModules.push('--modules=/tmp/niri-integration-keyboard.so');
        }
        start('weston', ['--backend=headless', '--renderer=pixman', '--shell=kiosk', '--socket=weston-headless', `--width=${outputWidth}`, `--height=${outputHeight}`, '--idle-time=0', '--no-config', '--fake-seat', ...westonModules], 'weston');
        await waitFor('headless Weston socket', () => existsSync(westonSocket) && lstatSync(westonSocket).isSocket());
        env.WAYLAND_DISPLAY = westonSocket;
        if (replay.fixture === barSelection) {
            run('env', ['GSETTINGS_BACKEND=keyfile', 'nu', '--no-config-file', '-c', 'use /project/runtime/theme.nu; theme prepare']);
            appendFileSync('/project/test-fixtures/ui/niri.kdl', '\ninclude "~/.nugu-runtime/niri.kdl"\n');
        }
        run('niri', ['validate', '--config', '/project/test-fixtures/ui/niri.kdl']);
        const compositor = start('niri', ['--config', '/project/test-fixtures/ui/niri.kdl'], 'niri');
        const endpoints = await waitFor('nested compositor sockets', () => {
            const files = readdirSync(runtime);
            const display = files.find(name => /^wayland-\d+$/.test(name));
            const socket = files.find(name => /^niri\..*\.sock$/.test(name));
            return display && socket ? [join(runtime, display), join(runtime, socket)] : null;
        });
        env = { ...env, ...childEnvironment(runtime, ...endpoints), DBUS_SYSTEM_BUS_ADDRESS: env.DBUS_SYSTEM_BUS_ADDRESS };
        await waitFor('Niri consumed private login/locale properties', () => {
            const log = readFileSync(join(evidence, 'session-bus.log'), 'utf8');
            return ['org.freedesktop.login1.Manager.LidClosed', ...['X11Model', 'X11Layout', 'X11Variant', 'X11Options'].map(name => `org.freedesktop.locale1.${name}`)].every(name => log.includes(`read ${name}\n`));
        });
        assert.equal(run('busctl', ['--address', env.DBUS_SESSION_BUS_ADDRESS, 'get-property', 'org.freedesktop.login1', '/org/freedesktop/login1', 'org.freedesktop.login1.Manager', 'LidClosed']), 'b false');
        assert.equal(run('busctl', ['--address', env.DBUS_SESSION_BUS_ADDRESS, 'get-property', 'org.freedesktop.locale1', '/org/freedesktop/locale1', 'org.freedesktop.locale1', 'X11Layout']), 's "us"');
        assert.notEqual(env.WAYLAND_DISPLAY, westonSocket, 'input must target niri, not Weston');
        // niri writes the PNG, then reports it to the fixture's notification server
        // from its encoder thread. A fixture snapshot that counts received
        // notifications as `notices` makes every capture wait for that report, so
        // no D-Bus call is in flight when a suite ends and teardown starts.
        async function screenshot(name, settleMs = 300, delivered = true) {
            // Never change the failing UI to make evidence look safe or successful.
            // Password-mode pixels are already masked; revealed input refuses capture.
            // Motion evidence samples in-flight frames; ordinary/failure captures
            // retain their settled default and the same safety/log checks.
            assert(Number.isSafeInteger(settleMs) && settleMs >= 0 && settleMs <= 300);
            await delay(settleMs);
            assert.equal(compositor.exitCode, null, 'child compositor exited before capture');
            assert.equal(compositor.signalCode, null, 'child compositor signalled before capture');
            childEnvironment(runtime, ...endpoints);
            let notices = null;
            if (fixtureProcess?.pid && fixtureProcess.exitCode === null && fixtureProcess.signalCode === null) {
                const before = snapshot();
                assertSafeCapture(before);
                if (delivered && Number.isInteger(before.notices)) notices = before.notices;
            }
            const path = join(evidence, `${name}.png`);
            run('niri', ['msg', 'action', 'screenshot-screen', '--show-pointer', 'false', '--path', path]);
            // Failure capture must not run the fixture-log gate that caused the failure.
            const deadline = Date.now() + 3000;
            while (Date.now() < deadline && !(existsSync(path) && lstatSync(path).size > 0)) await delay(50);
            if (!(existsSync(path) && lstatSync(path).size > 0)) throw new Error(`timeout: screenshot ${name}`);
            if (notices !== null) await waitFor(`${name} screenshot notification delivered`, () => snapshot().notices > notices);
            return path;
        }
        failureScreenshot = name => screenshot(name, 300, false);
        writeFileSync(join(evidence, 'outputs.json'), run('niri', ['msg', '--json', 'outputs']));
        start('wdotool', ['--backend', 'wlr-protocols', 'prime'], 'input');
        await waitFor('virtual input ready', () => readFileSync(join(evidence, 'input.log'), 'utf8').includes('ready'));
        if (replay.fixture === 'qt-focus' || replay.fixture === 'qt-focus-editor') {
            const editorFirst = replay.fixture === 'qt-focus-editor';
            enterPhase(replay.fixture);
            // Niri's failure screenshot needs a notification daemon on the private
            // bus. This sidecar has no windows; the subject runs in plain qml.
            writeFileSync('/tmp/qt-focus-notifications.qml', 'import Quickshell\nimport Quickshell.Services.Notifications\nScope { NotificationServer {} }\n');
            start('qs', ['--no-color', '-p', '/tmp/qt-focus-notifications.qml'], 'qt-focus-notifications');
            await waitFor('diagnostic notification service', () => readFileSync(join(evidence, 'qt-focus-notifications.log'), 'utf8').includes('Configuration Loaded'));
            fixtureProcess = start('/usr/lib/qt6/bin/qml', ['/project/test-fixtures/ui/qt-focus.qml', ...(editorFirst ? ['--', '--editor-first'] : [])], 'qt-focus', {
                ...env, QT_FORCE_STDERR_LOGGING: '1', QT_MESSAGE_PATTERN: '%{type} %{category}: %{message}'
            });
            fixtureLog = join(evidence, 'qt-focus.log');
            const focused = name => (readFileSync(fixtureLog, 'utf8').match(new RegExp(`qt-focus:${name}=true`, 'g')) || []).length;
            snapshot = () => ({ control: 'plain Qt Window', plainFocusEvents: focused('plain'), editorFocusEvents: focused('editor') });
            await waitFor('plain Qt initial focus', () => focused('window-active') && focused(editorFirst ? 'editor' : 'plain'));
            if (!editorFirst) run('wdotool', ['--backend', 'wlr-protocols', 'key', 'Tab']);
            await waitFor('plain Qt editor focus', () => focused('editor'));
            run('wdotool', ['--backend', 'wlr-protocols', 'type', 'probe']);
            await waitFor('plain Qt editor input', () => readFileSync(fixtureLog, 'utf8').includes('qt-focus:typed=true'));
            run('wdotool', ['--backend', 'wlr-protocols', 'key', 'shift+Tab']);
            await waitFor('plain Qt non-editable focus return', () => focused('plain') >= (editorFirst ? 1 : 2));
            console.log('pass: plain Qt focus transitions and text input');
            return;
        }
        if (lifecycle) {
            for (const name of ['Privilege', 'Niri']) {
                const source = `/project/test-fixtures/ui/fixture-services/lifecycle/${name}.qml`;
                assertPureService(readFileSync(source, 'utf8'));
                copyFileSync(source, `/project/${name}.qml`);
            }
            // Keep the scanner root at /project, as for the original shared fixture.
            writeFileSync('/project/lifecycle-ui-test.qml', rootEntry(readFileSync('/project/test-fixtures/ui/lifecycle.qml', 'utf8'), 2));
        }
        // Every Bar fixture runs feature services as their feature-local doubles,
        // except those the native integration fixture proves for real.
        if (lifecycle || bar || integration) {
            for (const { source, target } of featureDoubles('/project', null, integration ? nativeFeatures : [])) {
                assertPureService(readFileSync(`/project/${source}`, 'utf8'));
                copyFileSync(`/project/${source}`, `/project/${target}`);
            }
        }
        let integrationSetup;
        async function prepareIntegration() {
            integrationSetup = await prepareNiriIntegration({ run, start, waitFor, runtime, nativeNiri, nativeSocket: endpoints[1] });
            childEnvironment(runtime, endpoints[0], integrationSetup.socket);
        }
        if (integration) await prepareIntegration();
        if (bar) prepareBar();
        const production = replay.fixture === 'shell';
        let productionEnv = env;
        if (production) {
            // The shipped composition runs against private stand-ins for the
            // services it expects: an empty PipeWire graph, UPower, power
            // profiles, a polkit authority, and a fixture logind session.
            // The sandbox grants no realtime scheduling: neither the daemon nor its
            // clients (the shell) load module-rt, whose failed promotion warns.
            for (const config of ['pipewire', 'client']) {
                mkdirSync(`/home/test/.config/pipewire/${config}.conf.d`, { recursive: true });
                writeFileSync(`/home/test/.config/pipewire/${config}.conf.d/nuguland-ui-test.conf`, 'context.properties = { module.rt = false }\n');
            }
            start('pipewire', [], 'pipewire');
            await waitFor('private pipewire socket', () => existsSync(join(process.env.XDG_RUNTIME_DIR, 'pipewire-0')));
            run('cc', ['-std=c17', '-Wall', '-Wextra', '-Werror', '/project/test-fixtures/ui/shell-services.c', ...busFlags, '-o', '/tmp/nuguland-shell-services']);
            start('/tmp/nuguland-shell-services', [], 'shell-services');
            await waitFor('private shell service stand-ins', () => readFileSync(join(evidence, 'shell-services.log'), 'utf8').includes('shell services ready'));
            run('cc', ['-std=c17', '-Wall', '-Wextra', '-Werror', '-shared', '-fPIC', '/project/test-fixtures/ui/session-shim.c', '-o', '/tmp/nuguland-session-shim.so']);
            productionEnv = { ...env, LD_PRELOAD: '/tmp/nuguland-session-shim.so' };
        }
        let fixture = production ? '/project/shell.qml' : controls ? '/project/ui-test.qml' : lifecycle ? '/project/lifecycle-ui-test.qml' : bar ? '/project/bar-ui-test.qml' : '/project/niri-integration-ui-test.qml';
        const firstLog = production ? 'shell' : controls ? 'quickshell' : lifecycle ? 'lifecycle' : bar ? 'bar' : 'niri-integration';
        if (replay.fixture === barSelection) {
            const themeEnv = { ...env, GSETTINGS_BACKEND: 'keyfile', GIO_USE_VFS: 'local' };
            const gioFlags = run('pkg-config', ['--cflags', '--libs', 'gio-2.0']).split(/\s+/);
            run('cc', ['-std=c17', '-Wall', '-Wextra', '-Werror', '/project/test-fixtures/ui/theme-portal.c', ...gioFlags, '-o', '/tmp/nuguland-theme-portal']);
            start('/tmp/nuguland-theme-portal', [], 'theme-portal', themeEnv);
            await waitFor('private desktop settings portal', () => run('busctl', ['--address', env.DBUS_SESSION_BUS_ADDRESS, 'call', 'org.freedesktop.DBus', '/org/freedesktop/DBus', 'org.freedesktop.DBus', 'NameHasOwner', 's', 'org.freedesktop.portal.Desktop']) === 'b true');
            writeFileSync('/tmp/theme-wezterm.lua', `local wez = require 'wezterm'
package.path = '/wezterm/?.lua;/wezterm/?/init.lua;' .. package.path
local cfg = wez.config_builder()
require 'bugabinga.theme' (cfg)
cfg.enable_wayland = true
cfg.enable_tab_bar = false
cfg.check_for_updates = false
local f = assert(io.open('/evidence/theme-wezterm-mode', 'w'))
f:write(cfg.color_scheme)
f:close()
return cfg
`);
            start('wezterm', ['--config-file', '/tmp/theme-wezterm.lua', 'start', '--always-new-process', '--', '/usr/bin/cat'], 'theme-wezterm', themeEnv);
            await waitFor('native terminal reads dark appearance', () => existsSync('/evidence/theme-wezterm-mode') && readFileSync('/evidence/theme-wezterm-mode', 'utf8') === 'nugu-dark');
            writeFileSync('/tmp/theme-neovide.lua', `vim.opt.runtimepath:append('/nvim-theme')
vim.g.neovide_theme = 'auto'
vim.cmd.colorscheme('nugu')
vim.api.nvim_buf_set_lines(0, 0, -1, false, {'retained editor draft'})
local function record()
  vim.schedule(function()
    local normal = vim.api.nvim_get_hl(0, {name = 'Normal'})
    vim.fn.writefile({vim.json.encode({mode = vim.o.background, foreground = normal.fg, background = normal.bg, draft = vim.api.nvim_get_current_line()})}, '/evidence/theme-neovide.json.tmp')
    assert(vim.uv.fs_rename('/evidence/theme-neovide.json.tmp', '/evidence/theme-neovide.json'))
  end)
end
vim.api.nvim_create_autocmd({'ColorScheme', 'OptionSet'}, {callback = record})
record()
`);
            start('neovide', ['--no-fork', '--', '-u', '/tmp/theme-neovide.lua', '--noplugin', '-i', 'NONE'], 'theme-neovide', themeEnv);
            await waitFor('native editor reads dark appearance', () => existsSync('/evidence/theme-neovide.json') && JSON.parse(readFileSync('/evidence/theme-neovide.json', 'utf8')).mode === 'dark');
        }
        // Production preparation creates this parent before Theme.qml watches the mode file.
        mkdirSync(join(process.env.XDG_STATE_HOME, 'nugu'), { recursive: true });
        fixtureProcess = start('qs', ['--no-color', '-p', fixture], firstLog, productionEnv);
        fixtureLog = join(evidence, `${firstLog}.log`);
        await waitFor('quickshell loaded', () => {
            const log = readFileSync(fixtureLog, 'utf8');
            assertFixtureLog(log);
            return log.includes('Configuration Loaded');
        });
        const qmllsConfig = await waitFor('generated qmlls configuration', () => {
            const config = readFileSync('/project/.qmlls.ini', 'utf8');
            return config.includes('importPaths=') && config.includes('buildDir=') ? config : null;
        });
        writeFileSync(join(evidence, 'qmlls.ini'), qmllsConfig);
        console.log('pass: Quickshell generated its upstream-recommended qmlls configuration');
        const ipc = (...args) => run('qs', ['ipc', '-p', fixture, 'call', 'uiTest', ...args]);
        snapshot = () => {
            const text = ipc('snapshot');
            assert(!text.includes('fixture-only'), 'snapshot exposed synthetic input');
            const state = JSON.parse(text);
            latestSnapshot = state;
            return state;
        };
        const input = (...args) => run('wdotool', ['--backend', 'wlr-protocols', ...args]);
        const key = key => input('key', key);
        const click = rect => {
            input('mousemove', String(Math.round(rect.x + rect.width / 2)), String(Math.round(rect.y + rect.height / 2)));
            input('click', '1');
        };
        // Bar suites see only snapshots whose labels are human and plain; the failure
        // screenshot reads the unguarded snapshot, so the offending pixels survive.
        const labelledSnapshot = () => {
            const state = snapshot();
            if (bar) {
                assertHumanLabels(state);
                assertPlainLabels(state);
            }
            return state;
        };
        async function check(label, predicate) {
            const state = await waitFor(label, () => { const state = labelledSnapshot(); return predicate(state) ? state : null; });
            appendFileSync(join(evidence, 'assertions.jsonl'), JSON.stringify({ label, state }) + '\n');
            console.log(`pass: ${label}`);
            return state;
        }
        let state;
        if (production) {
            enterPhase('shell');
            const nuguland = (...args) => run('qs', ['ipc', '-p', fixture, 'call', 'nuguland', ...args]);
            const diagnostics = () => JSON.parse(nuguland('diagnostics'));
            // Production has no uiTest target; failure capture and screenshots use the
            // redacted diagnostics snapshot. The stand-in authority never requests auth.
            // niri's screenshot reports arrive as toasts; native ids only increase.
            const toasts = () => JSON.parse(nuguland('notificationsState')).activeToasts;
            snapshot = () => {
                latestSnapshot = { ...diagnostics(), notices: Math.max(0, ...toasts().map(toast => Number(toast.id))) };
                return latestSnapshot;
            };
            await waitFor('production shell answers its diagnostics IPC (reachability)', () => diagnostics().version === 1);
            await waitFor('production polkit agent registers with the stand-in authority',
                () => /^register RegisterAuthenticationAgent/m.test(readFileSync(join(evidence, 'shell-services.log'), 'utf8')));
            console.log('pass: production shell started its services against the sandbox stand-ins');
            // Dismiss each delivered screenshot toast so the next capture shows the
            // shell, not harness toasts.
            const capture = async name => {
                await screenshot(name);
                nuguland('notificationsDismissToasts');
                await waitFor(`${name} screenshot notification dismissed`, () => toasts().length === 0);
            };
            await capture('shell-loaded');
            assert.equal(nuguland('setOrientation', 'vertical'), 'vertical');
            await waitFor('production IPC orientation remaps Bar', () => diagnostics().popup.orientation === 'vertical');
            assert.equal(nuguland('setOrientation', 'invalid'), 'vertical');
            assert.equal(nuguland('setOrientation', 'toggle'), 'horizontal');
            await waitFor('production toggle restores Bar', () => diagnostics().popup.orientation === 'horizontal');

            // Every popup builds its panel inside the production composition.
            for (const name of registryEntries(project).filter(entry => entry.kind === 'popup').map(entry => entry.name)) {
                nuguland('openRegisteredPopup', name);
                await waitFor(`production ${name} popup opens`, () => {
                    const popup = diagnostics().popup;
                    return popup.name === name && popup.phase === 'open';
                });
                console.log(`pass: production ${name} popup opens`);
                await capture(`shell-${name}`);
                nuguland('closePopup');
                await waitFor(`production ${name} popup closes`, () => diagnostics().popup.phase === 'closed');
            }
            // Every overlay builds and shows through its production IPC.
            nuguland('osdTrigger', 'volume', '40');
            await waitFor('production osd overlay shows', () => JSON.parse(nuguland('osdState')).visible === true);
            console.log('pass: production osd overlay shows');
            await capture('shell-osd');
        }
        if (controls) {
            enterPhase('controls');
            await runControls({ ipc, input, key, click, check, screenshot, delay });
        }
        const hasText = (rows, text) => rows.some(row => row.text === text);
        const within = (rect, width, height) => rect && rect.width > 0 && rect.height > 0 && rect.x >= 0 && rect.y >= 0 && rect.x + rect.width <= width && rect.y + rect.height <= height;
        // System's fixture content is fixed; calendar/Config fit their current content.
        const fitted = { system: 585 };
        function geometry(s, name, height) {
            const vertical = s.orientation === 'vertical';
            const width = { clock: 760, system: 780, config: 680 }[name];
            // The card fits the panel's natural height; the entry height is its maximum.
            const maximum = name === 'clock' ? 580 : 600;
            height ??= Math.min(maximum, s.popup.panelHeight + 48);
            assert(s.popup.panelHeight > 0, `${name} declares its natural height`);
            assert.equal(height, Math.min(maximum, s.popup.panelHeight + 48), `${name} card fits its content`);
            assert.deepEqual(s.popup.contentSize, { width, height });
            assert.deepEqual(s.card, {
                x: vertical ? 56 : Math.round((1280 - width) / 2) + 8,
                y: vertical ? Math.round((720 - height) / 2) + 8 : 56,
                width: width - 16, height: height - 16
            });
            assert(within(s.card, s.width, s.height));
            assert(within(s.panel, s.width, s.height));
        }
        function diagnostics() {
            const text = run('qs', ['ipc', '-p', fixture, 'call', 'nuguland', 'diagnostics']);
            assert(!text.includes('diagnostic-private-sentinel'), 'diagnostics exposed private fixture state');
            const data = JSON.parse(text);
            assert.equal(data.version, 1);
            assert.deepEqual(data.services.niri, { available: true, ready: true, windowCount: 1, workspaceCount: 1 });
            assert.deepEqual(data.services.vault, { status: 'locked', lockPending: false });
            assert.deepEqual(data.displays, [{ x: 0, y: 0, width: 1280, height: 720, scale: 1 }]);
            appendFileSync(join(evidence, 'diagnostics.jsonl'), text + '\n');
            return data;
        }
        async function opened(name, height = fitted[name]) {
            const s = await check(`${name} open in mapped ${snapshot().orientation} geometry`, s => s.popup.name === name && s.popup.phase === 'open' && s.card && s.card.y === s.popup.popupCardFrame.currentRect.y && s.card.height === s.popup.popupCardFrame.currentRect.height);
            geometry(s, name, height);
            const diagnostic = diagnostics();
            assert.equal(diagnostic.popup.name, name);
            assert.equal(diagnostic.popup.phase, 'open');
            assert.deepEqual(diagnostic.popup.card, s.card);
            return s;
        }
        if (lifecycle) state = await check('lifecycle initially closed without resource polling', s => !s.popup.open && !s.resources.open);
        if (replay.fixture === 'popups') {
            enterPhase('popups');
            await runPopups({ ipc, snapshot, input, key, click, check, screenshot, opened, hasText });
        }
        if (replay.fixture === 'privilege') {
            enterPhase('privilege');
            await runPrivilege({ ipc, input, key, click, check, screenshot, delay, within, hasText });
        }
        if (lifecycle) {
            const diagnostic = diagnostics();
            const transitions = await waitFor('transition log reaches diagnostic operation', () => {
                const log = readFileSync(fixtureLog, 'utf8');
                const events = log.split('\n').filter(line => line.includes('"kind":"popup-transition"')).map(line => JSON.parse(line.slice(line.indexOf('{'))));
                return diagnostic.popup.operationId === 0 || events.at(-1)?.operationId === diagnostic.popup.operationId ? events : null;
            });
            assert(!JSON.stringify(transitions).includes('diagnostic-private-sentinel'));
            if (replay.fixture === 'popups') {
                assert.deepEqual(transitions.slice(0, 4).map(({ operationId, event }) => [operationId, event]), [[1, 'opening'], [1, 'opened'], [2, 'switched'], [3, 'switched']]);
                assert.equal(transitions.at(-1).event, 'closed');
                assert.equal(transitions.at(-1).operationId, diagnostic.popup.operationId);
                for (let i = 1; i < transitions.length; i++) {
                    const event = transitions[i];
                    const previous = transitions[i - 1];
                    assert.equal(event.operationId, previous.operationId + (event.event === 'opened' ? 0 : 1));
                    if (event.event === 'opened') assert.equal(previous.event, 'opening');
                }
                console.log('pass: redacted diagnostics correlate with runtime popup transitions');
            } else assert.equal(transitions.length, 0);
            console.log('lifecycle UI assertions passed; screenshots require visual review');
        }
        if (bar) {
            enterPhase(replay.fixture);
            await runBar({ ipc, snapshot: labelledSnapshot, input, key, click, check, screenshot, run, delay, only: replay.fixture === barSelection ? '' : replay.fixture });
        }
        if (productionProof) {
            // Only the Bar fixture stops; the compositor, input and private bus stay alive.
            await stopChild(fixtureProcess);
            assertFixtureLog(readFileSync(fixtureLog, 'utf8'));
            children.splice(children.indexOf(fixtureProcess), 1);
            latestSnapshot = null;
            enterPhase(`${replay.fixture}-production`);
            for (const { target, text } of productionProof) writeFileSync(`/project/${target}`, text);
            const { default: proof } = await import(`/project/features/${replay.fixture}/fixtures/production.mjs`);
            await proof({ env, start, stop: stopChild, waitFor, ipc, screenshot, snapshot, click, key, input,
                setFixture(path, log, child) { fixture = path; fixtureLog = log; fixtureProcess = child; }
            });
        }
        if (integration) {
            enterPhase('niri');
            await runNiriIntegration({
                run, start, check, snapshot, ipc, screenshot, click, input, key, waitFor, evidence, runtime,
                modeFile: integrationSetup.modeFile,
                compositorKey: async name => {
                    childEnvironment(runtime, ...endpoints);
                    assert.equal(compositor.exitCode, null);
                    assert.equal(compositor.signalCode, null);
                    const keys = { Escape: [1], Return: [28], 'ctrl+c': [29, 46] }[name];
                    assert(keys, 'unsupported nested compositor key');
                    for (const [key, pressed] of [...keys.map(key => [key, 1]), ...keys.toReversed().map(key => [key, 0])]) {
                        const command = Buffer.alloc(12);
                        [compositor.pid, key, pressed].forEach((value, index) => command.writeUInt32LE(value, index * 4));
                        writeFileSync(join(runtime, 'niri-integration-keyboard.fifo'), command);
                        appendFileSync(join(evidence, 'input.log'), `nested compositor ${compositor.pid}: key ${key} state ${pressed}\n`);
                        await delay(50);
                    }
                },
                stop: async child => {
                    await stopChild(child);
                    children.splice(children.indexOf(child), 1);
                }
            });
        }
        enterPhase('runtime-diagnostics');
    } catch (error) {
        failure = error;
    } finally {
        await finishUiRun(failure, {
            children,
            checkLogs: () => {
                let diagnostics;
                const temporaryQtFocusWarnings = {};
                for (const log of runtimeLogs) {
                    const text = readFileSync(log, 'utf8');
                    if (log === join(evidence, 'niri.log')) diagnostics = assertNiriLog(text);
                    else if (qtFixtureLogs.has(log)) {
                        const count = assertFixtureLog(text);
                        if (count) temporaryQtFocusWarnings[basename(log)] = count;
                    } else assertCleanLog(text);
                }
                writeFileSync(join(evidence, 'runtime-diagnostics.json'), JSON.stringify({ ...diagnostics, temporaryQtFocusWarnings }, null, 2));
            },
            capture: error => captureUiFailure(error, {
                evidence, fixture: replay.fixture, phase, snapshot: latestSnapshot, screenshot: failureScreenshot
            })
        });
    }
}

if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
    try {
        if (process.argv[2] === '--inside') await inside(replayRequest(process.argv.slice(3)));
        else {
            const replay = replayRequest(process.argv.slice(2));
            const removed = pruneEvidence();
            if (removed.length) {
                const megabytes = removed.reduce((sum, run) => sum + run.bytes, 0) / 1e6;
                console.log(`pruned ${removed.length} old evidence runs (${megabytes.toFixed(1)} MB); kept the newest 3 per fixture`);
            }
            if (replay.fixture === 'all') await outerAll();
            else await outer(replay);
        }
    } catch (error) {
        console.error(error.stack);
        process.exitCode = 1;
    }
}