feat(browser): compare scenario and storage evidence
This commit is contained in:
@@ -24,9 +24,10 @@ import type {
|
||||
WebMcpDiscovery,
|
||||
} from "../domain/webMcpDiscovery.js";
|
||||
import type {
|
||||
CompareWebCapturesInput,
|
||||
WebCaptureDiff,
|
||||
} from "../domain/webCaptureDiff.js";
|
||||
BrowserCaptureComparison,
|
||||
BrowserCaptureComparisonInput,
|
||||
} from "../domain/browserCaptureComparison.js";
|
||||
import { commitBrowserScenarioNormalization } from "../domain/browserScenarioNormalization.js";
|
||||
import type {
|
||||
CaptureWebScreenshotInput,
|
||||
CompareWebScreenshotsInput,
|
||||
@@ -40,7 +41,7 @@ type BrowserEvidenceInput =
|
||||
| AnalyzeWebBundleInput
|
||||
| ObserveWebSessionInput
|
||||
| DiscoverWebMcpToolsInput
|
||||
| CompareWebCapturesInput
|
||||
| BrowserCaptureComparisonInput
|
||||
| CaptureWebScreenshotInput
|
||||
| CompareWebScreenshotsInput;
|
||||
type BrowserEvidenceResult =
|
||||
@@ -49,7 +50,7 @@ type BrowserEvidenceResult =
|
||||
| WebBundleAnalysis
|
||||
| WebObservationSession
|
||||
| WebMcpDiscovery
|
||||
| WebCaptureDiff
|
||||
| BrowserCaptureComparison
|
||||
| WebScreenshot
|
||||
| WebScreenshotDiff;
|
||||
type BrowserEvidenceOperation =
|
||||
@@ -92,6 +93,22 @@ const browserParameters = (
|
||||
input: BrowserEvidenceInput,
|
||||
): EvidenceObservation["parameters"] => {
|
||||
if (!("cdp_endpoint" in input)) {
|
||||
if (
|
||||
"before_scenario" in input &&
|
||||
input.before_scenario !== undefined &&
|
||||
input.after_scenario !== undefined
|
||||
)
|
||||
return {
|
||||
comparison_kind: "browser_scenario",
|
||||
before_browser: input.before_scenario.browser,
|
||||
after_browser: input.after_scenario.browser,
|
||||
before_start_origin: input.before_scenario.scenario.start_origin,
|
||||
after_start_origin: input.after_scenario.scenario.start_origin,
|
||||
max_changes: input.max_changes,
|
||||
normalization_sha256: commitBrowserScenarioNormalization(
|
||||
input.normalization,
|
||||
).sha256,
|
||||
};
|
||||
if ("max_changes" in input)
|
||||
return {
|
||||
before_target_id: input.before.inspection.target.target_id,
|
||||
|
||||
@@ -19,9 +19,9 @@ import type {
|
||||
WebMcpDiscovery,
|
||||
} from "../domain/webMcpDiscovery.js";
|
||||
import type {
|
||||
CompareWebCapturesInput,
|
||||
WebCaptureDiff,
|
||||
} from "../domain/webCaptureDiff.js";
|
||||
BrowserCaptureComparison,
|
||||
BrowserCaptureComparisonInput,
|
||||
} from "../domain/browserCaptureComparison.js";
|
||||
import type {
|
||||
CaptureWebScreenshotInput,
|
||||
CompareWebScreenshotsInput,
|
||||
@@ -55,8 +55,8 @@ export interface BrowserObservationPort {
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<WebMcpDiscovery, AnalysisError>>;
|
||||
compareCaptures(
|
||||
input: CompareWebCapturesInput,
|
||||
): Promise<Result<WebCaptureDiff, AnalysisError>>;
|
||||
input: BrowserCaptureComparisonInput,
|
||||
): Promise<Result<BrowserCaptureComparison, AnalysisError>>;
|
||||
captureScreenshot(
|
||||
input: CaptureWebScreenshotInput,
|
||||
options?: ExecutionOptions,
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
import type { AnalyzeWebBundleInput } from "../domain/webBundleAnalysis.js";
|
||||
import type { ObserveWebSessionInput } from "../domain/browserSession.js";
|
||||
import type { DiscoverWebMcpToolsInput } from "../domain/webMcpDiscovery.js";
|
||||
import type { CompareWebCapturesInput } from "../domain/webCaptureDiff.js";
|
||||
import type { BrowserCaptureComparisonInput } from "../domain/browserCaptureComparison.js";
|
||||
import type {
|
||||
CaptureWebScreenshotInput,
|
||||
CompareWebScreenshotsInput,
|
||||
@@ -151,7 +151,7 @@ export const discoverWebMcpTools = async (
|
||||
/** Compare two already-normalized web captures without external access. */
|
||||
export const compareWebCaptureEvidence = async (
|
||||
browser: BrowserObservationPort | undefined,
|
||||
input: CompareWebCapturesInput,
|
||||
input: BrowserCaptureComparisonInput,
|
||||
): Promise<Result<Evidence, AnalysisError>> => {
|
||||
const ready = requireBrowser(browser, "compare_web_captures");
|
||||
if (!ready.ok) return ready;
|
||||
|
||||
@@ -27,11 +27,11 @@ import {
|
||||
type WebMcpDiscovery,
|
||||
} from "../domain/webMcpDiscovery.js";
|
||||
import {
|
||||
compareWebCaptures,
|
||||
webCaptureDiffSchema,
|
||||
type CompareWebCapturesInput,
|
||||
type WebCaptureDiff,
|
||||
} from "../domain/webCaptureDiff.js";
|
||||
browserCaptureComparisonSchema,
|
||||
compareBrowserCaptures,
|
||||
type BrowserCaptureComparison,
|
||||
type BrowserCaptureComparisonInput,
|
||||
} from "../domain/browserCaptureComparison.js";
|
||||
import {
|
||||
webScreenshotDiffSchema,
|
||||
webScreenshotSchema,
|
||||
@@ -248,10 +248,12 @@ export class CdpBrowserProvider implements BrowserObservationPort {
|
||||
}
|
||||
|
||||
async compareCaptures(
|
||||
input: CompareWebCapturesInput,
|
||||
): Promise<Result<WebCaptureDiff, AnalysisError>> {
|
||||
input: BrowserCaptureComparisonInput,
|
||||
): Promise<Result<BrowserCaptureComparison, AnalysisError>> {
|
||||
try {
|
||||
return ok(webCaptureDiffSchema.parse(compareWebCaptures(input)));
|
||||
return ok(
|
||||
browserCaptureComparisonSchema.parse(compareBrowserCaptures(input)),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(providerError(cause, "compare_web_captures"));
|
||||
}
|
||||
|
||||
@@ -232,10 +232,17 @@ export const captureAccessibility = (
|
||||
readonly total: number;
|
||||
readonly nodes: WebPageInspection["accessibility"]["nodes"];
|
||||
readonly textCapture: WebPageInspection["accessibility"]["text_capture"];
|
||||
readonly treeIncomplete: boolean;
|
||||
} => {
|
||||
const all = results.flatMap((result) =>
|
||||
recordsValue(requiredRecord(result).nodes),
|
||||
);
|
||||
const nodeIds = new Set(
|
||||
all.flatMap((node) => {
|
||||
const nodeId = stringValue(node.nodeId);
|
||||
return nodeId === undefined ? [] : [nodeId];
|
||||
}),
|
||||
);
|
||||
let retainedBytes = 0;
|
||||
let excludedFields = 0;
|
||||
let truncatedFields = 0;
|
||||
@@ -269,6 +276,7 @@ export const captureAccessibility = (
|
||||
name: captureText(node.name),
|
||||
description: captureText(node.description),
|
||||
ignored: node.ignored === true,
|
||||
states: accessibilityStates(node.properties),
|
||||
};
|
||||
});
|
||||
for (const node of all.slice(maximum)) {
|
||||
@@ -281,6 +289,14 @@ export const captureAccessibility = (
|
||||
return {
|
||||
total: all.length,
|
||||
nodes,
|
||||
treeIncomplete: all.some(
|
||||
(node) =>
|
||||
Array.isArray(node.childIds) &&
|
||||
node.childIds.some((childId) => {
|
||||
const id = stringValue(childId);
|
||||
return id !== undefined && !nodeIds.has(id);
|
||||
}),
|
||||
),
|
||||
textCapture: {
|
||||
status: options.unavailable
|
||||
? "unavailable"
|
||||
@@ -296,6 +312,56 @@ export const captureAccessibility = (
|
||||
};
|
||||
};
|
||||
|
||||
const ACCESSIBILITY_STATE_NAMES = new Set([
|
||||
"atomic",
|
||||
"autocomplete",
|
||||
"busy",
|
||||
"checked",
|
||||
"disabled",
|
||||
"editable",
|
||||
"expanded",
|
||||
"focusable",
|
||||
"focused",
|
||||
"hasPopup",
|
||||
"hidden",
|
||||
"invalid",
|
||||
"level",
|
||||
"live",
|
||||
"modal",
|
||||
"multiline",
|
||||
"multiselectable",
|
||||
"orientation",
|
||||
"pressed",
|
||||
"readonly",
|
||||
"required",
|
||||
"selected",
|
||||
"valuemax",
|
||||
"valuemin",
|
||||
]);
|
||||
|
||||
const accessibilityStates = (
|
||||
value: unknown,
|
||||
): WebPageInspection["accessibility"]["nodes"][number]["states"] => {
|
||||
const states = new Map<string, boolean | number | string>();
|
||||
for (const property of recordsValue(value)) {
|
||||
const name = stringValue(property.name);
|
||||
if (name === undefined || !ACCESSIBILITY_STATE_NAMES.has(name)) continue;
|
||||
const raw = recordValue(property.value)?.value;
|
||||
const state =
|
||||
typeof raw === "boolean"
|
||||
? raw
|
||||
: typeof raw === "number"
|
||||
? numberValue(raw)
|
||||
: typeof raw === "string"
|
||||
? raw.slice(0, 256)
|
||||
: undefined;
|
||||
if (state !== undefined) states.set(name, state);
|
||||
}
|
||||
return [...states]
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([name, state]) => ({ name, value: state }));
|
||||
};
|
||||
|
||||
const axText = (value: unknown): string | null =>
|
||||
boundedText(recordValue(value)?.value, 1_024);
|
||||
|
||||
|
||||
@@ -4,6 +4,11 @@ import type {
|
||||
} from "../domain/browserObservation.js";
|
||||
import { CdpConnection } from "./CdpConnection.js";
|
||||
import { optionalCdpCommand } from "./CdpOptionalCommand.js";
|
||||
import {
|
||||
captureStorageFingerprints,
|
||||
type CapturedCache,
|
||||
type CapturedStorageItems,
|
||||
} from "./CdpCaptureStorageFingerprints.js";
|
||||
import {
|
||||
numberValue,
|
||||
recordValue,
|
||||
@@ -34,77 +39,109 @@ export const captureStorage = async (
|
||||
),
|
||||
);
|
||||
const local = context.input.include_storage_keys
|
||||
? await storageKeys(context, origin, true, limitations)
|
||||
: [];
|
||||
? await storageItems(context, origin, true, limitations)
|
||||
: emptyStorageItems;
|
||||
const session = context.input.include_storage_keys
|
||||
? await storageKeys(context, origin, false, limitations)
|
||||
: [];
|
||||
const indexed = context.input.include_storage_keys
|
||||
? stringArray(
|
||||
recordValue(
|
||||
await optionalCdpCommand(
|
||||
context,
|
||||
"IndexedDB.requestDatabaseNames",
|
||||
{ securityOrigin: origin },
|
||||
limitations,
|
||||
),
|
||||
)?.databaseNames,
|
||||
? await storageItems(context, origin, false, limitations)
|
||||
: emptyStorageItems;
|
||||
const indexedRaw = context.input.include_storage_keys
|
||||
? await optionalCdpCommand(
|
||||
context,
|
||||
"IndexedDB.requestDatabaseNames",
|
||||
{ securityOrigin: origin },
|
||||
limitations,
|
||||
)
|
||||
: [];
|
||||
const caches = context.input.include_storage_keys
|
||||
? recordsValue(
|
||||
recordValue(
|
||||
await optionalCdpCommand(
|
||||
context,
|
||||
"CacheStorage.requestCacheNames",
|
||||
{ securityOrigin: origin },
|
||||
limitations,
|
||||
),
|
||||
)?.caches,
|
||||
).flatMap((cache) => {
|
||||
const name = stringValue(cache.cacheName);
|
||||
return name === undefined ? [] : [name.slice(0, 1_024)];
|
||||
})
|
||||
: [];
|
||||
: undefined;
|
||||
const indexedValues = recordValue(indexedRaw)?.databaseNames;
|
||||
const indexed = stringArray(indexedValues);
|
||||
const cacheRaw = context.input.include_storage_keys
|
||||
? await optionalCdpCommand(
|
||||
context,
|
||||
"CacheStorage.requestCacheNames",
|
||||
{ securityOrigin: origin },
|
||||
limitations,
|
||||
)
|
||||
: undefined;
|
||||
const cacheValues = recordsValue(recordValue(cacheRaw)?.caches);
|
||||
const caches = cacheValues.flatMap((cache) => {
|
||||
const name = stringValue(cache.cacheName);
|
||||
const id = stringValue(cache.cacheId);
|
||||
return name === undefined || id === undefined
|
||||
? []
|
||||
: [{ name: name.slice(0, 1_024), id } satisfies CapturedCache];
|
||||
});
|
||||
const maximum = context.input.limits.max_storage_keys;
|
||||
const fingerprints = context.input.include_storage_keys
|
||||
? await captureStorageFingerprints({
|
||||
context,
|
||||
origin,
|
||||
local,
|
||||
session,
|
||||
indexedDbNames: indexed.slice(0, maximum),
|
||||
caches: caches.slice(0, maximum),
|
||||
limitations,
|
||||
})
|
||||
: { items: [], complete: false, truncated: false };
|
||||
const truncated =
|
||||
[local.items, session.items, indexed, caches].some(
|
||||
(items) => items.length > maximum,
|
||||
) || fingerprints.truncated;
|
||||
const structuredStorageComplete =
|
||||
indexedRaw !== undefined &&
|
||||
Array.isArray(indexedValues) &&
|
||||
indexed.length === indexedValues.length &&
|
||||
cacheRaw !== undefined &&
|
||||
caches.length === cacheValues.length;
|
||||
return {
|
||||
value: {
|
||||
origin,
|
||||
usage_bytes: numberValue(quota?.usage) ?? null,
|
||||
quota_bytes: numberValue(quota?.quota) ?? null,
|
||||
local_storage_keys: local.slice(0, maximum),
|
||||
session_storage_keys: session.slice(0, maximum),
|
||||
local_storage_keys: local.items.map(({ key }) => key).slice(0, maximum),
|
||||
session_storage_keys: session.items
|
||||
.map(({ key }) => key)
|
||||
.slice(0, maximum),
|
||||
indexed_db_names: indexed.slice(0, maximum),
|
||||
cache_names: caches.slice(0, maximum),
|
||||
cache_names: caches.map(({ name }) => name).slice(0, maximum),
|
||||
content_fingerprints: [...fingerprints.items],
|
||||
fingerprint_algorithm: "sha256",
|
||||
fingerprints_complete:
|
||||
fingerprints.complete && structuredStorageComplete && !truncated,
|
||||
values_redacted: true,
|
||||
},
|
||||
truncated: [local, session, indexed, caches].some(
|
||||
(items) => items.length > maximum,
|
||||
),
|
||||
truncated,
|
||||
};
|
||||
};
|
||||
|
||||
const storageKeys = async (
|
||||
const emptyStorageItems: CapturedStorageItems = {
|
||||
items: [],
|
||||
complete: false,
|
||||
};
|
||||
|
||||
const storageItems = async (
|
||||
context: Parameters<typeof captureStorage>[0],
|
||||
origin: string,
|
||||
isLocalStorage: boolean,
|
||||
limitations: string[],
|
||||
): Promise<readonly string[]> => {
|
||||
const result = recordValue(
|
||||
await optionalCdpCommand(
|
||||
context,
|
||||
"DOMStorage.getDOMStorageItems",
|
||||
{ storageId: { securityOrigin: origin, isLocalStorage } },
|
||||
limitations,
|
||||
),
|
||||
): Promise<CapturedStorageItems> => {
|
||||
const raw = await optionalCdpCommand(
|
||||
context,
|
||||
"DOMStorage.getDOMStorageItems",
|
||||
{ storageId: { securityOrigin: origin, isLocalStorage } },
|
||||
limitations,
|
||||
);
|
||||
return Array.isArray(result?.entries)
|
||||
? result.entries.flatMap((entry) => {
|
||||
if (!Array.isArray(entry)) return [];
|
||||
const key = stringValue(entry[0]);
|
||||
return key === undefined ? [] : [key.slice(0, 1_024)];
|
||||
})
|
||||
: [];
|
||||
const entries = recordValue(raw)?.entries;
|
||||
if (raw === undefined || !Array.isArray(entries))
|
||||
return { items: [], complete: false };
|
||||
const items = entries.flatMap((entry) => {
|
||||
if (!Array.isArray(entry)) return [];
|
||||
const key = stringValue(entry[0]);
|
||||
const value = stringValue(entry[1]);
|
||||
return key === undefined || value === undefined
|
||||
? []
|
||||
: [{ key: key.slice(0, 1_024), value }];
|
||||
});
|
||||
return { items, complete: items.length === entries.length };
|
||||
};
|
||||
|
||||
const stringArray = (value: unknown): readonly string[] =>
|
||||
|
||||
@@ -0,0 +1,501 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
|
||||
import type {
|
||||
InspectWebPageInput,
|
||||
WebPageInspection,
|
||||
} from "../domain/browserObservation.js";
|
||||
import { CdpConnection } from "./CdpConnection.js";
|
||||
import { optionalCdpCommand } from "./CdpOptionalCommand.js";
|
||||
import { recordValue, recordsValue, stringValue } from "./CdpCaptureValues.js";
|
||||
|
||||
const MAX_CACHE_BODY_BYTES = 64 * 1_024;
|
||||
|
||||
type StorageFingerprint =
|
||||
WebPageInspection["storage"]["content_fingerprints"][number];
|
||||
|
||||
export interface CapturedStorageItems {
|
||||
readonly items: readonly {
|
||||
readonly key: string;
|
||||
readonly value: string;
|
||||
}[];
|
||||
readonly complete: boolean;
|
||||
}
|
||||
|
||||
export interface CapturedCache {
|
||||
readonly name: string;
|
||||
readonly id: string;
|
||||
}
|
||||
|
||||
interface StorageFingerprintContext {
|
||||
readonly connection: CdpConnection;
|
||||
readonly sessionId: string | undefined;
|
||||
readonly input: InspectWebPageInput;
|
||||
readonly signal?: AbortSignal;
|
||||
}
|
||||
|
||||
interface FingerprintState {
|
||||
readonly items: StorageFingerprint[];
|
||||
readonly maximum: number;
|
||||
complete: boolean;
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
interface FingerprintRun {
|
||||
readonly context: StorageFingerprintContext;
|
||||
readonly limitations: string[];
|
||||
readonly state: FingerprintState;
|
||||
}
|
||||
|
||||
interface CaptureStorageFingerprintInput {
|
||||
readonly context: StorageFingerprintContext;
|
||||
readonly origin: string;
|
||||
readonly local: CapturedStorageItems;
|
||||
readonly session: CapturedStorageItems;
|
||||
readonly indexedDbNames: readonly string[];
|
||||
readonly caches: readonly CapturedCache[];
|
||||
readonly limitations: string[];
|
||||
}
|
||||
|
||||
/** Capture stable hashes of approved storage content without returning values. */
|
||||
export const captureStorageFingerprints = async ({
|
||||
context,
|
||||
origin,
|
||||
local,
|
||||
session,
|
||||
indexedDbNames,
|
||||
caches,
|
||||
limitations,
|
||||
}: CaptureStorageFingerprintInput): Promise<{
|
||||
readonly items: readonly StorageFingerprint[];
|
||||
readonly complete: boolean;
|
||||
readonly truncated: boolean;
|
||||
}> => {
|
||||
const state: FingerprintState = {
|
||||
items: [],
|
||||
maximum: context.input.limits.max_storage_keys,
|
||||
complete: local.complete && session.complete,
|
||||
truncated: false,
|
||||
};
|
||||
const run = { context, limitations, state };
|
||||
addStorageItems(state, "local_storage", local.items);
|
||||
addStorageItems(state, "session_storage", session.items);
|
||||
await addCookies(run, origin);
|
||||
await addIndexedDb(run, origin, indexedDbNames);
|
||||
await addCaches(run, caches);
|
||||
state.items.sort((left, right) =>
|
||||
compareCodePoints(
|
||||
`${left.scope}:${left.identity_sha256}`,
|
||||
`${right.scope}:${right.identity_sha256}`,
|
||||
),
|
||||
);
|
||||
return {
|
||||
items: state.items,
|
||||
complete:
|
||||
state.complete &&
|
||||
!state.truncated &&
|
||||
state.items.every(({ complete }) => complete),
|
||||
truncated: state.truncated,
|
||||
};
|
||||
};
|
||||
|
||||
const addStorageItems = (
|
||||
state: FingerprintState,
|
||||
scope: "local_storage" | "session_storage",
|
||||
items: CapturedStorageItems["items"],
|
||||
): void => {
|
||||
for (const item of items)
|
||||
addFingerprint(state, {
|
||||
scope,
|
||||
identity: item.key,
|
||||
value: item.value,
|
||||
complete: true,
|
||||
});
|
||||
};
|
||||
|
||||
const addCookies = async (
|
||||
run: FingerprintRun,
|
||||
origin: string,
|
||||
): Promise<void> => {
|
||||
const raw = await optionalCdpCommand(
|
||||
run.context,
|
||||
"Network.getCookies",
|
||||
{ urls: [origin] },
|
||||
run.limitations,
|
||||
);
|
||||
if (raw === undefined) {
|
||||
run.state.complete = false;
|
||||
return;
|
||||
}
|
||||
const cookieValues = recordValue(raw)?.cookies;
|
||||
if (!Array.isArray(cookieValues)) {
|
||||
run.state.complete = false;
|
||||
return;
|
||||
}
|
||||
const cookies = recordsValue(cookieValues);
|
||||
if (cookies.length !== cookieValues.length) run.state.complete = false;
|
||||
for (const cookie of cookies) {
|
||||
const name = stringValue(cookie.name);
|
||||
const value = stringValue(cookie.value);
|
||||
const domain = stringValue(cookie.domain);
|
||||
const path = stringValue(cookie.path);
|
||||
if (
|
||||
name === undefined ||
|
||||
value === undefined ||
|
||||
domain === undefined ||
|
||||
path === undefined
|
||||
) {
|
||||
run.state.complete = false;
|
||||
continue;
|
||||
}
|
||||
addFingerprint(run.state, {
|
||||
scope: "cookie",
|
||||
identity: {
|
||||
domain,
|
||||
path,
|
||||
name,
|
||||
partition_key: cookie.partitionKey ?? null,
|
||||
},
|
||||
value,
|
||||
complete: true,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const addIndexedDb = async (
|
||||
run: FingerprintRun,
|
||||
origin: string,
|
||||
names: readonly string[],
|
||||
): Promise<void> => {
|
||||
for (const databaseName of names) {
|
||||
if (run.state.items.length >= run.state.maximum) {
|
||||
run.state.truncated = true;
|
||||
return;
|
||||
}
|
||||
const raw = await optionalCdpCommand(
|
||||
run.context,
|
||||
"IndexedDB.requestDatabase",
|
||||
{ securityOrigin: origin, databaseName },
|
||||
run.limitations,
|
||||
);
|
||||
const database = recordValue(recordValue(raw)?.databaseWithObjectStores);
|
||||
if (raw === undefined || database === undefined) {
|
||||
run.state.complete = false;
|
||||
continue;
|
||||
}
|
||||
if (stringValue(database.name) !== databaseName) {
|
||||
run.state.complete = false;
|
||||
continue;
|
||||
}
|
||||
if (!Array.isArray(database.objectStores)) {
|
||||
run.state.complete = false;
|
||||
continue;
|
||||
}
|
||||
const stores = recordsValue(database.objectStores);
|
||||
if (stores.length !== database.objectStores.length)
|
||||
run.state.complete = false;
|
||||
addFingerprint(run.state, {
|
||||
scope: "indexed_db_schema",
|
||||
identity: databaseName,
|
||||
value: stores.map(indexedDbStoreSchema),
|
||||
complete: indexedDbSchemaComplete(stores),
|
||||
});
|
||||
for (const store of stores) {
|
||||
const objectStoreName = stringValue(store.name);
|
||||
if (objectStoreName === undefined) {
|
||||
run.state.complete = false;
|
||||
continue;
|
||||
}
|
||||
await addIndexedDbRecords(run, {
|
||||
origin,
|
||||
databaseName,
|
||||
objectStoreName,
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const indexedDbStoreSchema = (store: Readonly<Record<string, unknown>>) => ({
|
||||
name: stringValue(store.name) ?? null,
|
||||
key_path: stableValue(store.keyPath),
|
||||
auto_increment: store.autoIncrement === true,
|
||||
indexes: recordsValue(store.indexes).map((index) => ({
|
||||
name: stringValue(index.name) ?? null,
|
||||
key_path: stableValue(index.keyPath),
|
||||
unique: index.unique === true,
|
||||
multi_entry: index.multiEntry === true,
|
||||
})),
|
||||
});
|
||||
|
||||
const indexedDbSchemaComplete = (
|
||||
stores: readonly Readonly<Record<string, unknown>>[],
|
||||
): boolean =>
|
||||
stores.every(
|
||||
(store) =>
|
||||
stringValue(store.name) !== undefined &&
|
||||
stableValueComplete(store.keyPath) &&
|
||||
typeof store.autoIncrement === "boolean" &&
|
||||
Array.isArray(store.indexes) &&
|
||||
recordsValue(store.indexes).length === store.indexes.length &&
|
||||
recordsValue(store.indexes).every(
|
||||
(index) =>
|
||||
stringValue(index.name) !== undefined &&
|
||||
stableValueComplete(index.keyPath) &&
|
||||
typeof index.unique === "boolean" &&
|
||||
typeof index.multiEntry === "boolean",
|
||||
),
|
||||
);
|
||||
|
||||
const addIndexedDbRecords = async (
|
||||
run: FingerprintRun,
|
||||
input: {
|
||||
readonly origin: string;
|
||||
readonly databaseName: string;
|
||||
readonly objectStoreName: string;
|
||||
},
|
||||
): Promise<void> => {
|
||||
const remaining = run.state.maximum - run.state.items.length;
|
||||
if (remaining <= 0) {
|
||||
run.state.truncated = true;
|
||||
return;
|
||||
}
|
||||
const raw = await optionalCdpCommand(
|
||||
run.context,
|
||||
"IndexedDB.requestData",
|
||||
{
|
||||
securityOrigin: input.origin,
|
||||
databaseName: input.databaseName,
|
||||
objectStoreName: input.objectStoreName,
|
||||
indexName: "",
|
||||
skipCount: 0,
|
||||
pageSize: remaining,
|
||||
},
|
||||
run.limitations,
|
||||
);
|
||||
const result = recordValue(raw);
|
||||
if (raw === undefined || result === undefined) {
|
||||
run.state.complete = false;
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!Array.isArray(result.objectStoreDataEntries) ||
|
||||
typeof result.hasMore !== "boolean"
|
||||
) {
|
||||
run.state.complete = false;
|
||||
return;
|
||||
}
|
||||
const entries = recordsValue(result.objectStoreDataEntries);
|
||||
if (entries.length !== result.objectStoreDataEntries.length)
|
||||
run.state.complete = false;
|
||||
for (const entry of entries) {
|
||||
const key = stableValue(entry.key);
|
||||
const primaryKey = stableValue(entry.primaryKey);
|
||||
const value = stableValue(entry.value);
|
||||
addFingerprint(run.state, {
|
||||
scope: "indexed_db_record",
|
||||
identity: {
|
||||
database: input.databaseName,
|
||||
store: input.objectStoreName,
|
||||
key,
|
||||
primaryKey,
|
||||
},
|
||||
value,
|
||||
complete: remoteObjectComplete(entry.value),
|
||||
});
|
||||
}
|
||||
if (result.hasMore === true || entries.length > remaining)
|
||||
run.state.truncated = true;
|
||||
};
|
||||
|
||||
const addCaches = async (
|
||||
run: FingerprintRun,
|
||||
caches: readonly CapturedCache[],
|
||||
): Promise<void> => {
|
||||
for (const cache of caches) {
|
||||
const remaining = run.state.maximum - run.state.items.length;
|
||||
if (remaining <= 0) {
|
||||
run.state.truncated = true;
|
||||
return;
|
||||
}
|
||||
const raw = await optionalCdpCommand(
|
||||
run.context,
|
||||
"CacheStorage.requestEntries",
|
||||
{ cacheId: cache.id, skipCount: 0, pageSize: remaining },
|
||||
run.limitations,
|
||||
);
|
||||
const result = recordValue(raw);
|
||||
if (raw === undefined || result === undefined) {
|
||||
run.state.complete = false;
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
!Array.isArray(result.cacheDataEntries) ||
|
||||
typeof result.returnCount !== "number"
|
||||
) {
|
||||
run.state.complete = false;
|
||||
continue;
|
||||
}
|
||||
const entries = recordsValue(result.cacheDataEntries);
|
||||
if (entries.length !== result.cacheDataEntries.length)
|
||||
run.state.complete = false;
|
||||
for (const entry of entries) await addCacheEntry(run, cache, entry);
|
||||
if (result.returnCount > entries.length) run.state.truncated = true;
|
||||
}
|
||||
};
|
||||
|
||||
const addCacheEntry = async (
|
||||
run: FingerprintRun,
|
||||
cache: CapturedCache,
|
||||
entry: Readonly<Record<string, unknown>>,
|
||||
): Promise<void> => {
|
||||
const requestURL = stringValue(entry.requestURL);
|
||||
const requestMethod = stringValue(entry.requestMethod);
|
||||
if (requestURL === undefined || requestMethod === undefined) {
|
||||
run.state.complete = false;
|
||||
return;
|
||||
}
|
||||
if (!Array.isArray(entry.requestHeaders)) {
|
||||
run.state.complete = false;
|
||||
return;
|
||||
}
|
||||
const headerRecords = recordsValue(entry.requestHeaders);
|
||||
const requestHeaders = headerRecords.flatMap((header) => {
|
||||
const name = stringValue(header.name);
|
||||
const value = stringValue(header.value);
|
||||
return name === undefined || value === undefined ? [] : [{ name, value }];
|
||||
});
|
||||
if (
|
||||
headerRecords.length !== entry.requestHeaders.length ||
|
||||
requestHeaders.length !== headerRecords.length
|
||||
) {
|
||||
run.state.complete = false;
|
||||
return;
|
||||
}
|
||||
const raw = await optionalCdpCommand(
|
||||
run.context,
|
||||
"CacheStorage.requestCachedResponse",
|
||||
{ cacheId: cache.id, requestURL, requestHeaders },
|
||||
run.limitations,
|
||||
);
|
||||
const body = stringValue(recordValue(recordValue(raw)?.response)?.body);
|
||||
const decoded = body === undefined ? null : decodeBase64(body);
|
||||
const complete =
|
||||
decoded !== null && decoded.byteLength <= MAX_CACHE_BODY_BYTES;
|
||||
if (!complete) run.state.complete = false;
|
||||
addFingerprint(run.state, {
|
||||
scope: "cache_entry",
|
||||
identity: { cache: cache.name, requestURL, requestMethod, requestHeaders },
|
||||
value: decoded ?? undefined,
|
||||
complete,
|
||||
});
|
||||
};
|
||||
|
||||
const addFingerprint = (
|
||||
state: FingerprintState,
|
||||
input: {
|
||||
readonly scope: StorageFingerprint["scope"];
|
||||
readonly identity: unknown;
|
||||
readonly value: unknown;
|
||||
readonly complete: boolean;
|
||||
},
|
||||
): void => {
|
||||
if (state.items.length >= state.maximum) {
|
||||
state.truncated = true;
|
||||
return;
|
||||
}
|
||||
state.items.push({
|
||||
scope: input.scope,
|
||||
identity_sha256: digest(input.identity),
|
||||
value_sha256: input.value === undefined ? null : digest(input.value),
|
||||
complete:
|
||||
input.complete &&
|
||||
stableValueComplete(input.identity) &&
|
||||
stableValueComplete(input.value),
|
||||
});
|
||||
};
|
||||
|
||||
const digest = (value: unknown): string =>
|
||||
createHash("sha256").update(encodedValue(value)).digest("hex");
|
||||
|
||||
const encodedValue = (value: unknown): Uint8Array | string => {
|
||||
if (value instanceof Uint8Array) return value;
|
||||
const encoded = canonicalize(stableValue(value));
|
||||
if (encoded === undefined) throw new TypeError("Expected canonical JSON");
|
||||
return encoded;
|
||||
};
|
||||
|
||||
const stableValue = (value: unknown, depth = 0): unknown => {
|
||||
if (
|
||||
value === null ||
|
||||
typeof value === "string" ||
|
||||
typeof value === "number" ||
|
||||
typeof value === "boolean"
|
||||
)
|
||||
return value;
|
||||
if (depth >= 8) return "<depth-limit>";
|
||||
if (Array.isArray(value))
|
||||
return value.slice(0, 64).map((item) => stableValue(item, depth + 1));
|
||||
const record = recordValue(value);
|
||||
if (record === undefined) return String(value);
|
||||
return Object.fromEntries(
|
||||
Object.entries(record)
|
||||
.filter(([key]) => key !== "objectId" && key !== "customPreview")
|
||||
.sort(([left], [right]) => compareCodePoints(left, right))
|
||||
.slice(0, 64)
|
||||
.map(([key, item]) => [key, stableValue(item, depth + 1)]),
|
||||
);
|
||||
};
|
||||
|
||||
const stableValueComplete = (value: unknown, depth = 0): boolean => {
|
||||
if (value instanceof Uint8Array) return true;
|
||||
if (
|
||||
value === null ||
|
||||
value === undefined ||
|
||||
typeof value === "string" ||
|
||||
typeof value === "number" ||
|
||||
typeof value === "boolean"
|
||||
)
|
||||
return true;
|
||||
if (depth >= 8) return false;
|
||||
if (Array.isArray(value))
|
||||
return (
|
||||
value.length <= 64 &&
|
||||
value.every((item) => stableValueComplete(item, depth + 1))
|
||||
);
|
||||
const record = recordValue(value);
|
||||
if (record === undefined) return false;
|
||||
const entries = Object.entries(record).filter(
|
||||
([key]) => key !== "objectId" && key !== "customPreview",
|
||||
);
|
||||
return (
|
||||
entries.length <= 64 &&
|
||||
entries.every(([, item]) => stableValueComplete(item, depth + 1))
|
||||
);
|
||||
};
|
||||
|
||||
const remoteObjectComplete = (value: unknown): boolean => {
|
||||
const record = recordValue(value);
|
||||
if (record === undefined) return true;
|
||||
return (
|
||||
record.objectId === undefined &&
|
||||
record.preview === undefined &&
|
||||
record.customPreview === undefined &&
|
||||
(record.type !== "object" || record.value !== undefined) &&
|
||||
stableValueComplete(record)
|
||||
);
|
||||
};
|
||||
|
||||
const decodeBase64 = (value: string): Buffer | null => {
|
||||
if (
|
||||
value.length % 4 !== 0 ||
|
||||
!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(
|
||||
value,
|
||||
)
|
||||
)
|
||||
return null;
|
||||
return Buffer.from(value, "base64");
|
||||
};
|
||||
|
||||
const compareCodePoints = (left: string, right: string): number =>
|
||||
left < right ? -1 : left > right ? 1 : 0;
|
||||
@@ -386,6 +386,7 @@ const accessibilityForFrames = async (
|
||||
);
|
||||
if (capture.textCapture.status === "truncated")
|
||||
events.completeness.truncate("accessibility");
|
||||
if (capture.treeIncomplete) events.completeness.truncate("accessibility");
|
||||
return capture;
|
||||
};
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import { CdpBrowserProvider } from "./browser/CdpBrowserProvider.js";
|
||||
import { logCliCommand } from "./cliLogging.js";
|
||||
import { parseConfig } from "./config.js";
|
||||
import { AnalysisInputError, projectAnalysisError } from "./domain/errors.js";
|
||||
import { compareWebCapturesInputSchema } from "./domain/webCaptureDiff.js";
|
||||
import { browserCaptureComparisonInputSchema } from "./domain/browserCaptureComparison.js";
|
||||
import { discoverWebMcpToolsInputSchema } from "./domain/webMcpDiscovery.js";
|
||||
import {
|
||||
captureWebScreenshotInputSchema,
|
||||
@@ -122,7 +122,8 @@ const registerCaptureDiff = (
|
||||
logger: Logger,
|
||||
): void => {
|
||||
cli.command(CLI_COMMANDS.compareWebCaptures, {
|
||||
description: "Compare two normalized web capture JSON values",
|
||||
description:
|
||||
"Compare two normalized passive captures or recorded browser scenarios",
|
||||
args: z.object({
|
||||
beforeJson: z.string().describe("Earlier normalized web capture JSON"),
|
||||
afterJson: z.string().describe("Later normalized web capture JSON"),
|
||||
@@ -135,16 +136,31 @@ const registerCaptureDiff = (
|
||||
.max(20_000)
|
||||
.default(2_000)
|
||||
.describe("Maximum normalized changes to return"),
|
||||
normalizationJson: z
|
||||
.string()
|
||||
.default('{"rules":[]}')
|
||||
.describe(
|
||||
"Recorded literal normalization policy for browser scenarios",
|
||||
),
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "compare-web-captures", async () => {
|
||||
const before = parseJson(args.beforeJson);
|
||||
const after = parseJson(args.afterJson);
|
||||
const parsed = compareWebCapturesInputSchema.safeParse({
|
||||
before,
|
||||
after,
|
||||
max_changes: options.maxChanges,
|
||||
});
|
||||
const scenarioComparison =
|
||||
browserCaptureComparisonInputSchema.safeParse({
|
||||
before_scenario: before,
|
||||
after_scenario: after,
|
||||
normalization: parseJson(options.normalizationJson),
|
||||
max_changes: options.maxChanges,
|
||||
});
|
||||
const parsed = scenarioComparison.success
|
||||
? scenarioComparison
|
||||
: browserCaptureComparisonInputSchema.safeParse({
|
||||
before,
|
||||
after,
|
||||
max_changes: options.maxChanges,
|
||||
});
|
||||
if (!parsed.success) return inputError("compare_web_captures");
|
||||
const result = await compareWebCaptureEvidence(
|
||||
new CdpBrowserProvider(),
|
||||
|
||||
@@ -18,9 +18,9 @@ import {
|
||||
webMcpDiscoverySchema,
|
||||
} from "../domain/webMcpDiscovery.js";
|
||||
import {
|
||||
compareWebCapturesInputSchema,
|
||||
webCaptureDiffSchema,
|
||||
} from "../domain/webCaptureDiff.js";
|
||||
browserCaptureComparisonWireSchema,
|
||||
browserCaptureComparisonSchema,
|
||||
} from "../domain/browserCaptureComparison.js";
|
||||
import {
|
||||
captureWebScreenshotInputSchema,
|
||||
compareWebScreenshotsInputSchema,
|
||||
@@ -38,12 +38,82 @@ const observationSessionOutputSchema = evidenceResult(
|
||||
webObservationSessionSchema,
|
||||
);
|
||||
const webMcpOutputSchema = evidenceResult(webMcpDiscoverySchema);
|
||||
const captureDiffOutputSchema = evidenceResult(webCaptureDiffSchema);
|
||||
const captureDiffOutputSchema = evidenceResult(browserCaptureComparisonSchema);
|
||||
const screenshotOutputSchema = evidenceResult(webScreenshotSchema);
|
||||
const screenshotDiffOutputSchema = evidenceResult(webScreenshotDiffSchema);
|
||||
|
||||
const endpoint = "http://127.0.0.1:9222";
|
||||
const origin = "https://app.example.test";
|
||||
const scenarioUrl = {
|
||||
url: `${origin}/`,
|
||||
origin,
|
||||
query_parameter_names: [],
|
||||
redacted: false,
|
||||
};
|
||||
const scenarioCompleteness = {
|
||||
status: "complete",
|
||||
equality_eligible: true,
|
||||
missing_sections: [],
|
||||
truncated_sections: [],
|
||||
};
|
||||
const scenarioArtifacts = {
|
||||
screenshot: { state: "not_requested" },
|
||||
dom: { state: "not_requested" },
|
||||
accessibility: { state: "not_requested" },
|
||||
url: { state: "not_requested" },
|
||||
history: { state: "not_requested" },
|
||||
storage: { state: "not_requested" },
|
||||
};
|
||||
const exampleScenarioCapture = () => ({
|
||||
schema_version: 1,
|
||||
browser: {
|
||||
mode: "connect",
|
||||
process_ownership: "external",
|
||||
cleanup: "disconnected-external",
|
||||
product: "Chromium",
|
||||
version: "149",
|
||||
},
|
||||
scenario: {
|
||||
start_origin: origin,
|
||||
allowed_origins: [origin],
|
||||
action_count: 1,
|
||||
secret_references: [],
|
||||
},
|
||||
duration_ms: 10,
|
||||
steps: [
|
||||
{
|
||||
step_index: 0,
|
||||
step_id: "scenario_start",
|
||||
action: "scenario_start",
|
||||
status: "completed",
|
||||
elapsed_ms: 0,
|
||||
before_url: scenarioUrl,
|
||||
after_url: scenarioUrl,
|
||||
error: null,
|
||||
event_sequence_start: 1,
|
||||
event_sequence_end: 0,
|
||||
artifacts: scenarioArtifacts,
|
||||
completeness: scenarioCompleteness,
|
||||
},
|
||||
{
|
||||
step_index: 1,
|
||||
step_id: "open-settings",
|
||||
action: "click",
|
||||
status: "completed",
|
||||
elapsed_ms: 10,
|
||||
before_url: scenarioUrl,
|
||||
after_url: scenarioUrl,
|
||||
error: null,
|
||||
event_sequence_start: 1,
|
||||
event_sequence_end: 0,
|
||||
artifacts: scenarioArtifacts,
|
||||
completeness: scenarioCompleteness,
|
||||
},
|
||||
],
|
||||
events: { retained: 0, dropped: 0, items: [] },
|
||||
completeness: scenarioCompleteness,
|
||||
limitations: [],
|
||||
});
|
||||
|
||||
/** Origin-scoped, passive browser reverse-engineering contracts. */
|
||||
export const BROWSER_TOOL_CONTRACTS = [
|
||||
@@ -209,16 +279,26 @@ export const BROWSER_TOOL_CONTRACTS = [
|
||||
name: "compare_web_captures",
|
||||
...toolContractMetadata("compare_web_captures"),
|
||||
description:
|
||||
"Compare two normalized web captures across DOM, scripts, resources, network, safe metadata, and optional WebMCP inventories. Stable observed changes are distinguished from unknown absence caused by incomplete capture coverage.",
|
||||
"Compare either passive web captures or step-indexed browser scenarios. Scenario comparison aligns exact step IDs, records deterministic literal normalization, and exposes bounded artifact-level changes plus alignment failures. Missing or truncated evidence never proves equality.",
|
||||
kind: "browser-provider",
|
||||
inputSchema: compareWebCapturesInputSchema,
|
||||
inputSchema: browserCaptureComparisonWireSchema,
|
||||
outputSchema: captureDiffOutputSchema,
|
||||
examples: [
|
||||
{
|
||||
title: "Compare two normalized captures",
|
||||
title: "Compare two recorded browser scenarios",
|
||||
input: {
|
||||
before: { inspection: exampleInspection() },
|
||||
after: { inspection: exampleInspection() },
|
||||
before_scenario: exampleScenarioCapture(),
|
||||
after_scenario: exampleScenarioCapture(),
|
||||
normalization: {
|
||||
rules: [
|
||||
{
|
||||
rule_id: "volatile-build-id",
|
||||
artifacts: ["dom", "accessibility"],
|
||||
match: "build-123",
|
||||
replacement: "[BUILD_ID]",
|
||||
},
|
||||
],
|
||||
},
|
||||
max_changes: 2_000,
|
||||
},
|
||||
},
|
||||
@@ -268,99 +348,6 @@ export const BROWSER_TOOL_CONTRACTS = [
|
||||
},
|
||||
] as const satisfies readonly ToolContract[];
|
||||
|
||||
function exampleCompleteness() {
|
||||
return {
|
||||
status: "complete_within_window",
|
||||
conditions: ["complete_within_window"],
|
||||
policy_filtered_sections: [],
|
||||
attach_limited_sections: [],
|
||||
truncated_sections: [],
|
||||
unavailable_sections: [],
|
||||
excluded: [],
|
||||
dropped_events: {
|
||||
scripts: 0,
|
||||
network_requests: 0,
|
||||
console_events: 0,
|
||||
websocket_connections: 0,
|
||||
websocket_frames: 0,
|
||||
webmcp_tools: 0,
|
||||
timeline_events: 0,
|
||||
total: 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function exampleInspection() {
|
||||
return {
|
||||
schema_version: 2,
|
||||
browser: {
|
||||
product: "Chrome/1",
|
||||
protocol_version: "1.3",
|
||||
revision: "example",
|
||||
user_agent: "Chrome",
|
||||
js_version: "1",
|
||||
},
|
||||
target: {
|
||||
target_id: "page-1",
|
||||
type: "page",
|
||||
title: "Example",
|
||||
url: `${origin}/`,
|
||||
origin,
|
||||
attached: false,
|
||||
},
|
||||
capture_window: {
|
||||
started_at: "2026-07-14T00:00:00.000Z",
|
||||
ended_at: "2026-07-14T00:00:01.000Z",
|
||||
observation_ms: 1_000,
|
||||
},
|
||||
completeness: exampleCompleteness(),
|
||||
frames: [],
|
||||
dom: { total_nodes: 0, nodes: [] },
|
||||
accessibility: {
|
||||
total_nodes: 0,
|
||||
text_capture: {
|
||||
status: "not_approved",
|
||||
retained_bytes: 0,
|
||||
excluded_fields: 0,
|
||||
truncated_fields: 0,
|
||||
},
|
||||
nodes: [],
|
||||
},
|
||||
scripts: { total: 0, items: [] },
|
||||
resources: [],
|
||||
network: {
|
||||
requests: [],
|
||||
websocket_events: [],
|
||||
coverage_started_at: "2026-07-14T00:00:00.000Z",
|
||||
prior_activity_available: false,
|
||||
},
|
||||
console: {
|
||||
events: [],
|
||||
coverage_started_at: "2026-07-14T00:00:00.000Z",
|
||||
prior_activity_available: false,
|
||||
},
|
||||
workers: [],
|
||||
metadata: {
|
||||
responses: [],
|
||||
dom_urls: [],
|
||||
agent_hints: [],
|
||||
excluded_dom_urls: 0,
|
||||
headers_allowlisted: true,
|
||||
},
|
||||
storage: {
|
||||
origin,
|
||||
usage_bytes: null,
|
||||
quota_bytes: null,
|
||||
local_storage_keys: [],
|
||||
session_storage_keys: [],
|
||||
indexed_db_names: [],
|
||||
cache_names: [],
|
||||
values_redacted: true,
|
||||
},
|
||||
limitations: [],
|
||||
};
|
||||
}
|
||||
|
||||
function exampleScreenshot() {
|
||||
return {
|
||||
uri: "rea://web-screenshot/sha256/153cf6c9a526a63053a37b10234c2fd85df38887c2dc0a800d90abfa6631d01c",
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
browserScenarioDiffSchema,
|
||||
compareBrowserScenarios,
|
||||
compareBrowserScenariosInputSchema,
|
||||
type BrowserScenarioDiff,
|
||||
type CompareBrowserScenariosInput,
|
||||
} from "./browserScenarioDiff.js";
|
||||
import {
|
||||
compareWebCaptures,
|
||||
captureSnapshotSchema,
|
||||
webCaptureDiffSchema,
|
||||
type CompareWebCapturesInput,
|
||||
type WebCaptureDiff,
|
||||
} from "./webCaptureDiff.js";
|
||||
|
||||
/** Top-level MCP shape for legacy page or step-indexed scenario comparison. */
|
||||
export const browserCaptureComparisonWireSchema = z
|
||||
.strictObject({
|
||||
before: captureSnapshotSchema
|
||||
.optional()
|
||||
.describe("Earlier passive web-page capture; pair with after."),
|
||||
after: captureSnapshotSchema
|
||||
.optional()
|
||||
.describe("Later passive web-page capture; pair with before."),
|
||||
before_scenario: compareBrowserScenariosInputSchema.shape.before_scenario
|
||||
.optional()
|
||||
.describe("Earlier browser scenario capture; pair with after_scenario."),
|
||||
after_scenario: compareBrowserScenariosInputSchema.shape.after_scenario
|
||||
.optional()
|
||||
.describe("Later browser scenario capture; pair with before_scenario."),
|
||||
normalization:
|
||||
compareBrowserScenariosInputSchema.shape.normalization.describe(
|
||||
"Scenario-only exact-literal normalization policy.",
|
||||
),
|
||||
max_changes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(20_000)
|
||||
.default(2_000)
|
||||
.describe("Maximum normalized change records to retain."),
|
||||
})
|
||||
.superRefine((input, context) => {
|
||||
const hasPassive = input.before !== undefined || input.after !== undefined;
|
||||
const hasScenario =
|
||||
input.before_scenario !== undefined || input.after_scenario !== undefined;
|
||||
if (hasPassive === hasScenario)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message:
|
||||
"Provide exactly one complete pair: before/after or before_scenario/after_scenario",
|
||||
});
|
||||
if (hasPassive && (input.before === undefined || input.after === undefined))
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "Passive comparison requires both before and after",
|
||||
});
|
||||
if (
|
||||
hasScenario &&
|
||||
(input.before_scenario === undefined ||
|
||||
input.after_scenario === undefined)
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message:
|
||||
"Browser scenario comparison requires both before_scenario and after_scenario",
|
||||
});
|
||||
if (hasPassive && input.normalization.rules.length > 0)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["normalization"],
|
||||
message:
|
||||
"Literal normalization rules apply only to browser scenario captures",
|
||||
});
|
||||
});
|
||||
|
||||
/** Parsed legacy page snapshots or step-indexed browser scenarios. */
|
||||
export const browserCaptureComparisonInputSchema =
|
||||
browserCaptureComparisonWireSchema.transform((input) => {
|
||||
if (
|
||||
input.before_scenario !== undefined &&
|
||||
input.after_scenario !== undefined
|
||||
)
|
||||
return {
|
||||
before_scenario: input.before_scenario,
|
||||
after_scenario: input.after_scenario,
|
||||
normalization: input.normalization,
|
||||
max_changes: input.max_changes,
|
||||
} satisfies CompareBrowserScenariosInput;
|
||||
if (input.before !== undefined && input.after !== undefined)
|
||||
return {
|
||||
before: input.before,
|
||||
after: input.after,
|
||||
max_changes: input.max_changes,
|
||||
} satisfies CompareWebCapturesInput;
|
||||
throw new TypeError("Capture comparison pair refinement failed");
|
||||
});
|
||||
/** Parsed browser capture comparison input. */
|
||||
export type BrowserCaptureComparisonInput = z.output<
|
||||
typeof browserCaptureComparisonInputSchema
|
||||
>;
|
||||
|
||||
/** Result from passive page or browser scenario comparison. */
|
||||
export const browserCaptureComparisonSchema = z.union([
|
||||
browserScenarioDiffSchema,
|
||||
webCaptureDiffSchema,
|
||||
]);
|
||||
/** Browser capture comparison result. */
|
||||
export type BrowserCaptureComparison = BrowserScenarioDiff | WebCaptureDiff;
|
||||
|
||||
/** Dispatch a parsed capture comparison to its pure domain comparator. */
|
||||
export const compareBrowserCaptures = (
|
||||
input: BrowserCaptureComparisonInput,
|
||||
): BrowserCaptureComparison =>
|
||||
isScenarioComparison(input)
|
||||
? compareBrowserScenarios(input)
|
||||
: compareWebCaptures(input);
|
||||
|
||||
const isScenarioComparison = (
|
||||
input: BrowserCaptureComparisonInput,
|
||||
): input is CompareBrowserScenariosInput => "before_scenario" in input;
|
||||
@@ -303,7 +303,7 @@ export type ListBrowserTargetsInput = z.infer<
|
||||
>;
|
||||
export type InspectWebPageInput = z.infer<typeof inspectWebPageInputSchema>;
|
||||
|
||||
const sanitizedBrowserUrlSchema = z.object({
|
||||
export const sanitizedBrowserUrlSchema = z.object({
|
||||
url: z.string().max(MAX_SANITIZED_BROWSER_URL_CHARS),
|
||||
origin: z.string().max(2_048).nullable(),
|
||||
query_parameter_names: z
|
||||
|
||||
@@ -63,6 +63,14 @@ const browserAxNodeSchema = z.object({
|
||||
name: z.string().nullable(),
|
||||
description: z.string().nullable(),
|
||||
ignored: z.boolean(),
|
||||
states: z
|
||||
.array(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
value: z.union([z.boolean(), z.number(), z.string()]),
|
||||
}),
|
||||
)
|
||||
.default([]),
|
||||
});
|
||||
const browserScriptSourceSchema = z.discriminatedUnion("included", [
|
||||
z.object({ included: z.literal(false), reason: z.string() }),
|
||||
@@ -295,6 +303,28 @@ export const webPageInspectionSchema = z.object({
|
||||
session_storage_keys: z.array(z.string()),
|
||||
indexed_db_names: z.array(z.string()),
|
||||
cache_names: z.array(z.string()),
|
||||
content_fingerprints: z
|
||||
.array(
|
||||
z.object({
|
||||
scope: z.enum([
|
||||
"cookie",
|
||||
"local_storage",
|
||||
"session_storage",
|
||||
"indexed_db_schema",
|
||||
"indexed_db_record",
|
||||
"cache_entry",
|
||||
]),
|
||||
identity_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
value_sha256: z
|
||||
.string()
|
||||
.regex(/^[a-f0-9]{64}$/u)
|
||||
.nullable(),
|
||||
complete: z.boolean(),
|
||||
}),
|
||||
)
|
||||
.default([]),
|
||||
fingerprint_algorithm: z.literal("sha256").default("sha256"),
|
||||
fingerprints_complete: z.boolean().default(false),
|
||||
values_redacted: z.literal(true),
|
||||
}),
|
||||
limitations: z.array(z.string()),
|
||||
|
||||
@@ -0,0 +1,513 @@
|
||||
import {
|
||||
type BrowserScenarioCapture,
|
||||
type BrowserScenarioStep,
|
||||
type BrowserStepArtifacts,
|
||||
} from "./browserScenarioCapture.js";
|
||||
import {
|
||||
browserScenarioDiffSchema,
|
||||
type BrowserScenarioAlignmentFailure,
|
||||
type BrowserScenarioArtifactDiff,
|
||||
type BrowserScenarioArtifactKind,
|
||||
type BrowserScenarioDiff,
|
||||
type BrowserScenarioEvidenceState,
|
||||
type BrowserScenarioNormalizationRule,
|
||||
type CompareBrowserScenariosInput,
|
||||
} from "./browserScenarioDiffValues.js";
|
||||
import {
|
||||
commitBrowserScenarioNormalization,
|
||||
digestCanonicalJson,
|
||||
digestNormalizedScenarioValue,
|
||||
} from "./browserScenarioNormalization.js";
|
||||
|
||||
export {
|
||||
browserScenarioDiffSchema,
|
||||
compareBrowserScenariosInputSchema,
|
||||
type BrowserScenarioDiff,
|
||||
type CompareBrowserScenariosInput,
|
||||
} from "./browserScenarioDiffValues.js";
|
||||
|
||||
type CaptureState<T> =
|
||||
| { readonly state: "captured"; readonly value: T }
|
||||
| { readonly state: "not_requested" }
|
||||
| { readonly state: "missing"; readonly reason: string }
|
||||
| {
|
||||
readonly state: "truncated";
|
||||
readonly observed: number;
|
||||
readonly retained: number;
|
||||
readonly reason: string;
|
||||
};
|
||||
|
||||
interface ComparableArtifact {
|
||||
readonly artifact: BrowserScenarioArtifactKind;
|
||||
readonly status: "changed" | "unchanged" | "unknown" | "not_compared";
|
||||
readonly diff: BrowserScenarioArtifactDiff | null;
|
||||
}
|
||||
|
||||
interface ScenarioAlignment {
|
||||
readonly before: ReadonlyMap<string, BrowserScenarioStep>;
|
||||
readonly after: ReadonlyMap<string, BrowserScenarioStep>;
|
||||
readonly orderedStepIds: readonly string[];
|
||||
readonly beforeOnly: readonly string[];
|
||||
readonly afterOnly: readonly string[];
|
||||
readonly failures: readonly BrowserScenarioAlignmentFailure[];
|
||||
}
|
||||
|
||||
interface AlignedStepComparison {
|
||||
readonly steps: BrowserScenarioDiff["steps"];
|
||||
readonly failures: readonly BrowserScenarioAlignmentFailure[];
|
||||
readonly totalArtifactDiffs: number;
|
||||
}
|
||||
|
||||
/** Compare scenario steps by stable step ID and apply only committed literal rules. */
|
||||
export const compareBrowserScenarios = (
|
||||
input: CompareBrowserScenariosInput,
|
||||
): BrowserScenarioDiff => {
|
||||
const normalization = commitBrowserScenarioNormalization(input.normalization);
|
||||
const alignment = alignScenarioSteps(
|
||||
input.before_scenario,
|
||||
input.after_scenario,
|
||||
);
|
||||
const compared = compareAlignedSteps({
|
||||
beforeCapture: input.before_scenario,
|
||||
afterCapture: input.after_scenario,
|
||||
alignment,
|
||||
rules: normalization.rules,
|
||||
maxChanges: input.max_changes,
|
||||
});
|
||||
const failures = [...alignment.failures, ...compared.failures];
|
||||
const alignmentStatus =
|
||||
failures.length === 0
|
||||
? "aligned"
|
||||
: compared.steps.length === 0
|
||||
? "failed"
|
||||
: "partial";
|
||||
const stepStatuses = compared.steps.map(({ status }) => status);
|
||||
const equalityEligible =
|
||||
input.before_scenario.completeness.equality_eligible &&
|
||||
input.after_scenario.completeness.equality_eligible &&
|
||||
alignmentStatus === "aligned";
|
||||
const overallStatus = stepStatuses.includes("changed")
|
||||
? "changed"
|
||||
: stepStatuses.includes("unknown") || !equalityEligible
|
||||
? "unknown"
|
||||
: "unchanged";
|
||||
|
||||
return browserScenarioDiffSchema.parse({
|
||||
schema_version: 1,
|
||||
comparison_kind: "browser_scenario",
|
||||
overall_status: overallStatus,
|
||||
normalization,
|
||||
alignment: {
|
||||
status: alignmentStatus,
|
||||
aligned_steps: compared.steps.length,
|
||||
before_only: alignment.beforeOnly,
|
||||
after_only: alignment.afterOnly,
|
||||
failures,
|
||||
},
|
||||
steps: compared.steps,
|
||||
artifact_diffs: {
|
||||
total: compared.totalArtifactDiffs,
|
||||
retained:
|
||||
compared.totalArtifactDiffs -
|
||||
Math.max(0, compared.totalArtifactDiffs - input.max_changes),
|
||||
omitted: Math.max(0, compared.totalArtifactDiffs - input.max_changes),
|
||||
},
|
||||
limitations: [
|
||||
"Steps align only by exact, unique step_id; missing, duplicate, or action-mismatched steps are reported and prevent an unchanged claim.",
|
||||
"Only declared literal normalization rules are applied, in canonical rule_id order, to already-redacted durable capture fields.",
|
||||
"Elapsed time and event sequence/index values are excluded as volatile; screenshot bytes are compared by content digest.",
|
||||
"A changed status proves an observed normalized difference. Missing or truncated evidence, incompatible capture context, or alignment failure prevents an unchanged claim.",
|
||||
...(compared.totalArtifactDiffs > input.max_changes
|
||||
? [
|
||||
`${String(compared.totalArtifactDiffs - input.max_changes)} artifact difference record(s) were omitted by max_changes.`,
|
||||
]
|
||||
: []),
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
const alignScenarioSteps = (
|
||||
beforeCapture: BrowserScenarioCapture,
|
||||
afterCapture: BrowserScenarioCapture,
|
||||
): ScenarioAlignment => {
|
||||
const beforeDuplicates = duplicateStepIds(beforeCapture.steps);
|
||||
const afterDuplicates = duplicateStepIds(afterCapture.steps);
|
||||
const before = uniqueSteps(beforeCapture.steps, beforeDuplicates);
|
||||
const after = uniqueSteps(afterCapture.steps, afterDuplicates);
|
||||
const beforeOnly = [...before.keys()]
|
||||
.filter((stepId) => !after.has(stepId))
|
||||
.sort();
|
||||
const afterOnly = [...after.keys()]
|
||||
.filter((stepId) => !before.has(stepId))
|
||||
.sort();
|
||||
const failures: BrowserScenarioAlignmentFailure[] = [
|
||||
...duplicateFailures("before", beforeDuplicates),
|
||||
...duplicateFailures("after", afterDuplicates),
|
||||
...missingFailures("before", afterOnly),
|
||||
...missingFailures("after", beforeOnly),
|
||||
];
|
||||
if (!captureContextsMatch(beforeCapture, afterCapture))
|
||||
failures.push({
|
||||
code: "capture_context_mismatch",
|
||||
step_id: null,
|
||||
reason:
|
||||
"Browser product/version or scenario origin scope differs between captures.",
|
||||
});
|
||||
return {
|
||||
before,
|
||||
after,
|
||||
beforeOnly,
|
||||
afterOnly,
|
||||
failures,
|
||||
orderedStepIds: beforeCapture.steps
|
||||
.map(({ step_id }) => step_id)
|
||||
.filter(
|
||||
(stepId, index, values) =>
|
||||
values.indexOf(stepId) === index &&
|
||||
before.has(stepId) &&
|
||||
after.has(stepId),
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
interface CompareAlignedStepsInput {
|
||||
readonly beforeCapture: BrowserScenarioCapture;
|
||||
readonly afterCapture: BrowserScenarioCapture;
|
||||
readonly alignment: ScenarioAlignment;
|
||||
readonly rules: readonly BrowserScenarioNormalizationRule[];
|
||||
readonly maxChanges: number;
|
||||
}
|
||||
|
||||
const compareAlignedSteps = (
|
||||
input: CompareAlignedStepsInput,
|
||||
): AlignedStepComparison => {
|
||||
const remaining = { value: input.maxChanges };
|
||||
let totalArtifactDiffs = 0;
|
||||
const steps: BrowserScenarioDiff["steps"] = [];
|
||||
const failures: BrowserScenarioAlignmentFailure[] = [];
|
||||
for (const stepId of input.alignment.orderedStepIds) {
|
||||
const beforeStep = input.alignment.before.get(stepId);
|
||||
const afterStep = input.alignment.after.get(stepId);
|
||||
if (beforeStep === undefined || afterStep === undefined) continue;
|
||||
if (beforeStep.action !== afterStep.action)
|
||||
failures.push({
|
||||
code: "action_mismatch",
|
||||
step_id: stepId,
|
||||
reason: `Aligned step action changed from ${beforeStep.action} to ${afterStep.action}.`,
|
||||
});
|
||||
const artifacts = compareStepArtifacts({
|
||||
beforeCapture: input.beforeCapture,
|
||||
beforeStep,
|
||||
afterCapture: input.afterCapture,
|
||||
afterStep,
|
||||
rules: input.rules,
|
||||
});
|
||||
const reportable = artifacts.flatMap(({ diff }) =>
|
||||
diff === null ? [] : [diff],
|
||||
);
|
||||
totalArtifactDiffs += reportable.length;
|
||||
const retained = reportable.slice(0, remaining.value);
|
||||
remaining.value -= retained.length;
|
||||
const statuses = artifacts.map(({ status }) => status);
|
||||
steps.push({
|
||||
step_id: stepId,
|
||||
before_step_index: beforeStep.step_index,
|
||||
after_step_index: afterStep.step_index,
|
||||
before_action: beforeStep.action,
|
||||
after_action: afterStep.action,
|
||||
status: statuses.includes("changed")
|
||||
? "changed"
|
||||
: statuses.includes("unknown")
|
||||
? "unknown"
|
||||
: "unchanged",
|
||||
artifact_diffs: retained,
|
||||
omitted_artifact_diffs: reportable.length - retained.length,
|
||||
});
|
||||
}
|
||||
return { steps, failures, totalArtifactDiffs };
|
||||
};
|
||||
|
||||
const duplicateStepIds = (
|
||||
steps: readonly BrowserScenarioStep[],
|
||||
): ReadonlySet<string> => {
|
||||
const seen = new Set<string>();
|
||||
const duplicates = new Set<string>();
|
||||
for (const { step_id: stepId } of steps) {
|
||||
if (seen.has(stepId)) duplicates.add(stepId);
|
||||
seen.add(stepId);
|
||||
}
|
||||
return duplicates;
|
||||
};
|
||||
|
||||
const uniqueSteps = (
|
||||
steps: readonly BrowserScenarioStep[],
|
||||
duplicates: ReadonlySet<string>,
|
||||
): ReadonlyMap<string, BrowserScenarioStep> =>
|
||||
new Map(
|
||||
steps.flatMap((step) =>
|
||||
duplicates.has(step.step_id) ? [] : [[step.step_id, step] as const],
|
||||
),
|
||||
);
|
||||
|
||||
const duplicateFailures = (
|
||||
side: "before" | "after",
|
||||
duplicates: ReadonlySet<string>,
|
||||
): BrowserScenarioAlignmentFailure[] =>
|
||||
[...duplicates].sort().map((stepId) => ({
|
||||
code:
|
||||
side === "before"
|
||||
? "duplicate_before_step_id"
|
||||
: "duplicate_after_step_id",
|
||||
step_id: stepId,
|
||||
reason: `${side} capture contains duplicate step_id ${stepId}.`,
|
||||
}));
|
||||
|
||||
const missingFailures = (
|
||||
side: "before" | "after",
|
||||
stepIds: readonly string[],
|
||||
): BrowserScenarioAlignmentFailure[] =>
|
||||
stepIds.map((stepId) => ({
|
||||
code: side === "before" ? "missing_before_step" : "missing_after_step",
|
||||
step_id: stepId,
|
||||
reason: `Step ${stepId} is missing from the ${side} capture.`,
|
||||
}));
|
||||
|
||||
const captureContextsMatch = (
|
||||
before: BrowserScenarioCapture,
|
||||
after: BrowserScenarioCapture,
|
||||
): boolean =>
|
||||
before.browser.product === after.browser.product &&
|
||||
before.browser.version === after.browser.version &&
|
||||
before.scenario.start_origin === after.scenario.start_origin &&
|
||||
digestCanonicalJson([...before.scenario.allowed_origins].sort()) ===
|
||||
digestCanonicalJson([...after.scenario.allowed_origins].sort());
|
||||
|
||||
interface CompareStepArtifactsInput {
|
||||
readonly beforeCapture: BrowserScenarioCapture;
|
||||
readonly beforeStep: BrowserScenarioStep;
|
||||
readonly afterCapture: BrowserScenarioCapture;
|
||||
readonly afterStep: BrowserScenarioStep;
|
||||
readonly rules: readonly BrowserScenarioNormalizationRule[];
|
||||
}
|
||||
|
||||
const compareStepArtifacts = (
|
||||
input: CompareStepArtifactsInput,
|
||||
): ComparableArtifact[] => {
|
||||
const common = {
|
||||
beforeStep: input.beforeStep,
|
||||
afterStep: input.afterStep,
|
||||
rules: input.rules,
|
||||
};
|
||||
return [
|
||||
compareCapturedValues({
|
||||
...common,
|
||||
artifact: "action_state",
|
||||
before: captured(actionState(input.beforeStep)),
|
||||
after: captured(actionState(input.afterStep)),
|
||||
}),
|
||||
compareCapturedValues({
|
||||
...common,
|
||||
artifact: "screenshot",
|
||||
before: input.beforeStep.artifacts.screenshot,
|
||||
after: input.afterStep.artifacts.screenshot,
|
||||
project: screenshotProjection,
|
||||
}),
|
||||
compareCapturedValues({
|
||||
...common,
|
||||
artifact: "dom",
|
||||
before: input.beforeStep.artifacts.dom,
|
||||
after: input.afterStep.artifacts.dom,
|
||||
project: ({ text }) => text,
|
||||
}),
|
||||
compareCapturedValues({
|
||||
...common,
|
||||
artifact: "accessibility",
|
||||
before: input.beforeStep.artifacts.accessibility,
|
||||
after: input.afterStep.artifacts.accessibility,
|
||||
project: ({ text }) => text,
|
||||
}),
|
||||
compareCapturedValues({
|
||||
...common,
|
||||
artifact: "url",
|
||||
before: input.beforeStep.artifacts.url,
|
||||
after: input.afterStep.artifacts.url,
|
||||
}),
|
||||
compareCapturedValues({
|
||||
...common,
|
||||
artifact: "history",
|
||||
before: input.beforeStep.artifacts.history,
|
||||
after: input.afterStep.artifacts.history,
|
||||
}),
|
||||
compareCapturedValues({
|
||||
...common,
|
||||
artifact: "storage",
|
||||
before: input.beforeStep.artifacts.storage,
|
||||
after: input.afterStep.artifacts.storage,
|
||||
}),
|
||||
compareCapturedValues({
|
||||
...common,
|
||||
artifact: "events",
|
||||
before: captured(
|
||||
eventsFor(input.beforeCapture, input.beforeStep.step_index),
|
||||
),
|
||||
after: captured(
|
||||
eventsFor(input.afterCapture, input.afterStep.step_index),
|
||||
),
|
||||
beforeState: eventEvidenceState(input.beforeCapture, input.beforeStep),
|
||||
afterState: eventEvidenceState(input.afterCapture, input.afterStep),
|
||||
}),
|
||||
];
|
||||
};
|
||||
|
||||
interface CompareCapturedValuesInput<Value> {
|
||||
readonly artifact: BrowserScenarioArtifactKind;
|
||||
readonly before: CaptureState<Value>;
|
||||
readonly after: CaptureState<Value>;
|
||||
readonly beforeStep: BrowserScenarioStep;
|
||||
readonly afterStep: BrowserScenarioStep;
|
||||
readonly rules: readonly BrowserScenarioNormalizationRule[];
|
||||
readonly project?: (value: Value) => unknown;
|
||||
readonly beforeState?: BrowserScenarioEvidenceState;
|
||||
readonly afterState?: BrowserScenarioEvidenceState;
|
||||
}
|
||||
|
||||
const compareCapturedValues = <Value>(
|
||||
input: CompareCapturedValuesInput<Value>,
|
||||
): ComparableArtifact => {
|
||||
const {
|
||||
artifact,
|
||||
before,
|
||||
after,
|
||||
beforeStep,
|
||||
afterStep,
|
||||
rules,
|
||||
project = (value) => value,
|
||||
} = input;
|
||||
const beforeState =
|
||||
input.beforeState ?? artifactEvidenceState(artifact, before, beforeStep);
|
||||
const afterState =
|
||||
input.afterState ?? artifactEvidenceState(artifact, after, afterStep);
|
||||
if (beforeState === "not_requested" && afterState === "not_requested")
|
||||
return { artifact, status: "not_compared", diff: null };
|
||||
const beforeSha256 =
|
||||
beforeState === "captured" && before.state === "captured"
|
||||
? digestNormalizedScenarioValue(project(before.value), artifact, rules)
|
||||
: null;
|
||||
const afterSha256 =
|
||||
afterState === "captured" && after.state === "captured"
|
||||
? digestNormalizedScenarioValue(project(after.value), artifact, rules)
|
||||
: null;
|
||||
if (
|
||||
beforeState !== "captured" ||
|
||||
afterState !== "captured" ||
|
||||
before.state !== "captured" ||
|
||||
after.state !== "captured"
|
||||
)
|
||||
return {
|
||||
artifact,
|
||||
status: "unknown",
|
||||
diff: {
|
||||
artifact,
|
||||
status: "unknown",
|
||||
before_state: beforeState,
|
||||
after_state: afterState,
|
||||
before_sha256: beforeSha256,
|
||||
after_sha256: afterSha256,
|
||||
reason: `Artifact coverage is not comparable (${beforeState} before, ${afterState} after).`,
|
||||
},
|
||||
};
|
||||
if (beforeSha256 === null || afterSha256 === null)
|
||||
throw new TypeError("Captured artifact digest refinement failed");
|
||||
if (beforeSha256 === afterSha256)
|
||||
return { artifact, status: "unchanged", diff: null };
|
||||
return {
|
||||
artifact,
|
||||
status: "changed",
|
||||
diff: {
|
||||
artifact,
|
||||
status: "changed",
|
||||
before_state: beforeState,
|
||||
after_state: afterState,
|
||||
before_sha256: beforeSha256,
|
||||
after_sha256: afterSha256,
|
||||
reason: null,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const artifactEvidenceState = <Value>(
|
||||
artifact: BrowserScenarioArtifactKind,
|
||||
state: CaptureState<Value>,
|
||||
step: BrowserScenarioStep,
|
||||
): BrowserScenarioEvidenceState => {
|
||||
if (state.state !== "captured") return state.state;
|
||||
const section = artifact === "action_state" ? "action" : artifact;
|
||||
if (step.completeness.truncated_sections.includes(section))
|
||||
return "truncated";
|
||||
if (step.completeness.missing_sections.includes(section)) return "missing";
|
||||
return "captured";
|
||||
};
|
||||
|
||||
const eventEvidenceState = (
|
||||
capture: BrowserScenarioCapture,
|
||||
step: BrowserScenarioStep,
|
||||
): BrowserScenarioEvidenceState => {
|
||||
const sections = [
|
||||
"events",
|
||||
"frames",
|
||||
"workers",
|
||||
"popups",
|
||||
"websockets",
|
||||
] as const;
|
||||
if (
|
||||
capture.events.dropped > 0 ||
|
||||
sections.some(
|
||||
(section) =>
|
||||
capture.completeness.truncated_sections.includes(section) ||
|
||||
step.completeness.truncated_sections.includes(section),
|
||||
)
|
||||
)
|
||||
return "truncated";
|
||||
if (
|
||||
sections.some(
|
||||
(section) =>
|
||||
capture.completeness.missing_sections.includes(section) ||
|
||||
step.completeness.missing_sections.includes(section),
|
||||
)
|
||||
)
|
||||
return "missing";
|
||||
return "captured";
|
||||
};
|
||||
|
||||
const actionState = (step: BrowserScenarioStep) => ({
|
||||
action: step.action,
|
||||
status: step.status,
|
||||
before_url: step.before_url,
|
||||
after_url: step.after_url,
|
||||
error: step.error,
|
||||
});
|
||||
|
||||
const eventsFor = (
|
||||
capture: BrowserScenarioCapture,
|
||||
stepIndex: number,
|
||||
): readonly unknown[] =>
|
||||
capture.events.items.flatMap(
|
||||
({ sequence: _sequence, step_index: eventStepIndex, ...event }) =>
|
||||
eventStepIndex === stepIndex ? [event] : [],
|
||||
);
|
||||
|
||||
const captured = <Value>(value: Value): CaptureState<Value> => ({
|
||||
state: "captured",
|
||||
value,
|
||||
});
|
||||
|
||||
const screenshotProjection = (
|
||||
screenshot: Extract<
|
||||
BrowserStepArtifacts["screenshot"],
|
||||
{ state: "captured" }
|
||||
>["value"],
|
||||
) => ({
|
||||
sha256: screenshot.sha256,
|
||||
bytes: screenshot.bytes,
|
||||
media_type: screenshot.media_type,
|
||||
});
|
||||
@@ -0,0 +1,201 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { browserScenarioCaptureSchema } from "./browserScenarioCapture.js";
|
||||
|
||||
/** Scenario artifact families compared after step alignment. */
|
||||
export const browserScenarioArtifactKindSchema = z.enum([
|
||||
"action_state",
|
||||
"screenshot",
|
||||
"dom",
|
||||
"accessibility",
|
||||
"url",
|
||||
"history",
|
||||
"storage",
|
||||
"events",
|
||||
]);
|
||||
/** Scenario artifact family. */
|
||||
export type BrowserScenarioArtifactKind = z.infer<
|
||||
typeof browserScenarioArtifactKindSchema
|
||||
>;
|
||||
|
||||
const normalizableArtifactKindSchema = z.enum([
|
||||
"action_state",
|
||||
"dom",
|
||||
"accessibility",
|
||||
"url",
|
||||
"history",
|
||||
"storage",
|
||||
"events",
|
||||
]);
|
||||
|
||||
const normalizationRuleSchema = z.strictObject({
|
||||
rule_id: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(64)
|
||||
.describe("Stable rule identity; rules execute in rule_id order."),
|
||||
artifacts: z
|
||||
.array(normalizableArtifactKindSchema)
|
||||
.min(1)
|
||||
.max(7)
|
||||
.describe("Artifact families whose durable string fields use this rule."),
|
||||
match: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(4_096)
|
||||
.describe(
|
||||
"Exact public literal to replace; regular expressions are not used.",
|
||||
),
|
||||
replacement: z
|
||||
.string()
|
||||
.max(4_096)
|
||||
.describe("Recorded replacement text used in normalized comparison."),
|
||||
});
|
||||
|
||||
const normalizationInputSchema = z
|
||||
.strictObject({
|
||||
rules: z.array(normalizationRuleSchema).max(128).default([]),
|
||||
})
|
||||
.superRefine((normalization, context) => {
|
||||
const ruleIds = new Set<string>();
|
||||
for (const [index, rule] of normalization.rules.entries()) {
|
||||
if (ruleIds.has(rule.rule_id))
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["rules", index, "rule_id"],
|
||||
message: "Normalization rule IDs must be unique",
|
||||
});
|
||||
ruleIds.add(rule.rule_id);
|
||||
if (new Set(rule.artifacts).size !== rule.artifacts.length)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["rules", index, "artifacts"],
|
||||
message: "Normalization rule artifact kinds must be unique",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/** Input for step-aligned comparison of two browser scenario captures. */
|
||||
export const compareBrowserScenariosInputSchema = z.strictObject({
|
||||
before_scenario: browserScenarioCaptureSchema.describe(
|
||||
"Earlier complete capture_browser_scenario result.",
|
||||
),
|
||||
after_scenario: browserScenarioCaptureSchema.describe(
|
||||
"Later complete capture_browser_scenario result.",
|
||||
),
|
||||
normalization: normalizationInputSchema
|
||||
.default({ rules: [] })
|
||||
.describe(
|
||||
"Bounded exact-literal rules committed in the comparison result.",
|
||||
),
|
||||
max_changes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(20_000)
|
||||
.default(2_000)
|
||||
.describe("Maximum changed or unknown artifact records to retain."),
|
||||
});
|
||||
/** Parsed browser scenario comparison input. */
|
||||
export type CompareBrowserScenariosInput = z.infer<
|
||||
typeof compareBrowserScenariosInputSchema
|
||||
>;
|
||||
|
||||
const evidenceStateSchema = z.enum([
|
||||
"captured",
|
||||
"not_requested",
|
||||
"missing",
|
||||
"truncated",
|
||||
]);
|
||||
|
||||
const artifactDiffSchema = z.strictObject({
|
||||
artifact: browserScenarioArtifactKindSchema,
|
||||
status: z.enum(["changed", "unknown"]),
|
||||
before_state: evidenceStateSchema,
|
||||
after_state: evidenceStateSchema,
|
||||
before_sha256: z
|
||||
.string()
|
||||
.regex(/^[a-f0-9]{64}$/u)
|
||||
.nullable(),
|
||||
after_sha256: z
|
||||
.string()
|
||||
.regex(/^[a-f0-9]{64}$/u)
|
||||
.nullable(),
|
||||
reason: z.string().min(1).max(2_048).nullable(),
|
||||
});
|
||||
const alignmentFailureSchema = z.strictObject({
|
||||
code: z.enum([
|
||||
"duplicate_before_step_id",
|
||||
"duplicate_after_step_id",
|
||||
"missing_before_step",
|
||||
"missing_after_step",
|
||||
"action_mismatch",
|
||||
"capture_context_mismatch",
|
||||
]),
|
||||
step_id: z.string().min(1).max(64).nullable(),
|
||||
reason: z.string().min(1).max(2_048),
|
||||
});
|
||||
const builtInNormalizationSchema = z.enum([
|
||||
"ignore_step_elapsed_ms",
|
||||
"ignore_event_sequence",
|
||||
"ignore_event_step_index",
|
||||
"compare_screenshot_content_digest",
|
||||
"compare_normalized_text_content",
|
||||
]);
|
||||
|
||||
/** Step alignment, recorded normalization, and bounded artifact differences. */
|
||||
export const browserScenarioDiffSchema = z.strictObject({
|
||||
schema_version: z.literal(1),
|
||||
comparison_kind: z.literal("browser_scenario"),
|
||||
overall_status: z.enum(["changed", "unchanged", "unknown"]),
|
||||
normalization: z.strictObject({
|
||||
built_in_rules: z.array(builtInNormalizationSchema).length(5),
|
||||
rules: z.array(normalizationRuleSchema).max(128),
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
}),
|
||||
alignment: z.strictObject({
|
||||
status: z.enum(["aligned", "partial", "failed"]),
|
||||
aligned_steps: z.number().int().min(0).max(129),
|
||||
before_only: z.array(z.string().min(1).max(64)).max(129),
|
||||
after_only: z.array(z.string().min(1).max(64)).max(129),
|
||||
failures: z.array(alignmentFailureSchema).max(520),
|
||||
}),
|
||||
steps: z
|
||||
.array(
|
||||
z.strictObject({
|
||||
step_id: z.string().min(1).max(64),
|
||||
before_step_index: z.number().int().min(0).max(128),
|
||||
after_step_index: z.number().int().min(0).max(128),
|
||||
before_action: z.string().min(1).max(64),
|
||||
after_action: z.string().min(1).max(64),
|
||||
status: z.enum(["changed", "unchanged", "unknown"]),
|
||||
artifact_diffs: z.array(artifactDiffSchema).max(8),
|
||||
omitted_artifact_diffs: z.number().int().min(0).max(8),
|
||||
}),
|
||||
)
|
||||
.max(129),
|
||||
artifact_diffs: z.strictObject({
|
||||
total: z.number().int().min(0).max(1_032),
|
||||
retained: z.number().int().min(0).max(1_032),
|
||||
omitted: z.number().int().min(0).max(1_032),
|
||||
}),
|
||||
limitations: z.array(z.string().min(1).max(2_048)).max(64),
|
||||
});
|
||||
/** Browser scenario comparison result. */
|
||||
export type BrowserScenarioDiff = z.infer<typeof browserScenarioDiffSchema>;
|
||||
/** Reportable changed or unknown scenario artifact. */
|
||||
export type BrowserScenarioArtifactDiff =
|
||||
BrowserScenarioDiff["steps"][number]["artifact_diffs"][number];
|
||||
/** One explicit reason scenario step alignment was not exact. */
|
||||
export type BrowserScenarioAlignmentFailure =
|
||||
BrowserScenarioDiff["alignment"]["failures"][number];
|
||||
/** Comparable capture state. */
|
||||
export type BrowserScenarioEvidenceState =
|
||||
BrowserScenarioArtifactDiff["before_state"];
|
||||
/** Scenario normalization policy after boundary parsing. */
|
||||
export type BrowserScenarioNormalization =
|
||||
CompareBrowserScenariosInput["normalization"];
|
||||
/** One exact literal scenario normalization rule. */
|
||||
export type BrowserScenarioNormalizationRule =
|
||||
BrowserScenarioNormalization["rules"][number];
|
||||
@@ -0,0 +1,71 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
|
||||
import type {
|
||||
BrowserScenarioArtifactKind,
|
||||
BrowserScenarioDiff,
|
||||
BrowserScenarioNormalization,
|
||||
BrowserScenarioNormalizationRule,
|
||||
} from "./browserScenarioDiffValues.js";
|
||||
|
||||
const BUILT_IN_RULES = [
|
||||
"ignore_step_elapsed_ms",
|
||||
"ignore_event_sequence",
|
||||
"ignore_event_step_index",
|
||||
"compare_screenshot_content_digest",
|
||||
"compare_normalized_text_content",
|
||||
] as const;
|
||||
|
||||
/** Canonically order and commit a parsed browser scenario normalization policy. */
|
||||
export const commitBrowserScenarioNormalization = (
|
||||
input: BrowserScenarioNormalization,
|
||||
): BrowserScenarioDiff["normalization"] => {
|
||||
const rules = [...input.rules]
|
||||
.map((rule) => ({
|
||||
...rule,
|
||||
artifacts: [...rule.artifacts].sort(),
|
||||
}))
|
||||
.sort((left, right) => left.rule_id.localeCompare(right.rule_id));
|
||||
const commitment = { built_in_rules: [...BUILT_IN_RULES], rules };
|
||||
return { ...commitment, sha256: digestCanonicalJson(commitment) };
|
||||
};
|
||||
|
||||
/** Digest one artifact after applying committed exact-literal rules. */
|
||||
export const digestNormalizedScenarioValue = (
|
||||
value: unknown,
|
||||
artifact: BrowserScenarioArtifactKind,
|
||||
rules: readonly BrowserScenarioNormalizationRule[],
|
||||
): string => digestCanonicalJson(normalize(value, artifact, rules));
|
||||
|
||||
/** Compute a canonical SHA-256 commitment for JSON-compatible domain data. */
|
||||
export const digestCanonicalJson = (value: unknown): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined) throw new TypeError("Expected canonical JSON");
|
||||
return createHash("sha256").update(encoded).digest("hex");
|
||||
};
|
||||
|
||||
const normalize = (
|
||||
value: unknown,
|
||||
artifact: BrowserScenarioArtifactKind,
|
||||
rules: readonly BrowserScenarioNormalizationRule[],
|
||||
): unknown => {
|
||||
if (artifact === "screenshot") return value;
|
||||
if (typeof value === "string")
|
||||
return rules
|
||||
.filter(({ artifacts }) => artifacts.includes(artifact))
|
||||
.reduce(
|
||||
(normalized, rule) =>
|
||||
normalized.split(rule.match).join(rule.replacement),
|
||||
value,
|
||||
);
|
||||
if (Array.isArray(value))
|
||||
return value.map((item) => normalize(item, artifact, rules));
|
||||
if (typeof value !== "object" || value === null) return value;
|
||||
return Object.fromEntries(
|
||||
Object.entries(value).map(([key, item]) => [
|
||||
key,
|
||||
normalize(item, artifact, rules),
|
||||
]),
|
||||
);
|
||||
};
|
||||
+259
-48
@@ -12,7 +12,8 @@ import {
|
||||
type WebMcpDiscovery,
|
||||
} from "./webMcpDiscovery.js";
|
||||
|
||||
const captureSnapshotSchema = z.object({
|
||||
/** One normalized passive page snapshot accepted by capture comparison. */
|
||||
export const captureSnapshotSchema = z.object({
|
||||
inspection: webPageInspectionSchema,
|
||||
webmcp: webMcpDiscoverySchema.nullable().default(null),
|
||||
});
|
||||
@@ -52,6 +53,8 @@ export const webCaptureDiffSchema = z.object({
|
||||
network: dimensionSchema,
|
||||
metadata: dimensionSchema,
|
||||
webmcp: dimensionSchema,
|
||||
accessibility: dimensionSchema,
|
||||
storage: dimensionSchema,
|
||||
}),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
@@ -64,16 +67,67 @@ type Change = Dimension["changes"][number];
|
||||
export const compareWebCaptures = (
|
||||
input: CompareWebCapturesInput,
|
||||
): WebCaptureDiff => {
|
||||
let remaining = input.max_changes;
|
||||
const dimension = (
|
||||
const remaining = { value: input.max_changes };
|
||||
const before = input.before.inspection;
|
||||
const after = input.after.inspection;
|
||||
const dimensions = compareWebCaptureDimensions(input, remaining);
|
||||
const statuses = Object.values(dimensions).map(({ status }) => status);
|
||||
return webCaptureDiffSchema.parse({
|
||||
schema_version: 1,
|
||||
overall_status: statuses.includes("changed")
|
||||
? "changed"
|
||||
: statuses.includes("unknown")
|
||||
? "unknown"
|
||||
: "unchanged",
|
||||
before_target: {
|
||||
target_id: before.target.target_id,
|
||||
url: before.target.url,
|
||||
},
|
||||
after_target: {
|
||||
target_id: after.target.target_id,
|
||||
url: after.target.url,
|
||||
},
|
||||
dimensions,
|
||||
limitations: [
|
||||
"A changed status proves an observed difference; an unknown status means absence could not be established from capture completeness.",
|
||||
"Network comparison covers only activity observed after each CDP attachment.",
|
||||
"Accessibility roles, ignored state, text, and hierarchy are compared only when the accessibility tree was fully captured and text capture was approved and not truncated.",
|
||||
"Storage key inventories are compared only when approved and complete; usage and quota are compared only when reported. Redacted content is compared through complete SHA-256 fingerprints.",
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
const compareIdentities = (
|
||||
before: ReadonlyMap<string, string>,
|
||||
after: ReadonlyMap<string, string>,
|
||||
): Change[] => {
|
||||
const changes: Change[] = [];
|
||||
for (const [identity, fingerprint] of before) {
|
||||
const next = after.get(identity);
|
||||
if (next === undefined) changes.push({ identity, change: "removed" });
|
||||
else if (next !== fingerprint)
|
||||
changes.push({ identity, change: "modified" });
|
||||
}
|
||||
for (const identity of after.keys())
|
||||
if (!before.has(identity)) changes.push({ identity, change: "added" });
|
||||
return changes.sort(
|
||||
(left, right) =>
|
||||
left.identity.localeCompare(right.identity) ||
|
||||
left.change.localeCompare(right.change),
|
||||
);
|
||||
};
|
||||
|
||||
const compareDimension =
|
||||
(remaining: { value: number }) =>
|
||||
(
|
||||
before: ReadonlyMap<string, string>,
|
||||
after: ReadonlyMap<string, string>,
|
||||
complete: boolean,
|
||||
reason: string,
|
||||
): Dimension => {
|
||||
const all = compareIdentities(before, after);
|
||||
const retained = all.slice(0, remaining);
|
||||
remaining -= retained.length;
|
||||
const retained = all.slice(0, remaining.value);
|
||||
remaining.value -= retained.length;
|
||||
return {
|
||||
status: all.length > 0 ? "changed" : complete ? "unchanged" : "unknown",
|
||||
total_changes: all.length,
|
||||
@@ -82,9 +136,84 @@ export const compareWebCaptures = (
|
||||
reason: all.length === 0 && !complete ? reason : null,
|
||||
};
|
||||
};
|
||||
|
||||
const accessibilityDimension = (
|
||||
before: WebPageInspection,
|
||||
after: WebPageInspection,
|
||||
remaining: { value: number },
|
||||
): Dimension => {
|
||||
const beforeAccess = accessibilityComparable(before);
|
||||
const afterAccess = accessibilityComparable(after);
|
||||
const textComparable = beforeAccess.text && afterAccess.text;
|
||||
const nodesComparable = beforeAccess.nodes && afterAccess.nodes;
|
||||
return compareDimension(remaining)(
|
||||
singleton(
|
||||
"accessibility_tree",
|
||||
digest(
|
||||
accessibilityProjection(
|
||||
before.accessibility,
|
||||
textComparable,
|
||||
nodesComparable,
|
||||
),
|
||||
),
|
||||
),
|
||||
singleton(
|
||||
"accessibility_tree",
|
||||
digest(
|
||||
accessibilityProjection(
|
||||
after.accessibility,
|
||||
textComparable,
|
||||
nodesComparable,
|
||||
),
|
||||
),
|
||||
),
|
||||
beforeAccess.complete && afterAccess.complete,
|
||||
"Accessibility tree or text capture was incomplete in at least one observation.",
|
||||
);
|
||||
};
|
||||
|
||||
const storageDimension = (
|
||||
before: WebPageInspection,
|
||||
after: WebPageInspection,
|
||||
remaining: { value: number },
|
||||
): Dimension => {
|
||||
const keysComplete =
|
||||
storageKeysComparable(before) && storageKeysComparable(after);
|
||||
const usageComplete =
|
||||
before.storage.usage_bytes !== null &&
|
||||
after.storage.usage_bytes !== null &&
|
||||
before.storage.quota_bytes !== null &&
|
||||
after.storage.quota_bytes !== null;
|
||||
const comparableFingerprints = storageFingerprintIdentities(
|
||||
before.storage,
|
||||
after.storage,
|
||||
);
|
||||
return compareDimension(remaining)(
|
||||
storageMap(
|
||||
before.storage,
|
||||
keysComplete,
|
||||
usageComplete,
|
||||
comparableFingerprints,
|
||||
),
|
||||
storageMap(
|
||||
after.storage,
|
||||
keysComplete,
|
||||
usageComplete,
|
||||
comparableFingerprints,
|
||||
),
|
||||
storageComparable(before, after, keysComplete, usageComplete),
|
||||
"Storage fingerprints, inventories, usage, or quota were unavailable or truncated in at least one observation.",
|
||||
);
|
||||
};
|
||||
|
||||
const compareWebCaptureDimensions = (
|
||||
input: CompareWebCapturesInput,
|
||||
remaining: { value: number },
|
||||
): WebCaptureDiff["dimensions"] => {
|
||||
const before = input.before.inspection;
|
||||
const after = input.after.inspection;
|
||||
const dimensions = {
|
||||
const dimension = compareDimension(remaining);
|
||||
return {
|
||||
dom_structure: dimension(
|
||||
singleton("document", digest(domProjection(before))),
|
||||
singleton("document", digest(domProjection(after))),
|
||||
@@ -132,49 +261,9 @@ export const compareWebCaptures = (
|
||||
webMcpComplete(input.before.webmcp) && webMcpComplete(input.after.webmcp),
|
||||
"WebMCP discovery was unavailable or incomplete in at least one capture.",
|
||||
),
|
||||
accessibility: accessibilityDimension(before, after, remaining),
|
||||
storage: storageDimension(before, after, remaining),
|
||||
};
|
||||
const statuses = Object.values(dimensions).map(({ status }) => status);
|
||||
return webCaptureDiffSchema.parse({
|
||||
schema_version: 1,
|
||||
overall_status: statuses.includes("changed")
|
||||
? "changed"
|
||||
: statuses.includes("unknown")
|
||||
? "unknown"
|
||||
: "unchanged",
|
||||
before_target: {
|
||||
target_id: before.target.target_id,
|
||||
url: before.target.url,
|
||||
},
|
||||
after_target: {
|
||||
target_id: after.target.target_id,
|
||||
url: after.target.url,
|
||||
},
|
||||
dimensions,
|
||||
limitations: [
|
||||
"A changed status proves an observed difference; an unknown status means absence could not be established from capture completeness.",
|
||||
"Network comparison covers only activity observed after each CDP attachment.",
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
const compareIdentities = (
|
||||
before: ReadonlyMap<string, string>,
|
||||
after: ReadonlyMap<string, string>,
|
||||
): Change[] => {
|
||||
const changes: Change[] = [];
|
||||
for (const [identity, fingerprint] of before) {
|
||||
const next = after.get(identity);
|
||||
if (next === undefined) changes.push({ identity, change: "removed" });
|
||||
else if (next !== fingerprint)
|
||||
changes.push({ identity, change: "modified" });
|
||||
}
|
||||
for (const identity of after.keys())
|
||||
if (!before.has(identity)) changes.push({ identity, change: "added" });
|
||||
return changes.sort(
|
||||
(left, right) =>
|
||||
left.identity.localeCompare(right.identity) ||
|
||||
left.change.localeCompare(right.change),
|
||||
);
|
||||
};
|
||||
|
||||
const keyed = <T>(
|
||||
@@ -284,3 +373,125 @@ const digest = (value: unknown): string => {
|
||||
if (encoded === undefined) throw new TypeError("Expected canonical JSON");
|
||||
return createHash("sha256").update(encoded).digest("hex");
|
||||
};
|
||||
|
||||
const accessibilityComparable = (
|
||||
inspection: WebPageInspection,
|
||||
): {
|
||||
readonly text: boolean;
|
||||
readonly nodes: boolean;
|
||||
readonly complete: boolean;
|
||||
} => {
|
||||
const text =
|
||||
inspection.accessibility.text_capture.status === "included" &&
|
||||
inspection.accessibility.text_capture.excluded_fields === 0 &&
|
||||
inspection.accessibility.text_capture.truncated_fields === 0;
|
||||
const nodes =
|
||||
inspection.accessibility.total_nodes ===
|
||||
inspection.accessibility.nodes.length;
|
||||
const complete =
|
||||
text && nodes && sectionsComplete(inspection, ["accessibility"]);
|
||||
return { text, nodes, complete };
|
||||
};
|
||||
|
||||
const accessibilityProjection = (
|
||||
accessibility: WebPageInspection["accessibility"],
|
||||
includeText: boolean,
|
||||
includeNodes: boolean,
|
||||
): unknown => {
|
||||
const result = {
|
||||
total_nodes: accessibility.total_nodes,
|
||||
} as { total_nodes: number; nodes?: readonly unknown[] };
|
||||
if (!includeNodes) return result;
|
||||
const nodeIndexes = new Map(
|
||||
accessibility.nodes.map((node, index) => [node.node_id, index]),
|
||||
);
|
||||
result.nodes = accessibility.nodes.map((node) => ({
|
||||
parent_index:
|
||||
node.parent_id === null ? null : (nodeIndexes.get(node.parent_id) ?? -1),
|
||||
role: node.role,
|
||||
ignored: node.ignored,
|
||||
states: node.states,
|
||||
...(includeText ? { name: node.name, description: node.description } : {}),
|
||||
}));
|
||||
return result;
|
||||
};
|
||||
|
||||
const storageKeysComparable = (inspection: WebPageInspection): boolean =>
|
||||
sectionsComplete(inspection, ["storage_keys"]);
|
||||
|
||||
const storageComparable = (
|
||||
before: WebPageInspection,
|
||||
after: WebPageInspection,
|
||||
keysComplete: boolean,
|
||||
usageComplete: boolean,
|
||||
): boolean =>
|
||||
keysComplete &&
|
||||
usageComplete &&
|
||||
before.storage.fingerprints_complete &&
|
||||
after.storage.fingerprints_complete;
|
||||
|
||||
const storageMap = (
|
||||
storage: WebPageInspection["storage"],
|
||||
includeKeys: boolean,
|
||||
includeUsage: boolean,
|
||||
fingerprintIdentities: ReadonlySet<string>,
|
||||
): ReadonlyMap<string, string> => {
|
||||
const map = new Map<string, string>([
|
||||
[
|
||||
"storage:summary",
|
||||
digest({
|
||||
origin: storage.origin,
|
||||
values_redacted: storage.values_redacted,
|
||||
...(includeUsage
|
||||
? {
|
||||
usage_bytes: storage.usage_bytes,
|
||||
quota_bytes: storage.quota_bytes,
|
||||
}
|
||||
: {}),
|
||||
}),
|
||||
],
|
||||
]);
|
||||
if (!includeKeys) return map;
|
||||
const add = (kind: string, keys: readonly string[]) => {
|
||||
for (const key of keys) {
|
||||
map.set(`storage:${kind}:${key}`, digest(key));
|
||||
}
|
||||
};
|
||||
add("local_storage", storage.local_storage_keys);
|
||||
add("session_storage", storage.session_storage_keys);
|
||||
add("indexed_db", storage.indexed_db_names);
|
||||
add("cache", storage.cache_names);
|
||||
for (const fingerprint of storage.content_fingerprints) {
|
||||
const identity = `${fingerprint.scope}:${fingerprint.identity_sha256}`;
|
||||
if (!fingerprintIdentities.has(identity)) continue;
|
||||
map.set(`storage:content:${identity}`, digest(fingerprint.value_sha256));
|
||||
}
|
||||
return map;
|
||||
};
|
||||
|
||||
const storageFingerprintIdentities = (
|
||||
before: WebPageInspection["storage"],
|
||||
after: WebPageInspection["storage"],
|
||||
): ReadonlySet<string> => {
|
||||
const beforeComplete = completeStorageFingerprints(before);
|
||||
const afterComplete = completeStorageFingerprints(after);
|
||||
if (before.fingerprints_complete && after.fingerprints_complete)
|
||||
return new Set([...beforeComplete.keys(), ...afterComplete.keys()]);
|
||||
return new Set(
|
||||
[...beforeComplete.keys()].filter((identity) =>
|
||||
afterComplete.has(identity),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const completeStorageFingerprints = (
|
||||
storage: WebPageInspection["storage"],
|
||||
): ReadonlyMap<string, string | null> =>
|
||||
new Map(
|
||||
storage.content_fingerprints
|
||||
.filter(({ complete }) => complete)
|
||||
.map(({ scope, identity_sha256, value_sha256 }) => [
|
||||
`${scope}:${identity_sha256}`,
|
||||
value_sha256,
|
||||
]),
|
||||
);
|
||||
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
import { analyzeWebBundleInputSchema } from "../domain/webBundleAnalysis.js";
|
||||
import { observeWebSessionInputSchema } from "../domain/browserSession.js";
|
||||
import { discoverWebMcpToolsInputSchema } from "../domain/webMcpDiscovery.js";
|
||||
import { compareWebCapturesInputSchema } from "../domain/webCaptureDiff.js";
|
||||
import { browserCaptureComparisonInputSchema } from "../domain/browserCaptureComparison.js";
|
||||
import {
|
||||
captureWebScreenshotInputSchema,
|
||||
compareWebScreenshotsInputSchema,
|
||||
@@ -127,7 +127,7 @@ export const registerBrowserTools = (
|
||||
});
|
||||
registerBrowserTool(server, options, {
|
||||
contract: captureDiffContract,
|
||||
schema: compareWebCapturesInputSchema,
|
||||
schema: browserCaptureComparisonInputSchema,
|
||||
execute: (parsed, _context) =>
|
||||
compareWebCaptureEvidence(options.browser, parsed),
|
||||
});
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const browsers: FakeCdpBrowser[] = [];
|
||||
const INTEGRATION_TEST_TIMEOUT_MS = 40_000;
|
||||
const INTEGRATION_TEST_TIMEOUT_MS = 60_000;
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(browsers.splice(0).map(async (browser) => browser.close()));
|
||||
@@ -97,6 +97,26 @@ describe("browser CLI parity", () => {
|
||||
},
|
||||
},
|
||||
});
|
||||
const scenarioCapture = completeScenarioCapture();
|
||||
const scenarioCompared = await runCli(
|
||||
[
|
||||
"compare-web-captures",
|
||||
JSON.stringify(scenarioCapture),
|
||||
JSON.stringify(scenarioCapture),
|
||||
"--normalization-json",
|
||||
'{"rules":[]}',
|
||||
"--json",
|
||||
],
|
||||
environment,
|
||||
);
|
||||
expect(scenarioCompared).toMatchObject({
|
||||
operation: "compare_web_captures",
|
||||
normalized_result: {
|
||||
comparison_kind: "browser_scenario",
|
||||
overall_status: "unchanged",
|
||||
alignment: { status: "aligned", aligned_steps: 2 },
|
||||
},
|
||||
});
|
||||
const analyzed = await runCli(
|
||||
[
|
||||
"analyze-web-bundle",
|
||||
@@ -277,5 +297,66 @@ const normalizedResult = (value: unknown): Record<string, unknown> => {
|
||||
return value.normalized_result;
|
||||
};
|
||||
|
||||
const completeScenarioCapture = () => {
|
||||
const url = {
|
||||
url: "https://app.example.test/",
|
||||
origin: "https://app.example.test",
|
||||
query_parameter_names: [],
|
||||
redacted: false,
|
||||
};
|
||||
const completeness = {
|
||||
status: "complete",
|
||||
equality_eligible: true,
|
||||
missing_sections: [],
|
||||
truncated_sections: [],
|
||||
};
|
||||
const artifacts = {
|
||||
screenshot: { state: "not_requested" },
|
||||
dom: { state: "not_requested" },
|
||||
accessibility: { state: "not_requested" },
|
||||
url: { state: "captured", value: url },
|
||||
history: { state: "not_requested" },
|
||||
storage: { state: "not_requested" },
|
||||
};
|
||||
const step = (stepIndex: number, stepId: string, action: string) => ({
|
||||
step_index: stepIndex,
|
||||
step_id: stepId,
|
||||
action,
|
||||
status: "completed",
|
||||
elapsed_ms: stepIndex,
|
||||
before_url: url,
|
||||
after_url: url,
|
||||
error: null,
|
||||
event_sequence_start: 1,
|
||||
event_sequence_end: 0,
|
||||
artifacts,
|
||||
completeness,
|
||||
});
|
||||
return {
|
||||
schema_version: 1,
|
||||
browser: {
|
||||
mode: "connect",
|
||||
process_ownership: "external",
|
||||
cleanup: "disconnected-external",
|
||||
product: "Chromium",
|
||||
version: "149",
|
||||
},
|
||||
scenario: {
|
||||
start_origin: "https://app.example.test",
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
action_count: 1,
|
||||
secret_references: [],
|
||||
},
|
||||
duration_ms: 1,
|
||||
steps: [
|
||||
step(0, "scenario_start", "scenario_start"),
|
||||
step(1, "open-settings", "click"),
|
||||
],
|
||||
events: { retained: 0, dropped: 0, items: [] },
|
||||
completeness,
|
||||
limitations: [],
|
||||
};
|
||||
};
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
compareBrowserScenarios,
|
||||
compareBrowserScenariosInputSchema,
|
||||
} from "../src/domain/browserScenarioDiff.js";
|
||||
import {
|
||||
browserScenarioCaptureSchema,
|
||||
type BrowserScenarioCapture,
|
||||
} from "../src/domain/browserScenarioCapture.js";
|
||||
|
||||
describe("browser scenario comparison", () => {
|
||||
it("records canonical literal normalization and ignores declared volatile fields", () => {
|
||||
const before = scenarioCapture({
|
||||
domText: "<main data-build='build-123'>Settings</main>",
|
||||
elapsedMs: 11,
|
||||
eventSequence: 3,
|
||||
});
|
||||
const after = scenarioCapture({
|
||||
domText: "<main data-build='build-456'>Settings</main>",
|
||||
elapsedMs: 900,
|
||||
eventSequence: 88,
|
||||
});
|
||||
const rules = [
|
||||
{
|
||||
rule_id: "new-build",
|
||||
artifacts: ["dom"] as const,
|
||||
match: "build-456",
|
||||
replacement: "[BUILD]",
|
||||
},
|
||||
{
|
||||
rule_id: "old-build",
|
||||
artifacts: ["dom"] as const,
|
||||
match: "build-123",
|
||||
replacement: "[BUILD]",
|
||||
},
|
||||
];
|
||||
|
||||
const compared = compareBrowserScenarios(
|
||||
compareBrowserScenariosInputSchema.parse({
|
||||
before_scenario: before,
|
||||
after_scenario: after,
|
||||
normalization: { rules },
|
||||
}),
|
||||
);
|
||||
const reordered = compareBrowserScenarios(
|
||||
compareBrowserScenariosInputSchema.parse({
|
||||
before_scenario: before,
|
||||
after_scenario: after,
|
||||
normalization: {
|
||||
rules: [...rules].reverse().map((rule) => ({
|
||||
...rule,
|
||||
artifacts: [...rule.artifacts].reverse(),
|
||||
})),
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(compared.overall_status).toBe("unchanged");
|
||||
expect(compared.alignment.status).toBe("aligned");
|
||||
expect(compared.artifact_diffs.total).toBe(0);
|
||||
expect(compared.normalization).toMatchObject({
|
||||
rules: [
|
||||
{ rule_id: "new-build", artifacts: ["dom"] },
|
||||
{ rule_id: "old-build", artifacts: ["dom"] },
|
||||
],
|
||||
});
|
||||
expect(reordered.normalization.sha256).toBe(compared.normalization.sha256);
|
||||
});
|
||||
|
||||
it("exposes action mismatches and normalized artifact-level changes", () => {
|
||||
const before = scenarioCapture({
|
||||
domText: "<main>Settings</main>",
|
||||
});
|
||||
const after = scenarioCapture({
|
||||
action: "dblclick",
|
||||
domText: "<main>Advanced settings</main>",
|
||||
});
|
||||
|
||||
const compared = compareBrowserScenarios(
|
||||
compareBrowserScenariosInputSchema.parse({
|
||||
before_scenario: before,
|
||||
after_scenario: after,
|
||||
}),
|
||||
);
|
||||
const step = compared.steps.find(
|
||||
({ step_id: stepId }) => stepId === "open-settings",
|
||||
);
|
||||
|
||||
expect(compared.overall_status).toBe("changed");
|
||||
expect(compared.alignment).toMatchObject({
|
||||
status: "partial",
|
||||
failures: [
|
||||
expect.objectContaining({
|
||||
code: "action_mismatch",
|
||||
step_id: "open-settings",
|
||||
}),
|
||||
],
|
||||
});
|
||||
expect(step).toMatchObject({
|
||||
status: "changed",
|
||||
artifact_diffs: [
|
||||
expect.objectContaining({
|
||||
artifact: "action_state",
|
||||
status: "changed",
|
||||
}),
|
||||
expect.objectContaining({ artifact: "dom", status: "changed" }),
|
||||
],
|
||||
});
|
||||
expect(compared.artifact_diffs).toEqual({
|
||||
total: 2,
|
||||
retained: 2,
|
||||
omitted: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("reports missing aligned steps without claiming equality", () => {
|
||||
const before = scenarioCapture({});
|
||||
const after = scenarioCapture({ stepId: "open-profile" });
|
||||
|
||||
const compared = compareBrowserScenarios(
|
||||
compareBrowserScenariosInputSchema.parse({
|
||||
before_scenario: before,
|
||||
after_scenario: after,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(compared.overall_status).toBe("unknown");
|
||||
expect(compared.alignment).toMatchObject({
|
||||
status: "partial",
|
||||
aligned_steps: 1,
|
||||
before_only: ["open-settings"],
|
||||
after_only: ["open-profile"],
|
||||
failures: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
code: "missing_before_step",
|
||||
step_id: "open-profile",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
code: "missing_after_step",
|
||||
step_id: "open-settings",
|
||||
}),
|
||||
]),
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects ambiguous input pairs and duplicate normalization rule IDs", () => {
|
||||
const capture = scenarioCapture({});
|
||||
expect(
|
||||
compareBrowserScenariosInputSchema.safeParse({
|
||||
before_scenario: capture,
|
||||
after_scenario: capture,
|
||||
normalization: {
|
||||
rules: [
|
||||
{
|
||||
rule_id: "volatile",
|
||||
artifacts: ["dom"],
|
||||
match: "one",
|
||||
replacement: "[VALUE]",
|
||||
},
|
||||
{
|
||||
rule_id: "volatile",
|
||||
artifacts: ["url"],
|
||||
match: "two",
|
||||
replacement: "[VALUE]",
|
||||
},
|
||||
],
|
||||
},
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
interface ScenarioCaptureOptions {
|
||||
readonly stepId?: string;
|
||||
readonly action?: string;
|
||||
readonly domText?: string;
|
||||
readonly elapsedMs?: number;
|
||||
readonly eventSequence?: number;
|
||||
}
|
||||
|
||||
const scenarioCapture = (
|
||||
options: ScenarioCaptureOptions,
|
||||
): BrowserScenarioCapture => {
|
||||
const url = {
|
||||
url: "https://app.example.test/settings",
|
||||
origin: "https://app.example.test",
|
||||
query_parameter_names: [],
|
||||
redacted: false,
|
||||
};
|
||||
const completeness = {
|
||||
status: "complete",
|
||||
equality_eligible: true,
|
||||
missing_sections: [],
|
||||
truncated_sections: [],
|
||||
};
|
||||
const artifacts = (text: string) => ({
|
||||
screenshot: { state: "not_requested" },
|
||||
dom: { state: "captured", value: textArtifact(text) },
|
||||
accessibility: { state: "not_requested" },
|
||||
url: { state: "captured", value: url },
|
||||
history: { state: "not_requested" },
|
||||
storage: { state: "not_requested" },
|
||||
});
|
||||
const eventSequence = options.eventSequence ?? 1;
|
||||
return browserScenarioCaptureSchema.parse({
|
||||
schema_version: 1,
|
||||
browser: {
|
||||
mode: "launch",
|
||||
process_ownership: "provider-owned",
|
||||
cleanup: "terminated-owned-process",
|
||||
product: "Chromium",
|
||||
version: "149.0",
|
||||
},
|
||||
scenario: {
|
||||
start_origin: "https://app.example.test",
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
action_count: 1,
|
||||
secret_references: [],
|
||||
},
|
||||
duration_ms: options.elapsedMs ?? 10,
|
||||
steps: [
|
||||
{
|
||||
step_index: 0,
|
||||
step_id: "scenario_start",
|
||||
action: "scenario_start",
|
||||
status: "completed",
|
||||
elapsed_ms: 0,
|
||||
before_url: url,
|
||||
after_url: url,
|
||||
error: null,
|
||||
event_sequence_start: 1,
|
||||
event_sequence_end: 0,
|
||||
artifacts: artifacts("<main>Ready</main>"),
|
||||
completeness,
|
||||
},
|
||||
{
|
||||
step_index: 1,
|
||||
step_id: options.stepId ?? "open-settings",
|
||||
action: options.action ?? "click",
|
||||
status: "completed",
|
||||
elapsed_ms: options.elapsedMs ?? 10,
|
||||
before_url: url,
|
||||
after_url: url,
|
||||
error: null,
|
||||
event_sequence_start: eventSequence,
|
||||
event_sequence_end: eventSequence,
|
||||
artifacts: artifacts(options.domText ?? "<main>Settings</main>"),
|
||||
completeness,
|
||||
},
|
||||
],
|
||||
events: {
|
||||
retained: 1,
|
||||
dropped: 0,
|
||||
items: [
|
||||
{
|
||||
sequence: eventSequence,
|
||||
step_index: 1,
|
||||
kind: "console",
|
||||
level: "info",
|
||||
text: "settings-ready",
|
||||
url: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
completeness,
|
||||
limitations: [],
|
||||
});
|
||||
};
|
||||
|
||||
const textArtifact = (text: string) => {
|
||||
const bytes = Buffer.from(text);
|
||||
return {
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
bytes: bytes.byteLength,
|
||||
text,
|
||||
};
|
||||
};
|
||||
@@ -364,6 +364,22 @@ describe("CdpBrowserProvider", () => {
|
||||
session_storage_keys: ["public-key"],
|
||||
indexed_db_names: ["app-db"],
|
||||
cache_names: ["assets-v1"],
|
||||
content_fingerprints: expect.arrayContaining([
|
||||
expect.objectContaining({ scope: "cookie", complete: true }),
|
||||
expect.objectContaining({ scope: "local_storage", complete: true }),
|
||||
expect.objectContaining({ scope: "session_storage", complete: true }),
|
||||
expect.objectContaining({
|
||||
scope: "indexed_db_schema",
|
||||
complete: true,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
scope: "indexed_db_record",
|
||||
complete: true,
|
||||
}),
|
||||
expect.objectContaining({ scope: "cache_entry", complete: true }),
|
||||
]),
|
||||
fingerprint_algorithm: "sha256",
|
||||
fingerprints_complete: true,
|
||||
values_redacted: true,
|
||||
}),
|
||||
);
|
||||
@@ -388,6 +404,9 @@ describe("CdpBrowserProvider", () => {
|
||||
"unknown-origin-console-secret",
|
||||
"unknown-console-value-secret",
|
||||
"storage-secret",
|
||||
"cookie-secret",
|
||||
"indexed-db-secret",
|
||||
"cache-body-secret",
|
||||
"secret-id",
|
||||
"dom-url-secret",
|
||||
"link-secret",
|
||||
|
||||
@@ -83,6 +83,11 @@ describe("CDP document capture", () => {
|
||||
role: { value: "button" },
|
||||
name: { value: "😀a" },
|
||||
description: { value: "éé" },
|
||||
childIds: ["missing-child"],
|
||||
properties: [
|
||||
{ name: "disabled", value: { value: true } },
|
||||
{ name: "valuetext", value: { value: "private value" } },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -95,7 +100,12 @@ describe("CDP document capture", () => {
|
||||
},
|
||||
);
|
||||
|
||||
expect(capture.nodes[0]).toMatchObject({ name: "😀", description: "é" });
|
||||
expect(capture.nodes[0]).toMatchObject({
|
||||
name: "😀",
|
||||
description: "é",
|
||||
states: [{ name: "disabled", value: true }],
|
||||
});
|
||||
expect(capture.treeIncomplete).toBe(true);
|
||||
expect(capture.textCapture).toEqual({
|
||||
status: "truncated",
|
||||
retained_bytes: 6,
|
||||
|
||||
Vendored
+83
@@ -399,10 +399,20 @@ const resultFor = (
|
||||
return storageUsageResult();
|
||||
case "DOMStorage.getDOMStorageItems":
|
||||
return domStorageResult(options);
|
||||
case "Network.getCookies":
|
||||
return cookieStorageResult();
|
||||
case "IndexedDB.requestDatabaseNames":
|
||||
return indexedDbResult(options);
|
||||
case "IndexedDB.requestDatabase":
|
||||
return indexedDbDatabaseResult(command);
|
||||
case "IndexedDB.requestData":
|
||||
return indexedDbDataResult();
|
||||
case "CacheStorage.requestCacheNames":
|
||||
return cacheStorageResult(options);
|
||||
case "CacheStorage.requestEntries":
|
||||
return cacheEntriesResult(port);
|
||||
case "CacheStorage.requestCachedResponse":
|
||||
return cachedResponseResult();
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
@@ -476,11 +486,53 @@ const domStorageResult = (options: FakeOptions) => ({
|
||||
: [["public-key", "storage-secret"]],
|
||||
});
|
||||
|
||||
const cookieStorageResult = () => ({
|
||||
cookies: [
|
||||
{
|
||||
name: "session",
|
||||
value: "cookie-secret",
|
||||
domain: "127.0.0.1",
|
||||
path: "/",
|
||||
secure: false,
|
||||
httpOnly: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const indexedDbResult = (options: FakeOptions) => ({
|
||||
databaseNames:
|
||||
options.extraCollections === true ? ["app-db", "second-db"] : ["app-db"],
|
||||
});
|
||||
|
||||
const indexedDbDatabaseResult = (command: FakeCdpCommand) => ({
|
||||
databaseWithObjectStores: {
|
||||
name:
|
||||
typeof command.params.databaseName === "string"
|
||||
? command.params.databaseName
|
||||
: "app-db",
|
||||
version: 1,
|
||||
objectStores: [
|
||||
{
|
||||
name: "records",
|
||||
keyPath: { type: "string", string: "id" },
|
||||
autoIncrement: false,
|
||||
indexes: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const indexedDbDataResult = () => ({
|
||||
objectStoreDataEntries: [
|
||||
{
|
||||
key: { type: "string", value: "row-1" },
|
||||
primaryKey: { type: "string", value: "row-1" },
|
||||
value: { type: "string", value: "indexed-db-secret" },
|
||||
},
|
||||
],
|
||||
hasMore: false,
|
||||
});
|
||||
|
||||
const cacheStorageResult = (options: FakeOptions) => ({
|
||||
caches: [
|
||||
{ cacheName: "assets-v1", cacheId: "secret-id" },
|
||||
@@ -490,6 +542,26 @@ const cacheStorageResult = (options: FakeOptions) => ({
|
||||
],
|
||||
});
|
||||
|
||||
const cacheEntriesResult = (port: number) => ({
|
||||
cacheDataEntries: [
|
||||
{
|
||||
requestURL: `http://127.0.0.1:${String(port)}/cached`,
|
||||
requestMethod: "GET",
|
||||
requestHeaders: [],
|
||||
responseTime: 1,
|
||||
responseStatus: 200,
|
||||
responseStatusText: "OK",
|
||||
responseType: "basic",
|
||||
responseHeaders: [],
|
||||
},
|
||||
],
|
||||
returnCount: 1,
|
||||
});
|
||||
|
||||
const cachedResponseResult = () => ({
|
||||
response: { body: Buffer.from("cache-body-secret").toString("base64") },
|
||||
});
|
||||
|
||||
const versionTargetId = (options: FakeOptions): string =>
|
||||
options.electronFileUrl === undefined ? "allowed-page" : "electron-page";
|
||||
|
||||
@@ -670,6 +742,17 @@ const accessibilityTree = (
|
||||
role: { type: "role", value: "button" },
|
||||
name: { type: "computedString", value: "Submit report" },
|
||||
description: { type: "computedString", value: "Sends the form" },
|
||||
childIds: extraCollections ? ["ax-2"] : [],
|
||||
properties: [
|
||||
{
|
||||
name: "disabled",
|
||||
value: { type: "boolean", value: false },
|
||||
},
|
||||
{
|
||||
name: "expanded",
|
||||
value: { type: "booleanOrUndefined", value: false },
|
||||
},
|
||||
],
|
||||
},
|
||||
...(extraCollections
|
||||
? [
|
||||
|
||||
@@ -125,6 +125,191 @@ describe("web capture diff", () => {
|
||||
expect(result.dimensions.network.status).toBe("unknown");
|
||||
expect(result.dimensions.network.total_changes).toBe(0);
|
||||
});
|
||||
|
||||
it("detects accessibility semantics and storage inventory changes", async () => {
|
||||
const browser = await startFakeCdpBrowser({ extraCollections: true });
|
||||
browsers.push(browser);
|
||||
const captured = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
include_accessibility_text: true,
|
||||
include_storage_keys: true,
|
||||
}),
|
||||
);
|
||||
if (!captured.ok) throw captured.error;
|
||||
const compareAfter = (after: typeof captured.value) =>
|
||||
compareWebCaptures(
|
||||
compareWebCapturesInputSchema.parse({
|
||||
before: { inspection: captured.value },
|
||||
after: { inspection: after },
|
||||
}),
|
||||
);
|
||||
const roleChanged = structuredClone(captured.value);
|
||||
const namedNode = roleChanged.accessibility.nodes[0];
|
||||
if (namedNode === undefined)
|
||||
throw new Error("Expected accessibility nodes");
|
||||
namedNode.role = "menuitem";
|
||||
|
||||
const nameChanged = structuredClone(captured.value);
|
||||
const renamedNode = nameChanged.accessibility.nodes[0];
|
||||
if (renamedNode === undefined)
|
||||
throw new Error("Expected accessibility nodes");
|
||||
renamedNode.name = "Send report";
|
||||
|
||||
const stateChanged = structuredClone(captured.value);
|
||||
const stateNode = stateChanged.accessibility.nodes[0];
|
||||
const disabledState = stateNode?.states.find(
|
||||
({ name }) => name === "disabled",
|
||||
);
|
||||
if (disabledState === undefined)
|
||||
throw new Error("Expected an accessibility state");
|
||||
disabledState.value = true;
|
||||
|
||||
const hierarchyChanged = structuredClone(captured.value);
|
||||
const childNode = hierarchyChanged.accessibility.nodes[1];
|
||||
if (childNode === undefined)
|
||||
throw new Error("Expected an accessibility child");
|
||||
childNode.parent_id = null;
|
||||
|
||||
const storageChanged = structuredClone(captured.value);
|
||||
storageChanged.storage.local_storage_keys.push("new-key");
|
||||
|
||||
for (const after of [
|
||||
roleChanged,
|
||||
nameChanged,
|
||||
stateChanged,
|
||||
hierarchyChanged,
|
||||
])
|
||||
expect(compareAfter(after).dimensions.accessibility).toMatchObject({
|
||||
status: "changed",
|
||||
changes: [
|
||||
{
|
||||
identity: "accessibility_tree",
|
||||
change: "modified",
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(compareAfter(storageChanged).dimensions.storage).toMatchObject({
|
||||
status: "changed",
|
||||
changes: [expect.objectContaining({ change: "added" })],
|
||||
});
|
||||
});
|
||||
|
||||
it("uses complete redacted fingerprints but keeps incomplete evidence unknown", async () => {
|
||||
const browser = await startFakeCdpBrowser({ extraCollections: true });
|
||||
browsers.push(browser);
|
||||
const captured = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
include_accessibility_text: true,
|
||||
include_storage_keys: true,
|
||||
}),
|
||||
);
|
||||
if (!captured.ok) throw captured.error;
|
||||
const identical = structuredClone(captured.value);
|
||||
const identity = compareWebCaptures(
|
||||
compareWebCapturesInputSchema.parse({
|
||||
before: { inspection: captured.value },
|
||||
after: { inspection: identical },
|
||||
}),
|
||||
);
|
||||
expect(identity.dimensions.accessibility.status).toBe("unchanged");
|
||||
expect(identity.dimensions.storage).toMatchObject({
|
||||
status: "unchanged",
|
||||
total_changes: 0,
|
||||
});
|
||||
|
||||
const changedFingerprint = structuredClone(captured.value);
|
||||
const fingerprint = changedFingerprint.storage.content_fingerprints.find(
|
||||
({ complete, value_sha256: valueSha256 }) =>
|
||||
complete && valueSha256 !== null,
|
||||
);
|
||||
if (fingerprint === undefined || fingerprint.value_sha256 === null)
|
||||
throw new Error("Expected a complete content fingerprint");
|
||||
fingerprint.value_sha256 = "f".repeat(64);
|
||||
const storageChanged = compareWebCaptures(
|
||||
compareWebCapturesInputSchema.parse({
|
||||
before: { inspection: captured.value },
|
||||
after: { inspection: changedFingerprint },
|
||||
}),
|
||||
);
|
||||
expect(storageChanged.dimensions.storage).toMatchObject({
|
||||
status: "changed",
|
||||
total_changes: 1,
|
||||
changes: [expect.objectContaining({ change: "modified" })],
|
||||
});
|
||||
|
||||
const incompleteStorage = structuredClone(captured.value);
|
||||
incompleteStorage.storage.fingerprints_complete = false;
|
||||
const storageUnknown = compareWebCaptures(
|
||||
compareWebCapturesInputSchema.parse({
|
||||
before: { inspection: captured.value },
|
||||
after: { inspection: incompleteStorage },
|
||||
}),
|
||||
);
|
||||
expect(storageUnknown.dimensions.storage).toMatchObject({
|
||||
status: "unknown",
|
||||
total_changes: 0,
|
||||
});
|
||||
|
||||
const evidenceQualityChanged = structuredClone(captured.value);
|
||||
evidenceQualityChanged.storage.fingerprints_complete = false;
|
||||
const incompleteFingerprint =
|
||||
evidenceQualityChanged.storage.content_fingerprints[0];
|
||||
if (incompleteFingerprint === undefined)
|
||||
throw new Error("Expected a content fingerprint");
|
||||
incompleteFingerprint.complete = false;
|
||||
const evidenceOnly = compareWebCaptures(
|
||||
compareWebCapturesInputSchema.parse({
|
||||
before: { inspection: captured.value },
|
||||
after: { inspection: evidenceQualityChanged },
|
||||
}),
|
||||
);
|
||||
expect(evidenceOnly.dimensions.storage).toMatchObject({
|
||||
status: "unknown",
|
||||
total_changes: 0,
|
||||
});
|
||||
|
||||
const withoutText = structuredClone(captured.value);
|
||||
withoutText.accessibility.text_capture.status = "not_approved";
|
||||
withoutText.accessibility.text_capture.excluded_fields = 1;
|
||||
for (const node of withoutText.accessibility.nodes) {
|
||||
node.name = null;
|
||||
node.description = null;
|
||||
}
|
||||
const missingText = compareWebCaptures(
|
||||
compareWebCapturesInputSchema.parse({
|
||||
before: { inspection: captured.value },
|
||||
after: { inspection: withoutText },
|
||||
}),
|
||||
);
|
||||
expect(missingText.dimensions.accessibility).toMatchObject({
|
||||
status: "unknown",
|
||||
total_changes: 0,
|
||||
});
|
||||
|
||||
const truncated = structuredClone(captured.value);
|
||||
truncated.accessibility.total_nodes += 1;
|
||||
truncated.completeness.truncated_sections.push("accessibility");
|
||||
const incompleteTree = compareWebCaptures(
|
||||
compareWebCapturesInputSchema.parse({
|
||||
before: { inspection: truncated },
|
||||
after: { inspection: structuredClone(truncated) },
|
||||
}),
|
||||
);
|
||||
expect(incompleteTree.dimensions.accessibility).toMatchObject({
|
||||
status: "unknown",
|
||||
total_changes: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const markSectionsComplete = (
|
||||
|
||||
Reference in New Issue
Block a user