mirror of
https://github.com/morluto/rea.git
synced 2026-11-29 01:46:39 +00:00
* feat(delivery)!: bound default results by an agent result budget Omitted detail now returns complete Evidence only when it fits the new delivery.agent_result_budget_bytes runtime setting (default 49152 compact JSON bytes, about 12k tokens at an estimated 4 bytes per token). Larger results are retained and delivered as the producer's summary with a limitation naming the budget and the recovery call; nothing is refused or truncated. inspect_analysis_view gains an evidence-json view that pages the exact JSON text of retained Evidence. The CLI applies the same budget and publishes the complete bundle with --evidence_output. inspect_managed_members type_names now also narrows member_refs and exported_types, and inspect-byte-entropy gains CLI evidence delivery. BREAKING CHANGE: An omitted detail no longer always returns complete Evidence inline on MCP or the CLI for tools with a detail selector (including inspect_managed_members, inspect_managed_artifact, inspect_byte_entropy, inspect_artifact, analyze_javascript_application, list_procedures, list_strings and the other operations listed in src/domain/agentBudgetOperations.ts). Over the budget they return the retained summary; pass detail complete (--detail complete) for complete inline delivery. inspect_managed_members type_names narrows member_refs and exported_types. Fixes #14172 Fixes #14180 Part of #14187 Part of #14156 * test(schemas): record advertised summaries for budgeted detail * fix(delivery): keep budgeted summaries canonical and carry delivery facts beside them Review fixes for the agent result budget: - Deliver the producer's own summary record, identical to detail summary, so its identity holds in summary consumers such as compare_artifacts. The budget, sizes, retention and the exact paging call travel as delivery facts: a second MCP text block and _meta, or a delivery field in CLI output. - Capture the caller's detail for application-validated tools too, so inspect_binary_layout and similar tools are budgeted. - Keep recovery facts when a budgeted summary itself exceeds the frame. - Size an omitted evidence-json limit by escaped UTF-8 bytes and never split a surrogate pair, even in a one-unit page. - Add the REA_AGENT_RESULT_BUDGET_BYTES launch seed; the shared test environment raises it for semantic tests, and budget tests clear it. - Align tool descriptions and verifiers that read complete Evidence. * fix(delivery): retain the budgeted summary like an explicit summary * fix(delivery): read the budget seed from the captured environment and count delivery facts in the frame - The agent result budget seed is read from the environment the server or CLI invocation captured: ToolResultDelivery takes it at construction, and a CLI invocation binds it in its publication context. The ambient process environment is no longer read. - The frame check reserves the bytes of the delivery block and _meta that are added after encoding, so a budgeted response cannot exceed the frame. - Conformance workflows that resend complete Evidence raise the budget through the shared inline-Evidence environment, as do the artifact and binary layout verifiers. * fix(delivery)!: request complete Evidence explicitly and never spill CLI overflow - Shared test and verifier environments no longer raise the agent result budget. Every test and verifier workflow that reads complete Evidence from a budgeted tool now requests it with detail complete or --detail complete, including the real-provider verifiers outside PR CI (Ghidra, Hopper, IDA, Kuna and client verifiers). Default delivery is exercised as shipped. - Budgeting applies only to tools with a detail selector, so every budgeted call has a complete opt-out. - CLI overflow without --evidence_output writes nothing; its delivery facts carry exact rerun argv for --detail complete and --evidence_output, omitted when the command declares sensitive values. * test(delivery): prove captured budget seeds with valid in-range values * test: state complete-detail requests once and fix codemod regressions - Add tests/support/completeDetail.ts with COMPLETE_DETAIL and completeArguments so tests that read complete Evidence request it in one place, keeping functions within max-lines-per-function without raising the limit. - Restore provider-client tests (GhidraClient, Hopper health): their callTool("name", ...) calls are bridge requests, not MCP tools, and take no detail. - Update the game-scale type inventory test for member_refs narrowing. * test: request complete Evidence in shared JavaScript analysis helpers and remaining CLI workflows * test: request complete Evidence by default in the shared test transports The shared MCP client helpers (createTestMcp, connectLocalToolsMcp and the CLI fixture's shared MCP session) and the CLI runners (the cli fixture and the shared CLI session) now apply one named default, completeEvidenceByDefault. A budgeted tool called with neither detail nor view gets detail complete; the CLI does the same with --detail complete, chosen by the command's tool contract. A budgeted operation that resolves to no contract fails loudly at load. Tests whose subject is delivery opt out with delivery "budgeted". This is a test-harness choice; production delivery is unchanged and the budget tests prove the default path. Per-call complete-detail edits are reverted in the 204 test files whose transports all apply the default. Explicit requests remain where a test drives its own SDK client, server, CLI instance or process, and where the detail choice is the test's subject. * test: resolve CLI complete-detail defaults from the CLI registry The Real Apple and browser verifiers read complete Evidence through artifactCliEvidence, which ran the compiled CLI without a detail choice and got the budgeted {summary, delivery} output. The helper now requests complete Evidence for commands that take --detail, read from the compiled CLI's own registry (scripts/lib/complete-evidence-cli.mjs). The test harness default had a sibling bug: it treated every cli-flagged budgeted contract as taking --detail, but only Evidence-delivery commands do (inspect-binary-layout does not). It now reads the source CLI registry too, and covers every command the CLI budgets. * test(verifiers): request complete Evidence at each verifier's SDK client and CLI argv The real-browser failure was the same missing normalized_result as the Apple one: browser-capture-metadata-budget-e2e reads analyze-web-bundle through artifactCliEvidence, fixed in the previous commit. The shared verifier module, scripts/lib/complete-evidence.mjs, now owns both transports: - completeEvidenceClient wraps each verifier's SDK Client once, so every callTool to a budgeted tool with neither detail nor view requests complete Evidence, whatever local call helper a verifier uses (86 clients, including the Ghidra, Hopper, IDA and Kuna verifiers' argument-less list_procedures and inspect_native_load_image calls). - completeEvidenceCliArguments covers the remaining verifier CLI argv that chose no detail, such as function, decompile, analyze and the Android and Apple commands. Commands and tools that are not budgeted are sent as written. * test(delivery): await async completeEvidenceCliArguments helper in boundary test * test(delivery): request complete detail in Electron CLI artifact format test * docs(delivery): document delivery.rerun as add-only argument arrays * test(schemas): record advertised summaries for the unified delivery budget Tool descriptions now name the agent result budget, and the evidence-json default page is derived from the 32 KiB default, which changes the advertised input digests of the 28 affected tools. Recorded from the Build package job's output. * test(delivery): pin the budget boundary and keep failures unbudgeted Main's retainedSummaryDelivery tests pinned the size decision at exactly 32,768 and 32,769 UTF-8 JSON bytes. Unifying that decision into budgetedSummaryBytes deleted them, and their port never landed, so the byte measurement went unchecked. Restore them against budgetedSummaryBytes at the configured budget and one byte over, for the default and a runtime budget, with ASCII, escaped and multibyte text, plus each condition of the decision. Off-by-one mutants (< for <=, a cap one byte short) fail six cases; measuring UTF-16 code units instead of UTF-8 bytes fails the multibyte cases. An MCP case pins that a target failure from a budgeted tool under the minimum budget is identical with detail omitted and complete, with no delivery facts. * test(verifiers): route literal CLI argv for budgeted commands through complete Evidence real-browser failed with "Scenario CLI did not report external disconnect ownership": runScenarioCli ran capture-browser-scenario without --detail, so an over-budget capture came back as its summary, which has no browser.cleanup. The earlier sweep counted these files as covered because their MCP clients were wrapped, but their CLI argv was not. Route the shared runScenarioCli helper (five callers), the local cli helpers in the module, source-map and script-export verifiers, and every other literal argv for a budgeted CLI command without --detail or --view (EVM interface, binary layout, packet capture, devicetree, DOM destinations, Ghidra relocation symbols, WABT cleanup, Termux browser) through completeEvidenceCliArguments. A sweep of scripts/ for budgeted command literals with --json and no detail selection now finds none. * fix(verifiers): leave clients without callTool unwrapped The native verifier cleanup test drives native-value-e2e with a connection double whose Client has only connect and close. completeEvidenceClient bound client.callTool unconditionally, so wrapping threw a TypeError before connect ran. That TypeError replaced the primary connection failure the test asserts is preserved, and all four fault cases failed in Test shard 5 and Portable tests. A client without callTool has no tool call to complete, so the helper now returns it unchanged. Locally all five fault modes of the fixture now exit 0. * fix(delivery): keep the catalog recorder on shipped helpers and expect view-implied summary The verifier sweep wrapped record-mcp-catalog.mjs in completeEvidenceClient, which lives in an unshipped helper. deferredRuntime copies only the package's shipped files plus the recorder, so the recorder failed to load (ERR_MODULE_NOT_FOUND) and its cleanup recorder never wrote. The recorder only lists tools and prompts, so the wrapper had no effect; it is removed. This branch makes a view with no --detail select summary delivery, as MCP does for a view. Three CLI cases still expected the old view refusal; with a view alone the missing input is now the summary bundle, so they expect evidence_output, and a view with --detail complete still refuses the view. * fix(delivery): request complete Evidence where callers need the whole result Budgeted delivery made four callers receive a summary they cannot use: - The GitHub Actions example uploads the analysis as a CI artifact, so it now asks for --detail complete; over budget it had saved a summary. - javascriptIntegrityPolicyCli spawns the CLI itself, outside the test harness default, and reads normalized_result; it now applies the same completeEvidenceCliArguments default. - nativeObservationViewsMcp builds its own client to prove complete observations overflow into a paging continuation; it now applies the harness default so each call asks for complete Evidence. - The CLI parity goldens are re-recorded for the --detail and --evidence_output options the budgeted commands now advertise. * fix(tests): give processes tests spawn the largest agent result budget About 90 tests spawn scripts/rea.mjs or a server directly, outside the harness default that asks for complete Evidence, and read analysis facts from the result. Over the default budget they received a summary instead; javascriptChildHandleOwnership failed this way. The Vitest environment now seeds REA_AGENT_RESULT_BUDGET_BYTES with the largest accepted value, so a spawned CLI or server delivers complete Evidence, as the in-process default does. Delivery tests keep their own budget: agentResultBudgetMcp builds its server without the seed, so its default-budget cases still exercise the shipped default. * fix(tests): give budgeted harness tests the shipped agent result budget The test environment seeds the largest agent result budget so spawned processes deliver complete Evidence. In-memory servers built by createApplicationMcpHarness (and connectGhidraMcp, which uses it) inherit process.env too, so a test that chose testDelivery "budgeted" kept the seed: the 600-row list_procedures case and the omitted-detail web page views returned complete Evidence instead of a summary. testDeliveryEnvironment now owns that choice: a budgeted test's server environment drops the seed and uses the shipped default. The application harness applies it to every server it builds. * fix(tests): expect view-implied summary delivery in the Playwright trace refusal A view with no --detail now selects summary delivery, so its refusal names the missing evidence_output bundle; --detail complete still refuses the view. The trace test still expected a view refusal in both cases.
589 lines
20 KiB
JavaScript
589 lines
20 KiB
JavaScript
#!/usr/bin/env node
|
|
|
|
import { Client } from "@modelcontextprotocol/client";
|
|
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
|
import { access } from "node:fs/promises";
|
|
import { fileURLToPath } from "node:url";
|
|
|
|
import { CdpBrowserProvider } from "../dist/browser/CdpBrowserProvider.js";
|
|
import { startRuntimeFixtureBrowser } from "./lib/browser-runtime-fixture-lifecycle.mjs";
|
|
|
|
import { createBrowserScenarioProvider } from "../dist/composition/browserScenario.js";
|
|
import {
|
|
inspectWebPageInputSchema,
|
|
listBrowserTargetsInputSchema,
|
|
} from "../dist/domain/browserObservation.js";
|
|
import { observeWebSessionInputSchema } from "../dist/domain/browserSession.js";
|
|
import { compareWebCapturesInputSchema } from "../dist/domain/webCaptureDiffSchemas.js";
|
|
import {
|
|
captureWebScreenshotInputSchema,
|
|
compareWebScreenshotsInputSchema,
|
|
} from "../dist/domain/webScreenshot.js";
|
|
import { startBrowserVerifierSite } from "./fixtures/browser-verifier-site.mjs";
|
|
import { startPageCdpProxy } from "./fixtures/page-cdp-proxy.mjs";
|
|
import {
|
|
assertBundleAnalysis,
|
|
assertObservation,
|
|
assertSensitiveShapes,
|
|
} from "./lib/browser-verifier-assertions.mjs";
|
|
import {
|
|
assertScenarioCapture,
|
|
browserScenario,
|
|
runScenarioCli,
|
|
scenarioProfiles,
|
|
verifyScenarioFailureEvidence,
|
|
} from "./lib/browser-scenario-verifier.mjs";
|
|
import { completeVerifierRun, createVerifierRun } from "./lib/verifier-run.mjs";
|
|
import { withVerifierCleanup } from "./lib/verifier-cleanup.mjs";
|
|
import { requireOrdinaryWindowsVerifierCaller } from "./lib/windows-ordinary-user-verifier.mjs";
|
|
import { verifyLargeScreenshotE2e } from "./lib/browser-screenshot-e2e.mjs";
|
|
import { verifyViewportScreenshotE2e } from "./lib/browser-viewport-screenshot-e2e.mjs";
|
|
import { verifyPopupEventCoverage } from "./lib/browser-popup-e2e.mjs";
|
|
import { verifyBrowserNetworkEvidence } from "./lib/browser-network-e2e.mjs";
|
|
import { verifyBrowserScriptExport } from "./lib/browser-script-export-e2e.mjs";
|
|
import { verifyBrowserModules } from "./lib/browser-module-e2e.mjs";
|
|
import { verifyBrowserDomDestinations } from "./lib/browser-dom-destinations-e2e.mjs";
|
|
import { verifyBrowserSocketTransport } from "./lib/browser-socket-e2e.mjs";
|
|
import { verifyBrowserCaptureMetadataBudget } from "./lib/browser-capture-metadata-budget-e2e.mjs";
|
|
import { artifactCliEvidence, artifactMcpResult } from "./lib/artifact-e2e.mjs";
|
|
import { verifyScenarioEnvironment } from "./lib/browser-scenario-environment-e2e.mjs";
|
|
import { verifyScenarioStorage } from "./lib/browser-scenario-storage-e2e.mjs";
|
|
import { verifyScenarioStorageFingerprints } from "./lib/browser-scenario-storage-fingerprints-e2e.mjs";
|
|
import { verifyScenarioServiceWorkers } from "./lib/browser-scenario-service-workers-e2e.mjs";
|
|
import { verifyBrowserUrlUserInfo } from "./lib/browser-url-userinfo-e2e.mjs";
|
|
import { completeEvidenceClient } from "./lib/complete-evidence.mjs";
|
|
|
|
const SCENARIO_SECRET_VALUE = "rea-browser-verifier-secret";
|
|
const SCENARIO_URL_SECRET_VALUE = "rea-browser-url-verifier-secret";
|
|
process.env.REA_BROWSER_VERIFIER_SECRET = SCENARIO_SECRET_VALUE;
|
|
process.env.REA_BROWSER_VERIFIER_URL = SCENARIO_URL_SECRET_VALUE;
|
|
const verifierRun = createVerifierRun();
|
|
|
|
await requireOrdinaryWindowsVerifierCaller();
|
|
const executable = await browserExecutable();
|
|
let site;
|
|
let browser;
|
|
let pageProxy;
|
|
let report;
|
|
await withVerifierCleanup(async () => {
|
|
site = await startBrowserVerifierSite();
|
|
browser = await startRuntimeFixtureBrowser(
|
|
executable,
|
|
`${site.origin}/app?startup=browser-secret-value`,
|
|
);
|
|
const endpoint = `http://127.0.0.1:${String(browser.port)}`;
|
|
const provider = new CdpBrowserProvider();
|
|
const target = await pageTarget(provider, endpoint);
|
|
const observed = await provider.inspectPage(
|
|
inspectWebPageInputSchema.parse({
|
|
cdp_endpoint: endpoint,
|
|
allowed_origins: [site.origin],
|
|
target_id: target,
|
|
observation_ms: 1_000,
|
|
include_storage_keys: true,
|
|
include_storage_fingerprints: true,
|
|
}),
|
|
);
|
|
if (!observed.ok) throw observed.error;
|
|
assertObservation(observed.value, site.origin);
|
|
const domDestinations = await verifyBrowserDomDestinations({
|
|
cdp_endpoint: endpoint,
|
|
target_id: target,
|
|
});
|
|
const serialized = JSON.stringify(observed.value);
|
|
if (
|
|
!observed.value.target.url.includes("startup=browser-secret-value") ||
|
|
!observed.value.network.requests.some((request) =>
|
|
request.url.includes("token=network-secret-value"),
|
|
)
|
|
)
|
|
throw new Error(
|
|
"Passive browser result did not preserve ordinary URL queries",
|
|
);
|
|
for (const secret of [
|
|
"request-secret-value",
|
|
"request-body-secret-value",
|
|
"response-secret-value",
|
|
"storage-secret-value",
|
|
"websocket-secret-value",
|
|
])
|
|
if (serialized.includes(secret))
|
|
throw new Error(
|
|
`Passive browser result included unselected structured data: ${secret}`,
|
|
);
|
|
|
|
const sourceCaptureInput = inspectWebPageInputSchema.parse({
|
|
cdp_endpoint: endpoint,
|
|
allowed_origins: [site.origin],
|
|
target_id: target,
|
|
observation_ms: 1_000,
|
|
include_accessibility_text: true,
|
|
include_script_sources: true,
|
|
include_console_text: true,
|
|
include_json_body_shapes: true,
|
|
include_websocket_shapes: true,
|
|
});
|
|
const withSource = await provider.inspectPage(sourceCaptureInput);
|
|
if (!withSource.ok) throw withSource.error;
|
|
const source = withSource.value.scripts.items.find(
|
|
(script) =>
|
|
script.source.included &&
|
|
script.source.artifact.text.includes("reaSourceMarker"),
|
|
);
|
|
if (source === undefined)
|
|
throw new Error(
|
|
"Real Chrome did not return explicitly approved script source",
|
|
);
|
|
if (
|
|
!withSource.value.accessibility.nodes.some((node) =>
|
|
node.name?.includes("ax-private-label-value"),
|
|
)
|
|
)
|
|
throw new Error(
|
|
"Real Chrome did not return independently approved accessibility text",
|
|
);
|
|
assertSensitiveShapes(withSource.value);
|
|
|
|
const bundle = await verifyPublicBundle(endpoint, target, site.origin);
|
|
|
|
// Equality needs the same selected facts on both sides. The earlier passive
|
|
// capture deliberately omits source, so it cannot establish source equality.
|
|
const repeatedSource = await provider.inspectPage(sourceCaptureInput);
|
|
if (!repeatedSource.ok) throw repeatedSource.error;
|
|
const captureDiff = await provider.compareCaptures(
|
|
compareWebCapturesInputSchema.parse({
|
|
before: { inspection: withSource.value },
|
|
after: { inspection: repeatedSource.value },
|
|
}),
|
|
);
|
|
if (!captureDiff.ok) throw captureDiff.error;
|
|
if (
|
|
captureDiff.value.dimensions.dom_structure.status !== "unchanged" ||
|
|
captureDiff.value.dimensions.scripts.status !== "unchanged"
|
|
)
|
|
throw new Error(
|
|
`Real Chrome stable capture identities did not reconcile: ${JSON.stringify(
|
|
{
|
|
dom_structure: captureDiff.value.dimensions.dom_structure,
|
|
scripts: captureDiff.value.dimensions.scripts,
|
|
before_completeness: withSource.value.completeness,
|
|
after_completeness: repeatedSource.value.completeness,
|
|
},
|
|
)}`,
|
|
);
|
|
|
|
const screenshot = await provider.captureScreenshot(
|
|
captureWebScreenshotInputSchema.parse({
|
|
cdp_endpoint: endpoint,
|
|
allowed_origins: [site.origin],
|
|
target_id: target,
|
|
}),
|
|
);
|
|
if (!screenshot.ok) throw screenshot.error;
|
|
if (
|
|
screenshot.value.viewport.width < 1 ||
|
|
screenshot.value.viewport.height < 1 ||
|
|
screenshot.value.artifact.bytes < 1
|
|
)
|
|
throw new Error("Real Chrome screenshot artifact was empty");
|
|
const screenshotDiff = await provider.compareScreenshots(
|
|
compareWebScreenshotsInputSchema.parse({
|
|
before: screenshot.value.artifact,
|
|
after: screenshot.value.artifact,
|
|
}),
|
|
);
|
|
if (!screenshotDiff.ok) throw screenshotDiff.error;
|
|
if (
|
|
screenshotDiff.value.status !== "identical" ||
|
|
screenshotDiff.value.changed_pixels !== 0
|
|
)
|
|
throw new Error("Real Chrome PNG artifact did not compare identically");
|
|
|
|
const sessionPromise = provider.observeSession(
|
|
observeWebSessionInputSchema.parse({
|
|
cdp_endpoint: endpoint,
|
|
allowed_origins: [site.origin],
|
|
target_id: target,
|
|
observation_ms: 1_500,
|
|
}),
|
|
);
|
|
await delay(250);
|
|
site.triggerSessionNavigation();
|
|
const session = await sessionPromise;
|
|
if (!session.ok) throw session.error;
|
|
if (
|
|
!session.value.timeline.some(
|
|
({ type }) => type === "same_document_navigation",
|
|
) ||
|
|
!session.value.target.final_url?.includes("/app/session-1")
|
|
)
|
|
throw new Error("Real Chrome same-origin SPA timeline was missing");
|
|
|
|
pageProxy = await startPageCdpProxy(endpoint);
|
|
await verifyPageScopedTransport(provider, pageProxy, site.origin);
|
|
const browserSocketTransport = await verifyBrowserSocketTransport({
|
|
provider,
|
|
profile: browser.profile,
|
|
endpoint,
|
|
target,
|
|
origin: site.origin,
|
|
});
|
|
const attachedScenarioInput = browserScenario(
|
|
{
|
|
mode: "connect",
|
|
cdp_endpoint: endpoint,
|
|
target_id: target,
|
|
},
|
|
site.origin,
|
|
);
|
|
let attachedScenario;
|
|
try {
|
|
attachedScenario = await runScenarioCli(attachedScenarioInput);
|
|
} catch (cliError) {
|
|
const direct = await createBrowserScenarioProvider(
|
|
process.env,
|
|
).captureScenario(attachedScenarioInput);
|
|
if (!direct.ok) {
|
|
const underlying = direct.error.cause;
|
|
const details =
|
|
underlying instanceof Error
|
|
? `${underlying.name}: ${underlying.message}`
|
|
: String(underlying ?? direct.error.message);
|
|
throw new Error(
|
|
`Attached browser scenario failed through both CLI and provider: ${details}`,
|
|
{ cause: cliError },
|
|
);
|
|
}
|
|
throw new Error(
|
|
"Attached browser scenario failed through CLI, but direct provider capture succeeded",
|
|
{ cause: cliError },
|
|
);
|
|
}
|
|
if (
|
|
attachedScenario.normalized_result?.browser?.cleanup !==
|
|
"disconnected-external" ||
|
|
attachedScenario.normalized_result?.browser?.process_ownership !==
|
|
"external"
|
|
)
|
|
throw new Error(
|
|
"Scenario CLI did not report external disconnect ownership",
|
|
);
|
|
const versionResponse = await fetch(`${endpoint}/json/version`);
|
|
if (!versionResponse.ok || browser.process.exitCode !== null)
|
|
throw new Error("Scenario attachment terminated its external browser");
|
|
|
|
const profilesBefore = await scenarioProfiles();
|
|
process.stderr.write("Browser verifier: scenario environment\n");
|
|
const scenarioEnvironment = await verifyScenarioEnvironment(
|
|
endpoint,
|
|
target,
|
|
site.origin,
|
|
);
|
|
process.stderr.write("Browser verifier: scenario storage\n");
|
|
const scenarioStorage = await verifyScenarioStorage({
|
|
executable,
|
|
endpoint,
|
|
targetId: target,
|
|
});
|
|
process.stderr.write("Browser verifier: scenario storage fingerprints\n");
|
|
const scenarioStorageFingerprints = await verifyScenarioStorageFingerprints(
|
|
executable,
|
|
site.origin,
|
|
);
|
|
process.stderr.write("Browser verifier: scenario service workers\n");
|
|
const scenarioServiceWorkers = await verifyScenarioServiceWorkers(
|
|
endpoint,
|
|
target,
|
|
);
|
|
const launchedScenario = await createBrowserScenarioProvider(
|
|
process.env,
|
|
).captureScenario(
|
|
browserScenario(
|
|
{
|
|
mode: "launch",
|
|
executable_path: executable,
|
|
},
|
|
site.origin,
|
|
),
|
|
);
|
|
if (!launchedScenario.ok) throw launchedScenario.error;
|
|
if (
|
|
launchedScenario.value.browser.cleanup !== "terminated-owned-process" ||
|
|
launchedScenario.value.browser.process_ownership !== "provider-owned"
|
|
)
|
|
throw new Error("Scenario launch did not report owned-process cleanup");
|
|
const profilesAfter = await scenarioProfiles();
|
|
if ([...profilesAfter].some((entry) => !profilesBefore.has(entry)))
|
|
throw new Error("Scenario launch retained a temporary browser profile");
|
|
assertScenarioCapture(launchedScenario.value);
|
|
const scenarioFailure = await verifyScenarioFailureEvidence(
|
|
executable,
|
|
site.origin,
|
|
);
|
|
const scenarioResults = JSON.stringify([
|
|
attachedScenario,
|
|
launchedScenario.value,
|
|
]);
|
|
for (const retainedValue of [
|
|
"token=network-secret-value",
|
|
"token=websocket-url-secret",
|
|
"authorization=Bearer console-secret-value",
|
|
"websocket-secret-value",
|
|
])
|
|
if (!scenarioResults.includes(retainedValue))
|
|
throw new Error(
|
|
`Browser scenario did not preserve selected value: ${retainedValue}`,
|
|
);
|
|
for (const unselectedValue of [
|
|
SCENARIO_SECRET_VALUE,
|
|
SCENARIO_URL_SECRET_VALUE,
|
|
"request-secret-value",
|
|
"request-body-secret-value",
|
|
"response-secret-value",
|
|
"storage-secret-value",
|
|
])
|
|
if (scenarioResults.includes(unselectedValue))
|
|
throw new Error(
|
|
`Browser scenario included unselected structured value: ${unselectedValue}`,
|
|
);
|
|
|
|
process.stderr.write("Browser verifier: large screenshot\n");
|
|
const largeScreenshot = await verifyLargeScreenshotE2e(endpoint, site.origin);
|
|
process.stderr.write("Browser verifier: visual viewport screenshot\n");
|
|
const viewportScreenshot = await verifyViewportScreenshotE2e(
|
|
endpoint,
|
|
site.origin,
|
|
);
|
|
process.stderr.write("Browser verifier: popup coverage\n");
|
|
const popupEvents = await verifyPopupEventCoverage(executable);
|
|
const networkEvidence = await verifyBrowserNetworkEvidence(
|
|
executable,
|
|
undefined,
|
|
{ cdp_endpoint: endpoint, target_id: target },
|
|
);
|
|
const scriptExport = await verifyBrowserScriptExport(executable, undefined, {
|
|
cdp_endpoint: endpoint,
|
|
target_id: target,
|
|
});
|
|
const moduleTrace = await verifyBrowserModules(executable);
|
|
const captureMetadata = await verifyBrowserCaptureMetadataBudget(endpoint);
|
|
const urlUserInfo = await verifyBrowserUrlUserInfo(endpoint, site.origin);
|
|
report = {
|
|
browser: observed.value.browser.product,
|
|
endpoint,
|
|
target,
|
|
domNodes: observed.value.dom.nodes.length,
|
|
accessibilityNodes: observed.value.accessibility.nodes.length,
|
|
scripts: observed.value.scripts.items.length,
|
|
networkRequests: observed.value.network.requests.length,
|
|
consoleEvents: observed.value.console.events.length,
|
|
websocketConnections: observed.value.network.websocket_connections.length,
|
|
websocketFrames: observed.value.network.websocket_connections.reduce(
|
|
(total, connection) => total + connection.events.length,
|
|
0,
|
|
),
|
|
bundleScripts: bundle.capture.scripts_analyzed,
|
|
sourceMaps: bundle.observations.source_maps.processed,
|
|
bundle_cli_and_stdio_mcp: true,
|
|
sessionEvents: session.value.timeline.length,
|
|
pageScopedTransport: true,
|
|
browserSocketTransport,
|
|
screenshotBytes: screenshot.value.artifact.bytes,
|
|
largeScreenshot,
|
|
popupEvents,
|
|
networkEvidence,
|
|
scriptExport,
|
|
moduleTrace,
|
|
captureMetadata,
|
|
urlUserInfo,
|
|
domDestinations,
|
|
browserScenarioCli: true,
|
|
browserScenarioAttachCleanup: "disconnected-external",
|
|
browserScenarioLaunchCleanup: "terminated-owned-process",
|
|
scenarioFailure,
|
|
scenarioEnvironment,
|
|
scenarioStorage,
|
|
scenarioStorageFingerprints,
|
|
scenarioServiceWorkers,
|
|
viewportScreenshot,
|
|
verified: true,
|
|
};
|
|
}, [
|
|
async () => {
|
|
if (pageProxy !== undefined) {
|
|
process.stderr.write("Browser verifier cleanup: closing page proxy\n");
|
|
await pageProxy.close();
|
|
}
|
|
},
|
|
async () => {
|
|
if (browser !== undefined) {
|
|
process.stderr.write("Browser verifier cleanup: stopping owned Chrome\n");
|
|
await browser.close();
|
|
}
|
|
},
|
|
async () => {
|
|
if (site !== undefined) {
|
|
process.stderr.write("Browser verifier cleanup: closing fixture site\n");
|
|
await site.close();
|
|
}
|
|
},
|
|
]);
|
|
process.stdout.write(
|
|
`${JSON.stringify({
|
|
verifier_run: await completeVerifierRun(verifierRun),
|
|
...report,
|
|
})}\n`,
|
|
);
|
|
|
|
async function verifyPublicBundle(endpoint, target, origin) {
|
|
const evidence = await artifactCliEvidence("analyze-web-bundle", endpoint, [
|
|
target,
|
|
"--allowed-origins",
|
|
origin,
|
|
"--fetch-source-maps",
|
|
"--observation-ms",
|
|
"200",
|
|
]);
|
|
assertBundleAnalysis(evidence.normalized_result);
|
|
const transport = new StdioClientTransport({
|
|
command: process.execPath,
|
|
args: [fileURLToPath(new URL("./rea.mjs", import.meta.url)), "mcp"],
|
|
env: {
|
|
PATH: process.env.PATH ?? "",
|
|
REA_LOG_LEVEL: "silent",
|
|
},
|
|
stderr: "pipe",
|
|
});
|
|
const client = completeEvidenceClient(
|
|
new Client({ name: "browser-bundle-e2e", version: "1" }),
|
|
);
|
|
try {
|
|
await client.connect(transport);
|
|
const result = await artifactMcpResult(client, "analyze_web_bundle", {
|
|
cdp_endpoint: endpoint,
|
|
target_id: target,
|
|
allowed_origins: [origin],
|
|
fetch_source_maps: true,
|
|
observation_ms: 200,
|
|
});
|
|
assertBundleAnalysis(result);
|
|
} finally {
|
|
try {
|
|
await client.close();
|
|
} finally {
|
|
await transport.close();
|
|
}
|
|
}
|
|
return evidence.normalized_result;
|
|
}
|
|
|
|
async function verifyPageScopedTransport(provider, proxy, origin) {
|
|
const target = await pageTarget(provider, proxy.endpoint);
|
|
const input = inspectWebPageInputSchema.parse({
|
|
cdp_endpoint: proxy.endpoint,
|
|
allowed_origins: [origin],
|
|
target_id: target,
|
|
observation_ms: 100,
|
|
});
|
|
const observed = await provider.inspectPage(input);
|
|
if (!observed.ok) throw observed.error;
|
|
if (observed.value.dom.nodes.length < 1)
|
|
throw new Error("Page-scoped CDP transport returned no DOM nodes");
|
|
|
|
const controller = new AbortController();
|
|
const cancelledPromise = provider.inspectPage(
|
|
{ ...input, observation_ms: 5_000 },
|
|
{ signal: controller.signal },
|
|
);
|
|
await delay(100);
|
|
controller.abort();
|
|
const cancelled = await cancelledPromise;
|
|
if (
|
|
cancelled.ok ||
|
|
cancelled.error._tag !== "AnalysisCancelledError" ||
|
|
cancelled.error.operation !== "inspect_web_page"
|
|
)
|
|
throw new Error(
|
|
"Page-scoped CDP cancellation lost its operation semantics",
|
|
);
|
|
|
|
const disconnectedPromise = provider.observeSession(
|
|
observeWebSessionInputSchema.parse({
|
|
cdp_endpoint: proxy.endpoint,
|
|
allowed_origins: [origin],
|
|
target_id: target,
|
|
observation_ms: 5_000,
|
|
}),
|
|
{
|
|
progress: {
|
|
report(event) {
|
|
if (event.phase === "browser_observation" && event.completed === 1)
|
|
proxy.disconnectClients();
|
|
return Promise.resolve();
|
|
},
|
|
},
|
|
},
|
|
);
|
|
const disconnected = await disconnectedPromise;
|
|
if (
|
|
!disconnected.ok ||
|
|
disconnected.value.window.end_reason !== "transport_disconnected" ||
|
|
!disconnected.value.timeline.some(
|
|
({ type }) => type === "transport_disconnected",
|
|
) ||
|
|
disconnected.value.timeline.some(({ type }) => type === "target_terminated")
|
|
)
|
|
throw new Error(
|
|
"Page-scoped CDP disconnect must report transport loss without claiming a target crash",
|
|
);
|
|
const remaining = await provider.listTargets(
|
|
listBrowserTargetsInputSchema.parse({ cdp_endpoint: proxy.endpoint }),
|
|
);
|
|
if (!remaining.ok) throw remaining.error;
|
|
if (!remaining.value.targets.some(({ target_id }) => target_id === target))
|
|
throw new Error("Page-scoped CDP disconnect removed its live target");
|
|
}
|
|
|
|
async function browserExecutable() {
|
|
const candidates = [
|
|
process.env.REA_BROWSER_EXECUTABLE,
|
|
process.argv[2],
|
|
"/usr/bin/google-chrome-stable",
|
|
"/usr/bin/google-chrome",
|
|
"/usr/bin/chromium",
|
|
"/usr/bin/chromium-browser",
|
|
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
|
].filter(
|
|
(candidate) => typeof candidate === "string" && candidate.length > 0,
|
|
);
|
|
for (const candidate of candidates) {
|
|
try {
|
|
await access(candidate);
|
|
return candidate;
|
|
} catch {
|
|
// Continue through explicit and platform-default candidates.
|
|
}
|
|
}
|
|
throw new Error(
|
|
"No Chrome-family executable found; set REA_BROWSER_EXECUTABLE to run real-browser verification",
|
|
);
|
|
}
|
|
|
|
async function pageTarget(provider, endpoint) {
|
|
for (let attempt = 0; attempt < 100; attempt += 1) {
|
|
const listed = await provider.listTargets(
|
|
listBrowserTargetsInputSchema.parse({
|
|
cdp_endpoint: endpoint,
|
|
}),
|
|
);
|
|
if (listed.ok && listed.value.targets[0] !== undefined)
|
|
return listed.value.targets[0].target_id;
|
|
await delay(25);
|
|
}
|
|
throw new Error("Real Chrome did not expose the local test page target");
|
|
}
|
|
|
|
function delay(milliseconds) {
|
|
return new Promise((resolve) => setTimeout(resolve, milliseconds));
|
|
}
|