Reverse engineer anything with agents, from app behavior down to native binaries.
TypeScript agent-skillsai-agentsbinary-analysisclaude-codeclicodexcordisdecompilerdeveloper-toolsdshdsh-pluginghidrahopperllmmcpmodel-context-protocolreareverse-engineeringstatic-analysistouhou
fix(erlang): derive budget recovery from parser-owned facts
morlutoa4a548718d69
diff --git a/src/erlang/BeamParser.test.ts b/src/erlang/BeamParser.test.tsindex 64695b30a..fb3e2ee32 100644--- a/src/erlang/BeamParser.test.ts+++ b/src/erlang/BeamParser.test.ts@@ -1,5 +1,6 @@import { createHash } from "node:crypto";-import { expect, it } from "vitest";+import { expect, it, vi } from "vitest";+import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js";import {MAX_INSPECT_ERLANG_BEAM_TABLE_ROWS,inspectErlangBeamInputSchema,@@ -11,7 +12,9 @@ import {erlangBeamManyAtomsFixture,erlangBeamOtp29Fixture,} from "./Beam.fixture.js";-import { parseErlangBeam } from "./BeamParser.js";+import { BeamCapacityFailure, parseErlangBeam } from "./BeamParser.js";+import { BeamProvider } from "./BeamProvider.js";+import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";const defaults = inspectErlangBeamInputSchema.parse({path: "/artifacts/app.beam",@@ -198,3 +201,94 @@ it("fails when the atom budget is exhausted", () => {),).toThrow(ArtifactReaderFailure);});++it("does not infer a BEAM budget from diagnostic prose", async () => {+ const provider = new BeamProvider();+ const injection = vi+ .spyOn(ArtifactResourceScope.prototype, "run")+ .mockRejectedValueOnce(+ new ArtifactReaderFailure(+ "limit",+ "atom row budget wording from another boundary",+ { boundary: "capacity" },+ ),+ );+ try {+ const result = await provider.inspect(defaults);+ if (result.ok) throw new Error("Expected unknown capacity failure");+ expect(result.error).toBeInstanceOf(AnalysisResourceConstraintError);+ if (!(result.error instanceof AnalysisResourceConstraintError))+ throw new Error("Missing resource error");+ expect(result.error.retryable).toBeUndefined();+ expect(result.error.remediationAction).toBeUndefined();+ } finally {+ injection.mockRestore();+ await provider.close();+ }+});++it.each([+ {+ resource: "atoms",+ bytes: erlangBeamManyAtomsFixture(3),+ settings: { max_atoms: 1 },+ maximum: 1,+ remediation: "Raise max_atoms above 1",+ },+ {+ resource: "chunks",+ bytes: erlangBeamFixture(),+ settings: { max_chunks: 1 },+ maximum: 1,+ remediation: "Raise max_chunks above 1",+ },+ {+ resource: "table-rows",+ bytes: erlangBeamDeclaredRowsFixture([+ ["ExpT", MAX_INSPECT_ERLANG_BEAM_TABLE_ROWS + 1],+ ]),+ settings: {},+ maximum: MAX_INSPECT_ERLANG_BEAM_TABLE_ROWS,+ remediation: `${String(MAX_INSPECT_ERLANG_BEAM_TABLE_ROWS)}-row ceiling`,+ },+])(+ "retains the producing $resource allowance when diagnostic wording changes",+ async ({ resource, bytes, settings, maximum, remediation }) => {+ const input = inspectErlangBeamInputSchema.parse({+ path: defaults.path,+ ...settings,+ });+ let cause: unknown;+ try {+ parse(bytes, input);+ } catch (failure) {+ cause = failure;+ }+ expect(cause).toBeInstanceOf(BeamCapacityFailure);+ if (!(cause instanceof BeamCapacityFailure))+ throw new Error("Missing named parser allowance");+ expect(cause).toMatchObject({+ resource,+ maximum,+ reason: "limit",+ boundary: "capacity",+ });+ cause.message = "BEAM parser allowance exhausted.";+ const provider = new BeamProvider();+ const injection = vi+ .spyOn(ArtifactResourceScope.prototype, "run")+ .mockRejectedValueOnce(cause);+ try {+ const result = await provider.inspect(input);+ if (result.ok) throw new Error("Expected named capacity failure");+ expect(result.error).toMatchObject({+ _tag: "AnalysisResourceConstraintError",+ retryable: false,+ remediationAction: expect.stringContaining(remediation),+ });+ } finally {+ injection.mockRestore();+ await provider.close();+ }+ },+);diff --git a/src/erlang/BeamParser.ts b/src/erlang/BeamParser.tsindex 82a401fa5..bac7568d4 100644--- a/src/erlang/BeamParser.ts+++ b/src/erlang/BeamParser.ts@@ -7,6 +7,18 @@ import {type InspectErlangBeamInput,} from "../domain/erlang/beam.js";+/** The producing parser names its count allowance independently of diagnostic text. */+export class BeamCapacityFailure extends ArtifactReaderFailure {+ constructor(+ readonly resource: "atoms" | "chunks" | "table-rows",+ readonly maximum: number,+ message: string,+ ) {+ super("limit", message, { boundary: "capacity" });+ this.name = "BeamCapacityFailure";+ }+}+const fail = (message: string): never => {throw new ArtifactReaderFailure("format", message);};@@ -77,10 +89,10 @@ const parseAtoms = (const compact = declared < 0;const count = Math.abs(declared);if (count > maxAtoms)- throw new ArtifactReaderFailure(- "limit",+ throw new BeamCapacityFailure(+ "atoms",+ maxAtoms,`BEAM atom table exceeds the ${String(maxAtoms)}-atom budget.`,- { boundary: "capacity" },);const atoms: NonNullable<ErlangBeam["atoms"]> = [];let at = 4;@@ -169,10 +181,10 @@ export const parseErlangBeam = (while (at < formEnd) {if (formEnd - at < 8) fail("BEAM chunk header is truncated.");if (chunks.length >= input.max_chunks)- throw new ArtifactReaderFailure(- "limit",+ throw new BeamCapacityFailure(+ "chunks",+ input.max_chunks,`BEAM form exceeds the ${String(input.max_chunks)}-chunk budget.`,- { boundary: "capacity" },);const name = chunkName(bytes, at);const size = u32(bytes, at + 4);@@ -215,12 +227,12 @@ export const parseErlangBeam = (declaredRows("ExpT") + declaredRows("ImpT") + declaredRows("FunT") >MAX_INSPECT_ERLANG_BEAM_TABLE_ROWS)- throw new ArtifactReaderFailure(- "limit",+ throw new BeamCapacityFailure(+ "table-rows",+ MAX_INSPECT_ERLANG_BEAM_TABLE_ROWS,`BEAM tables exceed the ${String(MAX_INSPECT_ERLANG_BEAM_TABLE_ROWS,)}-row budget.`,- { boundary: "capacity" },);const exports =payloads.get("ExpT") === undefineddiff --git a/src/erlang/BeamProvider.ts b/src/erlang/BeamProvider.tsindex d4b79afbd..7c6a2ef3e 100644--- a/src/erlang/BeamProvider.ts+++ b/src/erlang/BeamProvider.ts@@ -21,12 +21,11 @@ import {MAX_INSPECT_ERLANG_BEAM_ATOMS,MAX_INSPECT_ERLANG_BEAM_CHUNKS,MAX_INSPECT_ERLANG_BEAM_FILE_BYTES,- MAX_INSPECT_ERLANG_BEAM_TABLE_ROWS,type InspectErlangBeamInput,} from "../domain/erlang/beam.js";import { err, ok } from "../domain/result.js";import { ProviderCleanupError } from "../domain/providerCleanupError.js";-import { parseErlangBeam } from "./BeamParser.js";+import { BeamCapacityFailure, parseErlangBeam } from "./BeamParser.js";/** Bundled format reader identity; module names are separate observed facts. */export const ERLANG_BEAM_PROVIDER_IDENTITY = {@@ -91,23 +90,26 @@ export class BeamProvider implements BeamPort {}const inputBudgetRemediation = (- boundary: "file-size" | "capacity",+ cause: ArtifactReaderFailure,input: InspectErlangBeamInput,- message: string,-): string => {- if (boundary === "file-size")+): string | undefined => {+ if (cause.boundary === "file-size")return input.max_file_bytes >= MAX_INSPECT_ERLANG_BEAM_FILE_BYTES? `The file exceeds the ${String(MAX_INSPECT_ERLANG_BEAM_FILE_BYTES)}-byte input ceiling this operation accepts; select a smaller artifact.`: `Raise max_file_bytes above ${String(input.max_file_bytes)} bytes or select a smaller artifact; the limit is the caller-selected input read budget.`;- if (message.includes("atom"))- return input.max_atoms >= MAX_INSPECT_ERLANG_BEAM_ATOMS- ? `The file exceeds the ${String(MAX_INSPECT_ERLANG_BEAM_ATOMS)}-atom ceiling this operation accepts; select a smaller artifact.`- : `Raise max_atoms above ${String(input.max_atoms)} or select a smaller artifact; the limit is the caller-selected atom budget.`;- if (message.includes("row budget"))- return `The file exceeds the ${String(MAX_INSPECT_ERLANG_BEAM_TABLE_ROWS)}-row ceiling this operation accepts; select a smaller artifact.`;- return input.max_chunks >= MAX_INSPECT_ERLANG_BEAM_CHUNKS- ? `The file exceeds the ${String(MAX_INSPECT_ERLANG_BEAM_CHUNKS)}-chunk ceiling this operation accepts; select a smaller artifact.`- : `Raise max_chunks above ${String(input.max_chunks)} or select a smaller artifact; the limit is the caller-selected chunk budget.`;+ if (!(cause instanceof BeamCapacityFailure)) return undefined;+ switch (cause.resource) {+ case "atoms":+ return cause.maximum >= MAX_INSPECT_ERLANG_BEAM_ATOMS+ ? `The file exceeds the ${String(MAX_INSPECT_ERLANG_BEAM_ATOMS)}-atom ceiling this operation accepts; select a smaller artifact.`+ : `Raise max_atoms above ${String(cause.maximum)} or select a smaller artifact; the limit is the caller-selected atom budget.`;+ case "table-rows":+ return `The file exceeds the ${String(cause.maximum)}-row ceiling this operation accepts; select a smaller artifact.`;+ case "chunks":+ return cause.maximum >= MAX_INSPECT_ERLANG_BEAM_CHUNKS+ ? `The file exceeds the ${String(MAX_INSPECT_ERLANG_BEAM_CHUNKS)}-chunk ceiling this operation accepts; select a smaller artifact.`+ : `Raise max_chunks above ${String(cause.maximum)} or select a smaller artifact; the limit is the caller-selected chunk budget.`;+ }};const beamFailurePrimary = (cause: unknown, input: InspectErlangBeamInput) => {@@ -125,7 +127,8 @@ const beamFailurePrimary = (cause: unknown, input: InspectErlangBeamInput) => {cause: artifactFileCancellationCause(cause),});if (cause instanceof ArtifactReaderFailure) {- if (cause.reason === "limit")+ if (cause.reason === "limit") {+ const remediationAction = inputBudgetRemediation(cause, input);return new AnalysisResourceConstraintError(OPERATION,cause.boundary ?? "memory",@@ -137,18 +140,15 @@ const beamFailurePrimary = (cause: unknown, input: InspectErlangBeamInput) => {},{cause,- ...(cause.boundary === undefined || cause.boundary === "memory"+ ...(remediationAction === undefined? {}: {retryable: false,- remediationAction: inputBudgetRemediation(- cause.boundary,- input,- cause.message,- ),+ remediationAction,}),},);+ }if (cause.reason === "path" || cause.reason === "format")return new AnalysisInputError(OPERATION, { cause }, [{diff --git a/tests/boundary/mcp/erlangBeamMcp.test.ts b/tests/boundary/mcp/erlangBeamMcp.test.tsindex 5c865f5b8..0b80c589e 100644--- a/tests/boundary/mcp/erlangBeamMcp.test.ts+++ b/tests/boundary/mcp/erlangBeamMcp.test.ts@@ -5,10 +5,15 @@ import { toolContract } from "../../../src/contracts/toolContracts.js";import { createServer } from "../../../src/server/createServer.js";import { createTestBinarySession } from "../../fixtures/binarySession.js";import { parseMcpToolError } from "../../fixtures/mcpToolError.js";-import { erlangBeamFixture } from "../../../src/erlang/Beam.fixture.js";+import {+ erlangBeamDeclaredRowsFixture,+ erlangBeamFixture,+} from "../../../src/erlang/Beam.fixture.js";import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";import { mcpTest, type TestMcp } from "../../support/mcp/mcpFixture.js";+import { MAX_INSPECT_ERLANG_BEAM_TABLE_ROWS } from "../../../src/domain/erlang/beam.js";+const connect = async (mcp: TestMcp) => {const session = createTestBinarySession(() => {throw new Error("BEAM inspection must not start a deep provider");@@ -67,3 +72,51 @@ mcpTest(}},);++mcpTest(+ "returns recovery for the actual exhausted BEAM allowance",+ async ({ mcp }) => {+ const { client, session } = await connect(mcp);+ const root = await createTestTempDirectory("rea-beam-capacity-");+ try {+ for (const [label, bytes, settings, remediation] of [+ [+ "atoms",+ erlangBeamFixture(),+ { max_atoms: 1 },+ "Raise max_atoms above 1",+ ],+ [+ "chunks",+ erlangBeamFixture(),+ { max_chunks: 1 },+ "Raise max_chunks above 1",+ ],+ [+ "rows",+ erlangBeamDeclaredRowsFixture([+ ["ExpT", MAX_INSPECT_ERLANG_BEAM_TABLE_ROWS + 1],+ ]),+ {},+ `${String(MAX_INSPECT_ERLANG_BEAM_TABLE_ROWS)}-row ceiling`,+ ],+ ] as const) {+ const path = join(root, `${label}.beam`);+ await writeFile(path, bytes);+ const response = await client.callTool({+ name: "inspect_erlang_beam",+ arguments: { path, ...settings },+ });+ expect(response.isError).toBe(true);+ const error = parseMcpToolError(response).error;+ expect(error).toMatchObject({+ code: "resource_constraint",+ retryable: false,+ remediation: { action: expect.stringContaining(remediation) },+ });+ }+ } finally {+ await session.close();+ }+ },+);