feat(browser): compare scenario and storage evidence

This commit is contained in:
morluto
2026-07-24 13:16:18 +00:00
parent 1ac3118aa2
commit f27dd745b8
24 changed files with 2668 additions and 234 deletions
+259 -48
View File
@@ -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,
]),
);