Files
reverse-engineering-anything/tests/support/analysis-efficiency/android-mapping.mjs
T
morluto 5c53bcaed8 feat(mcp)!: retire the full schema profiles and declare schema facts as typed annotations (#10693)
* test(mcp): check advertised schemas against a portable dialect in every profile

* fix(mcp): re-emit advertised patterns in a portable regex grammar

* fix(mcp): present discover_tools input through the selected profile

The hot-cold catalog registered discover_tools directly with the SDK, so
the default compact input profile still advertised its canonical schema,
including page-size defaults clients apply on their own (#5322). Route
every listed input schema, transport discovery included, through one
server-owned presentation, and pass the selected presentation to the
deferred server, which serves recorded tool schemas but not discovery.

* fix(mcp): keep the Evidence union on described borrowed inputs

borrowEvidenceInput installed its advertised projection on one schema
instance. A call site's .describe() rebuilds the schema from its
definition, so match_native_functions advertised left and right as
unconstrained values in every input profile. Install the projection in
the borrowed parser's constructor so derived schemas keep it, for both
borrowed inputs and borrowed arrays.

* fix(mcp): validate advertised dialect by selected profile

* fix(mcp): preserve schema widening through references

* feat(mcp): project compact input schemas into the portable advertised dialect

One projection (advertisedDialectProjection.ts) owns the compact input
advertisement: one type per node, items on every array, string literals
as enums, oneOf widened to anyOf, allOf merged, tuples as element unions,
exclusive bounds made inclusive, and every keyword outside the dialect
dropped. Each rewrite is exact or widening; server validation is
unchanged. The root description and sentences for dropped cross-field
constraints move to the tool description, which Codex and Zed keep.

The compact baseline falls to nullable values only (29), which the
dialect cannot express without narrowing an input. The gateway shape
repairs (typeArrayItemUnions, hasGatewayIncompatibleShape), the second
dependentRequired-to-prose copy and the strict-gateway test denylist are
removed; the dialect checker gates the inline presentation instead.

* feat(mcp): omit output schemas from tools/list by default

No surveyed model API reads an output schema, MCP client validators
repeat REA's own result validation, and complete output schemas were
about 92% of the default tools/list. REA_MCP_OUTPUT_SCHEMA_PROFILE now
resolves to off through one owner (resolveMcpOutputSchemaProfile);
compact and full remain selectable. structuredContent is still
delivered, and the deferred server serves both off and full from the
recorded catalog with the matching recorded identity.

Tests and artifact verifiers that validate results against complete
advertised output contracts select full explicitly.

* docs: describe omitted output schemas as the default in README translations

* fix(mcp): select schemas in verification workflows

* fix(mcp): refuse zero-padded repeat bounds and record host-specific path patterns

* fix(mcp): keep projected schemas permissive

* fix(mcp): keep references valid when presentation widens their targets

* fix(mcp): keep a single union branch's closure scoped to its properties

* fix(mcp): select complete output schemas in the Electron verifier

* fix(mcp): select complete output schemas in standalone verifier probes

* fix(mcp): keep an allOf member's tuple tail with its own positions

* fix(mcp): relax references into negations and conditionals presentation may remove

* refactor(contracts): declare root discriminators as typed schema annotations

* test(mcp): select the borrowed Evidence contract from its family

* fix(mcp): keep astral literals and dynamic references widening in every mode

* fix(mcp): omit astral literals and relax untracked references when presentation widens

* fix(mcp): select complete output schemas in every verifier transport

* fix(mcp): read reference pointers by schema position, not segment spelling

* fix(mcp): protect references into collapsing boolean unions and keep referencing branches out of the collapse

* fix(mcp): keep reduced schemas open when their root admits names by pattern

* test(mcp): keep the reduced-schema pattern case outside the size-limited block

* fix(mcp): omit patterns whose classes name astral characters

* fix(mcp): decide union collapse and pointer protection from canonical branches

* docs(mcp): document non-u astral matching and pin BMP agreement across V8 modes

* fix(mcp): keep prototype-named properties as own properties in the dialect projection

* test(mcp): select full output schemas in packet and signal schema checks

* test(mcp): expect the advertised base64 schema to omit the unbounded pad-bit probe

* fix(mcp): protect references into unevaluated keywords lost evaluation removes

* fix(mcp): validate the doctor probe reply against the canonical output contract (#10655)

* fix(mcp): validate the doctor probe reply against the canonical output contract

* test(mcp): replay doctor probe validation under every output profile

* test(mcp): accept typed-branch nullable unions in the advertised dialect (#10649)

* test(mcp): select full output schemas in HTTP session workflows

* fix(mcp): emit stack-safe classes with non-ASCII members and protect draft-07 reference siblings

* fix(mcp): protect references into literal siblings of relaxed draft-07 references

* feat(mcp): omit output schemas from tools/list by default (#10646)

* feat(mcp): omit output schemas from tools/list by default

No surveyed model API reads an output schema, MCP client validators
repeat REA's own result validation, and complete output schemas were
about 92% of the default tools/list. REA_MCP_OUTPUT_SCHEMA_PROFILE now
resolves to off through one owner (resolveMcpOutputSchemaProfile);
compact and full remain selectable. structuredContent is still
delivered, and the deferred server serves both off and full from the
recorded catalog with the matching recorded identity.

Tests and artifact verifiers that validate results against complete
advertised output contracts select full explicitly.

* fix(mcp): select schemas in verification workflows

* fix(mcp): select complete output schemas in the Electron verifier

* fix(mcp): select complete output schemas in standalone verifier probes

* fix(mcp): select complete output schemas in every verifier transport

* test(mcp): select full output schemas in packet and signal schema checks

* fix(mcp): validate the doctor probe reply against the canonical output contract (#10655)

* fix(mcp): validate the doctor probe reply against the canonical output contract

* test(mcp): replay doctor probe validation under every output profile

* test(mcp): accept typed-branch nullable unions in the advertised dialect (#10649)

* test(mcp): select full output schemas in HTTP session workflows

* fix(mcp): keep the Evidence union on described borrowed inputs (#10597)

* fix(mcp): keep the Evidence union on described borrowed inputs

borrowEvidenceInput installed its advertised projection on one schema
instance. A call site's .describe() rebuilds the schema from its
definition, so match_native_functions advertised left and right as
unconstrained values in every input profile. Install the projection in
the borrowed parser's constructor so derived schemas keep it, for both
borrowed inputs and borrowed arrays.

* test(mcp): select the borrowed Evidence contract from its family

* docs(mcp): admit baseline growth only for restored contract declarations

* fix(mcp): state reduced multi-type properties as typed branches, not type lists

The reduced fallback derived a property's types and emitted them as a type
list, which Gemini, Moonshot and Ark reject. A property whose canonical
schema is anyOf string and number therefore traded a typed union for a
rejected construct when the inline projection fell back. Emit one type, or
anyOf typed branches, so [T, null] becomes the dialect's nullable union.

* feat(mcp)!: retire the full schema profiles and declare complete observations as a typed annotation (#10718)

* refactor(mcp): declare complete observations as a typed annotation applied only on the wire

* test(mcp): compare complete-observation declarations with their owning text

* refactor(schema): couple Zod checks with their JSON Schema constraint keywords (#10725)

* refactor(schema): couple Zod checks with their JSON Schema constraint keywords

* refactor(schema): declare pattern approximations and object output roots as typed annotations (#10754)

* refactor(schema): declare pattern approximations and object output roots as typed annotations

* fix(schema): refuse pattern declarations JSON Schema cannot state

* test(schema): select guided_workflows from its contract family

* feat(mcp)!: retire the full input and output schema profiles (#10841)

* feat(mcp)!: retire the full input and output schema profiles

The compact input presentation is now the only advertised input schema, and
output schemas are either omitted (`off`, the default) or bounded
(`compact`). Catalog identity, the build-recorded digests and the recorded
startup catalog collapse to those presentations: two digest profiles instead
of six, one recorded catalog instead of two, and no input dialect baseline.

Tests and verifiers that validated replies against listed full output
schemas now validate against the canonical output contract, which REA
already enforces server-side; tests that asserted canonical input
restrictions read the canonical input schema instead of a full listing.

BREAKING CHANGE: `REA_MCP_INPUT_SCHEMA_PROFILE=full` and
`REA_MCP_OUTPUT_SCHEMA_PROFILE=full` are refused at startup and by `rea setup`
with a configuration error naming the setting. Remove the setting from the
client registration (or rerun setup with `REA_MCP_INPUT_SCHEMA_PROFILE=compact`
/ `REA_MCP_OUTPUT_SCHEMA_PROFILE=compact`). `REA_MCP_INPUT_SCHEMA_PROFILE`
still accepts `compact`. Server-side validation is unchanged.

* test(mcp): validate replies against canonical output contracts at every listed-schema reader

tools/list omits output schemas by default, so fixtures, verifiers and the
Android analysis runners that read a listed outputSchema now bind the
canonical contract instead. connectLocalToolsMcp and advertisedMcpToolSchemas
hand the SDK a definition carrying the canonical output schema, so the SDK
client and caller-supplied validators check every successful reply.

* test(mcp): resolve Android runners' output contracts from the selected repository

The Android efficiency runners imported the canonical output-schema helper from the harness checkout while --repository selects the revision under test. Import it from the selected repository, as the runners already do for the SDK and Ajv.

* test(mcp): let Android runners compare revisions before the canonical output helper

A selected revision without scripts/lib/canonical-output-schema.mjs could not start the Android runners. Choose the output contracts in one harness helper: the selected revision's canonical contracts when it has them, otherwise its listed schemas under the full output profile it still supports.

* fix(scripts): keep caller launch settings when the real Hopper verifier builds its server environment

The verifier deleted REA_VERIFY_SERVER_COMMAND and REA_VERIFY_SERVER_ARGS_JSON from process.env itself before reading them, so a caller selecting an installed REA command silently ran the checkout's dist/main.js. Copy the environment, as main does, so only the child's environment changes.

* test(mcp): validate whole replies against canonical output contracts wherever a listed definition is held

tools/list omits output schemas by default and the full output profile is gone, so tests that handed the SDK a listed definition no longer checked complete replies. Attach the canonical output schema with withCanonicalOutputSchema at every held REA tool definition. Environment-served tools (not REA contracts), and the deferred-runtime and doctor tests that exercise per-profile listings, keep their listed definitions.

* test(mcp): record the advertised catalog summary without the retired full profiles

Retiring the full input and output profiles leaves only the compact input and compact output listings, so the summary drops the full-profile digests and every pattern only the full listings carried. Regenerated with npm run verify:advertised-schemas -- --update-summary.
2026-11-15 21:51:18 +08:00

415 lines
14 KiB
JavaScript

/** Public MCP mapping investigation with a source inventory and raw DEX oracle. */
import { selectedOutputContracts } from "./selected-output-contracts.mjs";
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { readFile, writeFile, mkdir } from "node:fs/promises";
import { createRequire } from "node:module";
import { join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { parseArgs } from "node:util";
import { performance } from "node:perf_hooks";
const { values } = parseArgs({
options: {
repository: { type: "string" },
target: { type: "string" },
mapping: { type: "string" },
output: { type: "string" },
"java-home": { type: "string" },
jar: { type: "string" },
oracle: { type: "string" },
expectations: { type: "string" },
"class-name": { type: "string" },
repeats: { type: "string", default: "2" },
variants: { type: "boolean", default: false },
methods: { type: "string" },
detail: { type: "string" },
proof: { type: "boolean", default: false },
},
});
for (const name of [
"repository",
"target",
"mapping",
"output",
"java-home",
"jar",
])
assert.ok(values[name], `Missing --${name}`);
const repo = resolve(values.repository),
target = resolve(values.target),
mapping = resolve(values.mapping),
output = resolve(values.output);
await mkdir(output, { mode: 0o700 });
const sha256 = async (path) =>
createHash("sha256")
.update(await readFile(path))
.digest("hex");
const targetSha = await sha256(target),
mappingSha = await sha256(mapping);
const require = createRequire(join(repo, "package.json"));
const { Client } = await import(
pathToFileURL(require.resolve("@modelcontextprotocol/client"))
);
const { StdioClientTransport } = await import(
pathToFileURL(require.resolve("@modelcontextprotocol/client/stdio"))
);
const { Ajv2020 } = await import(
pathToFileURL(require.resolve("ajv/dist/2020.js"))
);
const outputContracts = await selectedOutputContracts(repo);
const { withCanonicalOutputSchema } = outputContracts;
const transport = new StdioClientTransport({
command: process.execPath,
args: [join(repo, "scripts/rea.mjs"), "mcp"],
cwd: repo,
env: {
PATH: process.env.PATH,
JAVA_HOME: resolve(values["java-home"]),
REA_JADX_MCP_JAR: resolve(values.jar),
REA_JADX_HEAP_MIB: "1024",
REA_JADX_ACTIVE_PROCESSOR_COUNT: "2",
NODE_OPTIONS: "--max-old-space-size=3072",
UV_THREADPOOL_SIZE: "2",
REA_LOG_LEVEL: "silent",
REA_MCP_TOOL_FAMILIES: values.proof ? "android,session" : "android",
REA_MCP_INPUT_SCHEMA_PROFILE: "compact",
// The run validates each result against the selected revision's output contract.
...outputContracts.environment,
},
stderr: "pipe",
maxBufferSize: 16 * 1024 * 1024,
});
let stderr = "";
transport.stderr?.on("data", (chunk) => {
if (stderr.length < 65536)
stderr += chunk.toString().slice(0, 65536 - stderr.length);
});
const client = new Client({ name: "rea-real-android-mapping", version: "1" });
const calls = [],
runs = [];
let catalog;
try {
await client.connect(transport);
catalog = await client.listTools();
await writeFile(join(output, "catalog.json"), JSON.stringify(catalog));
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const contracts = new Map();
for (const name of [
"inspect_android_class",
"inspect_android_method",
...(values.proof ? ["export_evidence_bundle"] : []),
]) {
const definitions = catalog.tools.filter((tool) => tool.name === name);
assert.equal(definitions.length, 1);
const definition = withCanonicalOutputSchema(definitions[0]);
contracts.set(name, {
definition,
validate: ajv.compile(definition.outputSchema),
});
}
const parents = [];
assert.ok(values.detail === undefined || values.detail === "summary");
const invoke = async (name, input) => {
const args = {
...input,
...(name !== "export_evidence_bundle" && values.detail !== undefined
? { detail: values.detail }
: {}),
};
const contract = contracts.get(name),
start = performance.now();
const result = await client.callTool(
{ name, arguments: args },
{ toolDefinition: contract.definition, timeout: 120000 },
);
const elapsed_ms = performance.now() - start;
calls.push({ name, arguments: args, result, elapsed_ms });
assert.notEqual(result.isError, true, JSON.stringify(result.content));
assert.ok(
contract.validate(result.structuredContent),
JSON.stringify(contract.validate.errors),
);
const evidence = result.structuredContent;
if (name === "export_evidence_bundle") return evidence;
assert.equal(evidence.subject.digest.sha256, targetSha);
const projection = evidence.normalized_result;
const normalized =
values.detail === "summary" ? projection.summary : projection;
if (values.detail === "summary") {
assert.equal(evidence.operation, "inspect_analysis_view");
assert.equal(evidence.raw_result, null);
assert.equal(projection.parent_operation, name);
} else assert.equal(evidence.parameters.mapping_path, args.mapping_path);
parents.push({
id:
values.detail === "summary"
? projection.parent_evidence_id
: evidence.evidence_id,
name,
args,
normalized,
});
const report = normalized.mapping;
assert.equal(report.association, "caller-selected");
assert.equal(report.file.path, args.mapping_path);
assert.equal(report.file.sha256, await sha256(args.mapping_path));
assert.equal(
report.coverage.mapped +
report.coverage.ambiguous +
report.coverage.unmapped,
report.coverage.symbols,
);
return normalized;
};
const raw = values.oracle
? JSON.parse(await readFile(values.oracle, "utf8"))
: undefined;
const expected = values.expectations
? JSON.parse(await readFile(values.expectations, "utf8")).classes
: undefined;
// Only class header identities are read here; member resolution is checked
// against handwritten original prototypes and independently decoded DEX.
const classNames = new Map(
[
...(await readFile(mapping, "utf8")).matchAll(
/^([^\s:]+) -> ([^\s:]+):$/gm,
),
].map((match) => [match[2], match[1]]),
);
const primitive = {
boolean: "Z",
byte: "B",
char: "C",
short: "S",
int: "I",
long: "J",
float: "F",
double: "D",
void: "V",
};
const originalType = (type) => {
if (type.endsWith("[]")) return "[" + originalType(type.slice(0, -2));
return primitive[type] ?? `L${type.replaceAll(".", "/")};`;
};
const selected = values["class-name"]
? [values["class-name"]]
: raw?.map((cls) => cls.raw_type.slice(1, -1).replaceAll("/", "."));
assert.ok(selected?.length);
if (expected) assert.equal(selected.length, expected.length);
const repeats = Number(values.repeats);
const requestedMethods =
values.methods === undefined
? undefined
: new Set(values.methods.split(","));
assert.ok(Number.isSafeInteger(repeats) && repeats > 0 && repeats <= 20);
for (let pass = 0; pass < repeats; pass++) {
const firstCall = calls.length,
start = performance.now();
const firstParent = parents.length;
for (const class_name of selected) {
const result = await invoke("inspect_android_class", {
path: target,
class_name,
mapping_path: mapping,
});
assert.equal(result.mapping.coverage.unmapped, 0);
assert.equal(result.mapping.coverage.ambiguous, 0);
if (!expected) continue;
const source = expected.find(
(cls) => cls.original_name === classNames.get(class_name),
);
const dex = raw.find(
(cls) => cls.raw_type === `L${class_name.replaceAll(".", "/")};`,
);
assert.ok(source && dex);
const fields = [],
methods = [];
for (const symbol of result.mapping.symbols) {
assert.equal(symbol.resolution.status, "mapped");
const mapped = symbol.resolution.mapped;
if (symbol.kind === "class") {
assert.equal(mapped.name, classNames.get(symbol.raw_name));
continue;
}
assert.equal(mapped.class, source.original_name);
if (symbol.kind === "field") {
assert.ok(
dex.fields.some(
(field) =>
field.raw_name === symbol.raw_name &&
field.dex_type === symbol.dex_type,
),
);
fields.push([mapped.name, originalType(mapped.type)]);
} else {
assert.ok(
dex.methods.some(
(method) =>
method.raw_name === symbol.raw_name &&
method.dex_descriptor === symbol.dex_descriptor,
),
);
const descriptor = `(${mapped.parameter_types.map(originalType).join("")})${originalType(mapped.return_type)}`;
methods.push([mapped.name, descriptor]);
if (
requestedMethods !== undefined &&
!requestedMethods.has(mapped.name)
)
continue;
const body = await invoke("inspect_android_method", {
path: target,
class_name,
method_name: symbol.name,
overload_index: symbol.overload_index,
mapping_path: mapping,
});
const annotation = body.mapping.symbols.filter(
(row) => row.kind === "method",
);
assert.equal(annotation.length, 1);
assert.deepEqual(annotation[0], symbol);
assert.equal(body.method.dex_descriptor, symbol.dex_descriptor);
}
}
assert.deepEqual(fields.sort(), Object.entries(source.fields).sort());
assert.deepEqual(
methods.sort(),
Object.entries(source.methods)
.flatMap(([name, descriptors]) =>
descriptors.map((descriptor) => [name, descriptor]),
)
.sort(),
);
if (requestedMethods !== undefined)
for (const name of requestedMethods)
assert.ok(
methods.some(([observed]) => observed === name),
`Requested original method absent: ${name}`,
);
assert.equal(fields.length, dex.fields.length);
assert.equal(methods.length, dex.methods.length);
}
if (values.proof) {
const path = join(output, `pass-${pass}-evidence.json`);
await invoke("export_evidence_bundle", { path });
const bundle = JSON.parse(await readFile(path, "utf8"));
for (const expected of parents.slice(firstParent)) {
const parent = bundle.records.find(
(record) => record.evidence_id === expected.id,
);
assert.ok(parent, "Complete source Evidence must remain exportable");
assert.equal(parent.operation, expected.name);
assert.equal(parent.subject.digest.sha256, targetSha);
assert.equal(
parent.parameters.mapping_path,
expected.args.mapping_path,
);
assert.deepEqual(parent.normalized_result, expected.normalized);
assert.notEqual(parent.raw_result, null);
}
}
runs.push({
temperature: pass === 0 ? "cold-provider" : "warm-session",
elapsed_ms: performance.now() - start,
calls: calls.length - firstCall,
});
}
if (values.variants) {
assert.ok(expected, "Variants require the source-built fixture");
const text = await readFile(mapping, "utf8");
const class_name = [...classNames].find(
([, original]) => original === "fixture.mapping.Original",
)?.[0];
assert.ok(class_name);
const lines = text.split("\n");
const fieldLine = lines.findIndex((line) =>
/^\s+java\.lang\.String title -> /u.test(line),
);
assert.ok(fieldLine > 0);
const partial = [...lines];
partial.splice(fieldLine, 1, " malformed member");
const partialPath = join(output, "partial-malformed.txt");
await writeFile(partialPath, partial.join("\n"));
const partialResult = await invoke("inspect_android_class", {
path: target,
class_name,
mapping_path: partialPath,
});
assert.equal(partialResult.mapping.records.malformed, 1);
assert.equal(partialResult.mapping.coverage.unmapped, 1);
assert.equal(partialResult.mapping.coverage.ambiguous, 0);
assert.ok(partialResult.mapping.coverage.mapped > 1);
const header = lines.findIndex(
(line) => line === `fixture.mapping.Original -> ${class_name}:`,
);
let end = header + 1;
while (end < lines.length && !/^[^\s#].* -> .*:$/u.test(lines[end])) end++;
const duplicatePath = join(output, "duplicate-class.txt");
await writeFile(
duplicatePath,
text + "\n" + lines.slice(header, end).join("\n"),
);
const duplicate = await invoke("inspect_android_class", {
path: target,
class_name,
mapping_path: duplicatePath,
});
assert.ok(duplicate.mapping.coverage.ambiguous > 0);
assert.equal(duplicate.mapping.coverage.unmapped, 0);
const owner = duplicate.mapping.symbols.find(
(row) => row.kind === "class" && row.raw_name === class_name,
);
assert.equal(owner.resolution.status, "ambiguous");
assert.equal(owner.resolution.candidate_count, 2);
const conflicting = [...lines];
conflicting.splice(
fieldLine + 1,
0,
'# {"id":"com.android.tools.r8.residualsignature","signature":"Ljava/lang/String;"}',
'# {"id":"com.android.tools.r8.residualsignature","signature":"I"}',
);
const conflictPath = join(output, "conflicting-residual.txt");
await writeFile(conflictPath, conflicting.join("\n"));
const conflict = await invoke("inspect_android_class", {
path: target,
class_name,
mapping_path: conflictPath,
});
assert.ok(
conflict.mapping.symbols.some(
(row) =>
row.kind === "field" &&
row.resolution.reason === "residual-signature-conflict",
),
);
}
await writeFile(join(output, "calls.json"), JSON.stringify(calls));
await writeFile(
join(output, "summary.json"),
JSON.stringify(
{
targetSha,
mappingSha,
classes: selected.length,
runs,
calls: calls.length,
},
null,
2,
),
);
console.log(
JSON.stringify({
targetSha,
mappingSha,
classes: selected.length,
runs,
calls: calls.length,
}),
);
} finally {
await client.close();
await writeFile(join(output, "stderr.log"), stderr);
}