Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

feat(native): let callers raise the Apple dispatch metadata input budget (#6233)

Kaoru0822363720562202
diff --git a/docs/native-investigation.md b/docs/native-investigation.md
index c1343a354..a47dd3093 100644
--- a/docs/native-investigation.md
+++ b/docs/native-investigation.md
@@ -467,6 +467,14 @@ complete observation.
vtable descriptors. Records include exact virtual addresses/file offsets and
artifact evidence. Vtable indexes are metadata word offsets; witness indexes
start after the conformance header. Names unavailable in metadata remain null.
+ The byte reader holds the whole selected file in memory, so it admits files up
+ to 64 MiB / 67108864 bytes by default. Select a larger budget with
+ `max_input_bytes` (CLI `--max-input-bytes`), at most 1 GiB / 1073741824
+ bytes. The whole file counts, including every slice of a universal Mach-O.
+ Results record `input_admission` with the effective budget, its source
+ (`default` or `caller`) and the bytes retained. A refusal names the observed
+ file size, the effective budget and its source, and either the budget to
+ select or, above 1 GiB, a deep analysis provider.
The `swift_class_vtable_descriptors` coverage counters count examined vtable
slots and successfully decoded slots, rather than type-section entries.
The `objc_class_method_ivar_metadata` counters count admitted class and
diff --git a/src/application/EnhancedTools.ts b/src/application/EnhancedTools.ts
index 7a22fd2cd..707e6318f 100644
--- a/src/application/EnhancedTools.ts
+++ b/src/application/EnhancedTools.ts
@@ -198,12 +198,13 @@ export class EnhancedTools {
): EnhancedResult {
switch (call.name) {
case "inspect_native_dispatch_metadata":
- return this.#inspectNativeDispatchMetadata(
- call.input.max_records,
+ return inspectNativeDispatch(this.analysis, call.input.max_records, {
signal,
- call.input.objc_class_import_addresses,
- call.input.objc_class_import_addresses_complete,
- );
+ objcClassImportAddresses: call.input.objc_class_import_addresses,
+ objcClassImportAddressesComplete:
+ call.input.objc_class_import_addresses_complete,
+ maxInputBytes: call.input.max_input_bytes,
+ });
case "get_objc_classes":
return this.#objcClasses(call.input.pattern, signal);
case "get_objc_protocols":
@@ -420,21 +421,6 @@ export class EnhancedTools {
);
}
- #inspectNativeDispatchMetadata(
- maxRecords: number,
- signal?: AbortSignal,
- objcClassImportAddresses?: readonly string[],
- objcClassImportAddressesComplete?: boolean,
- ): EnhancedResult {
- return inspectNativeDispatch(
- this.analysis,
- maxRecords,
- signal,
- objcClassImportAddresses,
- objcClassImportAddressesComplete,
- );
- }
-
async #objcProtocols(signal?: AbortSignal): EnhancedResult {
const names = await this.#allAddressed("list_names", signal);
return names.ok ? ok(discoverObjcProtocols(names.value)) : names;
diff --git a/src/application/native/NativeDispatchMetadataInspection.ts b/src/application/native/NativeDispatchMetadataInspection.ts
index f71cc39fd..fd384594a 100644
--- a/src/application/native/NativeDispatchMetadataInspection.ts
+++ b/src/application/native/NativeDispatchMetadataInspection.ts
@@ -20,12 +20,23 @@ export const NATIVE_DISPATCH_METADATA_SOURCES = {
export const inspectNativeDispatch = async (
analysis: AnalysisOperationPort,
maxRecords: number,
- signal?: AbortSignal,
- objcClassImportAddresses?: readonly string[],
- objcClassImportAddressesComplete?: boolean,
+ options: {
+ readonly signal?: AbortSignal | undefined;
+ readonly objcClassImportAddresses?: readonly string[] | undefined;
+ readonly objcClassImportAddressesComplete?: boolean | undefined;
+ /** Binary metadata input budget; symbol-only inventories ignore it. */
+ readonly maxInputBytes?: number | undefined;
+ } = {},
): EnhancedResult => {
+ const {
+ signal,
+ objcClassImportAddresses,
+ objcClassImportAddressesComplete,
+ maxInputBytes,
+ } = options;
const input = {
max_records: maxRecords,
+ ...(maxInputBytes === undefined ? {} : { max_input_bytes: maxInputBytes }),
...(objcClassImportAddresses === undefined
? {}
: {
diff --git a/src/application/native/NativeUiActionTrace.ts b/src/application/native/NativeUiActionTrace.ts
index d8e5b0965..6da173330 100644
--- a/src/application/native/NativeUiActionTrace.ts
+++ b/src/application/native/NativeUiActionTrace.ts
@@ -46,7 +46,7 @@ export const traceNativeUiAction = async (
},
signal === undefined ? {} : { signal },
),
- inspectNativeDispatch(analysis, 20_000, signal),
+ inspectNativeDispatch(analysis, 20_000, { signal }),
]);
if (!uiExecution.ok && uiExecution.error._tag === "AnalysisCancelledError")
return err(uiExecution.error);
diff --git a/src/cli/coreNativeCommands.ts b/src/cli/coreNativeCommands.ts
index 1c60d2fee..6eaff992e 100644
--- a/src/cli/coreNativeCommands.ts
+++ b/src/cli/coreNativeCommands.ts
@@ -1,3 +1,4 @@
+import { enhancedInputSchemas } from "../contracts/enhancedInputs.js";
import { z } from "incur";
import type { DirectAnalysis } from "../composition/directAnalysis.js";
@@ -272,6 +273,9 @@ const registerNativeDispatchMetadataCommand = (
.max(20_000)
.default(5_000)
.describe("Maximum symbol records to inspect"),
+ maxInputBytes:
+ enhancedInputSchemas.inspect_native_dispatch_metadata.shape
+ .max_input_bytes,
snapshot: snapshotSelectionOption.describe(
"Load or update the local analysis snapshot",
),
@@ -282,7 +286,12 @@ const registerNativeDispatchMetadataCommand = (
runDirectAnalysis(
args.path,
"inspect_native_dispatch_metadata",
- { max_records: options.maxRecords },
+ {
+ max_records: options.maxRecords,
+ ...(options.maxInputBytes === undefined
+ ? {}
+ : { max_input_bytes: options.maxInputBytes }),
+ },
directAnalysisOptionsFromCli(logger, options),
),
),
diff --git a/src/contracts/enhancedInputs.ts b/src/contracts/enhancedInputs.ts
index 029947485..5049e44ac 100644
--- a/src/contracts/enhancedInputs.ts
+++ b/src/contracts/enhancedInputs.ts
@@ -1,4 +1,5 @@
import { z } from "zod";
+import { MAXIMUM_DISPATCH_METADATA_INPUT_BYTES } from "../domain/native/objcSwiftMetadata.js";
import { nativeValueTraceInputSchema } from "../domain/native/nativeValueTrace.js";
const traceLiteralInputSchema = z.strictObject({
query: z.string().min(1),
@@ -37,6 +38,15 @@ export const enhancedInputSchemas = {
"Whether the candidate addresses include every selected class-label row; false keeps binding coverage partial when the existing record budget truncates the scan.",
)
.optional(),
+ max_input_bytes: z
+ .number()
+ .int()
+ .min(1)
+ .max(MAXIMUM_DISPATCH_METADATA_INPUT_BYTES)
+ .optional()
+ .describe(
+ "Largest target file REA reads into memory for binary metadata, in bytes. Omitted: 67108864 (64 MiB). The whole file counts, including every slice of a universal Mach-O. At most 1073741824 (1 GiB).",
+ ),
}),
get_objc_classes: z.strictObject({ pattern: z.string().default("") }),
get_objc_protocols: z.strictObject({}),
diff --git a/src/contracts/enhancedToolContracts.ts b/src/contracts/enhancedToolContracts.ts
index 3ecc2b9a7..1d1ae2463 100644
--- a/src/contracts/enhancedToolContracts.ts
+++ b/src/contracts/enhancedToolContracts.ts
@@ -27,7 +27,7 @@ const enhanced = <Name extends string, Schema extends z.ZodObject>(
export const ENHANCED_TOOL_CONTRACTS = [
enhanced(
"inspect_native_dispatch_metadata",
- "Inspect the bound provider's name inventory for Objective-C class/method symbols and Swift mangled symbols, returning at most max_records decoded names. Optional objc_class_import_addresses request exact pointer-slot binding facts for those addresses; they are decoded only from the selected Mach-O slice and retain partial or unsupported coverage when not established. Includes target SHA-256 when available, provider identity/version, analysis-profile digest, facet coverage, and per-record Evidence. This is static symbol and metadata evidence, not runtime metadata: ivar layouts, protocol conformances, witness/class tables, and relative pointers are explicitly marked unsupported unless a provider supplies those decoders. The provider controls how its name inventory is acquired.",
+ "Inspect the bound provider's name inventory for Objective-C class/method symbols and Swift mangled symbols, returning at most max_records decoded names. Optional objc_class_import_addresses request exact pointer-slot binding facts for those addresses; they are decoded only from the selected Mach-O slice and retain partial or unsupported coverage when not established. Includes target SHA-256 when available, provider identity/version, analysis-profile digest, facet coverage, and per-record Evidence. This is static symbol and metadata evidence, not runtime metadata: ivar layouts, protocol conformances, witness/class tables, and relative pointers are explicitly marked unsupported unless a provider supplies those decoders. The provider controls how its name inventory is acquired. The Mach-O byte reader holds the whole file in memory: max_input_bytes (default 64 MiB, at most 1 GiB) bounds it, and results record input_admission.",
enhancedInputSchemas.inspect_native_dispatch_metadata,
),
enhanced(
diff --git a/src/domain/native/objcSwiftMetadata.ts b/src/domain/native/objcSwiftMetadata.ts
index 57612ab16..61620c4fa 100644
--- a/src/domain/native/objcSwiftMetadata.ts
+++ b/src/domain/native/objcSwiftMetadata.ts
@@ -369,6 +369,30 @@ export const objcSwiftMetadataSchema = z.strictObject({
export type ObjcSwiftMetadata = z.infer<typeof objcSwiftMetadataSchema>;
/** Provider and target identity for one normalized dispatch-metadata result. */
+/** Retained-image budget when the caller selects none. */
+export const DEFAULT_DISPATCH_METADATA_INPUT_BYTES = 64 * 1024 * 1024;
+
+/**
+ * Largest caller-selected budget. The reader holds the whole selected file in
+ * REA's own heap; larger images belong to a deep provider that loads them in
+ * its own process.
+ */
+export const MAXIMUM_DISPATCH_METADATA_INPUT_BYTES = 1024 * 1024 * 1024;
+
+/** Effective input budget of one binary metadata read and the bytes it retained. */
+export const dispatchMetadataInputAdmissionSchema = z.strictObject({
+ maximum_bytes: z
+ .number()
+ .int()
+ .min(1)
+ .max(MAXIMUM_DISPATCH_METADATA_INPUT_BYTES),
+ source: z.enum(["default", "caller"]),
+ retained_bytes: z.number().int().nonnegative(),
+});
+export type DispatchMetadataInputAdmission = z.infer<
+ typeof dispatchMetadataInputAdmissionSchema
+>;
+
export const nativeDispatchMetadataResultSchema = z.strictObject({
target_sha256: z
.string()
@@ -381,6 +405,8 @@ export const nativeDispatchMetadataResultSchema = z.strictObject({
version: z.string().nullable(),
}),
analysis_profile_digest: z.string().min(1).nullable(),
+ /** Present when REA read the target bytes itself; symbol-only inventories have none. */
+ input_admission: dispatchMetadataInputAdmissionSchema.exactOptional(),
result: objcSwiftMetadataSchema,
});
diff --git a/src/native/AppleDispatchMetadata.ts b/src/native/AppleDispatchMetadata.ts
index cc812ab31..b99f78672 100644
--- a/src/native/AppleDispatchMetadata.ts
+++ b/src/native/AppleDispatchMetadata.ts
@@ -1,7 +1,10 @@
import { createHash } from "node:crypto";
import {
+ DEFAULT_DISPATCH_METADATA_INPUT_BYTES,
+ MAXIMUM_DISPATCH_METADATA_INPUT_BYTES,
objcSwiftMetadataSchema,
nativeDispatchMetadataResultSchema,
+ type DispatchMetadataInputAdmission,
type ObjcSwiftMetadata,
} from "../domain/native/objcSwiftMetadata.js";
import {
@@ -24,7 +27,6 @@ import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
-import { fixedNativeAllowance } from "../domain/native/nativeDeadlines.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import {
@@ -254,35 +256,78 @@ export const decodeAppleDispatchMetadata = (
return objcSwiftMetadataSchema.parse(result);
};
+const OPERATION = "inspect_native_dispatch_metadata";
+const MEBIBYTE = 1024 * 1024;
+const bytesWithUnits = (bytes: number): string =>
+ Number.isInteger(bytes / (MEBIBYTE * 1024))
+ ? `${String(bytes)} bytes (${String(bytes / (MEBIBYTE * 1024))} GiB)`
+ : Number.isInteger(bytes / MEBIBYTE)
+ ? `${String(bytes)} bytes (${String(bytes / MEBIBYTE)} MiB)`
+ : `${String(bytes)} bytes`;
+
+/** Refuse a file larger than the effective budget, naming how to raise it if possible. */
+const inputBudgetExceeded = (
+ admission: Omit<DispatchMetadataInputAdmission, "retained_bytes">,
+ observedBytes: number | null,
+): AnalysisResourceConstraintError => {
+ const budget = `${admission.source === "caller" ? "the selected max_input_bytes" : "the default input budget"} of ${bytesWithUnits(admission.maximum_bytes)}`;
+ const observed =
+ observedBytes === null ? "" : ` (${String(observedBytes)} bytes)`;
+ const remediationAction =
+ observedBytes === null
+ ? "The file grew while it was read. Retry once the file is stable."
+ : observedBytes <= MAXIMUM_DISPATCH_METADATA_INPUT_BYTES
+ ? `Retry with max_input_bytes (CLI --max-input-bytes) of at least ${String(observedBytes)}, at most ${bytesWithUnits(MAXIMUM_DISPATCH_METADATA_INPUT_BYTES)}; REA holds that many bytes in memory for the read.`
+ : `The file exceeds the largest selectable budget of ${bytesWithUnits(MAXIMUM_DISPATCH_METADATA_INPUT_BYTES)}; use a deep analysis provider for its Objective-C and Swift metadata.`;
+ return new AnalysisResourceConstraintError(
+ OPERATION,
+ "memory",
+ `Apple static metadata input${observed} exceeds ${budget}.`,
+ {
+ input_bytes: admission.maximum_bytes,
+ input_bytes_source: admission.source,
+ maximum_selectable_input_bytes: MAXIMUM_DISPATCH_METADATA_INPUT_BYTES,
+ ...(observedBytes === null
+ ? {}
+ : { observed_input_bytes: observedBytes }),
+ },
+ { retryable: false, remediationAction },
+ );
+};
+
+/** Optional per-read selections beyond the record budget. */
+export interface AppleDispatchMetadataOptions {
+ readonly signal?: AbortSignal | undefined;
+ readonly objcClassImportAddresses?: readonly string[] | undefined;
+ readonly objcClassImportAddressesComplete?: boolean | undefined;
+ /** Caller-selected input budget; the default applies when omitted. */
+ readonly maxInputBytes?: number | undefined;
+}
+
/**
- * Read digest-verified target bytes under a 64 MiB static metadata budget.
- * The caller's scope retains the target descriptor when its final close fails.
+ * Read digest-verified target bytes under the effective input budget and
+ * decode their static metadata. The caller's scope retains the target
+ * descriptor when its final close fails.
*/
export const inspectAppleDispatchMetadata = async (
target: BinaryTarget,
maxRecords: number,
resources: ArtifactResourceScope,
- signal?: AbortSignal,
- objcClassImportAddresses?: readonly string[],
- objcClassImportAddressesComplete = true,
+ options: AppleDispatchMetadataOptions = {},
) => {
+ const { signal } = options;
if (target.kind !== "executable" || !isMachOFormat(target.format))
throw new TypeError("Apple dispatch metadata requires a Mach-O target");
- const maximumBytes = 64 * 1024 * 1024;
- const capacityError = () =>
- new AnalysisResourceConstraintError(
- "inspect_native_dispatch_metadata",
- "memory",
- `Apple static metadata input exceeds its ${String(maximumBytes)}-byte (64 MiB) snapshot budget. This release has no runtime override.`,
- { input_bytes: maximumBytes },
- fixedNativeAllowance(
- "The Apple static metadata snapshot allowance",
- "parser",
- `${String(maximumBytes)} bytes`,
- ),
- );
+ const admission =
+ options.maxInputBytes === undefined
+ ? {
+ maximum_bytes: DEFAULT_DISPATCH_METADATA_INPUT_BYTES,
+ source: "default" as const,
+ }
+ : { maximum_bytes: options.maxInputBytes, source: "caller" as const };
+ const maximumBytes = admission.maximum_bytes;
const cancelled = () =>
- new AnalysisCancelledError("inspect_native_dispatch_metadata", {
+ new AnalysisCancelledError(OPERATION, {
cause: signal?.reason,
});
const { bytes, digest } = await withArtifactRegularFile(
@@ -291,13 +336,14 @@ export const inspectAppleDispatchMetadata = async (
signal,
async (handle) => {
const before = await handle.stat();
- if (before.size > maximumBytes) throw capacityError();
+ if (before.size > maximumBytes)
+ throw inputBudgetExceeded(admission, before.size);
if (signal?.aborted) throw cancelled();
const read = await readBoundedFileBytes(handle, maximumBytes, {
signal,
cancellationFailure: () => cancelled(),
});
- if (read === undefined) throw capacityError();
+ if (read === undefined) throw inputBudgetExceeded(admission, null);
const sha256 = createHash("sha256").update(read).digest("hex");
if (sha256 !== target.sha256)
throw new EvidenceIntegrityError(
@@ -312,19 +358,18 @@ export const inspectAppleDispatchMetadata = async (
target_architecture: target.architecture,
provider: APPLE_DISPATCH_METADATA_ANALYSIS_PROFILE.provider,
analysis_profile_digest: APPLE_DISPATCH_METADATA_ANALYSIS_PROFILE.digest,
+ input_admission: { ...admission, retained_bytes: bytes.length },
result: decodeAppleDispatchMetadata(
bytes,
maxRecords,
{ path: target.path, sha256: digest },
target.architecture,
- objcClassImportAddresses,
- objcClassImportAddressesComplete,
+ options.objcClassImportAddresses,
+ options.objcClassImportAddressesComplete ?? true,
),
});
};
-const OPERATION = "inspect_native_dispatch_metadata";
-
/** Translate the owned target read, keeping a failed close beside its physical outcome. */
export const appleDispatchMetadataFailure = (
cause: unknown,
diff --git a/src/native/NativeMacOSProvider.ts b/src/native/NativeMacOSProvider.ts
index bbc4ba5b2..157b73d4f 100644
--- a/src/native/NativeMacOSProvider.ts
+++ b/src/native/NativeMacOSProvider.ts
@@ -296,9 +296,13 @@ class NativeMacOSClient implements AnalysisClient {
this.target,
input.data.max_records,
this.#dispatchResources,
- options?.signal,
- input.data.objc_class_import_addresses,
- input.data.objc_class_import_addresses_complete ?? true,
+ {
+ signal: options?.signal,
+ objcClassImportAddresses: input.data.objc_class_import_addresses,
+ objcClassImportAddressesComplete:
+ input.data.objc_class_import_addresses_complete ?? true,
+ maxInputBytes: input.data.max_input_bytes,
+ },
),
);
return ok(
diff --git a/tests/boundary/cli/nativeDispatchInputBudget.test.ts b/tests/boundary/cli/nativeDispatchInputBudget.test.ts
new file mode 100644
index 000000000..581d41792
--- /dev/null
+++ b/tests/boundary/cli/nativeDispatchInputBudget.test.ts
@@ -0,0 +1,62 @@
+import { stat, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+import { describe, expect } from "vitest";
+
+import { parseEvidence } from "../../../src/domain/evidence.js";
+import { nativeDispatchMetadataResultSchema } from "../../../src/domain/native/objcSwiftMetadata.js";
+import { objcRecordBudgetMacho } from "../../fixtures/objcRecordBudgetMacho.js";
+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+import { cliTest } from "../../support/cli/cliFixture.js";
+
+describe.skipIf(process.platform !== "darwin")(
+ "native dispatch input budget through the public CLI",
+ () => {
+ cliTest(
+ "forwards --max-input-bytes to the byte reader and records its admission",
+ async ({ cli }) => {
+ const directory = await createTestTempDirectory("rea-objc-input-");
+ const path = join(directory, "fixture.macho");
+ await writeFile(path, objcRecordBudgetMacho("class"));
+ const size = (await stat(path)).size;
+ const run = (...flags: string[]) =>
+ cli.run({
+ arguments: [
+ "inspect-native-dispatch-metadata",
+ path,
+ ...flags,
+ "--json",
+ ],
+ environment: { REA_LOG_LEVEL: "silent" },
+ });
+ const admission = (output: Awaited<ReturnType<typeof run>>) => {
+ expect(output.exitCode, `${output.stdout}\n${output.stderr}`).toBe(0);
+ return nativeDispatchMetadataResultSchema.parse(
+ parseEvidence(output.json).normalized_result,
+ ).input_admission;
+ };
+
+ expect(admission(await run())).toEqual({
+ maximum_bytes: 67108864,
+ source: "default",
+ retained_bytes: size,
+ });
+ expect(admission(await run("--max-input-bytes", String(size)))).toEqual(
+ { maximum_bytes: size, source: "caller", retained_bytes: size },
+ );
+ const refused = await run("--max-input-bytes", String(size - 1));
+ expect(refused.exitCode).not.toBe(0);
+ expect(refused.json).toMatchObject({
+ code: "resource_constraint",
+ details: {
+ reported_limits: {
+ input_bytes: size - 1,
+ input_bytes_source: "caller",
+ observed_input_bytes: size,
+ },
+ },
+ });
+ },
+ );
+ },
+);
diff --git a/tests/boundary/filesystem/appleDispatchMetadataInputBudget.test.ts b/tests/boundary/filesystem/appleDispatchMetadataInputBudget.test.ts
new file mode 100644
index 000000000..d897a9073
--- /dev/null
+++ b/tests/boundary/filesystem/appleDispatchMetadataInputBudget.test.ts
@@ -0,0 +1,139 @@
+import { truncate, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+import { expect, it } from "vitest";
+
+import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
+import { enhancedInputSchemas } from "../../../src/contracts/enhancedInputs.js";
+import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
+import {
+ DEFAULT_DISPATCH_METADATA_INPUT_BYTES,
+ MAXIMUM_DISPATCH_METADATA_INPUT_BYTES,
+} from "../../../src/domain/native/objcSwiftMetadata.js";
+import {
+ appleDispatchMetadataFailure,
+ inspectAppleDispatchMetadata,
+} from "../../../src/native/AppleDispatchMetadata.js";
+import { withArtifactResourceScope } from "../../fixtures/artifactInventory.js";
+import { machoWithPropertyAttributes } from "../../fixtures/objcPropertyMacho.js";
+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+
+const fixtureTarget = async (bytes: Buffer, name = "fixture.bin") => {
+ const directory = await createTestTempDirectory("rea-dispatch-budget-");
+ const path = join(directory, name);
+ await writeFile(path, bytes);
+ const target = await parseBinaryTarget(path);
+ if (!target.ok) throw target.error;
+ return { path, target: target.value };
+};
+
+const inspect = (
+ target: Awaited<ReturnType<typeof fixtureTarget>>["target"],
+ maxInputBytes?: number,
+) =>
+ withArtifactResourceScope((resources) =>
+ resources.run(() =>
+ inspectAppleDispatchMetadata(target, 100, resources, { maxInputBytes }),
+ ),
+ );
+
+const refusal = async (
+ path: string,
+ run: () => Promise<unknown>,
+): Promise<ReturnType<typeof projectAnalysisError>> => {
+ const failure = await run().then(
+ () => undefined,
+ (cause: unknown) => cause,
+ );
+ if (failure === undefined) throw new Error("Expected a budget refusal");
+ return projectAnalysisError(appleDispatchMetadataFailure(failure, path));
+};
+
+it("records the default budget and the caller-selected budget it read under", async () => {
+ const bytes = machoWithPropertyAttributes("Tq,N");
+ const { target } = await fixtureTarget(bytes);
+ await expect(inspect(target)).resolves.toMatchObject({
+ input_admission: {
+ maximum_bytes: DEFAULT_DISPATCH_METADATA_INPUT_BYTES,
+ source: "default",
+ retained_bytes: bytes.length,
+ },
+ });
+ const exact = await inspect(target, bytes.length);
+ expect(exact.input_admission).toEqual({
+ maximum_bytes: bytes.length,
+ source: "caller",
+ retained_bytes: bytes.length,
+ });
+ // The budget changes admission only, never the decoded metadata.
+ expect(exact.result).toEqual((await inspect(target)).result);
+});
+
+it("names the observed size, effective budget, its source and the budget to select", async () => {
+ const bytes = machoWithPropertyAttributes("Tq,N");
+ const { path, target } = await fixtureTarget(bytes);
+ const projected = await refusal(path, () =>
+ inspect(target, bytes.length - 1),
+ );
+ expect(projected).toMatchObject({
+ code: "resource_constraint",
+ retryable: false,
+ message: `Apple static metadata input (${String(bytes.length)} bytes) exceeds the selected max_input_bytes of ${String(bytes.length - 1)} bytes.`,
+ remediation: {
+ action: `Retry with max_input_bytes (CLI --max-input-bytes) of at least ${String(bytes.length)}, at most 1073741824 bytes (1 GiB); REA holds that many bytes in memory for the read.`,
+ },
+ details: {
+ reported_limits: {
+ input_bytes: bytes.length - 1,
+ input_bytes_source: "caller",
+ maximum_selectable_input_bytes: MAXIMUM_DISPATCH_METADATA_INPUT_BYTES,
+ observed_input_bytes: bytes.length,
+ },
+ },
+ });
+ expect(JSON.stringify(projected)).not.toContain("no runtime override");
+});
+
+it("refuses files above the default without opt-in and points past the maximum to a deep provider", async () => {
+ // Sparse files: admission is decided from the stat size before any read.
+ const bytes = machoWithPropertyAttributes("Tq,N");
+ for (const [size, source, action] of [
+ [
+ DEFAULT_DISPATCH_METADATA_INPUT_BYTES + 1,
+ "default",
+ `of at least ${String(DEFAULT_DISPATCH_METADATA_INPUT_BYTES + 1)}`,
+ ],
+ [
+ MAXIMUM_DISPATCH_METADATA_INPUT_BYTES + 1,
+ "caller",
+ "use a deep analysis provider",
+ ],
+ ] as const) {
+ const { path, target } = await fixtureTarget(bytes, `large-${source}.bin`);
+ await truncate(path, size);
+ const projected = await refusal(path, () =>
+ inspect(
+ target,
+ source === "caller" ? MAXIMUM_DISPATCH_METADATA_INPUT_BYTES : undefined,
+ ),
+ );
+ expect(projected.details).toMatchObject({
+ reported_limits: {
+ input_bytes_source: source,
+ observed_input_bytes: size,
+ },
+ });
+ expect(projected.remediation.action).toContain(action);
+ }
+});
+
+it("validates max_input_bytes at the shared input contract", () => {
+ const schema = enhancedInputSchemas.inspect_native_dispatch_metadata;
+ expect(schema.parse({}).max_input_bytes).toBeUndefined();
+ expect(
+ schema.parse({ max_input_bytes: MAXIMUM_DISPATCH_METADATA_INPUT_BYTES })
+ .max_input_bytes,
+ ).toBe(MAXIMUM_DISPATCH_METADATA_INPUT_BYTES);
+ for (const value of [0, -1, 1.5, MAXIMUM_DISPATCH_METADATA_INPUT_BYTES + 1])
+ expect(schema.safeParse({ max_input_bytes: value }).success).toBe(false);
+});
diff --git a/tests/boundary/mcp/enhancedTools.04-uses-complete-inventories-inline.test.ts b/tests/boundary/mcp/enhancedTools.04-uses-complete-inventories-inline.test.ts
index c4a0d6b23..0a4513273 100644
--- a/tests/boundary/mcp/enhancedTools.04-uses-complete-inventories-inline.test.ts
+++ b/tests/boundary/mcp/enhancedTools.04-uses-complete-inventories-inline.test.ts
@@ -658,3 +658,34 @@ it("refuses document fallback while the current-selection owner reports incomple
expect(calls).toEqual(["current_document"]);
expect(failure.cleanupIncomplete).toBe(true);
});
+
+it("forwards max_input_bytes from the MCP tool to the binary metadata operation", async () => {
+ const received: unknown[] = [];
+ const client = await connect({
+ execute: (name, parameters) => {
+ if (name === "inspect_native_dispatch_metadata")
+ received.push(parameters);
+ return Promise.resolve(
+ err(
+ new AnalysisCapabilityUnavailableError(
+ "fixture",
+ name,
+ "Metadata is unavailable in this provider fixture",
+ ),
+ ),
+ );
+ },
+ });
+ await client.callTool({
+ name: "inspect_native_dispatch_metadata",
+ arguments: { max_input_bytes: 134217728 },
+ });
+ await client.callTool({
+ name: "inspect_native_dispatch_metadata",
+ arguments: {},
+ });
+ expect(received).toEqual([
+ { max_records: 5000, max_input_bytes: 134217728 },
+ { max_records: 5000 },
+ ]);
+});