refactor!: enforce canonical evidence and provider boundaries

Deliver complete Evidence directly through MCP with required nullable analysis profiles and immutable per-server delivery settings. Bind selected environments at construction and require typed cleanup outcomes with retained retry ownership.

Remove test-only routing, duplicate session and snapshot metadata, producer-field repairs, and ambiguous provider arguments. Separate artifact byte identity from occurrence classification and retain typed source-map and partial native facts across CLI, MCP, and verifier consumers.

BREAKING CHANGE: obsolete Evidence envelopes, session aliases, incomplete snapshots, and missing normalized producer facts are no longer accepted.
This commit is contained in:
morluto
2026-10-09 20:18:52 +08:00
parent 2a7746998d
commit 63bf91405c
514 changed files with 9296 additions and 5825 deletions
-2
View File
@@ -64,8 +64,6 @@ import { discoverWebMcp } from "./CdpWebMcpDiscovery.js";
import { captureCdpScreenshot } from "./CdpScreenshot.js";
import { comparePngScreenshots } from "./PngVisualDiff.js";
/** Public identity committed by passive browser observations. */
export { CDP_BROWSER_PROVIDER_IDENTITY } from "./providerIdentities.js";
import { CDP_BROWSER_PROVIDER_IDENTITY } from "./providerIdentities.js";
const IDENTITY = CDP_BROWSER_PROVIDER_IDENTITY;
const CLEANUP_DOMAINS = ["Network", "Debugger", "Runtime", "Page"] as const;
+3 -10
View File
@@ -7,6 +7,7 @@ import {
numberValue,
recordValue,
recordsValue,
scriptMetadataValues,
cdpStringValue,
type UnknownRecord,
} from "./CdpCaptureValues.js";
@@ -84,15 +85,7 @@ export const handleScriptParsed = (
rawUrl,
url: sanitized.url,
origin: sanitized.origin,
hash: cdpStringValue(params.hash) ?? "",
length: Math.max(
0,
Math.min(
Number.MAX_SAFE_INTEGER,
Math.trunc(numberValue(params.length) ?? 0),
),
),
isModule: params.isModule === true,
...scriptMetadataValues(params),
language: cdpStringValue(params.scriptLanguage) ?? null,
executionContextKey: executionContextKey(params.executionContextId),
};
@@ -135,7 +128,7 @@ const scriptMetadataStringBytes = (script: {
readonly rawUrl: string;
readonly url: string;
readonly origin: string | null;
readonly hash: string;
readonly hash: string | null;
readonly language: string | null;
readonly executionContextKey: string | null;
}): number =>
+3 -3
View File
@@ -5,9 +5,9 @@ export interface CapturedScript {
readonly rawUrl: string;
readonly url: string;
readonly origin: string | null;
readonly hash: string;
readonly length: number;
readonly isModule: boolean;
readonly hash: string | null;
readonly length: number | null;
readonly isModule: boolean | null;
readonly language: string | null;
readonly sourceMapUrl: string | null;
readonly sourceMapRawUrl: string | null;
+33
View File
@@ -26,6 +26,25 @@ export const cdpStringValue = (value: unknown): string | undefined =>
export const numberValue = (value: unknown): number | undefined =>
typeof value === "number" && Number.isFinite(value) ? value : undefined;
/** Preserve partial script declarations; omitted or invalid fields remain unknown. */
export const scriptMetadataValues = (
value: UnknownRecord | undefined,
): {
readonly hash: string | null;
readonly length: number | null;
readonly isModule: boolean | null;
} => {
const length = numberValue(value?.length);
return {
hash: cdpStringValue(value?.hash) ?? null,
length:
length !== undefined && Number.isSafeInteger(length) && length >= 0
? length
: null,
isModule: typeof value?.isModule === "boolean" ? value.isModule : null,
};
};
export const requiredRecord = (value: unknown): UnknownRecord => {
const record = recordValue(value);
if (record === undefined)
@@ -33,6 +52,20 @@ export const requiredRecord = (value: unknown): UnknownRecord => {
return record;
};
/** Require producer source text; an absent source is distinct from an empty script. */
export const requiredScriptSource = (
value: unknown,
operation: BrowserObservationOperation,
): string => {
const source = cdpStringValue(recordValue(value)?.scriptSource);
if (source === undefined)
throw new BrowserObservationError(operation, "protocol_error", {
detail:
"Debugger.getScriptSource returned malformed source text: scriptSource must be a string.",
});
return source;
};
export const isHttpUrl = (value: string | undefined): boolean => {
if (value === undefined) return false;
try {
-2
View File
@@ -29,8 +29,6 @@ import {
import { inspectCdpElectronPage } from "./CdpElectronInspection.js";
import { authorizedElectronFile } from "./ElectronFileScope.js";
/** Public identity committed by passive Electron observations. */
export { CDP_ELECTRON_PROVIDER_IDENTITY } from "./providerIdentities.js";
import { CDP_ELECTRON_PROVIDER_IDENTITY } from "./providerIdentities.js";
const IDENTITY = CDP_ELECTRON_PROVIDER_IDENTITY;
+5 -11
View File
@@ -3,15 +3,16 @@ import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
import {
numberValue,
recordValue,
scriptMetadataValues,
cdpStringValue,
} from "./CdpCaptureValues.js";
export interface ElectronScriptDraft {
readonly scriptId: string;
readonly rawUrl: string;
readonly hash: string;
readonly length: number;
readonly isModule: boolean;
readonly hash: string | null;
readonly length: number | null;
readonly isModule: boolean | null;
readonly language: string | null;
readonly executionContextKey: string | null;
}
@@ -52,9 +53,7 @@ export const ingestElectronScriptEvent = (input: {
input.scripts.push({
scriptId,
rawUrl,
hash: cdpStringValue(value?.hash) ?? "",
length: nonnegativeInteger(value?.length),
isModule: value?.isModule === true,
...scriptMetadataValues(value),
language: cdpStringValue(value?.scriptLanguage) ?? null,
executionContextKey: executionContextKey(value?.executionContextId),
});
@@ -72,11 +71,6 @@ const retainExecutionContext = (
frames.set(contextKey, frameId);
};
const nonnegativeInteger = (value: unknown): number => {
const number = numberValue(value);
return number === undefined ? 0 : Math.max(0, Math.trunc(number));
};
const executionContextKey = (value: unknown): string | null => {
const identifier = numberValue(value);
return identifier !== undefined && Number.isSafeInteger(identifier)
+3 -3
View File
@@ -6,7 +6,7 @@ import { canonicalDigest } from "../domain/comparisonSemantics.js";
import { createWebTextArtifact } from "../domain/webContentArtifact.js";
import type { CdpConnection } from "./CdpConnection.js";
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
import { requiredRecord, cdpStringValue } from "./CdpCaptureValues.js";
import { requiredScriptSource } from "./CdpCaptureValues.js";
import type { ElectronScriptDraft } from "./CdpElectronScriptEvents.js";
import { authorizedElectronFile } from "./ElectronFileScope.js";
@@ -86,15 +86,15 @@ const captureScriptSource = async (
reason: "source capture was not selected",
},
};
const result = requiredRecord(
const text = requiredScriptSource(
await input.connection.send(
"Debugger.getScriptSource",
{ scriptId: script.scriptId },
input.sessionId,
input.signal,
),
"inspect_electron_page",
);
const text = cdpStringValue(result.scriptSource) ?? "";
return {
source: {
included: true,
+3 -4
View File
@@ -7,10 +7,9 @@ import type { CapturedResource } from "./CdpCaptureDocuments.js";
import type { CdpCaptureEvents } from "./CdpCaptureEvents.js";
import type { CapturedScript } from "./CdpCaptureEventTypes.js";
import {
requiredRecord,
requiredScriptSource,
sourceExcluded,
sourceResult,
cdpStringValue,
} from "./CdpCaptureValues.js";
import type { CaptureContext } from "./CdpPageCapture.js";
import type { WebSourceMapRequest } from "./WebSourceMapFetcher.js";
@@ -107,15 +106,15 @@ const captureScriptSource = async (
state: ScriptDraftState,
): Promise<WebPageInspection["scripts"]["items"][number]["source"]> => {
const { context } = state;
const result = requiredRecord(
const content = requiredScriptSource(
await context.connection.send(
"Debugger.getScriptSource",
{ scriptId: script.scriptId },
context.sessionId,
context.signal,
),
context.operation,
);
const content = cdpStringValue(result.scriptSource) ?? "";
return sourceResult(content);
};
@@ -29,19 +29,6 @@ import type {
} from "./BrowserScenarioSessionPort.js";
const OPERATION = "capture_browser_scenario" as const;
let defaultFactory: Promise<BrowserScenarioSessionFactory> | undefined;
const lazyPlaywrightFactory: BrowserScenarioSessionFactory = {
async open(scenario, options) {
defaultFactory ??= import("./PlaywrightScenarioSession.js").then(
({ PlaywrightScenarioSessionFactory }) =>
new PlaywrightScenarioSessionFactory(),
);
return (await defaultFactory).open(scenario, options);
},
};
export { PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY } from "./providerIdentities.js";
import { PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY } from "./providerIdentities.js";
type SnapshotKind = BrowserScenario["capture"]["after_each_step"][number];
@@ -310,9 +297,7 @@ const runScenario = async (
/** Controlled Playwright/CDP scenario driver with exact process ownership. */
export class PlaywrightBrowserScenarioProvider implements BrowserScenarioCapturePort {
constructor(
private readonly factory: BrowserScenarioSessionFactory = lazyPlaywrightFactory,
) {}
constructor(private readonly factory: BrowserScenarioSessionFactory) {}
identity(): ProviderIdentity {
return PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY;
@@ -9,17 +9,39 @@ import {
import { createElectronActiveObservationFixtureResult } from "../domain/javascript/electronActiveObservation.fixture.js";
import { runElectronActions } from "./PlaywrightElectronActiveActions.js";
it("keeps legacy Electron results explicit about unavailable retention data", () => {
const { retention: _retention, ...legacyResult } =
createElectronActiveObservationFixtureResult("/opt/app");
const parsed = electronActiveObservationResultSchema.parse({
...legacyResult,
ipc: { ...legacyResult.ipc, dropped: undefined },
timeline: { ...legacyResult.timeline, dropped: undefined },
});
expect(parsed.retention).toBeNull();
expect(parsed.ipc.dropped).toBeNull();
expect(parsed.timeline.dropped).toBeNull();
it("requires observed Electron retention and coverage instead of repairing old results", () => {
const result = createElectronActiveObservationFixtureResult("/opt/app");
for (const field of ["retention", "timeline", "coverage"] as const) {
expect(
electronActiveObservationResultSchema.safeParse({
...result,
[field]: undefined,
}).success,
).toBe(false);
}
for (const section of ["ipc", "timeline"] as const) {
expect(
electronActiveObservationResultSchema.safeParse({
...result,
[section]: { ...result[section], dropped: undefined },
}).success,
).toBe(false);
}
expect(
electronActiveObservationResultSchema.safeParse({
...result,
retention: null,
}).success,
).toBe(false);
expect(
electronActiveObservationResultSchema.safeParse({
...result,
ipc: {
...result.ipc,
events: [{ ...result.ipc.events[0], source: undefined }],
},
}).success,
).toBe(false);
});
it("parses window, renderer, and deep-link actions for agents", () => {
@@ -246,7 +268,7 @@ it("accepts complete Electron input and observation strings", () => {
title: longText,
},
],
ipc: { events: [event], observed: 1 },
ipc: { events: [event], observed: 1, dropped: 0 },
timeline: {
events: [
{
@@ -258,6 +280,7 @@ it("accepts complete Electron input and observation strings", () => {
},
],
observed: 1,
dropped: 0,
},
limitations: [longText],
});
+8 -61
View File
@@ -3,71 +3,16 @@ import { z } from "zod";
import type { ExecutionOptions } from "../application/AnalysisProvider.js";
import { BrowserObservationError } from "../domain/browserObservationError.js";
import type {
ElectronActiveObservationInput,
ElectronActiveObservationResult,
import {
electronActiveTimelineEventSchema,
type ElectronActiveObservationInput,
type ElectronActiveObservationResult,
} from "../domain/javascript/electronActiveObservation.js";
const OPERATION = "capture_electron_scenario" as const;
const hookEventSchema = z.strictObject({
sequence: z.number().int().min(1),
correlation_id: z.string().nullable(),
kind: z.enum([
"main-handler-invocation",
"main-event-invocation",
"utility-process-fork",
"utility-process-message",
"ipc-main-to-renderer",
"ipc-utility-to-main",
"ipc-renderer-send",
"ipc-renderer-invoke",
"ipc-renderer-post-message",
"app-lifecycle",
"window-lifecycle",
"web-contents-lifecycle",
"navigation",
"shell-attempt",
"process-lifecycle",
"permission",
"popup-attempt",
"download",
"protocol",
"preload",
"native-addon",
"updater",
"error",
]),
event: z.string().nullable(),
phase: z.enum(["attempted", "completed", "blocked", "failed", "observed"]),
channel: z.string().nullable(),
direction: z
.enum([
"renderer-to-main",
"main-to-renderer",
"main-to-utility",
"utility-to-main",
])
.nullable(),
sender: z.string().nullable(),
receiver: z.string().nullable(),
frame: z.string().nullable(),
target: z.string().nullable(),
argument_shapes: z.array(z.string()),
result_shape: z.string().nullable(),
process_type: z.string().nullable(),
source: z.string(),
capture_method: z.enum(["api-wrapper", "event-emitter", "process-hook"]),
artifact_path: z.string().nullable(),
artifact_sha256: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.nullable(),
error: z.boolean(),
});
const hookSnapshotSchema = z.strictObject({
events: z.array(hookEventSchema),
events: z.array(electronActiveTimelineEventSchema),
retention_budget_bytes: z.number().int().min(0),
estimated_retained_bytes: z.number().int().min(0),
event_serialized_byte_upper_bound: z.number().int().min(0),
@@ -113,7 +58,9 @@ type ElectronAction = ElectronActiveObservationInput["actions"][number];
type ElectronActions = ElectronActiveObservationResult["actions"];
export type ElectronHookSnapshot = z.infer<typeof hookSnapshotSchema>;
export type ElectronHookEvent = z.infer<typeof hookEventSchema>;
export type ElectronHookEvent = z.infer<
typeof electronActiveTimelineEventSchema
>;
export type ElectronMetrics = z.infer<typeof metricSchema>[];
type ElectronWindowMetadata = z.infer<typeof windowMetadataSchema>;
@@ -0,0 +1,35 @@
import { afterEach, expect, it, vi } from "vitest";
import { electronActiveObservationInputSchema } from "../domain/javascript/electronActiveObservation.js";
import { PlaywrightElectronActiveProvider } from "./PlaywrightElectronActiveProvider.js";
afterEach(() => vi.unstubAllEnvs());
it("passes the selected environment and ownership token to Electron launch", async () => {
vi.stubEnv("LANG", "ambient-language");
let launchedEnvironment: unknown;
const provider = new PlaywrightElectronActiveProvider(
{
LANG: "selected-language",
PATH: "/selected/bin",
REA_PRIVATE_VALUE: "not-a-launch-setting",
},
async (options) => {
launchedEnvironment = options?.env;
throw new Error("launch boundary reached");
},
);
const result = await provider.capture(
electronActiveObservationInputSchema.parse({
executable_path: process.execPath,
application_path: process.execPath,
}),
);
expect(result.ok).toBe(false);
expect(launchedEnvironment).toEqual({
LANG: "selected-language",
PATH: "/selected/bin",
REA_PROCESS_RUN_ID: expect.any(String),
});
});
@@ -43,8 +43,6 @@ import { projectElectronActiveCapture } from "./PlaywrightElectronActiveProjecti
const OPERATION = "capture_electron_scenario" as const;
const STARTUP_TIMEOUT_MS = 60_000;
/** Public identity for provider-owned Electron runtime experiments. */
export { PLAYWRIGHT_ELECTRON_ACTIVE_PROVIDER_IDENTITY } from "./providerIdentities.js";
import { PLAYWRIGHT_ELECTRON_ACTIVE_PROVIDER_IDENTITY } from "./providerIdentities.js";
const hookPath = fileURLToPath(
@@ -60,6 +58,12 @@ type ElectronPaths = {
/** Launch an owned Electron application through the official Playwright API. */
export class PlaywrightElectronActiveProvider implements ElectronActiveObservationPort {
constructor(
private readonly environment: Readonly<Record<string, string | undefined>>,
private readonly launch: typeof electron.launch = (options) =>
electron.launch(options),
) {}
identity(): ProviderIdentity {
return PLAYWRIGHT_ELECTRON_ACTIVE_PROVIDER_IDENTITY;
}
@@ -89,10 +93,10 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
await systemProcessOwnershipHost.captureBaseline?.(options.signal);
if (options.signal?.aborted)
throw new BrowserObservationError(OPERATION, "cancelled");
application = await electron.launch({
application = await this.launch({
executablePath: paths.executable,
cwd: paths.root,
env: safeElectronEnvironment(runId),
env: safeElectronEnvironment(this.environment, runId),
args: ["-r", hookPath, paths.application, ...input.args],
timeout: Math.max(1, startupDeadline - Date.now()),
});
@@ -353,7 +357,10 @@ const canonicalPaths = async (
return { executable, application, root };
};
const safeElectronEnvironment = (runId: string): Record<string, string> =>
const safeElectronEnvironment = (
environment: Readonly<Record<string, string | undefined>>,
runId: string,
): Record<string, string> =>
Object.fromEntries([
...[
"HOME",
@@ -365,7 +372,7 @@ const safeElectronEnvironment = (runId: string): Record<string, string> =>
"DISPLAY",
"WAYLAND_DISPLAY",
]
.map((name) => [name, process.env[name]] as const)
.map((name) => [name, environment[name]] as const)
.filter(
(entry): entry is readonly [string, string] => entry[1] !== undefined,
),
+40 -2
View File
@@ -1,6 +1,44 @@
import { expect, it } from "vitest";
import { afterEach, expect, it, vi } from "vitest";
import { closePlaywrightScenarioBrowser } from "./PlaywrightScenarioBrowser.js";
import { browserScenarioSchema } from "../domain/browserScenario.js";
import {
closePlaywrightScenarioBrowser,
openPlaywrightScenarioBrowser,
} from "./PlaywrightScenarioBrowser.js";
afterEach(() => vi.unstubAllEnvs());
it("passes the selected environment to the actual browser launch boundary", async () => {
vi.stubEnv("LANG", "ambient-language");
const selected = {
LANG: "selected-language",
PATH: "/selected/bin",
REA_PRIVATE_VALUE: "not-a-launch-setting",
};
let launchedEnvironment: unknown;
const scenario = browserScenarioSchema.parse({
browser: { mode: "launch", executable_path: process.execPath },
start_url: { url: "https://example.test" },
actions: [
{ step_id: "settle", action: "wait_for_timeout", duration_ms: 1 },
],
});
await expect(
openPlaywrightScenarioBrowser(scenario, selected, {
connectOverCDP: async () => {
throw new Error("Unexpected connection");
},
launchPersistentContext: async (_profile, options) => {
launchedEnvironment = options?.env;
throw new Error("launch boundary reached");
},
}),
).rejects.toThrow("launch boundary reached");
expect(launchedEnvironment).toEqual({
LANG: "selected-language",
PATH: "/selected/bin",
});
});
it("returns cancellation instead of success when an attached browser hangs on close", async () => {
const controller = new AbortController();
+7 -2
View File
@@ -105,12 +105,17 @@ const configureAttachedEnvironment = async (
}
};
/** Launch or attach using the caller-selected environment and browser engine. */
export const openPlaywrightScenarioBrowser = async (
scenario: BrowserScenario,
environment: Readonly<Record<string, string | undefined>>,
launcher: Pick<
typeof chromium,
"connectOverCDP" | "launchPersistentContext"
> = chromium,
): Promise<OpenedScenarioBrowser> => {
if (scenario.browser.mode === "connect") {
const browser = await chromium.connectOverCDP(
const browser = await launcher.connectOverCDP(
scenario.browser.cdp_endpoint,
{ timeout: 0 },
);
@@ -130,7 +135,7 @@ export const openPlaywrightScenarioBrowser = async (
const profilePath = await mkdtemp(join(tmpdir(), "rea-browser-scenario-"));
await chmod(profilePath, 0o700);
try {
const context = await chromium.launchPersistentContext(profilePath, {
const context = await launcher.launchPersistentContext(profilePath, {
executablePath: resolve(scenario.browser.executable_path),
headless: scenario.browser.headless,
acceptDownloads: false,
+1 -3
View File
@@ -285,9 +285,7 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
/** Production Playwright/CDP session factory. */
export class PlaywrightScenarioSessionFactory implements BrowserScenarioSessionFactory {
constructor(
private readonly environment: Readonly<
Record<string, string | undefined>
> = process.env,
private readonly environment: Readonly<Record<string, string | undefined>>,
) {}
open(