fix(reverse): reconcile cleanup ownership and mutation diagnostics (#2799)

* feat(process): add owned debugger shutdown lifecycle

* feat(reverse): add local inspection commands

* feat(gdb): add persistent debugger integration

* feat(cutter): add Cutter bridge integration

* test(reverse): enforce complete integration coverage

* fix(process): preserve debugger shutdown ownership

* fix(reverse): retain evidence across interrupted commands

* fix(gdb): honor captured provider environment

* test(process): cover debugger shutdown retries

* fix(reverse): retain evidence for interrupted providers

* test(process): cover debugger shutdown retries

* fix(reverse): retain evidence for interrupted providers

* fix(server): snapshot provider environment at creation

* fix(reverse): close review gaps with complete coverage

* fix(reverse): address inspection review findings

* fix(gdb): bound sessions and retain cleanup ownership

* fix(ci): require reverse-tools quality lane

* fix(process): unref inherited debugger output pipes

* fix(reverse): address remaining PR 1960 findings

* fix(gdb): address remaining PR 1961 findings

* fix(reverse): account for unrestricted provider execution

* fix(process): retain debugger ownership until safe shutdown

* fix(process): preserve replacement debugger sessions

* fix(reverse): preserve admission and output provenance

* fix(process): retain exited debugger until output settles

* fix(mcp): bound provider admission and debugger cleanup

* fix(reverse): preserve failure provenance and classify E2BIG

* fix(gdb): preserve startup cleanup and detach safety

* fix(process): retain debugger ownership after detach failure

* fix(reverse): preserve mutation and failure provenance

* fix(gdb): address debugger review findings

* fix(reverse): rebind sessions after external mutation

* fix(process): cap debugger output after exit

* fix(gdb): protect one-shot detach verification

* feat(debugger): add reverse tool coverage gate

* test(debugger): cover integrated failure paths

* fix(gdb): bound and preserve session observations

* fix(gdb): address review regressions

* style: format merged integration files

* fix(reverse): preserve session and output evidence

* refactor(gdb): share repeated test and partial result setup

* fix(gdb): invalidate TTY proof for Python aliases

* fix(reverse): retain failure output byte counts

* test(process): synchronize late debugger output

* fix(gdb): invalidate TTY proof for wrapped commands

* fix(gdb): recognize wit command abbreviation

* test(reverse): wait for cancelled descendant readiness

* test(reverse): bound descendant cancellation cleanup

* style(reverse): format integration tests and adapters

* style: format reverse engineering integration files

* test(reverse): remove duplicate environment harness

* test(gdb): share session startup assertions

* fix(gdb): invalidate output proof for command abbreviations

* test(reverse): share composition edge case scenarios

* fix(ci): recognize verification and mutation tool entries

* test(rizin): cover successful fake inferior detach

* test(cli): align full output failure envelope

* test(cli): isolate reverse command lifecycle service

* test(process): share debugger output fixture setup

* fix(binary): preserve high-bit Windows signature bytes

* style(binary): format Windows signature parser

* test(mcp): preserve call coverage in unchanged comparison

* fix(ci): include reverse tools Vitest configs in lint cache

* fix(mcp): preserve target content on delivery errors

* ci: align duplication ceiling with expanded suite

* test(reverse): allow signal admission mutants

* fix(reverse): bound retained cleanup failures to process owners

* fix(test): replace drifting mutation ranges with owned selectors

* fix(reverse): admit persistent commands and retain cleanup ownership

* fix(cutter): recover timed-out commands from exact receipts

* fix(cutter): reject unsupported bridge request kinds

* fix(ci): repair client format and shared verification fixtures

* fix(native): preserve debugger cleanup ownership and bridge authentication

* test(native): retain diagnostics without perfect coverage requirements

* chore(licenses): refresh locked dependency inventory and notices

* fix(test): exclude transient command locks from mutation sandboxes

* fix(gdb): admit only platforms with safe detach verification

* fix(cutter): retain bounded completion receipts until acknowledgement

* fix(cutter): acknowledge commands rejected before UI dispatch

* test(reverse): fail cancellation checks before fixture teardown

* test(gdb): clean up the retained broken-stdin fixture owner

* docs(test): clarify focused provider verification scope

* fix(rizin): retain close cleanup failures

* fix(gdb): wait for inferior stop and bound MI buffering

* fix(cutter): retain failed receipt acknowledgements

* fix(rizin): return retained session identity on rebind failure

* fix(gdb): preserve startup cancellation and lossy status

* fix(rizin): retain launch provenance and assemble frames once

* fix(cutter): recover receipts across callers and bound discovery

* docs: describe debugger evidence and bridge recovery

* fix(process): keep cleanup incomplete while writers remain

Stopping a debugger no longer reports success when inherited output
streams stay open, so BinarySession cannot reopen a binary a child is
still changing. Concurrent Cutter cleanup retries share one receipt
acknowledgement instead of treating a consumed receipt as failure.

* fix(debuggers): recover cleanup with captured process identities

* fix(analysis): retire sessions after unrestricted commands

* fix(cli): preserve completed evidence after cleanup recovery

* fix(cutter): bound frame collection and coalesce cleanup

* fix(windows): resolve selected provider paths absolutely

* fix(gdb): report decoding loss in failed startup evidence

* fix(rizin): scope decoding loss to collected command frames

* test(mcp): cover snapshot retirement in reverse tools CI

---------

Co-authored-by: Daniel Gonçalves Araujo <47118053+dandgabr@users.noreply.github.com>
Co-authored-by: REA Maintainers <noreply@github.com>
Co-authored-by: OpenAI Codex <codex@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
This commit is contained in:
morluto
2026-10-14 04:47:34 +08:00
committed by GitHub
co-authored by Daniel Gonçalves Araujo REA Maintainers OpenAI Codex Cursor Agent
parent 2ad2a044d4
commit 4aa51bfe19
168 changed files with 32703 additions and 238 deletions
+25 -1
View File
@@ -65,7 +65,7 @@ export abstract class AnalysisError extends Error {
readonly diagnostics: Readonly<Record<string, JsonValue>> | undefined;
readonly capturedOutput: AnalysisCapturedOutput | undefined;
readonly cleanup: AnalysisCleanupObservation | undefined;
readonly cleanupIncomplete: boolean;
cleanupIncomplete: boolean;
readonly cleanupResources: readonly string[];
constructor(message: string, options?: AnalysisErrorOptions) {
super(message, options);
@@ -89,6 +89,30 @@ export abstract class AnalysisError extends Error {
partialObservation: AnalysisPartialObservation | undefined;
readonly cleanupReport: ProcessCaptureCleanupReport | undefined = undefined;
/** Retain a later lifecycle failure without replacing the original typed error. */
retainSecondaryFailure(
failure: AnalysisError,
diagnostics: Readonly<Record<string, JsonValue>>,
): this {
// Secondary resources remain owned by their cleanup lifecycle; preserve
// the primary error's live cleanup status and original output.
Object.assign(this, {
diagnostics: structuredClone({ ...this.diagnostics, ...diagnostics }),
cause: new AggregateError(
this.cause === undefined ? [failure] : [this.cause, failure],
"Analysis failed and a later lifecycle operation also failed.",
{ cause: this.cause },
),
});
return this;
}
/** Clear live cleanup status only after its owning resource confirms retry success. */
resolveCleanup(): this {
this.cleanupIncomplete = false;
return this;
}
/** Retain a completed observation when a later step fails. */
retainPartialObservation(observation: AnalysisPartialObservation): this {
this.partialObservation ??= observation;
+3 -1
View File
@@ -86,13 +86,15 @@ export interface AnalysisInputIssue {
/** Provider output failed provider-neutral application parsing. */
export class AnalysisOutputError extends AnalysisError {
readonly _tag = "AnalysisOutputError";
readonly cleanupOnly: boolean;
constructor(
readonly operation: string,
readonly reason: string,
options?: AnalysisErrorOptions,
options?: AnalysisErrorOptions & { readonly cleanupOnly?: boolean },
) {
super(`Invalid analysis output for ${operation}: ${reason}`, options);
this.cleanupOnly = options?.cleanupOnly ?? false;
}
}
@@ -796,3 +796,32 @@ describe("analysis error projection: evidence files", () => {
},
);
});
it("retains the primary failure and both cleanup reports after a secondary failure", () => {
const primary = new AnalysisCancelledError("execute_rizin_command", {
capturedOutput: {
stdout: "partial",
stderr: "diagnostic",
truncated: false,
},
cleanup: { reason: "writer remains", resources: ["writer"] },
});
const secondary = new AnalysisOutputError("open_binary", "cannot rebind", {
cleanup: { reason: "provider remains", resources: ["provider", "writer"] },
});
const enriched = primary.retainSecondaryFailure(secondary, {
rebind_error: projectAnalysisError(secondary),
});
expect(enriched).toBe(primary);
expect(enriched._tag).toBe("AnalysisCancelledError");
expect(projectAnalysisError(enriched)).toMatchObject({
code: "cleanup_incomplete",
details: {
execution_failure: "cancelled",
resources: ["writer"],
cleanup_reason: "writer remains",
captured_output: { stdout: "partial", stderr: "diagnostic" },
diagnostics: { rebind_error: { code: "cleanup_incomplete" } },
},
});
});
+3 -3
View File
@@ -447,8 +447,8 @@ const lifecycleErrorDetails = (
if (error instanceof AnalysisCancelledError)
return {
operation: error.operation,
cleanup: error.cleanup === undefined ? "complete" : "incomplete",
...(error.cleanup === undefined
cleanup: error.cleanupIncomplete ? "incomplete" : "complete",
...(error.cleanup === undefined || !error.cleanupIncomplete
? {}
: {
cleanup_reason: error.cleanup.reason,
@@ -462,7 +462,7 @@ const lifecycleErrorDetails = (
return {
operation: error.operation,
timeout_ms: error.timeoutMs,
...(error.cleanup === undefined
...(error.cleanup === undefined || !error.cleanupIncomplete
? {}
: {
cleanup: "incomplete",
+1 -1
View File
@@ -11,7 +11,7 @@ import { AnalysisCancelledError } from "./analysisErrorCore.js";
/** A bounded passive browser observation failed at its CDP boundary. */
export class BrowserObservationError extends AnalysisError {
readonly _tag = "BrowserObservationError";
override readonly cleanupIncomplete: boolean;
override cleanupIncomplete: boolean;
override readonly cleanupResources: readonly string[];
override readonly userCategory: "cancelled" | undefined;
override readonly userMessage: string | undefined;
+7 -6
View File
@@ -72,13 +72,14 @@ const windowsHeaderSignature = (
bytes: Buffer | undefined,
): "PE" | "NE" | "LE" | "LX" | "other" | "unobserved" => {
if (bytes === undefined || bytes.length < 2) return "unobserved";
const prefix = bytes.toString("latin1", 0, 2);
if (prefix === "NE" || prefix === "LE" || prefix === "LX") return prefix;
if (prefix !== "PE") return "other";
const first = bytes[0];
const second = bytes[1];
if (first === 0x4e && second === 0x45) return "NE";
if (first === 0x4c && second === 0x45) return "LE";
if (first === 0x4c && second === 0x58) return "LX";
if (first !== 0x50 || second !== 0x45) return "other";
if (bytes.length < 4) return "unobserved";
return bytes.subarray(0, 4).equals(Buffer.from("PE\0\0", "binary"))
? "PE"
: "other";
return bytes[2] === 0 && bytes[3] === 0 ? "PE" : "other";
};
/**
+13 -1
View File
@@ -78,9 +78,21 @@ describe("Hopper boundary values", () => {
(_label, parse) => {
const result = parse();
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error._tag).toBe("HopperProtocolError");
if (!result.ok) expect(result.error._tag).toBe("AnalysisOutputError");
},
);
it("uses provider-neutral wording for malformed shared values", () => {
const result = parseSegments([{ name: 1 }]);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error._tag).toBe("AnalysisOutputError");
expect(result.error.operation).toBe("list_segments");
expect(result.error.reason).toBe(
"Provider returned an invalid segment list",
);
}
});
});
describe("provider-neutral inclusive function body evidence", () => {
+33 -21
View File
@@ -7,7 +7,6 @@ import { err, ok, type Result } from "./result.js";
import { nativeApiBoundarySchema } from "./native/nativeApiBoundary.js";
import { nativeValueFlowSchema } from "./native/nativeValueFlow.js";
import { AnalysisOutputError } from "./analysisErrorCore.js";
import { HopperProtocolError } from "./hopperErrors.js";
export interface AddressedName {
readonly address: string;
@@ -460,10 +459,11 @@ export const parseFunctionDossier = (
);
};
/** Parse Hopper's direct or wrapped procedure map into stable entries. */
/** Parse a provider's direct or wrapped procedure map into stable entries. */
export const parseProcedures = (
value: JsonValue,
): Result<readonly AddressedName[], HopperProtocolError> => {
operation = "list_procedures",
): Result<readonly AddressedName[], AnalysisOutputError> => {
const parsed = procedureMapSchema.safeParse(
unwrapProperty(value, "procedures"),
);
@@ -474,43 +474,48 @@ export const parseProcedures = (
name,
})),
)
: invalid("procedure map", parsed.error);
: invalid(operation, "procedure map", parsed.error);
};
/** Parse Hopper's direct or wrapped list of address/name records. */
/** Parse a provider's direct or wrapped list of address/name records. */
export const parseNames = (
value: JsonValue,
): Result<readonly AddressedName[], HopperProtocolError> => {
operation = "list_names",
): Result<readonly AddressedName[], AnalysisOutputError> => {
const unwrapped = unwrapProperty(value, "names");
const records = addressedNamesSchema.safeParse(unwrapped);
if (records.success) return ok(records.data);
const map = addressedNameMapSchema.safeParse(unwrapped);
return map.success
? ok(Object.entries(map.data).map(([address, name]) => ({ address, name })))
: invalid("name list", map.error);
: invalid(operation, "name list", map.error);
};
/** Parse callee/caller strings from direct or wrapped Hopper results. */
/** Parse callee/caller strings from direct or wrapped provider results. */
export const parseRelatedAddresses = (
value: JsonValue,
relation: "callees" | "callers",
): Result<readonly string[], HopperProtocolError> => {
operation = relation === "callees"
? "procedure_callees"
: "procedure_callers",
): Result<readonly string[], AnalysisOutputError> => {
const parsed = z.array(z.string()).safeParse(unwrapProperty(value, relation));
return parsed.success
? ok(parsed.data)
: invalid(`${relation} list`, parsed.error);
: invalid(operation, `${relation} list`, parsed.error);
};
/** Preserve reported address context in direct or wrapped provider segments. */
export const parseSegments = (
value: JsonValue,
): Result<readonly SegmentSummary[], HopperProtocolError> => {
operation = "list_segments",
): Result<readonly SegmentSummary[], AnalysisOutputError> => {
const parsed = z
.array(segmentSchema)
.safeParse(unwrapProperty(value, "segments"));
return parsed.success
? ok(parsed.data)
: invalid("segment list", parsed.error);
: invalid(operation, "segment list", parsed.error);
};
/** Return a reported overview base only when every parsed segment agrees. */
@@ -524,30 +529,32 @@ export const parseSegmentImageBase = (
: undefined;
};
/** Parse direct or wrapped Hopper document names. */
/** Parse direct or wrapped provider document names. */
export const parseDocuments = (
value: JsonValue,
): Result<readonly string[], HopperProtocolError> => {
operation = "list_documents",
): Result<readonly string[], AnalysisOutputError> => {
const parsed = z
.array(z.string())
.safeParse(unwrapProperty(value, "documents"));
return parsed.success
? ok(parsed.data)
: invalid("document list", parsed.error);
: invalid(operation, "document list", parsed.error);
};
/** Parse a direct or wrapped list when only its cardinality is required. */
export const parseListCount = (
value: JsonValue,
property: string,
): Result<number, HopperProtocolError> => {
operation = property === "procedures" ? "list_procedures" : "list_strings",
): Result<number, AnalysisOutputError> => {
const unwrapped = unwrapProperty(value, property);
const list = z.array(z.unknown()).safeParse(unwrapped);
if (list.success) return ok(list.data.length);
const map = z.record(z.string(), z.unknown()).safeParse(unwrapped);
return map.success
? ok(Object.keys(map.data).length)
: invalid(`${property} list`, map.error);
: invalid(operation, `${property} list`, map.error);
};
const unwrapProperty = (value: JsonValue, property: string): JsonValue => {
@@ -563,11 +570,16 @@ const unwrapProperty = (value: JsonValue, property: string): JsonValue => {
};
const invalid = <T>(
operation: string,
expected: string,
cause: z.ZodError,
): Result<T, HopperProtocolError> =>
): Result<T, AnalysisOutputError> =>
err(
new HopperProtocolError(`Hopper returned an invalid ${expected}`, {
cause,
}),
new AnalysisOutputError(
operation,
`Provider returned an invalid ${expected}`,
{
cause,
},
),
);
+1 -1
View File
@@ -4,7 +4,7 @@ import type { AnalysisPartialObservation } from "./analysisErrorBase.js";
/** Provider resources could not be proven closed after bounded cleanup. */
export class ProviderCleanupError extends ProviderAdapterError {
override readonly cleanupIncomplete = true;
override cleanupIncomplete = true;
override readonly cleanupResources: readonly string[];
override readonly userMessage =
"Provider cleanup could not be fully confirmed. Review the reported local resources before opening another target.";
+40
View File
@@ -0,0 +1,40 @@
import { z } from "zod";
const objdumpArtifactInputSchema = z
.object({
path: z.string().min(1),
operation: z.enum([
"file_headers",
"section_headers",
"symbols",
"relocations",
"dwarf",
"disassemble",
"disassemble_all",
]),
follow_debug_links: z.boolean().default(false),
})
.strict();
/** Caller-selected artifact facet or pathless provider capability query. */
export const objdumpInputSchema = z.discriminatedUnion("operation", [
objdumpArtifactInputSchema,
z.strictObject({ operation: z.literal("architectures") }),
]);
/** Caller-selected Rizin command against one local artifact. */
export const rizinInputSchema = z
.object({
path: z.string().min(1),
command: z
.string()
.min(1)
.refine(
(value) => !/[\r\n\u0000]/u.test(value),
"A single command line is required",
),
})
.strict();
export type ObjdumpInput = z.input<typeof objdumpInputSchema>;
export type RizinInput = z.input<typeof rizinInputSchema>;
+1 -1
View File
@@ -4,7 +4,7 @@ import type { AnalysisErrorOptions } from "./analysisErrorBase.js";
/** Publication failure retaining its input/output target and cleanup state. */
export class WebScriptExportError extends ArtifactOperationError {
override readonly userMessage: string;
override readonly cleanupIncomplete: boolean;
override cleanupIncomplete: boolean;
override readonly cleanupResources: readonly string[];
constructor(