feat(native): add inspection primitives, dispatch traces and approved UI observation (#500)

* fix(hopper): normalize string-backed addresses and update verification

* feat(native): add inspection primitives, dispatch traces and approved UI observation

* test: prioritize real artifact E2E and captured golden regressions

* fix(process): queue observed output before reactive rendering actions

* test: prune redundant cases and strengthen boundary assertions

* fix(cli): route native value tracing through shared workflows

* test: replace synthetic success with real workflows and captured data

* fix(catalog): separate portable metadata from native host availability
This commit is contained in:
morluto
2026-10-04 16:02:36 +08:00
committed by GitHub
parent 0356f7677f
commit 4fbc501121
205 changed files with 8136 additions and 1816 deletions
+1 -1
View File
@@ -124,7 +124,7 @@ describe("analysis error projection: provider failures", () => {
code: "provider_unavailable",
details: { failure_code: code, exit_code: exitCode },
});
expect(projected.message.length).toBeGreaterThan(20);
expect(projected.message).toMatch(/\S/u);
expect(JSON.stringify(projected)).not.toContain("/proc/");
}
});
+96
View File
@@ -0,0 +1,96 @@
import { describe, expect, it } from "vitest";
import {
appleAssetCatalogInputSchema,
parseAppleAssetCatalogRecords,
projectAppleAssetCatalogPage,
} from "./appleAssetCatalog.js";
describe("compiled Apple asset catalog projection", () => {
it("preserves metadata and paginates across catalog boundaries", () => {
const catalogs = [
{
path: "Resources/A/Assets.car",
sha256: "a".repeat(64),
records: parseAppleAssetCatalogRecords([
{ AssetStorageVersion: 1, Platform: "ios" },
{
Name: "Toolbar",
RenditionName: "toolbar@2x.png",
Scale: 2,
Idiom: "iphone",
Locale: "en",
Appearance: "dark",
},
]),
},
{
path: "Resources/B/Assets.car",
sha256: "b".repeat(64),
records: parseAppleAssetCatalogRecords([
{
Name: "Toolbar",
RenditionName: "toolbar~ipad.png",
PixelWidth: 64,
},
]),
},
];
const first = projectAppleAssetCatalogPage({
targetSha256: "c".repeat(64),
catalogs,
offset: 0,
limit: 2,
resourceReferences: [
{
sourceNodeId: "ib:Main.nib:object:1",
sourcePath: "Main.nib",
sourceArchiveSha256: "d".repeat(64),
field: "imageName",
key: "Toolbar",
},
{
sourceNodeId: "ib:Main.nib:object:2",
sourcePath: "Main.nib",
sourceArchiveSha256: "d".repeat(64),
field: "imageName",
key: "Missing",
},
],
});
expect(first.records.map(({ kind }) => kind)).toEqual([
"catalog",
"rendition",
]);
expect(first.records[1]?.metadata.Scale).toBe(2);
expect(first.records[1]?.metadata.Idiom).toBe("iphone");
expect(first.records[1]?.metadata.Locale).toBe("en");
expect(first.records[1]?.metadata.Appearance).toBe("dark");
expect(first.resource_key_matches).toEqual([
expect.objectContaining({ status: "ambiguous", key: "Toolbar" }),
expect.objectContaining({ status: "unmatched", key: "Missing" }),
]);
expect(first.next_offset).toBe(2);
expect(first.truncated).toBe(true);
const second = projectAppleAssetCatalogPage({
targetSha256: "c".repeat(64),
catalogs,
offset: 2,
limit: 2,
});
expect(second.records[0]?.catalog_path).toBe("Resources/B/Assets.car");
expect(second.next_offset).toBeNull();
expect(second.total_records).toBe(3);
});
it("rejects malformed pages and invalid utility data", () => {
expect(appleAssetCatalogInputSchema.safeParse({ offset: -1 }).success).toBe(
false,
);
expect(() =>
parseAppleAssetCatalogRecords({ Name: "not an array" }),
).toThrow(/JSON array/u);
expect(() => parseAppleAssetCatalogRecords([null])).toThrow(/record 0/u);
});
});
+168
View File
@@ -0,0 +1,168 @@
import { z } from "zod";
import { jsonValueSchema } from "./jsonValue.js";
/** Caller-controlled page bounds for compiled Apple asset metadata. */
export const appleAssetCatalogInputSchema = z.strictObject({
offset: z.number().int().min(0).default(0),
limit: z.number().int().min(1).max(10_000).default(1_000),
});
const catalogSchema = z.strictObject({
path: z.string().min(1),
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
record_count: z.number().int().nonnegative(),
});
const recordSchema = z.strictObject({
catalog_path: z.string().min(1),
catalog_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
index: z.number().int().nonnegative(),
kind: z.enum(["catalog", "rendition"]),
asset_name: z.string().nullable(),
rendition_name: z.string().nullable(),
metadata: z.record(z.string(), jsonValueSchema),
});
const resourceKeyMatchSchema = z.strictObject({
source_node_id: z.string().min(1),
source_path: z.string().min(1),
source_archive_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
field: z.string().min(1),
key: z.string().min(1),
status: z.enum(["matched", "ambiguous", "unmatched"]),
renditions: z.array(
z.strictObject({
catalog_path: z.string().min(1),
catalog_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
record_index: z.number().int().nonnegative(),
rendition_name: z.string().nullable(),
}),
),
});
/** Normalized result returned by asset catalog inspection. */
export const appleAssetCatalogResultSchema = z.strictObject({
target_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
catalogs: z.array(catalogSchema),
total_records: z.number().int().nonnegative(),
offset: z.number().int().nonnegative(),
limit: z.number().int().positive(),
records: z.array(recordSchema),
resource_key_matches: z.array(resourceKeyMatchSchema),
next_offset: z.number().int().nonnegative().nullable(),
truncated: z.boolean(),
limitations: z.array(z.string()),
});
export type AppleAssetCatalogRecord = z.infer<typeof recordSchema>;
/** Parse assetutil JSON records without discarding format-specific metadata. */
export const parseAppleAssetCatalogRecords = (
value: unknown,
): readonly Readonly<
Record<string, ReturnType<typeof jsonValueSchema.parse>>
>[] => {
if (!Array.isArray(value))
throw new Error("assetutil output must be a JSON array");
return value.map((record, index) => {
const parsed = z.record(z.string(), jsonValueSchema).safeParse(record);
if (!parsed.success)
throw new Error(`assetutil record ${index} is not a JSON object`);
return parsed.data;
});
};
/** Project catalog records and apply stable global pagination. */
export const projectAppleAssetCatalogPage = (input: {
readonly targetSha256: string;
readonly catalogs: readonly {
readonly path: string;
readonly sha256: string;
readonly records: readonly Readonly<
Record<string, ReturnType<typeof jsonValueSchema.parse>>
>[];
}[];
readonly offset: number;
readonly limit: number;
readonly resourceReferences?: readonly {
readonly sourceNodeId: string;
readonly sourcePath: string;
readonly sourceArchiveSha256: string;
readonly field: string;
readonly key: string;
}[];
}) => {
const all = input.catalogs.flatMap((catalog) =>
catalog.records.map(
(metadata, index): AppleAssetCatalogRecord => ({
catalog_path: catalog.path,
catalog_sha256: catalog.sha256,
index,
kind:
typeof metadata.RenditionName === "string" ||
typeof metadata.Name === "string"
? "rendition"
: "catalog",
asset_name: typeof metadata.Name === "string" ? metadata.Name : null,
rendition_name:
typeof metadata.RenditionName === "string"
? metadata.RenditionName
: null,
metadata,
}),
),
);
const records = all.slice(input.offset, input.offset + input.limit);
const next = input.offset + records.length;
const recordsByAssetName = new Map<string, typeof all>();
for (const record of all) {
if (record.kind !== "rendition" || record.asset_name === null) continue;
const matches = recordsByAssetName.get(record.asset_name) ?? [];
matches.push(record);
recordsByAssetName.set(record.asset_name, matches);
}
const resourceKeyMatches = (input.resourceReferences ?? []).map((source) => {
const matches = recordsByAssetName.get(source.key) ?? [];
return {
source_node_id: source.sourceNodeId,
source_path: source.sourcePath,
source_archive_sha256: source.sourceArchiveSha256,
field: source.field,
key: source.key,
status:
matches.length === 0
? ("unmatched" as const)
: matches.length === 1
? ("matched" as const)
: ("ambiguous" as const),
renditions: matches.map((record) => ({
catalog_path: record.catalog_path,
catalog_sha256: record.catalog_sha256,
record_index: record.index,
rendition_name: record.rendition_name,
})),
};
});
return appleAssetCatalogResultSchema.parse({
target_sha256: input.targetSha256,
catalogs: input.catalogs.map(
({ path, sha256, records: catalogRecords }) => ({
path,
sha256,
record_count: catalogRecords.length,
}),
),
total_records: all.length,
offset: input.offset,
limit: input.limit,
records,
resource_key_matches: resourceKeyMatches,
next_offset: next < all.length ? next : null,
truncated: input.offset > 0 || next < all.length,
limitations: [
"Rendition metadata is reported as emitted by the installed assetutil version; private fields and platform-specific interpretations are not normalized.",
"Asset catalog inspection does not decode or extract rendition image bytes.",
],
});
};
+1 -1
View File
@@ -244,7 +244,7 @@ describe("browser scenario comparison validation", () => {
});
});
it("rejects ambiguous input pairs and duplicate normalization rule IDs", () => {
it("rejects duplicate normalization rule IDs", () => {
const capture = scenarioCapture({});
expect(
compareBrowserScenariosInputSchema.safeParse({
+2
View File
@@ -276,6 +276,8 @@ export class ArtifactOperationError extends AnalysisError {
| "inspect_artifact"
| "extract_artifact"
| "decode_interface_builder"
| "inspect_asset_catalog"
| "inspect_keyed_archive"
| "analyze_javascript_application",
readonly reason:
| "cancelled"
@@ -132,7 +132,7 @@ describe("JavaScript semantic analysis: calls 1", () => {
({ method }) => method === "all",
);
expect(aggregate?.sourcePromiseIds).toHaveLength(2);
expect(aggregate?.returnSiteId).not.toBeNull();
expect(aggregate?.returnSiteId).toBeTypeOf("string");
});
});
+200
View File
@@ -0,0 +1,200 @@
import { z } from "zod";
import { jsonValueSchema, type JsonValue } from "./jsonValue.js";
/** Select one archive within the active bundle and optionally one named root. */
export const keyedArchiveInputSchema = z.strictObject({
path: z.string().min(1).default("."),
root: z.string().optional(),
offset: z.number().int().min(0).default(0),
limit: z.number().int().min(1).max(20_000).default(20_000),
});
const linkSchema = z.strictObject({
source: z.number().int().nonnegative().nullable(),
path: z.array(z.union([z.string(), z.number().int().nonnegative()])),
target: z.number().int().nonnegative().nullable(),
status: z.enum(["resolved", "nil", "unresolved", "malformed"]),
raw: jsonValueSchema,
});
/** Archive object identity is its original $objects index, never a recursive copy. */
export const keyedArchiveResultSchema = z.strictObject({
target_sha256: z.string(),
archive_path: z.string(),
archive_sha256: z.string(),
archive_format: z.enum(["binary-plist", "xml-plist"]),
roots: z.record(z.string(), jsonValueSchema),
objects: z.array(
z.strictObject({
id: z.number().int().nonnegative(),
kind: z.enum([
"nil",
"scalar",
"array",
"dictionary",
"class-descriptor",
"archived-object",
]),
class_id: z.number().int().nonnegative().nullable(),
class_name: z.string().nullable(),
status: z.enum(["observed", "unknown-class", "unresolved-class", "nil"]),
value: jsonValueSchema,
}),
),
references: z.array(linkSchema),
total_objects: z.number().int().nonnegative(),
total_references: z.number().int().nonnegative(),
offset: z.number().int().nonnegative(),
next_offset: z.number().int().nonnegative().nullable(),
truncated: z.boolean(),
limitations: z.array(z.string()),
});
const record = (
value: JsonValue | undefined,
): Record<string, JsonValue> | undefined =>
value !== null && typeof value === "object" && !Array.isArray(value)
? value
: undefined;
const uid = (value: JsonValue | undefined): JsonValue | undefined => {
const object = record(value);
if (object === undefined || Object.keys(object).length !== 1)
return undefined;
return Object.hasOwn(object, "UID") ? object.UID : object["CF$UID"];
};
/** Interpret serialized Foundation references without instantiating archive classes. */
export const projectKeyedArchive = (
value: unknown,
selection: { root?: string | undefined; offset: number; limit: number },
) => {
const archive = record(jsonValueSchema.parse(value));
if (
archive?.$archiver !== "NSKeyedArchiver" ||
!Array.isArray(archive.$objects)
)
throw new TypeError("Expected NSKeyedArchiver with an $objects array");
const table = archive.$objects;
if (table.length > 200_000)
throw new RangeError("Archive exceeds 200000 object-table entries");
const top = record(archive.$top);
if (top === undefined || Object.keys(top).length === 0)
throw new TypeError("Keyed archive has no $top roots");
if (selection.root !== undefined && !Object.hasOwn(top, selection.root))
throw new TypeError(`Archive root does not exist: ${selection.root}`);
const roots =
selection.root === undefined
? top
: { [selection.root]: top[selection.root] ?? null };
const references: z.infer<typeof linkSchema>[] = [];
const scan = (source: number | null, initial: JsonValue) => {
const pending: { value: JsonValue; path: (string | number)[] }[] = [
{ value: initial, path: [] },
];
let visited = 0;
while (pending.length > 0) {
const item = pending.pop();
if (item === undefined) break;
if (++visited > 200_000 || item.path.length > 128)
throw new RangeError(
"Archive exceeds 200000 values per object or 128 nesting levels",
);
const target = uid(item.value);
if (target !== undefined) {
const valid =
typeof target === "number" &&
Number.isSafeInteger(target) &&
target >= 0;
const index = valid ? target : null;
references.push({
source,
path: item.path,
target: index,
raw: item.value,
status:
index === null
? "malformed"
: index >= table.length
? "unresolved"
: index === 0 && table[0] === "$null"
? "nil"
: "resolved",
});
} else if (Array.isArray(item.value)) {
for (let index = item.value.length - 1; index >= 0; index--) {
const child = item.value[index];
if (child !== undefined)
pending.push({ value: child, path: [...item.path, index] });
}
} else {
const fields = record(item.value);
if (fields !== undefined)
for (const key of Object.keys(fields).sort().reverse()) {
const child = fields[key];
if (child !== undefined)
pending.push({ value: child, path: [...item.path, key] });
}
}
if (references.length > 200_000)
throw new RangeError("Archive exceeds 200000 reference edges");
}
};
scan(null, roots);
const objects = table.map((value, id) => {
scan(id, value);
const fields = record(value);
const classUid = uid(fields?.$class);
const classId =
typeof classUid === "number" &&
Number.isSafeInteger(classUid) &&
classUid >= 0
? classUid
: null;
const descriptor = classId === null ? undefined : record(table[classId]);
const className =
typeof descriptor?.$classname === "string" ? descriptor.$classname : null;
const isNil = id === 0 && value === "$null";
return {
id,
kind: isNil
? ("nil" as const)
: Array.isArray(value)
? ("array" as const)
: fields === undefined
? ("scalar" as const)
: typeof fields.$classname === "string"
? ("class-descriptor" as const)
: Object.hasOwn(fields, "$class")
? ("archived-object" as const)
: ("dictionary" as const),
class_id: classId,
class_name: className,
status: isNil
? ("nil" as const)
: fields !== undefined && Object.hasOwn(fields, "$class")
? className === null
? ("unresolved-class" as const)
: ("unknown-class" as const)
: ("observed" as const),
value,
};
});
const end = Math.min(objects.length, selection.offset + selection.limit);
const page = objects.slice(selection.offset, end);
const ids = new Set(page.map(({ id }) => id));
return {
roots,
objects: page,
references: references.filter(
({ source }) => source === null || ids.has(source),
),
total_objects: objects.length,
total_references: references.length,
offset: selection.offset,
next_offset: end < objects.length ? end : null,
truncated: page.length !== objects.length,
limitations: [
"Archive classes are never instantiated. Class names and serialized fields are observed; class-specific semantics are unknown.",
"Conditional references serialized as UID 0 cannot be distinguished from ordinary nil references. Missing fields remain absent in the raw serialized value.",
"Root selection selects the named $top entry; object pagination retains original indices and does not recursively expand references.",
],
};
};
+1
View File
@@ -53,6 +53,7 @@ const jumpTableDataSourceSchema = z
"ghidra-decompiler-load-table",
"ghidra-dispatch-block-data-reference",
"ghidra-aarch64-byte-table",
"ghidra-aarch64-halfword-table",
]),
entry_size_bytes: z.number().int().min(1).nullable(),
entry_count: z.number().int().min(0).nullable(),
+57
View File
@@ -0,0 +1,57 @@
import { z } from "zod";
/** Select a database type by exact category path or a defined typed data address. */
export const nativeDataTypeInputSchema = z
.strictObject({
type: z.string().min(1).optional(),
address: z.string().min(1).optional(),
document: z.string().optional(),
})
.refine(
(value) => (value.type === undefined) !== (value.address === undefined),
"Supply exactly one of type or address",
);
/** Types remain analysis database observations; child identities can be inspected separately. */
export const nativeDataTypeSchema = z.strictObject({
status: z.enum(["available", "unavailable"]),
reason: z.string().nullable(),
id: z.string().nullable(),
name: z.string().nullable(),
kind: z.enum([
"struct",
"union",
"enum",
"pointer",
"array",
"typedef",
"scalar",
"unsupported",
"unavailable",
]),
source: z.literal("analysis-database"),
source_archive: z.string().nullable(),
address: z.string().nullable(),
size_bytes: z.number().int().nonnegative().nullable(),
alignment_bytes: z.number().int().positive().nullable(),
packing_enabled: z.boolean().nullable(),
referenced_type: z.string().nullable(),
array_count: z.number().int().nonnegative().nullable(),
array_stride_bytes: z.number().int().nonnegative().nullable(),
fields: z.array(
z.strictObject({
ordinal: z.number().int().nonnegative(),
name: z.string().nullable(),
offset_bytes: z.number().int().nonnegative(),
size_bytes: z.number().int().nonnegative().nullable(),
type_id: z.string(),
bit_size: z.number().int().nonnegative().nullable(),
bit_offset: z.number().int().nonnegative().nullable(),
status: z.enum(["observed", "unsupported"]),
flexible_tail: z.literal("unknown"),
}),
),
members: z.array(z.strictObject({ name: z.string(), value: z.string() })),
total_fields: z.number().int().nonnegative(),
truncated: z.boolean(),
limitations: z.array(z.string()),
});
+90
View File
@@ -0,0 +1,90 @@
import { z } from "zod";
/** Exact instruction location within the active analysis program. */
export const nativeInstructionInputSchema = z.strictObject({
address: z.string().min(1),
document: z.string().optional(),
});
const reference = z.strictObject({
target_address: z.string(),
type: z.string(),
call: z.boolean(),
jump: z.boolean(),
indirect: z.boolean(),
computed: z.boolean(),
operand_index: z.number().int(),
});
/** Provider-decoded facts for one instruction; operand tokens preserve their native ordering. */
export const nativeInstructionSchema = z.strictObject({
address: z.string(),
status: z.enum([
"decoded",
"not-instruction-boundary",
"data",
"undecodable",
"outside-memory",
]),
procedure: z.string().nullable(),
architecture: z.string(),
mode: z.string(),
bytes: z.string().nullable(),
length: z.number().int().positive().nullable(),
mnemonic: z.string().nullable(),
raw_disassembly: z.string().nullable(),
operands: z.array(
z.strictObject({
index: z.number().int().nonnegative(),
raw: z.string(),
provider_type: z.number().int(),
components: z.array(
z.strictObject({
kind: z.enum(["register", "immediate", "address", "unknown"]),
text: z.string(),
value: z.string().nullable(),
bit_width: z.number().int().nonnegative().nullable(),
}),
),
memory_addressing: z.literal("unavailable"),
}),
),
flow: z.strictObject({
kind: z.enum([
"call",
"jump",
"return",
"fallthrough",
"terminal",
"unavailable",
]),
conditional: z.boolean(),
computed: z.boolean(),
direct_destinations: z.array(z.string()),
}),
references: z.array(reference),
limitations: z.array(z.string()),
});
/** Static target resolution preserves provider references as evidence, never runtime certainty. */
export const nativeCallTargetsSchema = z.strictObject({
call_site: z.string(),
procedure: z.string().nullable(),
status: z.enum([
"direct",
"resolved-indirect",
"ambiguous",
"unresolved",
"not-call",
"unavailable",
]),
mechanism: z.enum(["direct", "computed", "indirect", "unavailable"]),
targets: z.array(
z.strictObject({
address: z.string(),
procedure: z.string().nullable(),
status: z.enum(["direct", "resolved-indirect", "candidate"]),
basis: z.literal("provider-reference"),
references: z.array(reference),
}),
),
limitations: z.array(z.string()),
});
+5 -2
View File
@@ -168,6 +168,7 @@ describe("Interface Builder dispatch joins", () => {
objc_protocols: [],
swift_decls: [],
objc_ivars: [],
objc_protocol_records: [],
objc_dispatch_implementations: [
{
class_name: "BuildViewController",
@@ -189,7 +190,7 @@ describe("Interface Builder dispatch joins", () => {
expect(joined.edges).toContainEqual(
expect.objectContaining({
relation: "objc_dispatch",
resolution: "inferred",
resolution: "resolved",
to: "native:function:0x1000",
}),
);
@@ -228,6 +229,7 @@ describe("Interface Builder dispatch joins", () => {
objc_protocols: [],
swift_decls: [],
objc_ivars: [],
objc_protocol_records: [],
objc_dispatch_implementations: [
{
class_name: "BuildViewController",
@@ -260,7 +262,7 @@ describe("Interface Builder dispatch joins", () => {
expect(joined.edges).toContainEqual(
expect.objectContaining({
relation: "objc_dispatch",
resolution: "inferred",
resolution: "resolved",
to: "native:function:0x1000",
}),
);
@@ -304,6 +306,7 @@ describe("placeholder dispatch joins", () => {
objc_protocols: [],
swift_decls: [],
objc_ivars: [],
objc_protocol_records: [],
objc_dispatch_implementations: [
{
class_name: "BuildViewController",
+10 -5
View File
@@ -64,6 +64,8 @@ export const nativeInvestigationRelationSchema = z.enum([
"swift_vtable_dispatch",
"thunk_to",
"direct_call",
"indirect_call",
"provider_call",
"reads",
"writes",
"flows_to",
@@ -83,7 +85,7 @@ export const nativeInvestigationEdgeSchema = z.discriminatedUnion(
from: z.string().min(1),
to: z.string().min(1),
relation: nativeInvestigationRelationSchema,
resolution: z.enum(["observed", "inferred"]),
resolution: z.enum(["observed", "inferred", "resolved", "ambiguous"]),
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
limitations: z.array(z.string()),
}),
@@ -344,7 +346,7 @@ export const joinInterfaceBuilderDispatch = (
reason:
candidates.length > 1
? "selector_has_multiple_candidate_implementations"
: "implementation_not_resolved_from_provider_symbols",
: "implementation_not_resolved_from_binary_metadata_or_provider_symbols",
evidence: [
...action.evidence,
...candidates.flatMap(({ evidence }) => evidence),
@@ -378,15 +380,18 @@ export const joinInterfaceBuilderDispatch = (
from: selectorNodeId,
to: functionId,
relation: "objc_dispatch",
resolution: "inferred",
resolution:
className !== null && implementation.decode.status === "decoded"
? "resolved"
: "inferred",
evidence: [...action.evidence, ...implementation.evidence],
limitations:
className === null
? [
"The selector uniquely matches a symbolized method, but the Interface Builder receiver is an unresolved placeholder; runtime dispatch was not observed.",
"The selector uniquely matches a encoded or symbolized method, but the Interface Builder receiver is an unresolved placeholder; runtime dispatch was not observed.",
]
: [
"The Interface Builder target and symbolized method agree on class and selector; runtime dispatch and dynamically supplied targets were not observed.",
"The Interface Builder target and encoded or symbolized method agree on class and selector; runtime dispatch and dynamically supplied targets were not observed.",
],
});
resolved += 1;
+90
View File
@@ -0,0 +1,90 @@
import { z } from "zod";
const scope = {
pid: z.number().int().positive(),
window_id: z.number().int().positive(),
observation_approved: z.literal(true),
screenshot: z.boolean().default(true),
accessibility: z.boolean().default(true),
max_nodes: z.number().int().min(1).max(2_000).default(500),
};
/** Opt-in passive observation binds one already-running process and window. */
export const nativeUiObservationInputSchema = z.strictObject(scope);
/** Active scenarios require independent action approval and an explicit restore choice. */
export const nativeUiScenarioInputSchema = z.strictObject({
...scope,
actions_approved: z.literal(true),
restore: z.literal("leave-as-is"),
steps: z
.array(
z.discriminatedUnion("kind", [
z.strictObject({
kind: z.literal("click"),
path: z.array(z.number().int().nonnegative()).max(32),
}),
z.strictObject({
kind: z.literal("scroll"),
path: z.array(z.number().int().nonnegative()).max(32),
direction: z.enum(["increment", "decrement"]),
}),
z.strictObject({
kind: z.literal("key-entry"),
path: z.array(z.number().int().nonnegative()).max(32),
text: z.string().max(4_096),
}),
z.strictObject({
kind: z.literal("wait"),
milliseconds: z.number().int().min(0).max(10_000),
}),
]),
)
.min(1)
.max(16),
});
/** Ordered captures and failures distinguish missing observation from a failed action. */
export const nativeUiSnapshotSchema = z.strictObject({
window: z.strictObject({
pid: z.number().int().positive(),
window_id: z.number().int().positive(),
executable: z.string(),
launch_time: z.number(),
title: z.string(),
}),
nodes: z.array(
z.strictObject({
path: z.array(z.number().int().nonnegative()),
role: z.string().nullable(),
title: z.string().nullable(),
value: z.string().nullable(),
actions: z.array(z.string()),
children_count: z.number().int().nonnegative(),
}),
),
truncated: z.boolean(),
screenshot: z
.strictObject({
mime_type: z.literal("image/png"),
base64: z.string(),
sha256: z.string(),
width: z.number().int().positive(),
height: z.number().int().positive(),
})
.nullable(),
gaps: z.array(z.string()),
});
export const nativeUiResultSchema = z.strictObject({
target_sha256: z.string(),
initial: nativeUiSnapshotSchema,
steps: z.array(
z.strictObject({
index: z.number().int().nonnegative(),
kind: z.string(),
before: nativeUiSnapshotSchema,
after: nativeUiSnapshotSchema.nullable(),
outcome: z.enum(["completed", "failed", "cancelled"]),
reason: z.string().nullable(),
}),
),
restore: z.literal("leave-as-is"),
limitations: z.array(z.string()),
});
+21
View File
@@ -18,6 +18,9 @@ export const nativePcodeOperationSchema = z.strictObject({
sequence: z.number().int().nonnegative(),
opcode: z.string().min(1),
is_dead: z.boolean(),
block_membership: z
.enum(["member", "detached", "unavailable"])
.default("unavailable"),
inputs: z.array(nativeVarnodeSchema),
output: nativeVarnodeSchema.nullable(),
});
@@ -52,6 +55,24 @@ export const nativeValueFlowSchema = z.discriminatedUnion("available", [
operations: z.array(nativePcodeOperationSchema),
def_use: z.array(nativePcodeDefUseSchema),
effects: z.array(nativePcodeEffectSchema),
parameters: z
.array(
z.strictObject({
ordinal: z.number().int().nonnegative(),
name: z.string(),
data_type: z.string(),
}),
)
.default([]),
parameter_uses: z
.array(
z.strictObject({
ordinal: z.number().int().nonnegative(),
use: z.string(),
input_index: z.number().int().nonnegative(),
}),
)
.default([]),
truncated: z.boolean(),
omitted_operations_lower_bound: z.number().int().nonnegative(),
known_omitted_inputs: z.number().int().nonnegative(),
+73
View File
@@ -0,0 +1,73 @@
import { z } from "zod";
import { nativePcodeOperationSchema } from "./nativeValueFlow.js";
/** Work and output budgets for a static procedure-seeded dependency graph. */
export const nativeValueTraceInputSchema = z.strictObject({
procedure: z.string().min(1),
max_depth: z.number().int().min(0).max(16).default(3),
max_functions: z.number().int().min(1).max(64).default(16),
max_call_sites: z.number().int().min(1).max(4096).default(256),
max_nodes: z.number().int().min(1).max(20_000).default(5_000),
max_edges: z.number().int().min(1).max(40_000).default(10_000),
offset: z.number().int().min(0).default(0),
limit: z.number().int().min(1).max(5_000).default(1_000),
});
/** Def-use observations and call relationships retain separate authority. */
export const nativeValueTraceSchema = z.strictObject({
seed: z.string(),
target_sha256: z.string(),
nodes: z.array(
z.strictObject({
id: z.string(),
procedure: z.string(),
evidence_id: z.string(),
kind: z.enum(["operation", "parameter"]),
operation: nativePcodeOperationSchema.nullable(),
parameter: z
.strictObject({
ordinal: z.number().int().nonnegative(),
name: z.string(),
data_type: z.string(),
})
.nullable(),
}),
),
edges: z.array(
z.strictObject({
source: z.string(),
target: z.string(),
input_index: z.number().int().nonnegative().nullable(),
kind: z.enum([
"def-use",
"call",
"parameter-use",
"argument-binding",
"return-binding",
]),
status: z.enum(["derived", "direct", "resolved-indirect", "candidate"]),
evidence_id: z.string(),
}),
),
procedures: z.array(
z.strictObject({
address: z.string(),
depth: z.number().int().nonnegative(),
evidence_id: z.string(),
provider: z.string(),
analysis_profile_digest: z.string().nullable(),
}),
),
unknowns: z.array(
z.strictObject({
procedure: z.string(),
address: z.string().nullable(),
reason: z.string(),
}),
),
total_nodes: z.number().int().nonnegative(),
total_edges: z.number().int().nonnegative(),
decompilations: z.number().int().nonnegative(),
next_offset: z.number().int().nonnegative().nullable(),
truncated: z.boolean(),
limitations: z.array(z.string()),
});
+42
View File
@@ -61,6 +61,34 @@ export const objcClassSchema = z.strictObject({
protocols: z.array(z.string()).default([]),
ivar_count: z.number().int().nonnegative().default(0),
instance_size: z.number().int().nonnegative().nullable(),
location: z
.object({
address: z.string().nullable(),
file_offset: z.number().int().nonnegative().nullable(),
})
.optional(),
superclass_address: z.string().nullable().optional(),
metaclass_address: z.string().nullable().optional(),
decode: z
.object({
status: z.enum(["decoded", "partial", "unsupported", "invalid"]),
reason: z.string().nullable(),
})
.optional(),
evidence: z
.array(
z.object({
kind: z.literal("binary_metadata"),
description: z.string(),
location: z.object({
address: z.string().nullable(),
file_offset: z.number().int().nonnegative().nullable(),
}),
artifact_path: z.string(),
artifact_sha256: z.string(),
}),
)
.optional(),
});
export type ObjcClass = z.infer<typeof objcClassSchema>;
@@ -108,12 +136,25 @@ export const objcIvarSchema = z.strictObject({
name: z.string().min(1),
type_encoding: z.string().nullable(),
offset: z.number().int().nonnegative().nullable(),
size: z.number().int().nonnegative().nullable().default(null),
alignment: z.number().int().positive().nullable().default(null),
location: nativeMetadataLocationSchema,
decode: nativeMetadataDecodeSchema,
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
});
export type ObjcIvar = z.infer<typeof objcIvarSchema>;
/** Encoded Objective-C protocol declaration with required and optional method facts. */
export const objcProtocolRecordSchema = z.strictObject({
name: z.string(),
adopted_protocols: z.array(z.string()),
methods: z.array(objcMethodSchema),
optional_methods: z.array(objcMethodSchema),
location: nativeMetadataLocationSchema,
decode: nativeMetadataDecodeSchema,
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
});
/** Selector implementation resolved from a class or metaclass method list. */
export const objcDispatchImplementationSchema = z.strictObject({
class_name: z.string().min(1),
@@ -254,6 +295,7 @@ export const objcSwiftMetadataSchema = z.strictObject({
objc_protocols: z.array(objcProtocolSchema).default([]),
swift_decls: z.array(swiftDeclSchema).default([]),
objc_ivars: z.array(objcIvarSchema).default([]),
objc_protocol_records: z.array(objcProtocolRecordSchema).default([]),
objc_dispatch_implementations: z
.array(objcDispatchImplementationSchema)
.default([]),
@@ -129,7 +129,6 @@ describe("process reactive scenario schema", () => {
expect(processReactiveScenarioSchema.parse(baseScenario())).toMatchObject({
initial_state: "starting",
});
expect(PROCESS_REACTIVE_LIMITS.triggerDepth).toBe(256);
});
it("accepts caller-defined scenario sizes without count ceilings", () => {
+30 -11
View File
@@ -1,3 +1,4 @@
import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
import {
@@ -79,18 +80,36 @@ describe("protocol capture", () => {
});
describe("JSON-RPC decoding", () => {
it("decodes a simple JSON-RPC request", () => {
const payload = new TextEncoder().encode(
JSON.stringify({
jsonrpc: "2.0",
method: "add",
params: [1, 2],
id: 1,
}),
it("decodes the captured MCP SDK initialize request with exact field values", async () => {
const payload = await readFile(
new URL(
"../../tests/fixtures/golden/mcp-initialize.json",
import.meta.url,
),
);
const result = decodeJsonRpc(payload);
expect(result.decoded_fields.length).toBe(4);
expect(result.truncated).toBe(false);
expect(decodeJsonRpc(payload)).toEqual({
decoded_fields: [
{
path: "method",
wire_type: "json",
value: "initialize",
inferred: false,
},
{
path: "params",
wire_type: "json",
inferred: false,
value: {
protocolVersion: "2025-11-25",
capabilities: {},
clientInfo: { name: "rea-protocol-golden", version: "1" },
},
},
{ path: "jsonrpc", wire_type: "json", value: "2.0", inferred: false },
{ path: "id", wire_type: "json", value: 0, inferred: false },
],
truncated: false,
});
});
it("redacts credential-like fields", () => {
+1 -1
View File
@@ -134,7 +134,7 @@ describe("reconstruction coverage closure", () => {
);
});
it("never lets mock-strength or stale results satisfy stronger current claims", () => {
it("does not let stale verifier results satisfy current claims", () => {
const workspace = completeReconstructionCoverageData();
const semantic = workspace;
const stale = createReconstructionCoverageData({
@@ -1,4 +1,3 @@
import canonicalize from "canonicalize";
import { z } from "zod";
import { evidenceBundleSchema } from "./evidenceBundle.js";
@@ -298,16 +297,3 @@ export type ReviewedReconstructionObligation = z.infer<
export type ReconstructionObligationManifest = z.infer<
typeof reconstructionObligationManifestSchema
>;
/** Parse and canonically serialize one complete reconstruction obligation ledger. */
export const serializeReconstructionObligationLedger = (
input: unknown,
): string => {
const ledger = reconstructionObligationLedgerSchema.parse(input);
const encoded = canonicalize(ledger);
if (encoded === undefined)
throw new TypeError(
"Reconstruction obligation ledger is not canonical JSON",
);
return encoded;
};
+1 -1
View File
@@ -26,7 +26,7 @@ describe("reconstruction readiness report", () => {
expect(parsed.capabilities).toHaveLength(1_001);
});
it("passes the complete repository conformance journey deterministically", () => {
it("projects the complete conformance report deterministically", () => {
const first = createReconstructionReadinessReport(input());
const second = createReconstructionReadinessReport(input());
+1 -16
View File
@@ -90,6 +90,7 @@ describe("historical source to bundle comparison", () => {
expect(item(first, "src/merged-b.ts").status).toBe("merged");
expect(item(first, "src/duplicated.ts")).toMatchObject({
status: "duplicated",
candidates: [{}, {}],
confidence: "exact",
current_node_ids: [expect.any(String), expect.any(String)],
});
@@ -117,22 +118,6 @@ describe("historical source to bundle comparison", () => {
expect(result.coverage.status).toBe("partial");
});
it("retains every candidate without caller-selected caps", () => {
const result = compareSourceToBundle({
reference: historicalGraph("complete"),
application: {
evidenceId: EVIDENCE_ID,
rootArtifactSha256: HASH.artifact,
graph: applicationGraph("complete"),
},
});
expect(item(result, "src/duplicated.ts")).toMatchObject({
status: "duplicated",
candidates: [{}, {}],
});
});
it("evaluates all indexed candidates for each source file", () => {
const result = compareSourceToBundle({
reference: historicalGraph("complete", ["src/split.ts"]),
+13 -1
View File
@@ -48,7 +48,19 @@ describe("stable web inventory", () => {
};
it("excludes transient CDP and target identity from script keys", () => {
expect(stableWebScriptKey(script)).toBe(stableWebScriptKey({ ...script }));
const first = {
...script,
script_id: "session-one-script",
target_id: "tab-one",
capture_id: "capture-one",
};
const second = {
...script,
script_id: "session-two-script",
target_id: "tab-two",
capture_id: "capture-two",
};
expect(stableWebScriptKey(first)).toBe(stableWebScriptKey(second));
expect(stableWebScriptKey({ ...script, length: 1_025 })).not.toBe(
stableWebScriptKey(script),
);
-9
View File
@@ -4,18 +4,9 @@ import {
captureWebScreenshotInputSchema,
compareWebScreenshotsInputSchema,
createWebScreenshotArtifact,
webScreenshotArtifactSchema,
} from "./webScreenshot.js";
describe("inline web screenshots", () => {
it("accepts complete inline image artifacts above the former size ceiling", () => {
const artifact = createWebScreenshotArtifact(
Buffer.alloc(8 * 1_024 * 1_024 + 1),
);
expect(webScreenshotArtifactSchema.parse(artifact)).toEqual(artifact);
});
it("rejects removed screenshot size and pixel controls", () => {
expect(
captureWebScreenshotInputSchema.safeParse({