Add web layout probe evidence

This commit is contained in:
Meta Vens 2026-07-09 12:24:52 +01:00
commit c0c17beb45
17 changed files with 605 additions and 7 deletions

View file

@ -28,6 +28,7 @@
"schemas/gamecult.eve.provider_handoff.v1.schema.json",
"schemas/gamecult.eve.electron_shell_projection.v1.schema.json",
"schemas/gamecult.eve.tui_grid.v1.schema.json",
"schemas/gamecult.eve.web_layout_probe.v1.schema.json",
"schemas/gamecult.eve.runtime_capability.v1.schema.json",
"schemas/gamecult.eve.runtime_lifecycle.v1.schema.json",
"schemas/gamecult.eve.runtime_split_handoff.v1.schema.json",
@ -92,6 +93,7 @@
"gamecult.eve.provider_handoff.v1",
"gamecult.eve.electron_shell_projection.v1",
"gamecult.eve.tui_grid.v1",
"gamecult.eve.web_layout_probe.v1",
"gamecult.eve.runtime_capability.v1",
"gamecult.eve.runtime_lifecycle.v1",
"gamecult.eve.runtime_split_handoff.v1"

View file

@ -24,6 +24,7 @@
"gamecult.eve.runtime_split_handoff.v1": "schemas/gamecult.eve.runtime_split_handoff.v1.schema.json",
"gamecult.eve.runtime_release_request.v1": "schemas/gamecult.eve.runtime_release_request.v1.schema.json",
"gamecult.eve.runtime_capture_request.v1": "schemas/gamecult.eve.runtime_capture_request.v1.schema.json",
"gamecult.eve.web_layout_probe.v1": "schemas/gamecult.eve.web_layout_probe.v1.schema.json",
"gamecult.eve.provider_scenario.v1": "schemas/gamecult.eve.provider_scenario.v1.schema.json",
"gamecult.eve.provider_advertisement.v1": "schemas/gamecult.eve.provider_advertisement.v1.schema.json",
"gamecult.eve.provider_handoff.v1": "schemas/gamecult.eve.provider_handoff.v1.schema.json",
@ -1112,7 +1113,17 @@
},
"capture": {
"status": "chrome-headless",
"note": "Chrome headless captures phone, tablet, and desktop PNGs through the provider query parameter."
"note": "Chrome headless captures phone, tablet, and desktop PNGs through the provider query parameter.",
"layoutProbes": [
{
"fixtureId": "embedded-surface",
"providerId": "gamecult.eve.embedded-demo",
"surfaceId": "gamecult.eve.embedded-demo",
"schema": "gamecult.eve.web_layout_probe.v1",
"path": "artifacts/web-reference-layout-probe/latest/embedded-surface.json",
"runner": "scripts/run-web-reference-layout-probe-smoke.ps1"
}
]
}
},
{

View file

@ -2503,6 +2503,47 @@ function buildColorTokenMetric(runtime, fixture) {
}
function buildBoundingBoxMetric(runtime, fixture) {
const layoutProbe = readRuntimeLayoutProbe(runtime, fixture.id);
if (layoutProbe.config) {
if (layoutProbe.document && !layoutProbe.errors.length) {
const measured = Number(layoutProbe.document.summary?.measuredNodeCount || 0);
const total = Number(layoutProbe.document.summary?.nodeCount || 0);
return buildScreenshotMetric(runtime, fixture, {
metricKind: "bounding-boxes",
status: measured > 0 ? "pass" : "fail",
score: ratio(measured, total),
expected: {
schema: layoutProbe.config.schema || "",
path: layoutProbe.config.path || "",
providerId: layoutProbe.config.providerId || "",
surfaceId: layoutProbe.config.surfaceId || "",
},
actual: {
nodeCount: total,
measuredNodeCount: measured,
zeroAreaCount: Number(layoutProbe.document.summary?.zeroAreaCount || 0),
path: layoutProbe.config.path || "",
},
evidenceLayer: "runtime-layout-probe",
detail: "Compares runtime-owned DOM bounding boxes from the web reference layout probe.",
});
}
return buildScreenshotMetric(runtime, fixture, {
metricKind: "bounding-boxes",
status: "fail",
score: 0,
expected: {
schema: layoutProbe.config.schema || "",
path: layoutProbe.config.path || "",
},
actual: {
errors: layoutProbe.errors,
},
evidenceLayer: "runtime-layout-probe",
detail: "Declared runtime layout probe exists, but the artifact is missing or invalid.",
});
}
const captureStatus = runtime.capture?.status || "";
const runtimeHasCaptureBody = ["chrome-headless", "ssh-png", "adb-png", "golden", "ssh-golden"].includes(captureStatus);
let status = "pass";
@ -2564,7 +2605,7 @@ function buildScreenshotMetric(runtime, fixture, metric) {
score: Number(metric.score.toFixed(3)),
expected: metric.expected,
actual: metric.actual,
evidenceLayer: "surface-structure",
evidenceLayer: metric.evidenceLayer || "surface-structure",
detail: metric.detail,
};
}
@ -2573,6 +2614,37 @@ function ratio(numerator, denominator) {
return denominator ? Math.max(0, Math.min(1, numerator / denominator)) : 1;
}
function readRuntimeLayoutProbe(runtime, fixtureId) {
const config = (runtime.capture?.layoutProbes || []).find(candidate => candidate.fixtureId === fixtureId);
if (!config) return { config: null, document: null, errors: [] };
const errors = [];
const probePath = config.path || "";
const absoluteProbePath = path.join(repoRoot, probePath);
if (!probePath || !existsSync(absoluteProbePath)) {
return { config, document: null, errors: [`${probePath || "layoutProbe.path"}:missing`] };
}
let document;
try {
document = JSON.parse(readFileSync(absoluteProbePath, "utf8"));
} catch (error) {
return { config, document: null, errors: [`${probePath}:invalid-json:${error instanceof Error ? error.message : String(error)}`] };
}
if (config.schema && document.schema !== config.schema) errors.push(`${probePath}:schema:expected ${config.schema} got ${document.schema || ""}`);
if (config.providerId && document.providerId !== config.providerId) errors.push(`${probePath}:providerId:expected ${config.providerId} got ${document.providerId || ""}`);
if (config.surfaceId && document.surfaceId !== config.surfaceId) errors.push(`${probePath}:surfaceId:expected ${config.surfaceId} got ${document.surfaceId || ""}`);
if (document.fixtureId !== fixtureId) errors.push(`${probePath}:fixtureId:expected ${fixtureId} got ${document.fixtureId || ""}`);
const schemaPath = config.schema ? manifest.schemas?.[config.schema] : "";
if (schemaPath) {
try {
const schema = JSON.parse(readFileSync(path.join(repoRoot, schemaPath), "utf8"));
errors.push(...validateSchemaSubset(schema, document, `layoutProbe:${fixtureId}`));
} catch (error) {
errors.push(`${schemaPath}:unreadable:${error instanceof Error ? error.message : String(error)}`);
}
}
return { config, document, errors };
}
function collectSplitTargetBlockers(report) {
return (report.splitTargets || []).flatMap(target => target.blockerRecords || []);
}

View file

@ -0,0 +1,191 @@
import { createServer } from "node:http";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { existsSync, readFile as readFileCallback } from "node:fs";
import { spawn } from "node:child_process";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
const args = parseArgs(process.argv.slice(2));
const port = Number(args.port || 8892);
const debugPort = Number(args.debugPort || 18892);
const providerId = args.provider || "gamecult.eve.embedded-demo";
const fixtureId = args.fixture || "embedded-surface";
const width = Number(args.width || 1280);
const height = Number(args.height || 720);
const outputPath = path.resolve(repoRoot, args.output || `artifacts/web-reference-layout-probe/latest/${fixtureId}.json`);
const server = createStaticServer(repoRoot);
await new Promise(resolve => server.listen(port, "127.0.0.1", resolve));
const profile = await mkdtemp(path.join(os.tmpdir(), "eve-web-layout-probe-"));
try {
const url = `http://127.0.0.1:${port}/web/layout-probe.html?provider=${encodeURIComponent(providerId)}&fixture=${encodeURIComponent(fixtureId)}`;
const probe = await runChromeProbe(url, profile);
if (probe.error) throw new Error(probe.error);
if (probe.schema !== "gamecult.eve.web_layout_probe.v1") throw new Error(`Unexpected probe schema: ${probe.schema || ""}`);
if (probe.runtimeId !== "web") throw new Error(`Unexpected probe runtime: ${probe.runtimeId || ""}`);
if (probe.providerId !== providerId) throw new Error(`Unexpected probe provider: ${probe.providerId || ""}`);
if (probe.fixtureId !== fixtureId) throw new Error(`Unexpected probe fixture: ${probe.fixtureId || ""}`);
if (!probe.summary?.measuredNodeCount) throw new Error("Web layout probe measured no node boxes.");
await mkdir(path.dirname(outputPath), { recursive: true });
await writeFile(outputPath, `${JSON.stringify(probe, null, 2)}\n`);
console.log(outputPath);
} finally {
server.close();
await rm(profile, { recursive: true, force: true });
}
function createStaticServer(root) {
const types = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json; charset=utf-8",
".eve": "text/plain; charset=utf-8",
};
return createServer((request, response) => {
const urlPath = decodeURIComponent(new URL(request.url || "/", "http://localhost").pathname);
const clean = urlPath === "/" ? "/web/index.html" : urlPath;
const file = path.normalize(path.join(root, clean));
if (!file.startsWith(root)) {
response.writeHead(403);
response.end("forbidden");
return;
}
readFileCallback(file, (error, data) => {
if (error) {
response.writeHead(404);
response.end("not found");
return;
}
response.writeHead(200, { "content-type": types[path.extname(file)] || "application/octet-stream" });
response.end(data);
});
});
}
async function runChromeProbe(url, profile) {
const chrome = findChrome();
const child = spawn(chrome, [
"--headless=new",
"--disable-gpu",
"--hide-scrollbars",
`--remote-debugging-port=${debugPort}`,
`--user-data-dir=${profile}`,
`--window-size=${width},${height}`,
url,
], { stdio: ["ignore", "pipe", "pipe"] });
let stderr = "";
let closed = false;
child.stderr.on("data", chunk => { stderr += chunk; });
child.once("close", () => { closed = true; });
try {
const target = await waitForPageTarget(url);
const client = await connectCdp(target.webSocketDebuggerUrl);
try {
await client.send("Runtime.enable");
for (let attempt = 0; attempt < 100; attempt += 1) {
const ready = await client.send("Runtime.evaluate", {
expression: "document.body?.dataset.probeReady === 'true'",
returnByValue: true,
});
if (ready.result?.value === true) break;
await delay(100);
}
const result = await client.send("Runtime.evaluate", {
expression: "document.querySelector('#eve-layout-probe-output')?.textContent || ''",
returnByValue: true,
});
const text = result.result?.value || "";
if (!text.trim()) throw new Error("Chrome layout probe produced an empty output document.");
return JSON.parse(text);
} finally {
client.close();
}
} finally {
if (!closed) {
child.kill();
await new Promise(resolve => child.once("close", resolve));
}
if (stderr && process.env.EVE_DEBUG_WEB_LAYOUT_PROBE) process.stderr.write(stderr);
}
}
async function waitForPageTarget(url) {
for (let attempt = 0; attempt < 100; attempt += 1) {
try {
const response = await fetch(`http://127.0.0.1:${debugPort}/json`);
const targets = await response.json();
const target = targets.find(candidate => candidate.type === "page" && candidate.url === url)
|| targets.find(candidate => candidate.type === "page" && candidate.url?.includes("/web/layout-probe.html"));
if (target?.webSocketDebuggerUrl) return target;
} catch {
// Chrome is still booting.
}
await delay(100);
}
throw new Error(`Timed out waiting for Chrome DevTools target on port ${debugPort}.`);
}
function connectCdp(webSocketUrl) {
return new Promise((resolve, reject) => {
const socket = new WebSocket(webSocketUrl);
let nextId = 1;
const pending = new Map();
socket.addEventListener("open", () => {
resolve({
send(method, params = {}) {
const id = nextId++;
socket.send(JSON.stringify({ id, method, params }));
return new Promise((messageResolve, messageReject) => {
pending.set(id, { resolve: messageResolve, reject: messageReject });
});
},
close() {
socket.close();
},
});
});
socket.addEventListener("message", event => {
const message = JSON.parse(event.data);
if (!message.id || !pending.has(message.id)) return;
const callbacks = pending.get(message.id);
pending.delete(message.id);
if (message.error) callbacks.reject(new Error(message.error.message || JSON.stringify(message.error)));
else callbacks.resolve(message.result || {});
});
socket.addEventListener("error", reject);
});
}
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function findChrome() {
const candidates = [
process.env.CHROME_PATH,
path.join(process.env.ProgramFiles || "", "Google/Chrome/Application/chrome.exe"),
path.join(process.env["ProgramFiles(x86)"] || "", "Google/Chrome/Application/chrome.exe"),
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"/usr/bin/google-chrome",
"/usr/bin/chromium",
"/usr/bin/chromium-browser",
].filter(Boolean);
const chrome = candidates.find(candidate => existsSync(candidate));
if (!chrome) throw new Error("Chrome is required for the web layout probe and was not found.");
return chrome;
}
function parseArgs(values) {
const parsed = {};
for (let index = 0; index < values.length; index += 1) {
const key = values[index];
if (!key.startsWith("--")) continue;
parsed[key.slice(2)] = values[index + 1];
index += 1;
}
return parsed;
}