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(cleanup): project resources from unresolved owners
morlutobf7fad390c26
diff --git a/src/adb/AdbProvider.ts b/src/adb/AdbProvider.tsindex 0def72cca..db696e899 100644--- a/src/adb/AdbProvider.ts+++ b/src/adb/AdbProvider.ts@@ -170,7 +170,7 @@ const hashAdbFile = async (return await hashStableFile(path, {...(signal === undefined ? {} : { signal }),retainFailedClose: (handle) => {- closeLease = new AnalysisCleanupLease(() => handle.close());+ closeLease = new AnalysisCleanupLease(() => handle.close(), [path]);resources.retain({kind: "lease",resource: `${path} (ADB digest handle)`,@@ -326,7 +326,10 @@ const syncStagedAdbFile = async (}const resource = `${path} (ADB staged-output handle)`;const stagedOwner = owner;- const closeLease = new AnalysisCleanupLease(() => stagedOwner.close());+ const closeLease = new AnalysisCleanupLease(+ () => stagedOwner.close(),+ [resource],+ );const released = await resources.release({kind: "lease",resource,@@ -605,7 +608,10 @@ const publishScreenExclusively = async (// the visible file despite later cancellation so its receipt remains known.const ownedOutput = new OwnedFileHandle(output);const handleResource = `${outputPath} (ADB publication handle)`;- const closeOnly = new AnalysisCleanupLease(() => ownedOutput.close());+ const closeOnly = new AnalysisCleanupLease(+ () => ownedOutput.close(),+ [handleResource],+ );const removeOutput = async (expected: Awaited<ReturnType<typeof output.stat>>,): Promise<void> => {diff --git a/src/artifacts/AnalysisCleanupLease.test.ts b/src/artifacts/AnalysisCleanupLease.test.tsindex 214237f3e..a5a0e3bc6 100644--- a/src/artifacts/AnalysisCleanupLease.test.ts+++ b/src/artifacts/AnalysisCleanupLease.test.ts@@ -51,12 +51,19 @@ it("resolves an aggregate only after every bound owner releases", async () => {["first resource", "second resource"],{},);- const first = new AnalysisCleanupLease(async () => undefined);- const second = new AnalysisCleanupLease(async () => undefined);+ const first = new AnalysisCleanupLease(+ async () => undefined,+ ["first resource"],+ );+ const second = new AnalysisCleanupLease(+ async () => undefined,+ ["second resource"],+ );new AnalysisCleanupLeaseGroup(error, [first, second]);await first.release();expect(error.cleanupIncomplete).toBe(true);+ expect(error.cleanupResources).toEqual(["second resource"]);await second.release();expect(error.cleanupIncomplete).toBe(false);});diff --git a/src/artifacts/AnalysisCleanupLease.ts b/src/artifacts/AnalysisCleanupLease.tsindex 42ff77425..b823d1d73 100644--- a/src/artifacts/AnalysisCleanupLease.ts+++ b/src/artifacts/AnalysisCleanupLease.ts@@ -6,7 +6,15 @@ export class AnalysisCleanupLease {#errors: WeakRef<AnalysisError>[] = [];readonly #groups = new Set<AnalysisCleanupLeaseGroup>();- constructor(private readonly cleanup: () => Promise<void>) {}+ readonly cleanupResources: readonly string[] | undefined;++ constructor(+ private readonly cleanup: () => Promise<void>,+ resources?: readonly string[],+ ) {+ this.cleanupResources =+ resources === undefined ? undefined : [...resources];+ }async release(): Promise<void> {if (this.#released) return;@@ -55,9 +63,23 @@ export class AnalysisCleanupLeaseGroup {this.#error = new WeakRef(error);this.#pending = new Set(owners);if (this.#pending.size === 0) return;+ error.bindCleanupResourceOwner(this);for (const owner of this.#pending) owner.bindCleanupGroup(this);}+ /** Unlabelled owners keep attribution unknown; never match resources by text. */+ get cleanupResources(): readonly string[] | undefined {+ if (+ [...this.#pending].some((owner) => owner.cleanupResources === undefined)+ )+ return undefined;+ return [+ ...new Set(+ [...this.#pending].flatMap((owner) => owner.cleanupResources ?? []),+ ),+ ];+ }+get hasLiveError(): boolean {return this.#error.deref() !== undefined;}diff --git a/src/artifacts/ArtifactFileOperation.ts b/src/artifacts/ArtifactFileOperation.tsindex ece86f697..dbed70192 100644--- a/src/artifacts/ArtifactFileOperation.ts+++ b/src/artifacts/ArtifactFileOperation.ts@@ -176,7 +176,7 @@ export const withArtifactRegularFile = async <Value>({symlinks,retainFailedClose: (owner) => {- cleanupLease = new AnalysisCleanupLease(() => owner.close());+ cleanupLease = new AnalysisCleanupLease(() => owner.close(), [path]);resources.retain({kind: "lease",resource: path,@@ -218,7 +218,7 @@ export const withArtifactFileHandle = async <Value>(operation: (file: FileHandle) => Promise<Value>,): Promise<Value> => {const owner = new OwnedFileHandle(file);- const cleanupLease = new AnalysisCleanupLease(() => owner.close());+ const cleanupLease = new AnalysisCleanupLease(() => owner.close(), [path]);try {return await withOwnedFileHandle(path,diff --git a/src/browser/CdpTargetSessionOwner.ts b/src/browser/CdpTargetSessionOwner.tsindex 3da2a281a..a9baa7c1e 100644--- a/src/browser/CdpTargetSessionOwner.ts+++ b/src/browser/CdpTargetSessionOwner.ts@@ -144,7 +144,10 @@ export class CdpTargetSessionOwner {connection,operation,resource,- cleanupLease: new AnalysisCleanupLease(() => connection.close()),+ cleanupLease: new AnalysisCleanupLease(+ () => connection.close(),+ [resource],+ ),active: true,settled,settle,diff --git a/src/domain/analysisErrorBase.ts b/src/domain/analysisErrorBase.tsindex f02df6b60..c62ba7411 100644--- a/src/domain/analysisErrorBase.ts+++ b/src/domain/analysisErrorBase.ts@@ -60,6 +60,11 @@ export interface AnalysisErrorOptions extends ErrorOptions {readonly partialObservation?: AnalysisPartialObservation | undefined;}+/** Exact cleanup owner that can attribute its currently unresolved resources. */+export interface AnalysisCleanupResourceOwner {+ readonly cleanupResources: readonly string[] | undefined;+}+/** Base class for expected analysis, provider, and session failures. */export abstract class AnalysisError extends Error {readonly #cleanupDependencies = new Set<AnalysisError>();@@ -68,7 +73,8 @@ export abstract class AnalysisError extends Error {readonly capturedOutput: AnalysisCapturedOutput | undefined;readonly cleanup: AnalysisCleanupObservation | undefined;cleanupIncomplete: boolean;- readonly cleanupResources: readonly string[];+ #ownedCleanupResources: readonly string[];+ #cleanupResourceOwner: AnalysisCleanupResourceOwner | undefined;constructor(message: string, options?: AnalysisErrorOptions) {super(message, options);this.diagnostics =@@ -81,7 +87,7 @@ export abstract class AnalysisError extends Error {: { ...options.capturedOutput };this.cleanup = options?.cleanup;this.cleanupIncomplete = options?.cleanup !== undefined;- this.cleanupResources = options?.cleanup?.resources ?? [];+ this.#ownedCleanupResources = [...(options?.cleanup?.resources ?? [])];this.partialObservation = options?.partialObservation;}abstract readonly _tag: AnalysisErrorTag;@@ -91,6 +97,33 @@ export abstract class AnalysisError extends Error {partialObservation: AnalysisPartialObservation | undefined;readonly cleanupReport: ProcessCaptureCleanupReport | undefined = undefined;+ /** Live dependencies own current resource attribution; cleanup keeps history. */+ get cleanupResources(): readonly string[] {+ if (this.#cleanupDependencies.size === 0)+ return (+ this.#cleanupResourceOwner?.cleanupResources ??+ this.#ownedCleanupResources+ );+ return [+ ...new Set(+ [...this.#cleanupDependencies]+ .filter((dependency) => dependency.cleanupIncomplete)+ .flatMap((dependency) => dependency.cleanupResources),+ ),+ ];+ }++ /** Bind attribution only to the producer that owns the complete cleanup set. */+ bindCleanupResourceOwner(owner: AnalysisCleanupResourceOwner): this {+ this.#cleanupResourceOwner = owner;+ return this;+ }++ /** Initialize resource facts supplied by a more specific error producer. */+ protected setCleanupResources(resources: readonly string[]): void {+ this.#ownedCleanupResources = [...resources];+ }+/** Retain a later lifecycle failure without replacing the original typed error. */retainSecondaryFailure(failure: AnalysisError,diff --git a/src/domain/browserObservationError.ts b/src/domain/browserObservationError.tsindex 7bb5da8c1..a519900b7 100644--- a/src/domain/browserObservationError.ts+++ b/src/domain/browserObservationError.ts@@ -12,7 +12,6 @@ import { AnalysisCancelledError } from "./analysisErrorCore.js";export class BrowserObservationError extends AnalysisError {readonly _tag = "BrowserObservationError";override cleanupIncomplete: boolean;- override readonly cleanupResources: readonly string[];override readonly userCategory: "cancelled" | undefined;override readonly userMessage: string | undefined;@@ -26,9 +25,10 @@ export class BrowserObservationError extends AnalysisError {options?.detail ?? observationFailureMessage(operation, reason);this.cleanupIncomplete =this.cleanup !== undefined || reason === "cleanup_failed";- this.cleanupResources =+ this.setCleanupResources(this.cleanup?.resources ??- (reason === "cleanup_failed" ? ["browser_transport"] : []);+ (reason === "cleanup_failed" ? ["browser_transport"] : []),+ );this.userCategory =reason === "cancelled" ||options?.cause instanceof AnalysisCancelledError ||diff --git a/src/domain/providerCleanupError.test.ts b/src/domain/providerCleanupError.test.tsindex 6363fddba..2f208c6c2 100644--- a/src/domain/providerCleanupError.test.ts+++ b/src/domain/providerCleanupError.test.ts@@ -59,3 +59,40 @@ it.each([false, true])(]);},);++it.each(["alpha", "beta"])(+ "projects only unresolved resources through nested cleanup groups when %s closes first",+ (first) => {+ const alpha = new ProviderCleanupError("alpha", ["alpha-file"], {});+ const beta = new ProviderCleanupError("beta", ["beta-file"], {});+ const third = new ProviderCleanupError("third", ["third-file"], {});+ const children = new ProviderCleanupError(+ "rea",+ ["alpha-file", "beta-file"],+ {},+ ).bindCleanupDependencies([alpha, beta]);+ const outer = new ProviderCleanupError(+ "rea",+ ["alpha-file", "beta-file", "third-file"],+ {},+ ).bindCleanupDependencies([children, third]);+ const released = first === "alpha" ? alpha : beta;+ const remaining = first === "alpha" ? beta : alpha;+ released.resolveCleanup();+ expect(outer.cleanupIncomplete).toBe(true);+ expect(outer.cleanupResources).toEqual([+ ...remaining.cleanupResources,+ "third-file",+ ]);+ expect(projectAnalysisError(outer)).toMatchObject({+ code: "cleanup_incomplete",+ details: { resources: [...remaining.cleanupResources, "third-file"] },+ });+ remaining.resolveCleanup();+ expect(outer.cleanupIncomplete).toBe(true);+ expect(outer.cleanupResources).toEqual(["third-file"]);+ third.resolveCleanup();+ expect(outer.cleanupIncomplete).toBe(false);+ expect(projectAnalysisError(outer).code).not.toBe("cleanup_incomplete");+ },+);diff --git a/src/domain/providerCleanupError.ts b/src/domain/providerCleanupError.tsindex a21a6bcea..7a8299cb7 100644--- a/src/domain/providerCleanupError.ts+++ b/src/domain/providerCleanupError.ts@@ -5,7 +5,6 @@ import type { AnalysisPartialObservation } from "./analysisErrorBase.js";/** Provider resources could not be proven closed after bounded cleanup. */export class ProviderCleanupError extends ProviderAdapterError {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.";@@ -30,6 +29,6 @@ export class ProviderCleanupError extends ProviderAdapterError {...(partialObservation === undefined ? {} : { partialObservation }),diagnostics,});- this.cleanupResources = [...resources];+ this.setCleanupResources(resources);}}diff --git a/src/domain/webScriptExportError.ts b/src/domain/webScriptExportError.tsindex db01d50b2..dc970b9b2 100644--- a/src/domain/webScriptExportError.ts+++ b/src/domain/webScriptExportError.ts@@ -5,7 +5,6 @@ import type { AnalysisErrorOptions } from "./analysisErrorBase.js";export class WebScriptExportError extends ArtifactOperationError {override readonly userMessage: string;override cleanupIncomplete: boolean;- override readonly cleanupResources: readonly string[];constructor(reason: ArtifactOperationError["reason"],@@ -17,12 +16,12 @@ export class WebScriptExportError extends ArtifactOperationError {) {super("export_web_scripts", reason, undefined, undefined, options);this.userMessage = `Script export failed for ${target}: ${diagnostic}`;- this.cleanupResources = [+ this.setCleanupResources([...new Set([...(options.cleanup?.resources ?? []),...(options.residualPaths ?? []),]),- ];+ ]);this.cleanupIncomplete =options.cleanup !== undefined || (options.residualPaths?.length ?? 0) > 0;}diff --git a/src/ghidra/GhidraPspExtension.ts b/src/ghidra/GhidraPspExtension.tsindex bdd759fda..b418f3d49 100644--- a/src/ghidra/GhidraPspExtension.ts+++ b/src/ghidra/GhidraPspExtension.ts@@ -287,7 +287,7 @@ const readChildren = async (} catch (cause: unknown) {outcome = { kind: "failed", cause };}- const lease = new AnalysisCleanupLease(() => owner.close());+ const lease = new AnalysisCleanupLease(() => owner.close(), [path]);const attempt = await resources.release({kind: "lease",resource: path,diff --git a/src/ida/IdaSessionClient.ts b/src/ida/IdaSessionClient.tsindex 3dac1112e..ead692db1 100644--- a/src/ida/IdaSessionClient.ts+++ b/src/ida/IdaSessionClient.ts@@ -105,7 +105,6 @@ interface UpstreamSession {/** A failed cleanup retains its private workspace and reports the remaining resource. */class IdaCleanupError extends ProviderAdapterError {override readonly cleanupIncomplete = true;- override readonly cleanupResources: readonly string[];constructor(path: string,cause: unknown,@@ -146,7 +145,7 @@ class IdaCleanupError extends ProviderAdapterError {}),},});- this.cleanupResources = [path];+ this.setCleanupResources([path]);}}diff --git a/src/kuna/KunaInstallation.ts b/src/kuna/KunaInstallation.tsindex bde43dcc6..66dc551de 100644--- a/src/kuna/KunaInstallation.ts+++ b/src/kuna/KunaInstallation.ts@@ -87,7 +87,7 @@ export const createKunaFileCloseScope = (return {owner: {retain: (owner, resource) => {- const lease = new AnalysisCleanupLease(() => owner.close());+ const lease = new AnalysisCleanupLease(() => owner.close(), [resource]);leases.set(owner, lease);parent.retain({ close: () => lease.release() }, resource);},diff --git a/src/kuna/KunaProjectCache.ts b/src/kuna/KunaProjectCache.tsindex 56485e299..9dc5a1789 100644--- a/src/kuna/KunaProjectCache.ts+++ b/src/kuna/KunaProjectCache.ts@@ -1048,7 +1048,7 @@ export class KunaProjectCache {key,staging,resource,- lease: new AnalysisCleanupLease(async () => owner.close()),+ lease: new AnalysisCleanupLease(async () => owner.close(), [resource]),};this.#hashRecords.set(owner, retained);this.#retainedHashFiles.set(owner, retained);diff --git a/src/kuna/KunaTargetCommands.ts b/src/kuna/KunaTargetCommands.tsindex a3e11c296..3ebfe7c80 100644--- a/src/kuna/KunaTargetCommands.ts+++ b/src/kuna/KunaTargetCommands.ts@@ -118,7 +118,10 @@ export class KunaTargetCommands {reportedTimeoutMs: request.timeoutMs,launcher: this.lifetime.launcher,retainFailedFileClose: (owner, resource) => {- const lease = new AnalysisCleanupLease(() => owner.close());+ const lease = new AnalysisCleanupLease(+ () => owner.close(),+ [resource],+ );this.#resources.retain({ kind: "lease", resource, lease });failedHashClose = { owner, lease };},diff --git a/tests/process-global/ghidraImportSnapshotLifetime.test.ts b/tests/process-global/ghidraImportSnapshotLifetime.test.tsindex c4e81fb5b..66160bab6 100644--- a/tests/process-global/ghidraImportSnapshotLifetime.test.ts+++ b/tests/process-global/ghidraImportSnapshotLifetime.test.ts@@ -242,6 +242,7 @@ it("waits for mixed finalization and resolves cleanup only after both exact descfault.blocked.delete(fault.destinations[0]!);await destination.cleanupLease.release();expect(projected.cleanupIncomplete).toBe(true);+ expect(projected.cleanupResources).toEqual([path]);fault.blocked.clear();await resources.close();expect(projected.cleanupIncomplete).toBe(false);