refactor(mcp): make analysis states unrepresentable (#468)

* refactor(config): parse capability settings into exact states

* refactor(runtime): encode replay and process outcomes exactly

* refactor: make analysis states unrepresentable

* refactor(mcp): register canonical schemas with SDK

* fix: preserve capability and catalog invariants

* fix(build): remove stale compiled modules

* fix(replay): update real verifier policy dependency

* fix(package): verify the complete MCP catalog

* fix(test): supply complete replay reload policy

* refactor(contracts): centralize output schema lookup

* refactor(mcp): delegate protocol boundaries to SDK

* fix(browser): approve real source capture

* fix(mcp): preserve catalog guidance
This commit is contained in:
morluto
2026-08-10 02:28:11 +08:00
committed by GitHub
parent 6901edc05d
commit b8a9da0c0f
271 changed files with 5970 additions and 5699 deletions
+2
View File
@@ -202,6 +202,8 @@ const retain = <Groups extends Record<string, readonly Component[]>>(
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]
+2
View File
@@ -201,6 +201,8 @@ const retainComponents = <Groups extends Record<string, readonly Component[]>>(
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 retained = [...values]
+32 -49
View File
@@ -13,45 +13,13 @@ import { extname, isAbsolute, join, relative, resolve, sep } from "node:path";
import { promisify } from "node:util";
import { BinaryTargetError } from "./errors.js";
import type { BinaryArchitecture, BinaryTarget } from "./binaryTargetTypes.js";
import { err, ok, type Result } from "./result.js";
import { zipPackageFormatForPath } from "./zipPackageFormat.js";
const execFileAsync = promisify(execFile);
export type { BinaryArchitecture, BinaryTarget } from "./binaryTargetTypes.js";
/** Provider-neutral CPU families detected from supported executable headers. */
export type BinaryArchitecture = "x86" | "x86_64" | "arm" | "arm64";
/**
* Canonical local target identity and provider-neutral file classification.
* Provider adapters translate this metadata into their own open options.
*/
export interface BinaryTarget {
readonly path: string;
readonly sourcePath?: string;
readonly sha256: string;
readonly kind: "executable" | "database" | "archive" | "artifact";
readonly format:
| "analysis-database"
| "mach-o"
| "elf"
| "pe"
| "zip"
| "ipa"
| "apk"
| "msix"
| "appx"
| "asar"
| "dmg"
| "pkg"
| "plist"
| "javascript"
| "source-map";
readonly architecture?: BinaryArchitecture;
readonly availableArchitectures?: readonly BinaryArchitecture[];
/** Provider-neutral PE image role observed from COFF characteristics. */
readonly executableRole?: "application" | "shared-library" | "non-executable";
/** Whether a PE declares a non-empty CLI header data-directory entry. */
readonly managed?: boolean;
}
const execFileAsync = promisify(execFile);
/**
* Resolve and classify a readable local target before a provider is selected.
@@ -87,14 +55,16 @@ export const parseBinaryTarget = async (
format: "analysis-database",
});
const artifactFormat = await detectArtifactFormat(path, handle);
if (artifactFormat !== undefined)
return ok({
if (artifactFormat !== undefined) {
const identity = {
path,
sourcePath: canonical,
sha256: await sha256Handle(handle),
kind: isArchiveFormat(artifactFormat) ? "archive" : "artifact",
format: artifactFormat,
});
};
return isArchiveFormat(artifactFormat)
? ok({ ...identity, kind: "archive", format: artifactFormat })
: ok({ ...identity, kind: "artifact", format: artifactFormat });
}
const detected = await readExecutableMetadata(handle, hostArchitecture);
if (!detected.ok) return err(new BinaryTargetError(path, detected.error));
return ok({
@@ -165,7 +135,12 @@ const namedArtifactFormat = (
return /\.(?:m?js|cjs)$/u.test(lowerPath) ? "javascript" : undefined;
};
const isArchiveFormat = (format: BinaryTarget["format"]): boolean =>
const isArchiveFormat = (
format: Exclude<
BinaryTarget["format"],
"analysis-database" | "mach-o" | "elf" | "pe"
>,
): format is Extract<BinaryTarget, { kind: "archive" }>["format"] =>
["zip", "ipa", "apk", "msix", "appx", "asar", "dmg", "pkg"].includes(format);
const sha256Handle = async (handle: FileHandle): Promise<string> => {
@@ -268,14 +243,22 @@ const decodeXml = (value: string): string =>
.replaceAll("&quot;", '"')
.replaceAll("&apos;", "'");
type ExecutableMetadata = Pick<
BinaryTarget,
| "format"
| "architecture"
| "availableArchitectures"
| "executableRole"
| "managed"
>;
type ExecutableMetadata =
| {
readonly format: "mach-o" | "elf";
readonly architecture: BinaryArchitecture;
readonly availableArchitectures: readonly BinaryArchitecture[];
}
| {
readonly format: "pe";
readonly architecture: BinaryArchitecture;
readonly availableArchitectures: readonly BinaryArchitecture[];
readonly executableRole:
| "application"
| "shared-library"
| "non-executable";
readonly managed: boolean;
};
const readExecutableMetadata = async (
handle: FileHandle,
+65
View File
@@ -0,0 +1,65 @@
/** Provider-neutral CPU families detected from supported executable headers. */
export type BinaryArchitecture = "x86" | "x86_64" | "arm" | "arm64";
interface BinaryTargetIdentity {
readonly path: string;
readonly sourcePath?: string;
readonly sha256: string;
}
type NonExecutableMetadata = {
readonly architecture?: never;
readonly availableArchitectures?: never;
readonly executableRole?: never;
readonly managed?: never;
};
type ExecutableTarget = BinaryTargetIdentity & {
readonly kind: "executable";
readonly architecture: BinaryArchitecture;
readonly availableArchitectures: readonly BinaryArchitecture[];
};
/**
* Canonical local target identity and provider-neutral file classification.
* Each variant carries only metadata established for that exact file kind.
*/
export type BinaryTarget =
| (ExecutableTarget & {
readonly format: "mach-o" | "elf";
readonly executableRole?: never;
readonly managed?: never;
})
| (ExecutableTarget & {
readonly format: "pe";
/** Provider-neutral PE image role observed from COFF characteristics. */
readonly executableRole:
| "application"
| "shared-library"
| "non-executable";
/** Whether the PE declares a non-empty CLI header data-directory entry. */
readonly managed: boolean;
})
| (BinaryTargetIdentity &
NonExecutableMetadata & {
readonly kind: "database";
readonly format: "analysis-database";
})
| (BinaryTargetIdentity &
NonExecutableMetadata & {
readonly kind: "archive";
readonly format:
| "zip"
| "ipa"
| "apk"
| "msix"
| "appx"
| "asar"
| "dmg"
| "pkg";
})
| (BinaryTargetIdentity &
NonExecutableMetadata & {
readonly kind: "artifact";
readonly format: "plist" | "javascript" | "source-map";
});
+28 -79
View File
@@ -11,92 +11,41 @@ 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."),
const maxChangesSchema = z
.number()
.int()
.min(1)
.max(20_000)
.default(2_000)
.describe("Maximum normalized change records to retain.");
/** Top-level MCP shape for exactly one complete passive or scenario pair. */
export const browserCaptureComparisonInputSchema = z.union([
z.strictObject({
before: captureSnapshotSchema.describe("Earlier passive web-page capture."),
after: captureSnapshotSchema.describe("Later passive web-page capture."),
max_changes: maxChangesSchema,
}),
z.strictObject({
before_scenario:
compareBrowserScenariosInputSchema.shape.before_scenario.describe(
"Earlier browser scenario capture.",
),
after_scenario:
compareBrowserScenariosInputSchema.shape.after_scenario.describe(
"Later browser scenario capture.",
),
normalization:
compareBrowserScenariosInputSchema.shape.normalization.describe(
"Scenario-only exact-literal normalization policy.",
"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",
});
});
max_changes: maxChangesSchema,
}),
]);
/** 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
+119 -96
View File
@@ -207,103 +207,126 @@ const DEFAULT_BROWSER_INSPECTION_LIMITS = {
max_total_websocket_shape_bytes: 1_024 * 1_024,
} as const;
const inspectWebPageInputFacts = {
...approvedBrowserInput,
target_id: z.string().trim().min(1).max(256),
observation_ms: z.number().int().min(0).max(10_000).default(500),
include_accessibility_text: z.boolean().default(false),
include_console_text: z.boolean().default(false),
console_text_approved: z.boolean().default(false),
include_json_body_shapes: z.boolean().default(false),
json_body_schema_approved: z.boolean().default(false),
include_websocket_shapes: z.boolean().default(false),
websocket_shape_approved: z.boolean().default(false),
include_storage_keys: z.boolean().default(false),
include_storage_fingerprints: z.boolean().default(false),
limits: browserInspectionLimitsSchema.default(
DEFAULT_BROWSER_INSPECTION_LIMITS,
),
} as const;
const inspectWebPageWithoutSourceSchema = z.strictObject({
...inspectWebPageInputFacts,
include_script_sources: z.literal(false).default(false),
source_capture_approved: z.literal(false).default(false),
});
const inspectWebPageWithSourceShapeSchema = z.strictObject({
...inspectWebPageInputFacts,
include_script_sources: z.literal(true).default(true),
source_capture_approved: z.literal(true),
});
type InspectWebPageShape =
| z.output<typeof inspectWebPageWithoutSourceSchema>
| z.output<typeof inspectWebPageWithSourceShapeSchema>;
const refineInspectWebPageInput = (
input: InspectWebPageShape,
context: z.RefinementCtx,
): void => {
if (input.include_storage_fingerprints && !input.include_storage_keys)
context.addIssue({
code: "custom",
path: ["include_storage_fingerprints"],
message: "Storage fingerprints require storage key capture",
});
if (
input.limits.max_script_source_bytes >
input.limits.max_total_script_source_bytes
)
context.addIssue({
code: "custom",
path: ["limits", "max_script_source_bytes"],
message: "Per-script source limit cannot exceed the total source limit",
});
for (const [include, approved, path, message] of [
[
input.include_console_text,
input.console_text_approved,
"console_text_approved",
"Console text capture requires separate approval",
],
[
input.include_json_body_shapes,
input.json_body_schema_approved,
"json_body_schema_approved",
"JSON body schema capture requires separate approval",
],
[
input.include_websocket_shapes,
input.websocket_shape_approved,
"websocket_shape_approved",
"WebSocket shape capture requires separate approval",
],
] as const)
if (include && !approved)
context.addIssue({ code: "custom", path: [path], message });
if (
input.limits.max_console_text_field_bytes >
input.limits.max_total_console_text_bytes
)
context.addIssue({
code: "custom",
path: ["limits", "max_console_text_field_bytes"],
message:
"Per-field console text limit cannot exceed the total text limit",
});
if (input.limits.max_json_body_bytes > input.limits.max_total_json_body_bytes)
context.addIssue({
code: "custom",
path: ["limits", "max_json_body_bytes"],
message: "Per-body JSON limit cannot exceed the total body limit",
});
if (
input.limits.max_websocket_shape_bytes >
input.limits.max_total_websocket_shape_bytes
)
context.addIssue({
code: "custom",
path: ["limits", "max_websocket_shape_bytes"],
message: "Per-frame WebSocket limit cannot exceed the total frame limit",
});
if (
input.limits.max_ax_text_field_bytes > input.limits.max_total_ax_text_bytes
)
context.addIssue({
code: "custom",
path: ["limits", "max_ax_text_field_bytes"],
message:
"Per-field accessibility text limit cannot exceed the total text limit",
});
};
/** Source-capturing inspection input, reusable by static bundle analysis. */
export const inspectWebPageWithSourceInputSchema =
inspectWebPageWithSourceShapeSchema.superRefine(refineInspectWebPageInput);
/** Public input for one passive, bounded inspection of an existing page. */
export const inspectWebPageInputSchema = z
.object({
...approvedBrowserInput,
target_id: z.string().trim().min(1).max(256),
observation_ms: z.number().int().min(0).max(10_000).default(500),
include_accessibility_text: z.boolean().default(false),
include_console_text: z.boolean().default(false),
console_text_approved: z.boolean().default(false),
include_json_body_shapes: z.boolean().default(false),
json_body_schema_approved: z.boolean().default(false),
include_websocket_shapes: z.boolean().default(false),
websocket_shape_approved: z.boolean().default(false),
include_script_sources: z.boolean().default(false),
include_storage_keys: z.boolean().default(false),
include_storage_fingerprints: z.boolean().default(false),
limits: browserInspectionLimitsSchema.default(
DEFAULT_BROWSER_INSPECTION_LIMITS,
),
})
.superRefine((input, context) => {
if (input.include_storage_fingerprints && !input.include_storage_keys)
context.addIssue({
code: "custom",
path: ["include_storage_fingerprints"],
message: "Storage fingerprints require storage key capture",
});
if (
input.limits.max_script_source_bytes >
input.limits.max_total_script_source_bytes
)
context.addIssue({
code: "custom",
path: ["limits", "max_script_source_bytes"],
message: "Per-script source limit cannot exceed the total source limit",
});
for (const [include, approved, path, message] of [
[
input.include_console_text,
input.console_text_approved,
"console_text_approved",
"Console text capture requires separate approval",
],
[
input.include_json_body_shapes,
input.json_body_schema_approved,
"json_body_schema_approved",
"JSON body schema capture requires separate approval",
],
[
input.include_websocket_shapes,
input.websocket_shape_approved,
"websocket_shape_approved",
"WebSocket shape capture requires separate approval",
],
] as const)
if (include && !approved)
context.addIssue({ code: "custom", path: [path], message });
if (
input.limits.max_console_text_field_bytes >
input.limits.max_total_console_text_bytes
)
context.addIssue({
code: "custom",
path: ["limits", "max_console_text_field_bytes"],
message:
"Per-field console text limit cannot exceed the total text limit",
});
if (
input.limits.max_json_body_bytes > input.limits.max_total_json_body_bytes
)
context.addIssue({
code: "custom",
path: ["limits", "max_json_body_bytes"],
message: "Per-body JSON limit cannot exceed the total body limit",
});
if (
input.limits.max_websocket_shape_bytes >
input.limits.max_total_websocket_shape_bytes
)
context.addIssue({
code: "custom",
path: ["limits", "max_websocket_shape_bytes"],
message:
"Per-frame WebSocket limit cannot exceed the total frame limit",
});
if (
input.limits.max_ax_text_field_bytes >
input.limits.max_total_ax_text_bytes
)
context.addIssue({
code: "custom",
path: ["limits", "max_ax_text_field_bytes"],
message:
"Per-field accessibility text limit cannot exceed the total text limit",
});
});
export const inspectWebPageInputSchema = z.union([
inspectWebPageWithoutSourceSchema.superRefine(refineInspectWebPageInput),
inspectWebPageWithSourceInputSchema,
]);
export type ListBrowserTargetsInput = z.infer<
typeof listBrowserTargetsInputSchema
+3 -2
View File
@@ -230,8 +230,9 @@ const parseSnapshots = (
const assertCompatible = (
snapshots: ReadonlyMap<string, FunctionSnapshot>,
): void => {
const first = snapshots.values().next().value as FunctionSnapshot | undefined;
if (first === undefined) return;
const firstEntry = snapshots.values().next();
if (firstEntry.done) return;
const first = firstEntry.value;
for (const snapshot of snapshots.values()) {
if (
snapshot.subject.digest.sha256 !== first.subject.digest.sha256 ||
+3 -3
View File
@@ -166,8 +166,8 @@ export function failedAuthEvents(
export function authFlowDuration(
events: readonly AuthFlowEvent[],
): number | null {
if (events.length === 0) return null;
const first = events[0]!;
const last = events[events.length - 1]!;
const first = events.at(0);
const last = events.at(-1);
if (first === undefined || last === undefined) return null;
return last.at_ms - first.at_ms;
}
+46 -42
View File
@@ -36,50 +36,54 @@ export type ListElectronTargetsInput = z.infer<
>;
/** Input for passive structural inspection of one Electron file page. */
const inspectElectronPageFacts = {
...approvedElectronInput,
target_id: z.string().trim().min(1).max(256),
observation_ms: z.number().int().min(0).max(10_000).default(100),
limits: z
.object({
max_frames: z.number().int().min(1).max(1_000).default(200),
max_dom_nodes: z.number().int().min(1).max(10_000).default(2_000),
max_scripts: z.number().int().min(1).max(2_000).default(500),
max_resources: z.number().int().min(1).max(10_000).default(2_000),
max_workers: z.number().int().min(1).max(5_000).default(500),
max_script_source_bytes: z
.number()
.int()
.min(1)
.max(4 * 1_024 * 1_024)
.default(1_024 * 1_024),
max_total_script_source_bytes: z
.number()
.int()
.min(1)
.max(16 * 1_024 * 1_024)
.default(4 * 1_024 * 1_024),
})
.default({
max_frames: 200,
max_dom_nodes: 2_000,
max_scripts: 500,
max_resources: 2_000,
max_workers: 500,
max_script_source_bytes: 1_024 * 1_024,
max_total_script_source_bytes: 4 * 1_024 * 1_024,
}),
} as const;
export const inspectElectronPageInputSchema = z
.object({
...approvedElectronInput,
target_id: z.string().trim().min(1).max(256),
observation_ms: z.number().int().min(0).max(10_000).default(100),
include_script_sources: z.boolean().default(false),
source_capture_approved: z.boolean().default(false),
limits: z
.object({
max_frames: z.number().int().min(1).max(1_000).default(200),
max_dom_nodes: z.number().int().min(1).max(10_000).default(2_000),
max_scripts: z.number().int().min(1).max(2_000).default(500),
max_resources: z.number().int().min(1).max(10_000).default(2_000),
max_workers: z.number().int().min(1).max(5_000).default(500),
max_script_source_bytes: z
.number()
.int()
.min(1)
.max(4 * 1_024 * 1_024)
.default(1_024 * 1_024),
max_total_script_source_bytes: z
.number()
.int()
.min(1)
.max(16 * 1_024 * 1_024)
.default(4 * 1_024 * 1_024),
})
.default({
max_frames: 200,
max_dom_nodes: 2_000,
max_scripts: 500,
max_resources: 2_000,
max_workers: 500,
max_script_source_bytes: 1_024 * 1_024,
max_total_script_source_bytes: 4 * 1_024 * 1_024,
}),
})
.union([
z.object({
...inspectElectronPageFacts,
include_script_sources: z.literal(false).default(false),
source_capture_approved: z.literal(false).default(false),
}),
z.object({
...inspectElectronPageFacts,
include_script_sources: z.literal(true),
source_capture_approved: z.literal(true),
}),
])
.superRefine((input, context) => {
if (input.include_script_sources && !input.source_capture_approved)
context.addIssue({
code: "custom",
path: ["source_capture_approved"],
message: "Electron script source capture requires separate approval",
});
if (
input.limits.max_script_source_bytes >
input.limits.max_total_script_source_bytes
+4 -1
View File
@@ -93,7 +93,10 @@ export const collectContextBridgeMembers = (
unknown: 1,
omitted: 0,
};
const state = { members: [] as string[], unknown: 0 };
const state: { members: string[]; unknown: number } = {
members: [],
unknown: 0,
};
collectMembersAt(node, "", 0, state);
const members = [...new Set(state.members)].sort(compareCodePoints);
return {
+2 -1
View File
@@ -209,7 +209,8 @@ export function getDescendants(
const result: number[] = [];
const queue: number[] = [rootPid];
while (queue.length > 0) {
const pid = queue.shift()!;
const pid = queue.shift();
if (pid === undefined) break;
if (visited.has(pid)) continue;
visited.add(pid);
const node = byPid.get(pid);
+16 -9
View File
@@ -177,15 +177,22 @@ export const sorted = (values: readonly unknown[]): readonly unknown[] =>
export const combineCoverage = <Item>(
left: FunctionCollection<Item>,
right: FunctionCollection<Item>,
): FunctionCollection<Item> => ({
items: [...left.items, ...right.items],
total:
left.total === null || right.total === null
? null
: left.total + right.total,
complete: left.complete && right.complete,
truncated: left.truncated || right.truncated,
});
): FunctionCollection<Item> => {
const base = {
items: [...left.items, ...right.items],
total:
left.total === null || right.total === null
? null
: left.total + right.total,
};
return left.complete && right.complete
? { ...base, complete: true, truncated: false }
: {
...base,
complete: false,
truncated: left.truncated || right.truncated,
};
};
export const project = <Input, Output>(
collection: FunctionCollection<Input>,
+19 -11
View File
@@ -24,12 +24,14 @@ type DossierCollectionField = (typeof DOSSIER_COLLECTION_FIELDS)[number];
type DossierItem<Field extends DossierCollectionField> =
FunctionDossier[Field]["items"][number];
export interface FunctionCollection<Item = unknown> {
type FunctionCoverage =
| { readonly complete: true; readonly truncated: false }
| { readonly complete: false; readonly truncated: boolean };
export type FunctionCollection<Item = unknown> = {
readonly items: readonly Item[];
readonly total: number | null;
readonly complete: boolean;
readonly truncated: boolean;
}
} & FunctionCoverage;
type FunctionCollections = {
readonly [Field in DossierCollectionField]: FunctionCollection<
@@ -46,9 +48,10 @@ export interface FunctionSnapshot {
readonly pseudocode: {
readonly text: string;
readonly total: number;
readonly complete: boolean;
readonly truncated: boolean;
};
} & (
| { readonly complete: true; readonly truncated: false }
| { readonly complete: false; readonly truncated: true }
);
readonly collections: FunctionCollections;
readonly instructionScan: FunctionDossier["instruction_scan"];
readonly limitations: readonly string[];
@@ -172,8 +175,9 @@ const mergePseudocode = (
return {
text: orderedValues(characters).join(""),
total,
complete,
truncated: !complete,
...(complete
? { complete: true as const, truncated: false as const }
: { complete: false as const, truncated: true as const }),
};
};
@@ -210,8 +214,12 @@ const mergeCollection = <Field extends DossierCollectionField>(
return {
items: orderedValues(items),
total,
complete,
truncated: scanLimited || (!unavailable && !complete),
...(complete
? { complete: true as const, truncated: false as const }
: {
complete: false as const,
truncated: scanLimited || !unavailable,
}),
};
};
+57 -60
View File
@@ -1,6 +1,6 @@
import { z } from "zod";
import { jsonValueSchema, type JsonValue } from "./jsonValue.js";
import type { JsonValue } from "./jsonValue.js";
import { AnalysisOutputError, HopperProtocolError } from "./errors.js";
import { err, ok, type Result } from "./result.js";
import { nativeApiBoundarySchema } from "./nativeApiBoundary.js";
@@ -62,31 +62,24 @@ const segmentSchema = z.object({
writable: z.boolean().nullable().default(null),
executable: z.boolean().nullable().default(null),
});
const addressedPageSchema = z
.object({
items: z.array(z.object({ address: z.string(), value: z.string() })),
offset: z.number().int().min(0),
limit: z.number().int().min(1),
total: z.number().int().min(0),
next_offset: z.number().int().min(0).nullable(),
has_more: z.boolean(),
})
.superRefine((value, context) => {
if (value.has_more && value.next_offset === null) {
context.addIssue({
code: "custom",
message: "a page with more results must provide next_offset",
path: ["next_offset"],
});
}
if (!value.has_more && value.next_offset !== null) {
context.addIssue({
code: "custom",
message: "a complete page must not provide next_offset",
path: ["next_offset"],
});
}
});
const addressedPageFacts = {
items: z.array(z.object({ address: z.string(), value: z.string() })),
offset: z.number().int().min(0),
limit: z.number().int().min(1),
total: z.number().int().min(0),
} as const;
const addressedPageSchema = z.discriminatedUnion("has_more", [
z.object({
...addressedPageFacts,
has_more: z.literal(true),
next_offset: z.number().int().min(0),
}),
z.object({
...addressedPageFacts,
has_more: z.literal(false),
next_offset: z.null(),
}),
]);
const unavailableAnalysisFactSchema = z
.object({ available: z.literal(false), reason: z.string() })
.strict();
@@ -111,16 +104,25 @@ export const localVariableSchema = z
provenance: z.string().min(1),
})
.strict();
const boundedSchema = <T extends z.ZodType>(item: T) =>
z
.object({
items: z.array(item),
total: z.number().int().min(0).nullable(),
returned: z.number().int().min(0),
truncated: z.boolean(),
next_offset: z.number().int().min(0).nullable(),
})
.strict()
const boundedSchema = <T extends z.ZodType>(item: T) => {
const boundedFacts = {
items: z.array(item),
total: z.number().int().min(0).nullable(),
returned: z.number().int().min(0),
} as const;
return z
.discriminatedUnion("truncated", [
z.strictObject({
...boundedFacts,
truncated: z.literal(false),
next_offset: z.null(),
}),
z.strictObject({
...boundedFacts,
truncated: z.literal(true),
next_offset: z.number().int().min(0).nullable(),
}),
])
.superRefine((value, context) => {
if (value.returned !== value.items.length) {
context.addIssue({
@@ -136,14 +138,8 @@ const boundedSchema = <T extends z.ZodType>(item: T) =>
path: ["total"],
});
}
if (value.next_offset !== null && !value.truncated) {
context.addIssue({
code: "custom",
message: "a continuation requires truncated output",
path: ["next_offset"],
});
}
});
};
/** Provider-neutral bounded raw-instruction window for one analyzed function. */
export const functionInstructionWindowSchema = z
@@ -201,14 +197,22 @@ export const functionDossierSchema = z
})
.strict(),
pseudocode: z
.object({
text: z.string(),
total_chars: z.number().int().min(0),
returned_chars: z.number().int().min(0),
truncated: z.boolean(),
next_offset: z.number().int().min(0).nullable(),
})
.strict()
.discriminatedUnion("truncated", [
z.strictObject({
text: z.string(),
total_chars: z.number().int().min(0),
returned_chars: z.number().int().min(0),
truncated: z.literal(false),
next_offset: z.null(),
}),
z.strictObject({
text: z.string(),
total_chars: z.number().int().min(0),
returned_chars: z.number().int().min(0),
truncated: z.literal(true),
next_offset: z.number().int().min(0).nullable(),
}),
])
.superRefine((value, context) => {
if (value.returned_chars !== [...value.text].length) {
context.addIssue({
@@ -224,13 +228,6 @@ export const functionDossierSchema = z
path: ["total_chars"],
});
}
if (value.next_offset !== null && !value.truncated) {
context.addIssue({
code: "custom",
message: "a continuation requires truncated pseudocode",
path: ["next_offset"],
});
}
}),
assembly: boundedSchema(z.string()),
comments: boundedSchema(
@@ -276,7 +273,7 @@ export const functionDossierSchema = z
instruction_scan: z
.object({ scanned: z.number().int().min(0), truncated: z.boolean() })
.strict(),
native_api: nativeApiBoundarySchema.optional(),
native_api: nativeApiBoundarySchema.nullable().default(null),
limitations: z.array(z.string()).default([]),
})
.strict();
@@ -290,7 +287,7 @@ export const parseFunctionDossier = (
): Result<JsonValue, AnalysisOutputError> => {
const parsed = functionDossierSchema.safeParse(value);
return parsed.success
? ok(jsonValueSchema.parse(parsed.data))
? ok(parsed.data)
: err(
new AnalysisOutputError(
"analyze_function",
+6 -1
View File
@@ -16,6 +16,10 @@ const projectIssue = (
const path = issue.path.flatMap((part) =>
typeof part === "string" || typeof part === "number" ? [part] : [],
);
if (issue.code === "invalid_union")
return issue.errors.flatMap((branch) =>
branch.flatMap((branchIssue) => projectIssue(branchIssue, input)),
);
if (issue.code === "unrecognized_keys")
return issue.keys.map((key) => ({
path: [...path, key],
@@ -62,7 +66,8 @@ const valueAtPath = (
let current = input;
for (const part of path) {
if (typeof current !== "object" || current === null) return undefined;
current = (current as Readonly<Record<string | number, unknown>>)[part];
const next: unknown = Reflect.get(current, part);
current = next;
}
return current;
};
+28 -29
View File
@@ -53,36 +53,35 @@ export type InvestigationRunOptions = z.infer<
>;
/** Explicit write approval and two local versions for an automatic run. */
export const crossVersionInvestigationInputSchema = z
.object({
approved: z.literal(true),
workspace_path: z.string().min(1).max(4_096),
workspace_name: z.string().trim().min(1).max(200).default("default"),
expected_workspace_revision: z.number().int().min(1).optional(),
replay_run_id: z
.string()
.regex(/^run_[a-f0-9]{64}$/u)
.optional(),
left_path: z.string().min(1).max(4_096),
right_path: z.string().min(1).max(4_096),
integrity_policy: z.enum(["fail", "record-and-continue"]).default("fail"),
integrity_continue_approved: z.boolean().default(false),
const crossVersionInvestigationFacts = {
approved: z.literal(true),
workspace_path: z.string().min(1).max(4_096),
workspace_name: z.string().trim().min(1).max(200).default("default"),
expected_workspace_revision: z.number().int().min(1).optional(),
replay_run_id: z
.string()
.regex(/^run_[a-f0-9]{64}$/u)
.optional(),
left_path: z.string().min(1).max(4_096),
right_path: z.string().min(1).max(4_096),
options: investigationRunOptionsSchema.default(
DEFAULT_INVESTIGATION_RUN_OPTIONS,
),
} as const;
export const crossVersionInvestigationInputSchema = z.union([
z.object({
...crossVersionInvestigationFacts,
integrity_policy: z.literal("fail").default("fail"),
integrity_continue_approved: z.literal(false).default(false),
max_integrity_mismatches: z.number().int().min(1).max(100).default(10),
options: investigationRunOptionsSchema.default(
DEFAULT_INVESTIGATION_RUN_OPTIONS,
),
})
.superRefine((input, context) => {
if (
input.integrity_policy === "record-and-continue" &&
input.integrity_continue_approved !== true
)
context.addIssue({
code: "custom",
path: ["integrity_continue_approved"],
message: "record-and-continue requires explicit approval",
});
});
}),
z.object({
...crossVersionInvestigationFacts,
integrity_policy: z.literal("record-and-continue"),
integrity_continue_approved: z.literal(true),
max_integrity_mismatches: z.number().int().min(1).max(100).default(10),
}),
]);
export type CrossVersionInvestigationInput = z.infer<
typeof crossVersionInvestigationInputSchema
+121 -98
View File
@@ -114,46 +114,61 @@ const determinismSchema = z
})
.strict();
const controlledReplayInputShape = {
left: replaySideSchema,
right: replaySideSchema.optional(),
cases: z.array(explicitCaseSchema).max(128).default([]),
generator: generatorSchema.optional(),
determinism: determinismSchema.default({
clock_iso: "2000-01-01T00:00:00.000Z",
random_seed: 0,
locale: "en-US",
timezone: "UTC",
platform: "linux",
}),
limits: replayLimitsSchema.default({
wall_time_ms: 3_000,
memory_bytes: 128 * 1024 * 1024,
tasks: 8,
cpu_quota_percent: 50,
tmpfs_bytes: 16 * 1024 * 1024,
module_bytes: 4 * 1024 * 1024,
input_bytes: 256 * 1024,
protocol_bytes: 16 * 1024 * 1024,
output_bytes: 512 * 1024,
stderr_bytes: 32 * 1024,
result_depth: 16,
result_nodes: 10_000,
}),
reproducer_export: z
.strictObject({
path: absolutePathSchema,
approved: z.literal(true),
include_sources: z.boolean().default(false),
})
.optional(),
} as const;
/** Parse a replay request that can only construct a plan. */
export const controlledReplayPlanInputSchema = z.strictObject({
...controlledReplayInputShape,
mode: z.literal("plan"),
});
/** Parse a replay request carrying literal approval for one exact plan. */
export const controlledReplayExecutionInputSchema = z.strictObject({
...controlledReplayInputShape,
mode: z.literal("execute"),
approved: z.literal(true),
plan_digest: digestSchema,
});
/** Parse a controlled replay request into its legal plan or execution state. */
export const controlledReplayInputSchema = z
.object({
mode: z.enum(["plan", "execute"]),
left: replaySideSchema,
right: replaySideSchema.optional(),
cases: z.array(explicitCaseSchema).max(128).default([]),
generator: generatorSchema.optional(),
determinism: determinismSchema.default({
clock_iso: "2000-01-01T00:00:00.000Z",
random_seed: 0,
locale: "en-US",
timezone: "UTC",
platform: "linux",
}),
limits: replayLimitsSchema.default({
wall_time_ms: 3_000,
memory_bytes: 128 * 1024 * 1024,
tasks: 8,
cpu_quota_percent: 50,
tmpfs_bytes: 16 * 1024 * 1024,
module_bytes: 4 * 1024 * 1024,
input_bytes: 256 * 1024,
protocol_bytes: 16 * 1024 * 1024,
output_bytes: 512 * 1024,
stderr_bytes: 32 * 1024,
result_depth: 16,
result_nodes: 10_000,
}),
approved: z.boolean().default(false),
plan_digest: digestSchema.optional(),
reproducer_export: z
.object({
path: absolutePathSchema,
approved: z.boolean(),
include_sources: z.boolean().default(false),
})
.strict()
.optional(),
})
.strict()
.discriminatedUnion("mode", [
controlledReplayPlanInputSchema,
controlledReplayExecutionInputSchema,
])
.superRefine((value, context) => {
if (value.cases.length === 0 && value.generator === undefined)
context.addIssue({
@@ -167,15 +182,6 @@ export const controlledReplayInputSchema = z
path: ["generator", "count"],
message: "Explicit and generated replay cases must total at most 128",
});
if (
value.mode === "execute" &&
(value.approved !== true || value.plan_digest === undefined)
)
context.addIssue({
code: "custom",
path: ["approved"],
message: "Execution requires literal approval and a plan digest",
});
});
const moduleCommitmentSchema = z
@@ -216,7 +222,7 @@ const replayPlanSchema = z
filesystem: z
.object({
host_writes: z.literal(false),
private_tmpfs_bytes: z.number().int(),
private_tmpfs_bytes: z.number().int().nonnegative(),
})
.strict(),
runtime: z
@@ -273,34 +279,45 @@ const replayPlanSchema = z
})
.strict();
const replayOutcomeSchema = z
const replayOutcomeFacts = {
case_id: z.string(),
input_sha256: digestSchema,
} as const;
const replayExceptionSchema = z
.object({
case_id: z.string(),
outcome: z.enum([
"return",
"exception",
"serialization_error",
"denied",
"timeout",
"oom",
"crash",
"cancelled",
"protocol_error",
]),
value: z.json().optional(),
exception: z
.object({
name: z.string(),
message: z.string(),
stack: z.string().nullable(),
})
.strict()
.optional(),
input_sha256: digestSchema,
output_sha256: digestSchema.nullable(),
truncated: z.boolean(),
name: z.string(),
message: z.string(),
stack: z.string().nullable(),
})
.strict();
const replayOutcomeSchema = z.discriminatedUnion("outcome", [
z.strictObject({
...replayOutcomeFacts,
outcome: z.literal("return"),
value: z.json(),
output_sha256: digestSchema,
truncated: z.literal(false),
}),
z.strictObject({
...replayOutcomeFacts,
outcome: z.enum(["exception", "serialization_error", "denied"]),
exception: z.object(replayExceptionSchema.shape).strict(),
output_sha256: digestSchema,
truncated: z.literal(false),
}),
z.strictObject({
...replayOutcomeFacts,
outcome: z.enum(["timeout", "oom", "crash", "cancelled"]),
output_sha256: z.null(),
truncated: z.literal(false),
}),
z.strictObject({
...replayOutcomeFacts,
outcome: z.literal("protocol_error"),
output_sha256: z.null(),
truncated: z.literal(true),
}),
]);
export const replayExecutionResultSchema = z
.object({
@@ -360,31 +377,37 @@ export const replayEvidenceSchema = evidenceEnvelopeSchema
.omit({ normalized_result: true })
.extend({ normalized_result: replayExecutionResultSchema });
export const controlledReplayOutputSchema = z
.object({
phase: z.enum(["plan", "execute"]),
plan: replayPlanSchema.nullable(),
source_evidence: z.array(replayEvidenceSchema),
evidence: replayEvidenceSchema.nullable(),
})
.strict()
.superRefine((value, context) => {
if (
(value.phase === "plan" &&
(value.plan === null ||
value.evidence !== null ||
value.source_evidence.length !== 0)) ||
(value.phase === "execute" &&
(value.plan !== null ||
value.evidence === null ||
value.source_evidence.length === 0))
)
context.addIssue({
code: "custom",
message: "Replay output phase does not match its payload",
});
});
/** A replay plan result with no claimed runtime observation. */
export const controlledReplayPlanOutputSchema = z.strictObject({
phase: z.literal("plan"),
plan: replayPlanSchema,
source_evidence: z
.array(replayEvidenceSchema)
.length(0)
.brand<"NoReplayEvidence">(),
evidence: z.null(),
});
/** An executed replay result with its required source and aggregate Evidence. */
export const controlledReplayExecutionOutputSchema = z.strictObject({
phase: z.literal("execute"),
plan: z.null(),
source_evidence: z.array(replayEvidenceSchema).min(1),
evidence: replayEvidenceSchema,
});
/** Parse replay output into its legal plan or execution state. */
export const controlledReplayOutputSchema = z.discriminatedUnion("phase", [
controlledReplayPlanOutputSchema,
controlledReplayExecutionOutputSchema,
]);
export type ControlledReplayInput = z.infer<typeof controlledReplayInputSchema>;
export type ControlledReplayExecutionInput = z.infer<
typeof controlledReplayExecutionInputSchema
>;
export type ControlledReplayExecutionOutput = z.infer<
typeof controlledReplayExecutionOutputSchema
>;
export type ReplayPlan = z.infer<typeof replayPlanSchema>;
export type ReplayExecutionResult = z.infer<typeof replayExecutionResultSchema>;
@@ -24,10 +24,8 @@ interface GraphCoverageFacts {
readonly projectionOmissions: number;
readonly knownOmissions: number;
readonly omissionsKnown: boolean;
readonly inputTruncated: boolean;
readonly inputStatus: "complete" | "partial" | "truncated";
readonly outputTruncated: boolean;
readonly truncated: boolean;
readonly complete: boolean;
}
/** Combined graph plus omissions introduced while merging its observations. */
@@ -66,7 +64,7 @@ export const buildReconciledApplicationGraph = (
"Runtime presence is bounded to passive capture windows and does not prove feature execution.",
"Cross-layer observed_as edges are inferences; digest equality proves byte identity only.",
"Source-map relationships retain their original static authority and are not promoted into runtime matches.",
...(facts.inputTruncated
...(facts.inputStatus === "truncated"
? [
"One or more source graphs or passive captures were incomplete or truncated.",
]
@@ -154,6 +152,12 @@ const graphCoverageFacts = (
const inputTruncated =
input.layers.some(({ graph }) => graph.coverage.truncated) ||
captureTruncated;
const inputComplete =
input.layers.every(({ graph }) => graph.coverage.status === "complete") &&
input.captures.every(
({ inspection }) =>
inspection.completeness.status === "complete_within_window",
);
const outputTruncated = projectionOmissions > 0;
const sourceOmissions = input.layers.reduce(
(total, { graph }) => total + (graph.coverage.omitted_count ?? 0),
@@ -167,17 +171,12 @@ const graphCoverageFacts = (
projectionOmissions,
knownOmissions: projectionOmissions + sourceOmissions,
omissionsKnown,
inputTruncated,
inputStatus: inputTruncated
? "truncated"
: inputComplete
? "complete"
: "partial",
outputTruncated,
truncated: inputTruncated || outputTruncated,
complete:
!inputTruncated &&
!outputTruncated &&
input.layers.every(({ graph }) => graph.coverage.status === "complete") &&
input.captures.every(
({ inspection }) =>
inspection.completeness.status === "complete_within_window",
),
};
};
@@ -186,15 +185,15 @@ const graphCoverage = (
facts: GraphCoverageFacts,
nodeCount: number,
): JavaScriptApplicationGraph["coverage"] =>
facts.complete
facts.inputStatus === "complete" && !facts.outputTruncated
? { status: "complete", truncated: false, omitted_count: 0, limits: [] }
: facts.truncated
: facts.inputStatus === "truncated" || facts.outputTruncated
? {
status: "partial",
truncated: true,
omitted_count: facts.omissionsKnown ? facts.knownOmissions : null,
limits: [
...(facts.inputTruncated
...(facts.inputStatus === "truncated"
? [
{
name: "runtime-reconciliation-input-coverage",
@@ -81,14 +81,16 @@ const reconcileEntity = (
const combined = content.filter((candidate) =>
locatedKeys.has(candidateKey(candidate)),
);
if (combined.length === 1)
return matched(entity, combined[0]!, {
const combinedCandidate = combined.at(0);
if (combined.length === 1 && combinedCandidate !== undefined)
return matched(entity, combinedCandidate, {
basis: "content-and-location",
confidence: "high",
reason: "content-and-location-match",
});
if (content.length === 1) {
const candidate = content[0]!;
const contentCandidate = content.at(0);
if (content.length === 1 && contentCandidate !== undefined) {
const candidate = contentCandidate;
const digestBasis = candidate.digests.find(
({ sha256 }) => sha256 === entity.sourceSha256,
)?.basis;
@@ -123,8 +125,9 @@ const reconcileEntity = (
});
}
if (locations.length === 1) {
const located = locations[0]!;
const location = locations.at(0);
if (locations.length === 1 && location !== undefined) {
const located = location;
return matched(entity, located.candidate, {
basis: located.mapping.basis,
confidence: "medium",
@@ -314,52 +317,57 @@ const reconciliationEvidence = (
layer: ParsedStaticLayer,
basis: JavaScriptRuntimeReconciliationItem["basis"],
confidence: JavaScriptRuntimeReconciliationItem["confidence"],
): ApplicationGraphEvidence => ({
authority: "cross-layer-reconciliation",
state: "inferred",
confidence: confidence === "medium" ? "medium" : "high",
artifact:
entity.sourceSha256 === null
? {
available: false,
reason: "not-observed",
detail: "Runtime source bytes were not captured for this mapping.",
}
: {
available: true,
artifact_id: `art_${entity.sourceSha256}`,
sha256: entity.sourceSha256,
},
location: entity.node.observations[0]!.evidence.location,
extractor: {
name: "rea-javascript-runtime-reconciliation",
version: "1",
operation: "reconcile_javascript_runtime",
executable_sha256: null,
},
coverage:
layer.graph.coverage.status === "complete" &&
entity.capture.scriptsCompleteWithinScope
? { status: "complete", truncated: false, omitted_count: 0, limits: [] }
: {
status: "partial",
truncated: false,
omitted_count: null,
limits: [],
},
limitations: [
basis === "content-sha256" ||
basis === "module-source-sha256" ||
basis === "content-and-location"
? "Equal content digests establish byte identity, not execution causality."
: "Location correspondence is inferred from an artifact root or caller-declared mapping.",
"Passive script parsing or target presence does not prove feature execution.",
],
evidence_ids: [
layer.evidence.evidence_id,
entity.capture.evidence.evidence_id,
].sort(),
});
): ApplicationGraphEvidence => {
const observation = entity.node.observations.at(0);
if (observation === undefined)
throw new TypeError("Runtime reconciliation entity has no observation");
return {
authority: "cross-layer-reconciliation",
state: "inferred",
confidence: confidence === "medium" ? "medium" : "high",
artifact:
entity.sourceSha256 === null
? {
available: false,
reason: "not-observed",
detail: "Runtime source bytes were not captured for this mapping.",
}
: {
available: true,
artifact_id: `art_${entity.sourceSha256}`,
sha256: entity.sourceSha256,
},
location: observation.evidence.location,
extractor: {
name: "rea-javascript-runtime-reconciliation",
version: "1",
operation: "reconcile_javascript_runtime",
executable_sha256: null,
},
coverage:
layer.graph.coverage.status === "complete" &&
entity.capture.scriptsCompleteWithinScope
? { status: "complete", truncated: false, omitted_count: 0, limits: [] }
: {
status: "partial",
truncated: false,
omitted_count: null,
limits: [],
},
limitations: [
basis === "content-sha256" ||
basis === "module-source-sha256" ||
basis === "content-and-location"
? "Equal content digests establish byte identity, not execution causality."
: "Location correspondence is inferred from an artifact root or caller-declared mapping.",
"Passive script parsing or target presence does not prove feature execution.",
],
evidence_ids: [
layer.evidence.evidence_id,
entity.capture.evidence.evidence_id,
].sort(),
};
};
const strongestLocationBasis = (
values: readonly LocatedCandidate[],
@@ -27,8 +27,7 @@ interface ReconciliationProjection {
interface CompletionFlags {
readonly outputTruncated: boolean;
readonly inputTruncated: boolean;
readonly inputPartial: boolean;
readonly inputStatus: "complete" | "partial" | "truncated";
}
/** Build and verify the deterministic caller-visible reconciliation result. */
@@ -150,36 +149,44 @@ const reconciliationCoverage = (
completion: CompletionFlags,
): JavaScriptRuntimeReconciliationResult["coverage"] => ({
status:
completion.outputTruncated || completion.inputTruncated
completion.outputTruncated || completion.inputStatus === "truncated"
? "truncated"
: completion.inputPartial
: completion.inputStatus === "partial"
? "partial"
: "complete-within-inputs",
truncated: completion.outputTruncated || completion.inputTruncated,
truncated:
completion.outputTruncated || completion.inputStatus === "truncated",
omitted_runtime_entities: input.runtime.omittedEntities,
omitted_reconciliation_items: input.matching.omittedItems,
omitted_static_load_states: input.loadStates.omittedStates,
omitted_graph_items: input.omittedGraphItems,
});
const completionFlags = (input: ReconciliationProjection): CompletionFlags => ({
outputTruncated:
input.runtime.omittedEntities > 0 ||
input.matching.omittedItems > 0 ||
input.loadStates.omittedStates > 0 ||
input.omittedGraphItems > 0,
inputTruncated:
const completionFlags = (input: ReconciliationProjection): CompletionFlags => {
const inputTruncated =
input.layers.some(({ graph }) => graph.coverage.truncated) ||
input.captures.some(({ inspection }) =>
inspection.completeness.conditions.includes("truncated"),
),
inputPartial:
);
const inputPartial =
input.layers.some(({ graph }) => graph.coverage.status !== "complete") ||
input.captures.some(
({ inspection }) =>
inspection.completeness.status !== "complete_within_window",
),
});
);
return {
outputTruncated:
input.runtime.omittedEntities > 0 ||
input.matching.omittedItems > 0 ||
input.loadStates.omittedStates > 0 ||
input.omittedGraphItems > 0,
inputStatus: inputTruncated
? "truncated"
: inputPartial
? "partial"
: "complete",
};
};
const reconciliationLimitations = (completion: CompletionFlags): string[] =>
uniqueSorted([
@@ -189,7 +196,7 @@ const reconciliationLimitations = (completion: CompletionFlags): string[] =>
"Not-observed means absent from the bounded captures in scope, never globally unloaded.",
"Caller-declared file and URL mappings are inference inputs and do not expand CDP origin or filesystem-root authority.",
"Source-map authority remains separate from passive runtime authority.",
...(completion.inputPartial
...(completion.inputStatus !== "complete"
? ["One or more static graphs or passive captures were incomplete."]
: []),
...(completion.outputTruncated
+25 -11
View File
@@ -9,13 +9,19 @@ export interface KnownCollectionPage<Item> {
}
/** Fail-closed completeness derived from a known-total source page. */
export interface KnownPageCoverageAssessment {
readonly complete: boolean;
readonly sourceComplete: boolean;
export type KnownPageCoverageAssessment = {
readonly includedCount: number;
readonly omittedCount: number;
readonly sourceOmittedCount: number;
}
} & (
| {
readonly complete: true;
readonly sourceComplete: true;
readonly omittedCount: 0;
readonly sourceOmittedCount: 0;
}
| { readonly complete: false; readonly sourceComplete: boolean }
);
/**
* Assess source-page and downstream-projection completeness without treating an
@@ -37,11 +43,19 @@ export const assessKnownPageCoverage = <Item>(
page.returned === page.total &&
sourceOmittedCount === 0;
const omittedCount = Math.max(0, page.total - retainedCount);
return {
complete: sourceComplete && omittedCount === 0,
sourceComplete,
includedCount: retainedCount,
omittedCount,
sourceOmittedCount,
};
return sourceComplete && omittedCount === 0
? {
complete: true,
sourceComplete: true,
includedCount: retainedCount,
omittedCount: 0,
sourceOmittedCount: 0,
}
: {
complete: false,
sourceComplete,
includedCount: retainedCount,
omittedCount,
sourceOmittedCount,
};
};
+31 -21
View File
@@ -16,25 +16,35 @@ const inferenceEvidenceSchema = z
})
.strict();
const inferredBoundaryTypeSchema = z
.object({
role: z.enum(["return", "parameter"]),
ordinal: z.number().int().min(0).nullable(),
name: z.string().min(1).nullable(),
data_type: z.string().min(1),
size_bytes: z.number().int().min(0).nullable(),
storage: z.string().min(1).nullable(),
confidence: inferenceConfidenceSchema,
evidence: z.array(inferenceEvidenceSchema).min(1),
decompiler_artifacts: z.array(
z.enum([
"recovered-signature",
"register-or-stack-storage",
"compiler-generated-variable",
]),
),
})
.strict();
const inferredBoundaryTypeFacts = {
ordinal: z.number().int().min(0).nullable(),
name: z.string().min(1).nullable(),
data_type: z.string().min(1),
size_bytes: z.number().int().min(0).nullable(),
storage: z.string().min(1).nullable(),
confidence: inferenceConfidenceSchema,
evidence: z.array(inferenceEvidenceSchema).min(1),
decompiler_artifacts: z.array(
z.enum([
"recovered-signature",
"register-or-stack-storage",
"compiler-generated-variable",
]),
),
} as const;
const inferredReturnTypeSchema = z.strictObject({
...inferredBoundaryTypeFacts,
role: z.literal("return"),
ordinal: z.null(),
name: z.null(),
});
const inferredParameterTypeSchema = z.strictObject({
...inferredBoundaryTypeFacts,
role: z.literal("parameter"),
ordinal: z.number().int().min(0),
});
const jumpTableDataSourceSchema = z
.object({
@@ -77,8 +87,8 @@ const availableNativeApiBoundarySchema = z
provenance: z.string().min(1),
signature_source: z.string().min(1),
calling_convention: z.string().min(1),
return_type: inferredBoundaryTypeSchema,
parameters: z.array(inferredBoundaryTypeSchema),
return_type: inferredReturnTypeSchema,
parameters: z.array(inferredParameterTypeSchema),
parameters_truncated: z.boolean(),
jump_tables: z.array(inferredJumpTableSchema),
jump_tables_truncated: z.boolean(),
+17 -14
View File
@@ -1,8 +1,9 @@
import { z } from "zod";
import {
controlledReplayInputSchema,
controlledReplayOutputSchema,
controlledReplayExecutionOutputSchema,
controlledReplayPlanInputSchema,
controlledReplayPlanOutputSchema,
} from "./javascriptReplay.js";
import {
javascriptExportInstrumentationInputSchema,
@@ -12,22 +13,24 @@ import { runtimeCharacterizationPlanSchema } from "./runtimeCharacterization.js"
import { evidenceRecordSchema } from "./evidence.js";
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
const nodeCharacterizationExpectedEffectSchema = z.enum([
"pure",
"observation-only",
]);
const nodeRuntimeCharacterizationPlanSchema =
runtimeCharacterizationPlanSchema.extend({
expected_effect: nodeCharacterizationExpectedEffectSchema,
});
export const nodeCharacterizationPreparationInputSchema = z
.strictObject({
preparation_approved: z.literal(true),
selected_alias: z.string().min(1).max(200),
expected_effect: z.enum(["pure", "observation-only"]),
expected_effect: nodeCharacterizationExpectedEffectSchema,
instrumentation: javascriptExportInstrumentationInputSchema,
replay: controlledReplayInputSchema,
replay: controlledReplayPlanInputSchema,
})
.superRefine((input, context) => {
if (input.replay.mode !== "plan")
context.addIssue({
code: "custom",
path: ["replay", "mode"],
message: "Characterization preparation requires replay plan mode",
});
const selected = input.replay.left.modules.filter(
({ alias }) => alias === input.selected_alias,
);
@@ -68,20 +71,20 @@ export const nodeCharacterizationExecutionInputSchema = z.strictObject({
export const nodeCharacterizationPreparationOutputSchema = z.strictObject({
schema_version: z.literal(1),
phase: z.literal("preparation"),
plan: runtimeCharacterizationPlanSchema,
plan: nodeRuntimeCharacterizationPlanSchema,
transformation: javascriptExportTransformationManifestSchema,
transformation_evidence: evidenceRecordSchema,
replay: controlledReplayOutputSchema,
replay: controlledReplayPlanOutputSchema,
});
export const nodeCharacterizationExecutionOutputSchema = z.strictObject({
schema_version: z.literal(1),
phase: z.literal("execution"),
plan: runtimeCharacterizationPlanSchema,
plan: nodeRuntimeCharacterizationPlanSchema,
transformation: javascriptExportTransformationManifestSchema,
transformation_evidence: evidenceRecordSchema,
evidence: evidenceRecordSchema,
replay: controlledReplayOutputSchema,
replay: controlledReplayExecutionOutputSchema,
});
export type NodeCharacterizationPreparationInput = z.infer<
@@ -206,14 +206,16 @@ const replayTransitions = (
(run.controls[controlIndex]?.after_capture_order ??
Number.MAX_SAFE_INTEGER) < observation.capture_order
) {
const control = run.controls[controlIndex]!;
const control = run.controls[controlIndex];
if (control === undefined) break;
advanceControl(control, controlIndex);
controlIndex += 1;
}
advance({ kind: "observation", observation });
}
for (; controlIndex < run.controls.length; controlIndex += 1) {
const control = run.controls[controlIndex]!;
const control = run.controls[controlIndex];
if (control === undefined) break;
advanceControl(control, controlIndex);
}
require(transitionIndex ===
@@ -237,10 +239,11 @@ const validateControls = (
require(admittedOrders.has(
control.after_capture_order,
), `reactive_run.controls[${String(index)}].after_capture_order`, "reactive control cutoff must identify the last admitted observation");
const previous = run.controls.at(index - 1);
require(index === 0 ||
control.after_capture_order >=
run.controls[index - 1]!
.after_capture_order, `reactive_run.controls[${String(index)}].after_capture_order`, "reactive control cutoffs must be ordered");
(previous !== undefined &&
control.after_capture_order >=
previous.after_capture_order), `reactive_run.controls[${String(index)}].after_capture_order`, "reactive control cutoffs must be ordered");
}
};
+16 -6
View File
@@ -18,9 +18,16 @@ type RequireInvariant = (
const orderedTimestamps = (
values: readonly { readonly at_ms: number }[],
): boolean =>
values.every(
(value, index) => index === 0 || value.at_ms >= values[index - 1]!.at_ms,
);
values.every((value, index) => {
const previous = values[index - 1];
return previous === undefined || value.at_ms >= previous.at_ms;
});
const transitionsAreContiguous = (
previous: ProcessCapture["replay_transitions"][number] | undefined,
current: ProcessCapture["replay_transitions"][number],
): boolean =>
previous !== undefined && previous.state_after === current.state_before;
const validateCommitments = (
capture: ProcessCapture,
@@ -156,7 +163,7 @@ const shimPlans = (capture: ProcessCapture) =>
typeof shim.name === "string" &&
Array.isArray(shim.routes)
? shim.routes.map((route, routeIndex) => ({
command: shim.name as string,
command: shim.name,
route,
routeIndex,
}))
@@ -295,9 +302,12 @@ const validateReplayEvents = (
if (index === 0)
require(transition.state_before ===
machine?.initial_state, "replay_transitions", "first replay transition does not start at the declared initial state");
const previous = capture.replay_transitions[index - 1];
if (index > 0)
require(capture.replay_transitions[index - 1]!.state_after ===
transition.state_before, "replay_transitions", "replay transition states are not contiguous");
require(transitionsAreContiguous(
previous,
transition,
), "replay_transitions", "replay transition states are not contiguous");
}
};
+3 -2
View File
@@ -248,8 +248,9 @@ const assertComparable = (
...validateProcessCapture(left),
...validateProcessCapture(right),
];
if (invalid.length > 0)
throw new TypeError(`Invalid Process Capture v4: ${invalid[0]!.path}`);
const firstInvalid = invalid.at(0);
if (firstInvalid !== undefined)
throw new TypeError(`Invalid Process Capture v4: ${firstInvalid.path}`);
if (
left.schema_version !== right.schema_version ||
left.manifest.comparison_contract_sha256 !==
+6 -6
View File
@@ -100,15 +100,15 @@ type ProjectedRecord = Omit<
const atMilliseconds = (value: unknown): number | null => {
if (typeof value !== "object" || value === null) return null;
for (const name of ["at_ms", "dispatched_at_ms"])
if (name in value) {
const candidate = value[name as keyof typeof value];
if (typeof candidate === "number" && Number.isSafeInteger(candidate))
return candidate;
}
if ("at_ms" in value && isSafeMillisecond(value.at_ms)) return value.at_ms;
if ("dispatched_at_ms" in value && isSafeMillisecond(value.dispatched_at_ms))
return value.dispatched_at_ms;
return null;
};
const isSafeMillisecond = (value: unknown): value is number =>
typeof value === "number" && Number.isSafeInteger(value);
/** Derive the stable capture-local identity for one normalized observation. */
export const processObservationSubject = (
source: ProcessObservationSource,
+19 -11
View File
@@ -10,13 +10,14 @@ import {
import type { ProcessReactiveSnapshot } from "./processReactiveRuntime.js";
/** Internal bounded trigger-match result used by the pure reducer. */
export interface ProcessReactiveTriggerMatch {
readonly matched: boolean;
export type ProcessReactiveTriggerMatch = {
readonly eventIds: readonly string[];
readonly consumeIds: readonly string[];
readonly lastOrder: number;
readonly overflow: boolean;
}
} & (
| { readonly matched: true; readonly overflow: false }
| { readonly matched: false; readonly overflow: boolean }
);
interface EvaluationBudget {
remaining: number;
@@ -203,13 +204,20 @@ const matchTerminalText = (
const mergeMatches = (
matches: readonly ProcessReactiveTriggerMatch[],
): ProcessReactiveTriggerMatch => ({
matched: matches.every(({ matched }) => matched),
eventIds: [...new Set(matches.flatMap(({ eventIds }) => eventIds))],
consumeIds: [...new Set(matches.flatMap(({ consumeIds }) => consumeIds))],
lastOrder: Math.max(-1, ...matches.map(({ lastOrder }) => lastOrder)),
overflow: matches.some(({ overflow }) => overflow),
});
): ProcessReactiveTriggerMatch => {
const base = {
eventIds: [...new Set(matches.flatMap(({ eventIds }) => eventIds))],
consumeIds: [...new Set(matches.flatMap(({ consumeIds }) => consumeIds))],
lastOrder: Math.max(-1, ...matches.map(({ lastOrder }) => lastOrder)),
};
return matches.every(({ matched }) => matched)
? { ...base, matched: true, overflow: false }
: {
...base,
matched: false,
overflow: matches.some(({ overflow }) => overflow),
};
};
const matchEarliestPrefix = (
trigger: ProcessReactiveTrigger,
+11 -3
View File
@@ -43,6 +43,10 @@ const applyProcessReactiveTransition = (input: {
>[];
readonly evaluations: readonly ProcessReactiveEvaluation[];
}): ProcessReactiveDecision => {
if (input.effectResults.length !== input.transition.actions.length)
throw new TypeError(
"Reactive transition effects do not match the admitted actions",
);
const outcome =
input.transition.target.kind === "finish"
? input.transition.target.outcome
@@ -66,13 +70,17 @@ const applyProcessReactiveTransition = (input: {
const consumed = new Set(input.snapshot.consumed_event_ids);
for (const eventId of input.consumeEventIds) consumed.add(eventId);
const checkpoints = [...input.snapshot.checkpoints];
for (const [index, action] of input.transition.actions.entries())
for (const [index, action] of input.transition.actions.entries()) {
const effect = input.effectResults[index];
if (effect === undefined)
throw new TypeError("Reactive transition effect is missing");
if (action.type === "checkpoint")
checkpoints.push({
name: action.name,
event_id: input.effectResults[index]!.observation.event_id,
capture_order: input.effectResults[index]!.observation.capture_order,
event_id: effect.observation.event_id,
capture_order: effect.observation.capture_order,
});
}
const completedCaptureOrder = Math.max(
input.observation.capture_order,
...input.effectResults.map(({ observation }) => observation.capture_order),
+22 -9
View File
@@ -326,7 +326,9 @@ export const processScenarioSchema = z
.strict()
.superRefine((scenario, context) => {
for (let index = 1; index < scenario.events.length; index += 1) {
if (scenario.events[index]!.at_ms < scenario.events[index - 1]!.at_ms) {
const event = scenario.events[index];
const previous = scenario.events[index - 1];
if (eventsOutOfOrder(event, previous)) {
context.addIssue({
code: "custom",
message: "events must be ordered by at_ms",
@@ -408,6 +410,12 @@ export const processScenarioSchema = z
});
});
const eventsOutOfOrder = (
event: { readonly at_ms: number } | undefined,
previous: { readonly at_ms: number } | undefined,
): boolean =>
event !== undefined && previous !== undefined && event.at_ms < previous.at_ms;
/** Parsed instructions and resource bounds for one process experiment. */
export type ProcessScenario = z.infer<typeof processScenarioSchema>;
@@ -415,15 +423,20 @@ export type ProcessScenario = z.infer<typeof processScenarioSchema>;
export const parseProcessScenario = (input: unknown): ProcessScenario =>
processScenarioSchema.parse(input);
/** Operator-owned ceiling applied in addition to per-scenario approval. */
export interface ProcessExecutionPolicy {
readonly enabled: boolean;
readonly executableRoots: readonly string[];
readonly workingRoots: readonly string[];
/** Complete operator-owned ceiling for enabled process capture. */
export interface EnabledProcessExecutionPolicy {
readonly status: "enabled";
readonly executableRoots: readonly [string, ...string[]];
readonly workingRoots: readonly [string, ...string[]];
readonly allowedEnvironment: readonly string[];
readonly allowExternalNetwork: boolean;
readonly networkAccess: "none" | "external";
}
/** Parsed operator-owned process-capture policy. */
export type ProcessExecutionPolicy =
| { readonly status: "disabled" }
| EnabledProcessExecutionPolicy;
/** Explicit authorization result; denial reasons are safe to show callers. */
export type ProcessPolicyDecision =
| { readonly allowed: true }
@@ -449,9 +462,9 @@ export const authorizeProcessScenario = (
scenario: ProcessScenario,
policy: ProcessExecutionPolicy,
): ProcessPolicyDecision => {
if (!policy.enabled)
if (policy.status === "disabled")
return { allowed: false, reason: "process capture is disabled" };
if (scenario.network_access === "host" && !policy.allowExternalNetwork)
if (scenario.network_access === "host" && policy.networkAccess === "none")
return {
allowed: false,
reason: "host network access is not approved by operator policy",
+3 -2
View File
@@ -32,9 +32,10 @@ export const compareProcessTraces = (
...validateProcessCapture(left),
...validateProcessCapture(right),
];
if (captureIssues.length > 0)
const firstCaptureIssue = captureIssues.at(0);
if (firstCaptureIssue !== undefined)
throw new TypeError(
`Invalid Process Capture v4: ${captureIssues[0]!.path}`,
`Invalid Process Capture v4: ${firstCaptureIssue.path}`,
);
const specification =
processTraceSpecificationSchema.parse(specificationInput);
+8 -7
View File
@@ -128,7 +128,7 @@ export function decodeJsonRpc(rawPayload: Uint8Array): {
truncated: boolean;
} {
const text = new TextDecoder().decode(rawPayload);
const parsed = JSON.parse(text);
const parsed = jsonValueSchema.parse(JSON.parse(text));
const fields: DecodedField[] = [];
if (typeof parsed === "object" && parsed !== null) {
@@ -144,7 +144,7 @@ export function decodeJsonRpc(rawPayload: Uint8Array): {
fields.push({
path: key,
wire_type: "json",
value: value as never,
value,
inferred: false,
});
}
@@ -164,7 +164,8 @@ export function decodeMessagePack(rawPayload: Uint8Array): {
if (rawPayload.length === 0) {
return { decoded_fields: [], truncated: false };
}
const tag = rawPayload[0]!;
const tag = rawPayload[0];
if (tag === undefined) return { decoded_fields: [], truncated: false };
// Map type: 0x80-0x8f (fixmap), 0xde (map16), 0xdf (map32)
if ((tag >= 0x80 && tag <= 0x8f) || tag === 0xde || tag === 0xdf) {
fields.push({
@@ -217,10 +218,10 @@ export function decodeGrpcFrame(rawPayload: Uint8Array): {
}
const compressed = rawPayload[0] !== 0;
const length =
(rawPayload[1]! << 24) |
(rawPayload[2]! << 16) |
(rawPayload[3]! << 8) |
rawPayload[4]!;
((rawPayload[1] ?? 0) << 24) |
((rawPayload[2] ?? 0) << 16) |
((rawPayload[3] ?? 0) << 8) |
(rawPayload[4] ?? 0);
return {
decoded_fields: [
{
+5 -3
View File
@@ -40,7 +40,7 @@ const replayEventHeadersSchema = z
});
const replayEventFields = {
at_ms: z.number().int().nonnegative().safe(),
at_ms: z.number().int().safe().nonnegative(),
path: z.string().startsWith("/").max(8_192),
headers: replayEventHeadersSchema,
body: z.string().max(1_000_000),
@@ -125,7 +125,8 @@ export type ReplayMachineDecision =
const parseJson = (value: string): unknown => {
try {
return JSON.parse(value) as unknown;
const parsed: unknown = JSON.parse(value);
return parsed;
} catch {
return undefined;
}
@@ -148,7 +149,8 @@ const atPath = (
!Object.hasOwn(current, segment)
)
return undefined;
current = (current as Readonly<Record<string, unknown>>)[segment];
const next: unknown = Reflect.get(current, segment);
current = next;
}
return current;
};
+4 -6
View File
@@ -219,12 +219,10 @@ const comparisonCoverage = (
const scoringModel = (): SourceToBundleComparisonResult["scoring"] => ({
algorithm: "rea-source-to-bundle-signals/v1",
minimum_candidate_score: 20,
weights: Object.entries(SOURCE_TO_BUNDLE_SIGNAL_WEIGHTS).map(
([signal, weight]) => ({
signal: signal as keyof typeof SOURCE_TO_BUNDLE_SIGNAL_WEIGHTS,
weight,
}),
),
weights: SOURCE_TO_BUNDLE_SIGNAL_WEIGHTS.map(([signal, weight]) => ({
signal,
weight,
})),
});
const classifyMapping = (
@@ -9,14 +9,14 @@ const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
const nodeIdSchema = z.string().regex(/^jag_node_[a-f0-9]{64}$/u);
const boundedTextSchema = z.string().min(1).max(4_096);
export const SOURCE_TO_BUNDLE_SIGNAL_WEIGHTS = {
"exact-source-digest": 100,
"source-map-original-path": 70,
"current-path-exact": 60,
"current-path-suffix": 40,
"basename-match": 20,
"language-extension": 5,
} as const;
export const SOURCE_TO_BUNDLE_SIGNAL_WEIGHTS = [
["exact-source-digest", 100],
["source-map-original-path", 70],
["current-path-exact", 60],
["current-path-suffix", 40],
["basename-match", 20],
["language-extension", 5],
] as const;
const sourceToBundleSignalKindSchema = z.enum([
"exact-source-digest",
+10 -1
View File
@@ -53,6 +53,15 @@ const PATH_PROPERTIES = [
] as const;
const MAX_PATH_SUFFIXES = 128;
const signalWeight = (kind: SourceToBundleSignal["kind"]): number => {
const entry = SOURCE_TO_BUNDLE_SIGNAL_WEIGHTS.find(
([signal]) => signal === kind,
);
if (entry === undefined)
throw new TypeError(`Missing source-to-bundle signal weight: ${kind}`);
return entry[1];
};
/** Keep source-bearing application nodes in stable identifier order. */
export const sourceBearingNodes = (
nodes: readonly ApplicationNode[],
@@ -227,7 +236,7 @@ const signal = (
currentValues: readonly string[],
): SourceToBundleSignal => ({
kind,
weight: SOURCE_TO_BUNDLE_SIGNAL_WEIGHTS[kind],
weight: signalWeight(kind),
source_value: sourceValue,
current_values: [...new Set(currentValues)].sort(compareText).slice(0, 64),
});
+12 -8
View File
@@ -148,7 +148,9 @@ type Mapping = z.infer<typeof mappingSchema>;
type CorrelationItem = z.infer<typeof correlationItemSchema>;
type ComparisonStatus = z.infer<typeof comparisonStatusSchema>;
const EXPECTED = {
type ComparisonIdentity = readonly [string | readonly string[], string, string];
const EXPECTED: Readonly<Record<string, ComparisonIdentity>> = {
compare_artifacts: [
"rea.artifact-comparison/v1",
"rea-artifact-comparison",
@@ -164,7 +166,7 @@ const EXPECTED = {
"rea-process",
"REA deterministic process harness",
],
} as const;
};
/** Correlate only caller-declared static/runtime hypotheses. */
export const correlateStaticAndRuntime = (
@@ -307,11 +309,12 @@ const selectStatic = (
const matches = result.dimensions.filter(
({ dimension }) => dimension === selector.dimension,
);
if (matches.length !== 1)
const match = matches.at(0);
if (matches.length !== 1 || match === undefined)
throw new TypeError("Function selector must resolve exactly once");
return {
status: matches[0]!.status,
conclusion_kind: matches[0]!.conclusion_kind,
status: match.status,
conclusion_kind: match.conclusion_kind,
};
}
if (evidence.operation !== "compare_artifacts")
@@ -332,11 +335,12 @@ const selectStatic = (
const matches = result.changes.items.filter(
({ logical_path: path }) => path === selector.logical_path,
);
if (matches.length !== 1)
const match = matches.at(0);
if (matches.length !== 1 || match === undefined)
throw new TypeError(
"Artifact selector must resolve exactly one reported delta",
);
const status = matches[0]!.classification;
const status = match.classification;
return {
status,
conclusion_kind:
@@ -402,7 +406,7 @@ const parseRuntime = (input: unknown): Evidence => {
};
const assertComparisonIdentity = (evidence: Evidence): void => {
const expected = EXPECTED[evidence.operation as keyof typeof EXPECTED];
const expected = EXPECTED[evidence.operation];
if (
expected === undefined ||
!(Array.isArray(expected[0])
+15 -14
View File
@@ -1,6 +1,6 @@
import { z } from "zod";
import { inspectWebPageInputSchema } from "./browserObservation.js";
import { inspectWebPageWithSourceInputSchema } from "./browserObservation.js";
import { webTextArtifactSchema } from "./webContentArtifact.js";
const webBundleLimitsSchema = z.object({
@@ -24,12 +24,8 @@ const webBundleLimitsSchema = z.object({
});
/** Capture-and-analyze input with separate source and source-map approvals. */
export const analyzeWebBundleInputSchema = inspectWebPageInputSchema
.safeExtend({
include_script_sources: z.literal(true).default(true),
source_capture_approved: z.literal(true),
fetch_source_maps: z.boolean().default(false),
source_map_fetch_approved: z.boolean().default(false),
const analyzeWebBundleFactsSchema =
inspectWebPageWithSourceInputSchema.safeExtend({
analysis_limits: webBundleLimitsSchema.default({
max_findings: 1_000,
max_ast_nodes: 250_000,
@@ -39,14 +35,19 @@ export const analyzeWebBundleInputSchema = inspectWebPageInputSchema
max_source_map_mappings: 10_000,
max_original_sources: 2_000,
}),
})
});
export const analyzeWebBundleInputSchema = z
.union([
analyzeWebBundleFactsSchema.safeExtend({
fetch_source_maps: z.literal(false).default(false),
source_map_fetch_approved: z.literal(false).default(false),
}),
analyzeWebBundleFactsSchema.safeExtend({
fetch_source_maps: z.literal(true),
source_map_fetch_approved: z.literal(true),
}),
])
.superRefine((input, context) => {
if (input.fetch_source_maps && !input.source_map_fetch_approved)
context.addIssue({
code: "custom",
path: ["source_map_fetch_approved"],
message: "Source-map network fetch requires separate approval",
});
if (
input.analysis_limits.max_source_map_bytes >
input.analysis_limits.max_total_source_map_bytes
+16 -13
View File
@@ -405,22 +405,25 @@ const accessibilityProjection = (
includeText: boolean,
includeNodes: boolean,
): unknown => {
const result = {
total_nodes: accessibility.total_nodes,
} as { total_nodes: number; nodes?: readonly unknown[] };
if (!includeNodes) return result;
if (!includeNodes) return { total_nodes: accessibility.total_nodes };
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;
return {
total_nodes: accessibility.total_nodes,
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 }
: {}),
})),
};
};
const storageKeysComparable = (inspection: WebPageInspection): boolean =>