refactor(observation): retain complete tool results

This commit is contained in:
morluto
2026-09-29 12:42:08 +08:00
parent 34d00fd323
commit fa2b6c5a61
37 changed files with 425 additions and 701 deletions
+13 -64
View File
@@ -4,7 +4,6 @@ import canonicalize from "canonicalize";
import { z } from "zod";
import { parseArtifactInventoryEvidence } from "./artifactInventoryEvidence.js";
import { projectBoundedCartesian } from "./boundedCartesianProjection.js";
import { evidenceSchema } from "./evidence.js";
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
@@ -19,12 +18,7 @@ const componentSchema = z.strictObject({
/** Authenticated APK inventory pages projected as one Android application. */
export const androidApplicationProjectionInputSchema = z.strictObject({
inventory_evidence: z.array(evidenceSchema).min(1).max(100),
limits: z
.strictObject({
max_components: z.number().int().min(1).max(10_000).default(1_000),
})
.default({ max_components: 1_000 }),
inventory_evidence: z.array(evidenceSchema).min(1),
});
/** Deterministic, execution-free Android application inventory projection. */
@@ -32,7 +26,7 @@ export const androidApplicationProjectionResultSchema = z.strictObject({
projection_id: z.string().regex(/^adp_[a-f0-9]{64}$/u),
root_sha256: digestSchema,
root_format: z.literal("apk"),
source_evidence_ids: z.array(evidenceIdSchema).min(1).max(100),
source_evidence_ids: z.array(evidenceIdSchema).min(1),
components: z.strictObject({
manifests: z.array(componentSchema),
resources: z.array(componentSchema),
@@ -67,10 +61,8 @@ export const androidApplicationProjectionResultSchema = z.strictObject({
}),
),
coverage: z.strictObject({
status: z.enum(["complete-within-inventory", "partial", "truncated"]),
status: z.enum(["complete-within-inventory", "partial"]),
inventory_complete: z.boolean(),
omitted_components: z.number().int().min(0),
omitted_bridge_candidates: z.number().int().min(0),
}),
limitations: z.array(z.string().min(1).max(4_096)).max(100),
});
@@ -115,27 +107,15 @@ export const projectAndroidApplication = (
} satisfies Component;
});
const classified = classify(all);
const components = retain(classified, parsed.limits.max_components);
const omittedComponents = count(classified) - count(components);
const bridgeProjection = bridgeCandidates(
[...components.dex, ...components.jvm_classes],
components.native_libraries,
parsed.limits.max_components,
[...classified.dex, ...classified.jvm_classes],
classified.native_libraries,
);
const components = classified;
const limitations = [
...(!inventory.complete
? ["Source inventory pages are incomplete; absence is unknown."]
: []),
...(omittedComponents > 0
? [
`${String(omittedComponents)} component observations were omitted by the projection limit.`,
]
: []),
...(bridgeProjection.omitted > 0
? [
`${String(bridgeProjection.omitted)} bridge hypotheses were omitted by the projection limit.`,
]
: []),
"Manifest, resource, signing, and bytecode semantics require a dedicated Android provider; this projection reports exact inventory paths and hashes only.",
"Bridge candidates are path-based hypotheses, not decoded JNI declarations or observed runtime calls.",
];
@@ -149,15 +129,10 @@ export const projectAndroidApplication = (
runtime_families: runtimeFamilies(all),
bridge_candidates: bridgeProjection.candidates,
coverage: {
status:
omittedComponents > 0 || bridgeProjection.omitted > 0
? ("truncated" as const)
: inventory.complete
? ("complete-within-inventory" as const)
: ("partial" as const),
status: inventory.complete
? ("complete-within-inventory" as const)
: ("partial" as const),
inventory_complete: inventory.complete,
omitted_components: omittedComponents,
omitted_bridge_candidates: bridgeProjection.omitted,
},
limitations,
};
@@ -195,27 +170,6 @@ const classify = (all: readonly Component[]) => ({
),
});
const retain = <Groups extends Record<string, readonly Component[]>>(
groups: Groups,
maximum: number,
): { [Key in keyof Groups]: Component[] } => {
let remaining = maximum;
// SAFETY: the projection preserves every key from Groups and replaces only
// each readonly Component array with a bounded mutable Component array.
return Object.fromEntries(
Object.entries(groups).map(([key, values]) => {
const selected = [...values]
.sort((left, right) => compare(left.path, right.path))
.slice(0, remaining);
remaining -= selected.length;
return [key, selected];
}),
) as { [Key in keyof Groups]: Component[] };
};
const count = (groups: Record<string, readonly Component[]>): number =>
Object.values(groups).reduce((total, values) => total + values.length, 0);
const runtimeFamilies = (all: readonly Component[]) => {
const paths = all.map(({ path }) => path.toLowerCase());
const families = new Set<
@@ -247,21 +201,16 @@ const runtimeFamilies = (all: readonly Component[]) => {
const bridgeCandidates = (
managed: readonly Component[],
native: readonly Component[],
maximum: number,
) => {
const projection = projectBoundedCartesian(
managed,
native,
maximum,
(source, target) => ({
const candidates = managed.flatMap((source) =>
native.map((target) => ({
managed_path: source.path,
native_path: target.path,
basis: bridgeBasis(target.path),
}),
})),
);
return {
candidates: projection.values,
omitted: projection.omitted,
candidates,
};
};
+4 -4
View File
@@ -28,7 +28,7 @@ interface ParsedInventorySet {
readonly inventory: InventorySet;
}
/** Parse, merge, and verify a bounded set of inventory Evidence pages. */
/** Parse, merge, and verify inventory Evidence pages. */
export const parseArtifactInventoryEvidence = (
input: unknown,
): ParsedInventorySet =>
@@ -91,11 +91,11 @@ const assembleInventorySet = (
readonly inventory: ArtifactInventoryResult;
}[],
): ParsedInventorySet => {
if (pages.length === 0 || pages.length > 100)
throw new TypeError("Artifact comparison requires 1 to 100 Evidence pages");
if (pages.length === 0)
throw new TypeError("Artifact inventory requires Evidence pages");
const first = pages[0];
if (first === undefined)
throw new TypeError("Artifact comparison requires Evidence pages");
throw new TypeError("Artifact inventory requires Evidence pages");
const manifestJson = canonicalJson(first.inventory.manifest);
const nodes = new Map<string, ArtifactNode>();
const occurrences = new Map<string, ArtifactOccurrence>();
+2 -15
View File
@@ -14,14 +14,6 @@ import {
type WebCaptureDiff,
} from "./webCaptureDiff.js";
const maxChangesSchema = z
.number()
.int()
.min(1)
.max(20_000)
.default(2_000)
.describe("Maximum normalized change records to retain.");
/** Caller-visible object schema for passive and scenario capture comparisons. */
export const browserCaptureComparisonInputSchema = z
.strictObject({
@@ -41,7 +33,6 @@ export const browserCaptureComparisonInputSchema = z
.unwrap()
.optional()
.describe("Exact-literal normalization policy."),
max_changes: maxChangesSchema,
})
.superRefine((input, context) => {
const passive = input.before !== undefined && input.after !== undefined;
@@ -70,7 +61,7 @@ export type BrowserCaptureComparisonInput = z.output<
>;
type ScenarioCapturePair = Pick<
BrowserCaptureComparisonInput,
"before_scenario" | "after_scenario" | "normalization" | "max_changes"
"before_scenario" | "after_scenario" | "normalization"
> & {
before_scenario: NonNullable<
BrowserCaptureComparisonInput["before_scenario"]
@@ -107,9 +98,5 @@ const toPassiveComparison = (
): CompareWebCapturesInput => {
if (input.before === undefined || input.after === undefined)
throw new Error("Validated passive comparison is missing a capture");
return {
before: input.before,
after: input.after,
max_changes: input.max_changes,
};
return { before: input.before, after: input.after };
};
+2 -17
View File
@@ -102,30 +102,15 @@ export const listBrowserTargetsInputSchema = z.object({
...browserInput,
});
/** Collection bounds for passive browser capture, applied internally. */
/** Per-value limits for optional text and JSON-shape capture. */
export const DEFAULT_BROWSER_INSPECTION_LIMITS = {
max_frames: 200,
max_dom_nodes: 2_000,
max_ax_nodes: 2_000,
max_ax_text_field_bytes: 1_024,
max_total_ax_text_bytes: 64 * 1_024,
max_scripts: 200,
max_resources: 2_000,
max_workers: 500,
max_storage_keys: 1_000,
max_script_source_bytes: 1_024 * 1_024,
max_total_script_source_bytes: 4 * 1_024 * 1_024,
max_network_events: 1_000,
max_console_events: 200,
max_console_text_field_bytes: 1_024,
max_total_console_text_bytes: 64 * 1_024,
max_json_body_bytes: 1_024 * 1_024,
max_total_json_body_bytes: 4 * 1_024 * 1_024,
max_json_shape_nodes: 5_000,
max_json_shape_depth: 20,
max_websocket_events: 500,
max_websocket_shape_bytes: 64 * 1_024,
max_total_websocket_shape_bytes: 1_024 * 1_024,
};
const inspectWebPageInputFacts = {
@@ -176,7 +161,7 @@ export const inspectWebPageToolInputSchema = z.union([
inspectWebPageWithSourceInputSchema,
]);
/** Internal parsed input with REA's fixed collection bounds applied. */
/** Internal parsed input with per-value capture limits applied. */
export const inspectWebPageInputSchema =
inspectWebPageToolInputSchema.transform((input) => ({
...input,
+12 -5
View File
@@ -109,15 +109,22 @@ describe("browser scenario comparison", () => {
expect.objectContaining({ artifact: "dom", status: "changed" }),
],
});
expect(compared.artifact_diffs).toEqual({
total: 2,
retained: 2,
omitted: 0,
});
expect(compared.artifact_diffs).toEqual({ total: 2 });
});
});
describe("browser scenario comparison validation", () => {
it("does not accept caller limits that would omit difference records", () => {
const capture = scenarioCapture({});
expect(
compareBrowserScenariosInputSchema.safeParse({
before_scenario: capture,
after_scenario: capture,
max_changes: 1,
}).success,
).toBe(false);
});
it("reports missing aligned steps without claiming equality", () => {
const before = scenarioCapture({});
const after = scenarioCapture({ stepId: "open-profile" });
+1 -16
View File
@@ -76,7 +76,6 @@ export const compareBrowserScenarios = (
afterCapture: input.after_scenario,
alignment,
rules: normalization.rules,
maxChanges: input.max_changes,
});
const failures = [...alignment.failures, ...compared.failures];
const alignmentStatus =
@@ -110,21 +109,12 @@ export const compareBrowserScenarios = (
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.`,
]
: []),
],
});
};
@@ -178,13 +168,11 @@ interface CompareAlignedStepsInput {
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[] = [];
@@ -209,8 +197,6 @@ const compareAlignedSteps = (
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,
@@ -223,8 +209,7 @@ const compareAlignedSteps = (
: statuses.includes("unknown")
? "unknown"
: "unchanged",
artifact_diffs: retained,
omitted_artifact_diffs: reportable.length - retained.length,
artifact_diffs: reportable,
});
}
return { steps, failures, totalArtifactDiffs };
-10
View File
@@ -89,13 +89,6 @@ export const compareBrowserScenariosInputSchema = z.strictObject({
.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<
@@ -170,14 +163,11 @@ export const browserScenarioDiffSchema = z.strictObject({
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),
});
+7 -28
View File
@@ -25,7 +25,6 @@ const observationSchema = z.strictObject({
const runtimeObservationShape = {
family: runtimeFamilySchema,
observations: z.array(observationSchema),
omitted_observations: z.number().int().min(0),
};
const identifiedRuntimeSchema = z.discriminatedUnion("inspection", [
z.strictObject({
@@ -50,12 +49,7 @@ const identifiedRuntimeSchema = z.discriminatedUnion("inspection", [
/** Authenticated artifact inventory pages to classify by runtime family. */
const runtimeIdentificationInputSchema = z.strictObject({
inventory_evidence: z.array(evidenceSchema).min(1).max(100),
limits: z
.strictObject({
max_observations: z.number().int().min(1).max(10_000).default(1_000),
})
.default({ max_observations: 1_000 }),
inventory_evidence: z.array(evidenceSchema).min(1),
});
/** Provider-neutral runtime identification with explicit tooling availability. */
@@ -63,12 +57,11 @@ export const runtimeIdentificationResultSchema = z.strictObject({
identification_id: z.string().regex(/^rid_[a-f0-9]{64}$/u),
root_sha256: digestSchema,
root_format: z.string().min(1).max(100),
source_evidence_ids: z.array(evidenceIdSchema).min(1).max(100),
source_evidence_ids: z.array(evidenceIdSchema).min(1),
runtimes: z.array(identifiedRuntimeSchema),
coverage: z.strictObject({
status: z.enum(["complete-within-inventory", "partial", "truncated"]),
status: z.enum(["complete-within-inventory", "partial"]),
inventory_complete: z.boolean(),
omitted_observations: z.number().int().min(0),
}),
limitations: z.array(z.string().min(1).max(4_096)).max(100),
});
@@ -165,22 +158,15 @@ export const identifyRuntimes = (
sha256: rootObservation.sha256,
format: rootObservation.format,
});
let remaining = parsed.limits.max_observations;
let omitted = 0;
const runtimes = [...grouped.entries()]
.sort(([left], [right]) => compare(left, right))
.map(([family, values]) => {
const unique = deduplicate(values);
const observations = unique.slice(0, remaining);
remaining -= observations.length;
const omittedObservations = unique.length - observations.length;
omitted += omittedObservations;
const provider = providerFor(family, inventory.manifest.root_format);
return {
family,
...runtimeInspection(provider),
observations,
omitted_observations: omittedObservations,
observations: unique,
};
});
const limitations = [
@@ -189,9 +175,6 @@ export const identifyRuntimes = (
"Source inventory pages are incomplete; absent runtimes remain unknown.",
]
: []),
...(omitted > 0
? [`${String(omitted)} runtime observations were omitted by the limit.`]
: []),
"Runtime families are identified from exact artifact formats and paths; semantic claims require the named provider.",
];
const withoutId = {
@@ -202,14 +185,10 @@ export const identifyRuntimes = (
.sort(compare),
runtimes,
coverage: {
status:
omitted > 0
? ("truncated" as const)
: inventory.complete
? ("complete-within-inventory" as const)
: ("partial" as const),
status: inventory.complete
? ("complete-within-inventory" as const)
: ("partial" as const),
inventory_complete: inventory.complete,
omitted_observations: omitted,
},
limitations,
};
+32 -43
View File
@@ -26,10 +26,9 @@ type Change = WebCaptureChange;
export const compareWebCaptures = (
input: CompareWebCapturesInput,
): WebCaptureDiff => {
const remaining = { value: input.max_changes };
const before = input.before.inspection;
const after = input.after.inspection;
const dimensions = compareWebCaptureDimensions(input, remaining);
const dimensions = compareWebCaptureDimensions(input);
const statuses = Object.values(dimensions).map(({ status }) => status);
return webCaptureDiffSchema.parse({
overall_status: statuses.includes("changed")
@@ -75,52 +74,44 @@ const compareIdentities = (
);
};
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.value);
remaining.value -= retained.length;
if (all.length > 0)
return {
status: "changed",
total_changes: all.length,
changes: retained,
omitted_changes: all.length - retained.length,
const compareDimension = (
before: ReadonlyMap<string, string>,
after: ReadonlyMap<string, string>,
complete: boolean,
reason: string,
): Dimension => {
const all = compareIdentities(before, after);
if (all.length > 0)
return {
status: "changed",
total_changes: all.length,
changes: all,
reason: null,
};
return complete
? {
status: "unchanged",
total_changes: 0,
changes: [],
reason: null,
}
: {
status: "unknown",
total_changes: 0,
changes: [],
reason,
};
return complete
? {
status: "unchanged",
total_changes: 0,
changes: [],
omitted_changes: 0,
reason: null,
}
: {
status: "unknown",
total_changes: 0,
changes: [],
omitted_changes: 0,
reason,
};
};
};
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)(
return compareDimension(
singleton(
"accessibility_tree",
digest(
@@ -149,7 +140,6 @@ const accessibilityDimension = (
const storageDimension = (
before: WebPageInspection,
after: WebPageInspection,
remaining: { value: number },
): Dimension => {
const keysComplete =
storageKeysComparable(before) && storageKeysComparable(after);
@@ -162,7 +152,7 @@ const storageDimension = (
before.storage,
after.storage,
);
return compareDimension(remaining)(
return compareDimension(
storageMap(
before.storage,
keysComplete,
@@ -182,11 +172,10 @@ const storageDimension = (
const compareWebCaptureDimensions = (
input: CompareWebCapturesInput,
remaining: { value: number },
): WebCaptureDiff["dimensions"] => {
const before = input.before.inspection;
const after = input.after.inspection;
const dimension = compareDimension(remaining);
const dimension = compareDimension;
return {
dom_structure: dimension(
singleton("document", digest(domProjection(before))),
@@ -235,8 +224,8 @@ const compareWebCaptureDimensions = (
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),
accessibility: accessibilityDimension(before, after),
storage: storageDimension(before, after),
};
};
+3 -10
View File
@@ -10,10 +10,9 @@ export const captureSnapshotSchema = z.object({
});
/** Input for deterministic comparison of two normalized web captures. */
export const compareWebCapturesInputSchema = z.object({
export const compareWebCapturesInputSchema = z.strictObject({
before: captureSnapshotSchema,
after: captureSnapshotSchema,
max_changes: z.number().int().min(1).max(20_000).default(2_000),
});
const changeSchema = z.object({
@@ -23,7 +22,6 @@ const changeSchema = z.object({
const emptyDimensionShape = {
total_changes: z.literal(0),
changes: z.tuple([]),
omitted_changes: z.literal(0),
};
const dimensionSchema = z.union([
z
@@ -31,17 +29,13 @@ const dimensionSchema = z.union([
status: z.literal("changed"),
total_changes: z.number().int().min(1),
changes: z.array(changeSchema),
omitted_changes: z.number().int().min(0),
reason: z.null(),
})
.superRefine((dimension, context) => {
if (
dimension.changes.length + dimension.omitted_changes !==
dimension.total_changes
)
if (dimension.changes.length !== dimension.total_changes)
context.addIssue({
code: "custom",
message: "Retained and omitted changes must equal total changes",
message: "Inline changes must equal total changes",
path: ["total_changes"],
});
}),
@@ -60,7 +54,6 @@ const legacyUnknownDimension: z.input<typeof dimensionSchema> = {
status: "unknown",
total_changes: 0,
changes: [],
omitted_changes: 0,
reason: "Dimension was not recorded by this version 1 capture diff.",
};
+1 -10
View File
@@ -8,20 +8,11 @@ import {
import { jsonShapeSchema } from "./jsonShape.js";
/** Input for passive discovery of page-registered WebMCP tools. */
export const discoverWebMcpToolsInputSchema = z.object({
export const discoverWebMcpToolsInputSchema = z.strictObject({
cdp_endpoint: browserEndpointSchema,
allowed_origins: browserAllowedOriginsSchema,
target_id: z.string().trim().min(1).max(256),
observation_ms: z.number().int().min(0).max(10_000).default(100),
max_tools: z.number().int().min(1).max(5_000).default(500),
max_schema_bytes: z
.number()
.int()
.min(1)
.max(1_024 * 1_024)
.default(256 * 1_024),
max_schema_nodes: z.number().int().min(1).max(100_000).default(5_000),
max_schema_depth: z.number().int().min(1).max(100).default(20),
});
export type DiscoverWebMcpToolsInput = z.infer<
typeof discoverWebMcpToolsInputSchema