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(native): retain plist descriptor cleanup ownership
morlutoe09a503f44fb
diff --git a/src/native/NativeMacOSProvider.ts b/src/native/NativeMacOSProvider.tsindex 13d319840..982e05f79 100644--- a/src/native/NativeMacOSProvider.ts+++ b/src/native/NativeMacOSProvider.ts@@ -1,3 +1,10 @@+import {+ plistSourceFormat,+ requireRegularPlist,+ nativePlistFileFailure,+ unreadablePlist,+} from "./NativePlistSource.js";+import { bindArtifactFileCleanup } from "../artifacts/ArtifactFileOperation.js";import { snapshotEnvironment } from "../process/snapshotEnvironment.js";import {NATIVE_MACOS_PROVIDER_IDENTITY as IDENTITY,@@ -8,7 +15,7 @@ import { observeNativeUi } from "./NativeUiObservation.js";import { LldbCallTracer, type NativeCallTracer } from "./LldbCallTracer.js";import { observeNativeCalls } from "./NativeCallObservation.js";import { basename, dirname, isAbsolute, resolve } from "node:path";-import { open, realpath, stat } from "node:fs/promises";+import { realpath, stat } from "node:fs/promises";import { z } from "zod";@@ -40,10 +47,12 @@ import {AnalysisResourceConstraintError,AnalysisTimeoutError,} from "../domain/analysisErrorCore.js";-import { BinaryTargetError } from "../domain/configurationErrors.js";import { ProviderAdapterError } from "../domain/providerAdapterError.js";import { ProviderCleanupError } from "../domain/providerCleanupError.js";-import { AnalysisError } from "../domain/analysisErrorBase.js";+import {+ AnalysisError,+ resolvedAnalysisError,+} from "../domain/analysisErrorBase.js";import { regularFileCancellation } from "../filesystem/OwnedRegularFile.js";import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";import type { NativeUiObservationResult } from "../domain/native/nativeUiObservation.js";@@ -145,6 +154,7 @@ class NativeMacOSClient implements AnalysisClient {readonly #pendingNativeUiRuntimes = new Set<NativeUiHelperRuntime>();readonly #pendingCommands = new Set<Promise<unknown>>();readonly #signatureResources = new ArtifactResourceScope();+ readonly #plistResources = new ArtifactResourceScope();#nativeUiTail: Promise<void> = Promise.resolve();#closed = false;@@ -172,7 +182,9 @@ class NativeMacOSClient implements AnalysisClient {),);if (options?.signal?.aborted === true)- return err(new AnalysisCancelledError(operation));+ return err(+ new AnalysisCancelledError(operation, { cause: options.signal.reason }),+ );if (operation === "health")return ok(createAnalysisExecution(null, IDENTITY));if (operation === "inspect_native_dispatch_metadata") {@@ -276,13 +288,9 @@ class NativeMacOSClient implements AnalysisClient {locations: observation.value.locations,}),)- : observation;+ : err(resolvedAnalysisError(observation.error));} catch (cause: unknown) {- return err(- new AnalysisOutputError(operation, "Native output parsing failed", {- cause,- }),- );+ return err(nativeOutputFailure(operation, cause));}}@@ -292,21 +300,14 @@ class NativeMacOSClient implements AnalysisClient {const uiCleanupFailures = await this.#serializeNativeUi(() =>this.#retryNativeUiCleanup(),);- let signatureCleanup: AnalysisError | undefined;- try {- await this.#signatureResources.close();- } catch (cause: unknown) {- const observation = ArtifactReaderFailure.cleanupObservation(- cause,- "signature-snapshot",- );- signatureCleanup = new ProviderCleanupError(- IDENTITY.id,- observation.resources,- { reason: observation.reason },- { operation: "close_binary", cause },- );- }+ const signatureCleanup = await closeNativeFileScope(+ this.#signatureResources,+ "signature-snapshot",+ );+ const plistCleanup = await closeNativeFileScope(+ this.#plistResources,+ "plist-file",+ );const commandCleanup = await this.#retryNativeCommandCleanup();let result = await this.tracer.close();const cleanupErrors = [@@ -315,11 +316,17 @@ class NativeMacOSClient implements AnalysisClient {: [this.#nativeUiCleanupFailure(uiCleanupFailures, "close_binary")]),...(commandCleanup === undefined ? [] : [commandCleanup]),...(signatureCleanup === undefined ? [] : [signatureCleanup]),+ ...(plistCleanup === undefined ? [] : [plistCleanup]),];for (const cleanupError of cleanupErrors)result = result.ok? err(cleanupError)- : err(analysisErrorWithCleanupFailure(result.error, cleanupError));+ : err(+ analysisErrorWithCleanupFailure(+ result.error,+ cleanupError,+ ).bindCleanupDependencies([result.error, cleanupError]),+ );return result;}@@ -769,78 +776,105 @@ class NativeMacOSClient implements AnalysisClient {return err(new AnalysisOutputError("inspect_plist", "path was not a string"),);- const plist = await resolvePlistPath(this.target, requested);- if (!plist.ok) return plist;- const selected = await requireRegularPlist(plist.value, requested);- if (!selected.ok) return selected;- const classified = await this.#run(- "inspect_plist",- "file",- ["-b", plist.value],- { signal },- );- if (!classified.ok) return classified;- const json = await this.#run(- "inspect_plist",- "plutil",- ["-convert", "json", "-o", "-", "--", plist.value],- { signal, acceptNonZero: true },- );- if (!json.ok) return json;- // JSON cannot express data, dates, or non-finite reals; plutil rejects- // such plists, so decode its lossless XML conversion instead. JSON also- // prints an integral <real> like an <integer>, so a number beyond the- // exact JSON range takes its element type from the XML conversion.- const jsonDecoded = json.value.exitCode === 0;- const xml =- jsonDecoded && !plistJsonNeedsNumberTypes(json.value.stdout)- ? undefined- : await this.#run(+ try {+ return await this.#plistResources.run(async () => {+ try {+ const plist = await resolvePlistPath(this.target, requested);+ if (!plist.ok) return plist;+ const fileInput = {+ path: plist.value,+ requested,+ resources: this.#plistResources,+ signal,+ };+ const selected = await requireRegularPlist(fileInput);+ if (!selected.ok) return selected;+ const classified = await this.#run(+ "inspect_plist",+ "file",+ ["-b", plist.value],+ { signal },+ );+ if (!classified.ok) return classified;+ const json = await this.#run("inspect_plist","plutil",- ["-convert", "xml1", "-o", "-", "--", plist.value],- { signal, acceptNonZero: !jsonDecoded },+ ["-convert", "json", "-o", "-", "--", plist.value],+ { signal, acceptNonZero: true },);- if (xml !== undefined && !xml.ok) return xml;- if (xml !== undefined && xml.value.exitCode !== 0)+ if (!json.ok) return json;+ // JSON cannot express data, dates, or non-finite reals; plutil rejects+ // such plists, so decode its lossless XML conversion instead. JSON also+ // prints an integral <real> like an <integer>, so a number beyond the+ // exact JSON range takes its element type from the XML conversion.+ const jsonDecoded = json.value.exitCode === 0;+ const xml =+ jsonDecoded && !plistJsonNeedsNumberTypes(json.value.stdout)+ ? undefined+ : await this.#run(+ "inspect_plist",+ "plutil",+ ["-convert", "xml1", "-o", "-", "--", plist.value],+ { signal, acceptNonZero: !jsonDecoded },+ );+ if (xml !== undefined && !xml.ok) return xml;+ if (xml !== undefined && xml.value.exitCode !== 0)+ return err(+ unreadablePlist(+ plist.value,+ requested,+ `plutil could not decode it as a property list (${plutilDiagnostic(xml.value.stderr, plist.value)})`,+ ),+ );+ const parsed =+ xml === undefined+ ? parsePlistJson(json.value.stdout)+ : jsonDecoded+ ? parsePlistJson(json.value.stdout, xml.value.stdout)+ : parsePlistXml(xml.value.stdout);+ if (!parsed.ok) return parsed;+ const provenance = [+ classified.value,+ json.value,+ ...(xml === undefined ? [] : [xml.value]),+ ].map((item) => invocation(item, plist.value, "$PLIST"));+ const converted = xml?.value ?? json.value;+ const format = await plistSourceFormat(classified.value.stdout, {+ ...fileInput,+ capturedOutput: {+ stdout: converted.stdout,+ stderr: converted.stderr,+ truncated: false,+ stdout_bytes: converted.stdoutBytes,+ stderr_bytes: converted.stderrBytes,+ exit_code: converted.exitCode,+ signal: converted.signal,+ },+ });+ if (!format.ok) return format;+ const result = inspectPlistSchema.parse({+ format: format.value,+ value: parsed.value.value,+ bundle: parsed.value.bundle,+ source_path: plist.value,+ provenance,+ limitations: parsed.value.limitations,+ });+ return ok({+ result: jsonValueSchema.parse(result),+ limitations: parsed.value.limitations,+ locations: [{ kind: "artifact-path", path: plist.value }],+ });+ } catch (cause: unknown) {+ // Producer failures stay opaque; only scope admission failures reach the file mapper.+ return err(nativeOutputFailure("inspect_plist", cause));+ }+ });+ } catch (cause: unknown) {return err(- unreadablePlist(- plist.value,- requested,- `plutil could not decode it as a property list (${plutilDiagnostic(xml.value.stderr, plist.value)})`,- ),+ nativePlistFileFailure(cause, requested ?? this.target.path, requested),);- const parsed =- xml === undefined- ? parsePlistJson(json.value.stdout)- : jsonDecoded- ? parsePlistJson(json.value.stdout, xml.value.stdout)- : parsePlistXml(xml.value.stdout);- if (!parsed.ok) return parsed;- const provenance = [- classified.value,- json.value,- ...(xml === undefined ? [] : [xml.value]),- ].map((item) => invocation(item, plist.value, "$PLIST"));- const format = await plistSourceFormat(- classified.value.stdout,- plist.value,- requested,- );- if (!format.ok) return format;- const result = inspectPlistSchema.parse({- format: format.value,- value: parsed.value.value,- bundle: parsed.value.bundle,- source_path: plist.value,- provenance,- limitations: parsed.value.limitations,- });- return ok({- result: jsonValueSchema.parse(result),- limitations: parsed.value.limitations,- locations: [{ kind: "artifact-path", path: plist.value }],- });+ }}async #inspectMacho(@@ -913,6 +947,36 @@ const nativeCommandCleanupFailure = (},);+/** Each file workflow retains its own exact resource set through client close. */+const closeNativeFileScope = async (+ scope: ArtifactResourceScope,+ resource: string,+): Promise<AnalysisError | undefined> => {+ try {+ await scope.close();+ return undefined;+ } catch (cause: unknown) {+ const observation = ArtifactReaderFailure.cleanupObservation(+ cause,+ resource,+ );+ const failure = new ProviderCleanupError(+ IDENTITY.id,+ observation.resources,+ { reason: observation.reason },+ { operation: "close_binary", cause },+ );+ bindArtifactFileCleanup(cause, failure);+ return failure;+ }+};++const nativeOutputFailure = (+ operation: AnalysisOperation,+ cause: unknown,+): AnalysisError =>+ new AnalysisOutputError(operation, "Native output parsing failed", { cause });+interface NativeObservation {readonly result: JsonValue;readonly limitations: readonly string[];@@ -1143,125 +1207,12 @@ const parseEntitlements = (return { value: jsonValueSchema.parse(value), omittedPrototypeKeys };};-/**- * Report a plist that cannot be decoded as the caller's selection, or as the- * target's missing default, rather than as a failed tool run.- */-const unreadablePlist = (- path: string,- requested: string | undefined,- reason: string,-): AnalysisError => {- const sentence = reason.endsWith(".") ? reason : `${reason}.`;- // Name the default that is missing and the selection that still works.- const missingDefault = `The target has no readable default plist at ${path}: ${sentence} Select another plist in the target with the path input (CLI: --relative-path).`;- return requested === undefined- ? new AnalysisCapabilityUnavailableError(- IDENTITY.id,- "inspect_plist",- missingDefault,- { userMessage: missingDefault },- )- : new AnalysisInputError("inspect_plist", undefined, [- {- path: ["path"],- reason: "invalid_value",- message: `Cannot inspect ${path}: ${sentence}`,- },- ]);-};-/** plutil prefixes its diagnostic with the path the message already names. */const plutilDiagnostic = (stderr: string, path: string): string => {const text = stderr.trim();return text.startsWith(`${path}: `) ? text.slice(path.length + 2) : text;};-/** Bytes examined for leading markup when `file` reports only text. */-const PLIST_MARKUP_PROBE_BYTES = 4_096;--/**- * Preserve explicit source identities. For generic text, recognize XML- * markup rather than a lone `<`, which also opens an OpenStep data value.- * A prefix without recognizable markup stays unknown.- */-const plistSourceFormat = async (- description: string,- path: string,- requested: string | undefined,-): Promise<Result<"binary" | "xml" | "json" | "unknown", AnalysisError>> => {- if (/binary property list/iu.test(description)) return ok("binary");- if (/\bXML\b/iu.test(description)) return ok("xml");- if (/\bJSON\b/iu.test(description)) return ok("json");- if (!/\btext\b/iu.test(description)) return ok("unknown");- try {- const handle = await open(path, "r");- try {- const head = Buffer.alloc(PLIST_MARKUP_PROBE_BYTES);- const { bytesRead } = await handle.read(head, 0, head.length, 0);- const encoding =- head[0] === 0xff && head[1] === 0xfe- ? "utf-16le"- : head[0] === 0xfe && head[1] === 0xff- ? "utf-16be"- : "utf-8";- const text = new TextDecoder(encoding)- .decode(head.subarray(0, bytesRead))- .trimStart();- return ok(- /^<(?:[!?]|(?:plist|dict|array|string|integer|real|data|date|true|false)[\s/>])/u.test(- text,- )- ? "xml"- : "unknown",- );- } finally {- await handle.close();- }- } catch (cause: unknown) {- const code =- cause instanceof Error && "code" in cause ? cause.code : undefined;- if (code === "ENOENT" || code === "ENOTDIR")- return err(unreadablePlist(path, requested, "no file exists there"));- return err(- new ProviderAdapterError(IDENTITY.id, "inspect_plist", { cause }),- );- }-};--/**- * Admit a readable regular file before plutil runs, so a later plutil failure- * reflects the bytes rather than a missing path or a host permission denial.- */-const requireRegularPlist = async (- path: string,- requested: string | undefined,-): Promise<Result<null, AnalysisError>> => {- try {- if (!(await stat(path)).isFile())- return err(unreadablePlist(path, requested, "it is not a regular file"));- // Opening also observes ACL and macOS privacy denials that stat permits.- await (await open(path, "r")).close();- return ok(null);- } catch (cause: unknown) {- const code =- cause instanceof Error && "code" in cause ? cause.code : undefined;- if (code === "ENOENT" || code === "ENOTDIR")- return err(unreadablePlist(path, requested, "no file exists there"));- if (code === "EACCES" || code === "EPERM")- return err(- new BinaryTargetError(- path,- `permission denied while reading plist (${code})`,- { cause },- ),- );- return err(- new ProviderAdapterError(IDENTITY.id, "inspect_plist", { cause }),- );- }-};-/** The bundle whose Contents/MacOS directory directly holds `path`. */const macOSBundleRoot = (path: string): string | undefined => {const programs = dirname(path);diff --git a/src/native/NativePlistSource.ts b/src/native/NativePlistSource.tsnew file mode 100644index 000000000..1ed98a529--- /dev/null+++ b/src/native/NativePlistSource.ts@@ -0,0 +1,230 @@+import type { FileHandle } from "node:fs/promises";+import type { z } from "zod";+import type { inspectPlistSchema } from "../domain/native/nativeInspection.js";+import type {+ AnalysisError,+ AnalysisErrorOptions,+ AnalysisCapturedOutput,+} from "../domain/analysisErrorBase.js";+import {+ AnalysisCancelledError,+ AnalysisCapabilityUnavailableError,+ AnalysisInputError,+} from "../domain/analysisErrorCore.js";+import { BinaryTargetError } from "../domain/configurationErrors.js";+import { ProviderAdapterError } from "../domain/providerAdapterError.js";+import { ProviderCleanupError } from "../domain/providerCleanupError.js";+import { projectAnalysisError } from "../domain/analysisErrorProjection.js";+import { err, ok, type Result } from "../domain/result.js";+import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";+import {+ ArtifactFileCleanupFailure,+ artifactFilePrimaryFailure,+ artifactFileCancellationCause,+ bindArtifactFileCleanup,+ withArtifactRegularFile,+} from "../artifacts/ArtifactFileOperation.js";+import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";+import { NATIVE_MACOS_PROVIDER_IDENTITY as IDENTITY } from "./NativeMacOSProviderMetadata.js";++/**+ * Report a plist that cannot be decoded as the caller's selection, or as the+ * target's missing default, rather than as a failed tool run.+ */+export const unreadablePlist = (+ path: string,+ requested: string | undefined,+ reason: string,+ options?: AnalysisErrorOptions,+): AnalysisError => {+ const sentence = reason.endsWith(".") ? reason : `${reason}.`;+ // Name the default that is missing and the selection that still works.+ const missingDefault = `The target has no readable default plist at ${path}: ${sentence} Select another plist in the target with the path input (CLI: --relative-path).`;+ return requested === undefined+ ? new AnalysisCapabilityUnavailableError(+ IDENTITY.id,+ "inspect_plist",+ missingDefault,+ { ...options, userMessage: missingDefault },+ )+ : new AnalysisInputError("inspect_plist", options, [+ {+ path: ["path"],+ reason: "invalid_value",+ message: `Cannot inspect ${path}: ${sentence}`,+ },+ ]);+};++interface PlistFileInput {+ readonly path: string;+ readonly requested: string | undefined;+ readonly resources: ArtifactResourceScope;+ readonly signal: AbortSignal | undefined;+ readonly capturedOutput?: AnalysisCapturedOutput;+}++/** Translate only physical file outcomes, never a later signal or arbitrary abort value. */+export const nativePlistFileFailure = (+ cause: unknown,+ path: string,+ requested: string | undefined,+ capturedOutput?: AnalysisCapturedOutput,+): AnalysisError => {+ if (cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined) {+ const physical =+ cause instanceof ArtifactFileCleanupFailure+ ? cause.fileCleanupFailure+ : undefined;+ const previous =+ physical?.outcome.kind === "failed"+ ? nativePlistFileFailure(+ artifactFilePrimaryFailure(cause),+ path,+ requested,+ capturedOutput,+ )+ : physical?.completionCancellation === undefined+ ? undefined+ : new AnalysisCancelledError("inspect_plist", {+ cause: physical.completionCancellation.reason,+ capturedOutput,+ });+ const previousProjection =+ previous === undefined ? null : projectAnalysisError(previous);+ // The top-level capture owns the output once; this snapshot keeps the primary reason.+ const previousDetails = previousProjection?.details;+ const { captured_output: _capture, ...reasonDetails } =+ previousDetails ?? {};+ const previousError =+ previousProjection === null+ ? null+ : {+ ...previousProjection,+ ...(previousDetails === undefined+ ? {}+ : { details: reasonDetails }),+ };+ const failure = new ProviderCleanupError(+ IDENTITY.id,+ cause.cleanup.resources,+ {+ reason: cause.cleanup.reason,+ previous_error: previousError,+ },+ {+ operation: "inspect_plist",+ cause,+ cleanupPrimary: previous,+ capturedOutput,+ },+ );+ bindArtifactFileCleanup(cause, failure);+ return failure;+ }+ if (cause instanceof ArtifactReaderFailure && cause.reason === "cancelled")+ return new AnalysisCancelledError("inspect_plist", {+ cause: artifactFileCancellationCause(cause),+ capturedOutput,+ });+ if (cause instanceof ArtifactReaderFailure && cause.reason === "unavailable")+ return new AnalysisCapabilityUnavailableError(+ IDENTITY.id,+ "inspect_plist",+ cause.message,+ { cause, capturedOutput },+ );+ const code =+ cause instanceof Error && "code" in cause ? cause.code : undefined;+ if (code === "ENOENT" || code === "ENOTDIR")+ return unreadablePlist(path, requested, "no file exists there", {+ cause,+ capturedOutput,+ });+ if (code === "EISDIR" || code === "ENOTFILE")+ return unreadablePlist(path, requested, "it is not a regular file", {+ cause,+ capturedOutput,+ });+ if (code === "EACCES" || code === "EPERM")+ return new BinaryTargetError(+ path,+ `permission denied while reading plist (${code})`,+ { cause, capturedOutput },+ );+ return new ProviderAdapterError(IDENTITY.id, "inspect_plist", {+ cause,+ capturedOutput,+ diagnostics: {+ path,+ phase: "plist-file",+ reason: cause instanceof Error ? cause.message : String(cause),+ },+ });+};++const readPlistFile = async <Value>(+ input: PlistFileInput,+ read: (file: FileHandle) => Promise<Value>,+): Promise<Result<Value, AnalysisError>> => {+ try {+ return ok(+ await withArtifactRegularFile(+ input.path,+ input.resources,+ input.signal,+ read,+ "follow",+ ),+ );+ } catch (cause: unknown) {+ return err(+ nativePlistFileFailure(+ cause,+ input.path,+ input.requested,+ input.capturedOutput,+ ),+ );+ }+};++/** Shared admission verifies one readable regular descriptor without blocking on pipes. */+export const requireRegularPlist = (+ input: PlistFileInput,+): Promise<Result<null, AnalysisError>> =>+ readPlistFile(input, async () => null);++/** Bytes examined for leading markup when `file` reports only text. */+const PLIST_MARKUP_PROBE_BYTES = 4096;++/** Source classification remains independent of plutil's converted value format. */+export const plistSourceFormat = async (+ description: string,+ input: PlistFileInput,+): Promise<+ Result<z.infer<typeof inspectPlistSchema>["format"], AnalysisError>+> => {+ if (/binary property list/iu.test(description)) return ok("binary");+ if (/\bXML\b/iu.test(description)) return ok("xml");+ if (/\bJSON\b/iu.test(description)) return ok("json");+ if (!/\btext\b/iu.test(description)) return ok("unknown");+ return readPlistFile(input, async (file) => {+ const head = Buffer.alloc(PLIST_MARKUP_PROBE_BYTES);+ const { bytesRead } = await file.read(head, 0, head.length, 0);+ const encoding =+ head[0] === 0xff && head[1] === 0xfe+ ? "utf-16le"+ : head[0] === 0xfe && head[1] === 0xff+ ? "utf-16be"+ : "utf-8";+ const text = new TextDecoder(encoding)+ .decode(head.subarray(0, bytesRead))+ .trimStart();+ return /^<(?:[!?]|(?:plist|dict|array|string|integer|real|data|date|true|false)[\s/>])/u.test(+ text,+ )+ ? "xml"+ : "unknown";+ });+};diff --git a/tests/boundary/providers/native/nativePlistFileCleanup.test.ts b/tests/boundary/providers/native/nativePlistFileCleanup.test.tsnew file mode 100644index 000000000..d51c49f97--- /dev/null+++ b/tests/boundary/providers/native/nativePlistFileCleanup.test.ts@@ -0,0 +1,364 @@+import { open, writeFile, type FileHandle } from "node:fs/promises";+import { join } from "node:path";+import { expect, it, vi, onTestFinished } from "vitest";+import { NativeMacOSProvider } from "../../../../src/native/NativeMacOSProvider.js";+import { ArtifactFileCleanupFailure } from "../../../../src/artifacts/ArtifactFileOperation.js";+import {+ NativeFixtureRunner,+ nativeMachoTarget,+} from "../../../fixtures/nativeCommands.js";+import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";+import { OwnedFileHandle } from "../../../../src/filesystem/OwnedFileHandle.js";+import { ProviderCleanupError } from "../../../../src/domain/providerCleanupError.js";+import { resolvedAnalysisError } from "../../../../src/domain/analysisErrorBase.js";+import { AnalysisCleanupLease } from "../../../../src/artifacts/AnalysisCleanupLease.js";+import { ArtifactReaderFailure } from "../../../../src/artifacts/ArtifactReader.js";+import { err, ok } from "../../../../src/domain/result.js";+import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";++const fixture = async () => {+ const root = await createTestTempDirectory("rea-native-plist-lifetime-");+ const path = join(root, "selected.plist");+ await writeFile(path, "<plist><string>value</string></plist>");+ const probe = await open(path, "r");+ const prototype = Object.getPrototypeOf(probe) as FileHandle;+ await probe.close();+ const runner = new NativeFixtureRunner({+ file: "ASCII text",+ plutil: '"value"',+ });+ const client = new NativeMacOSProvider({}, runner, "darwin").createClient(+ nativeMachoTarget(join(root, "target")),+ );+ onTestFinished(async () => {+ await client.close();+ });+ return { path, prototype, runner, client };+};++it("does not adopt a command's arbitrary thrown cleanup marker as a file owner", async () => {+ const { client, path, runner } = await fixture();+ const foreign = ArtifactReaderFailure.withCleanup(+ new Error("opaque command failure"),+ { resources: ["unowned"], reason: "foreign marker" },+ );+ const run = vi.spyOn(runner, "run").mockRejectedValueOnce(foreign);+ onTestFinished(() => run.mockRestore());+ const result = await client.execute("inspect_plist", { path });+ expect(result.ok).toBe(false);+ if (result.ok) throw new Error("Expected opaque command failure");+ expect(result.error.cause).toBe(foreign);+ expect(result.error.cleanupIncomplete).toBe(false);+ expect(result.error.cleanupResources).toEqual([]);+});++it("keeps mixed client cleanup live until both file and tracer owners resolve", async () => {+ const root = await createTestTempDirectory("rea-native-mixed-close-");+ const path = join(root, "selected.plist");+ await writeFile(path, "<plist><string>value</string></plist>");+ const probe = await open(path, "r");+ const prototype = Object.getPrototypeOf(probe) as FileHandle;+ await probe.close();+ const traceFailure = new ProviderCleanupError(+ "native-macos",+ ["trace-owner"],+ {},+ );+ const traceLease = new AnalysisCleanupLease(async () => {}, ["trace-owner"]);+ traceLease.bindCleanupError(traceFailure);+ let traceAttempts = 0;+ const client = new NativeMacOSProvider(+ {},+ new NativeFixtureRunner({ file: "ASCII text", plutil: '"value"' }),+ "darwin",+ () => ({+ trace: async () => {+ throw new Error("Trace not requested");+ },+ close: async () => {+ traceAttempts += 1;+ if (traceAttempts < 3) return err(traceFailure);+ await traceLease.release();+ return ok(null);+ },+ }),+ ).createClient(nativeMachoTarget(join(root, "target")));+ let release: (() => Promise<void>) | undefined;+ const original = prototype.read;+ let fileAttempts = 0;+ const read = vi+ .spyOn(prototype, "read")+ .mockImplementationOnce(async function (+ this: FileHandle,+ ...args: Parameters<FileHandle["read"]>+ ) {+ release = this.close.bind(this);+ this.close = async () => {+ fileAttempts += 1;+ if (fileAttempts < 3) throw new Error("file close failed");+ await release!();+ };+ return Reflect.apply(original, this, args);+ });+ onTestFinished(async () => {+ read.mockRestore();+ await release?.();+ await traceLease.release();+ await client.close();+ });+ expect((await client.execute("inspect_plist", { path })).ok).toBe(false);+ const first = await client.close();+ expect(first.ok).toBe(false);+ if (first.ok) throw new Error("Expected both pending owners");+ expect(new Set(first.error.cleanupResources)).toEqual(+ new Set([path, "trace-owner"]),+ );+ expect((await client.close()).ok).toBe(false);+ expect(first.error.cleanupIncomplete).toBe(true);+ expect(first.error.cleanupResources).toEqual(["trace-owner"]);+ expect((await client.close()).ok).toBe(true);+ expect(first.error.cleanupIncomplete).toBe(false);+ expect(first.error.cleanupResources).toEqual([]);+});++it("retains prefix read and close failures through repeated client cleanup", async ({+ onTestFinished,+}) => {+ const root = await createTestTempDirectory("rea-native-plist-close-");+ const path = join(root, "selected.plist");+ await writeFile(path, "<plist><string>value</string></plist>");+ const probe = await open(path, "r");+ const prototype = Object.getPrototypeOf(probe) as FileHandle;+ await probe.close();+ const primary = Object.assign(new Error("controlled prefix read failure"), {+ code: "EIO",+ });+ const cleanup = new Error("controlled prefix close failure");+ let attempts = 0;+ let release: (() => Promise<void>) | undefined;+ const read = vi+ .spyOn(prototype, "read")+ .mockImplementationOnce(async function (this: FileHandle) {+ release = this.close.bind(this);+ this.close = async () => {+ attempts += 1;+ if (attempts <= 2) throw cleanup;+ await release!();+ };+ throw primary;+ });+ onTestFinished(async () => {+ read.mockRestore();+ await release?.();+ });+ const client = new NativeMacOSProvider(+ {},+ new NativeFixtureRunner({ file: "ASCII text", plutil: '"value"' }),+ "darwin",+ ).createClient(nativeMachoTarget(join(root, "target")));+ onTestFinished(async () => {+ await client.close();+ });+ const result = await client.execute("inspect_plist", { path });+ expect(result.ok).toBe(false);+ if (result.ok) throw new Error("Expected retained cleanup failure");+ expect(result.error).toMatchObject({+ cleanupIncomplete: true,+ operation: "inspect_plist",+ });+ expect(result.error.cleanupResources).toContain(path);+ expect(result.error.capturedOutput?.stdout).toBe('"value"');+ const projected = projectAnalysisError(result.error);+ expect(JSON.stringify(projected).match(/captured_output/gu)).toHaveLength(1);+ expect(result.error.cause).toBeInstanceOf(ArtifactFileCleanupFailure);+ const failure = result.error.cause as ArtifactFileCleanupFailure;+ expect(failure.fileCleanupFailure.outcome).toEqual({+ kind: "failed",+ cause: primary,+ });+ expect(failure.fileCleanupFailure.cleanupCause).toBe(cleanup);+ const first = await client.close();+ expect(first.ok).toBe(false);+ expect(attempts).toBe(2);+ const retried = await client.close();+ expect(retried.ok).toBe(true);+ expect(attempts).toBe(3);+ expect(result.error.cleanupIncomplete).toBe(false);+ expect(resolvedAnalysisError(result.error).cause).toBe(primary);+ expect(resolvedAnalysisError(result.error).capturedOutput?.stdout).toBe(+ '"value"',+ );+ if (!first.ok) expect(first.error.cleanupIncomplete).toBe(false);+});++for (const readFails of [false, true])+ it(`retains a ${readFails ? "failed" : "completed"} read when cancellation and close failure coincide`, async () => {+ const { client, path, prototype } = await fixture();+ const controller = new AbortController();+ const primary = new Error("physical read failed before cancellation");+ const cleanup = new Error("physical close failed");+ const reason = { caller: "final-close" };+ const original = prototype.read;+ let release: (() => Promise<void>) | undefined;+ let attempts = 0;+ const read = vi+ .spyOn(prototype, "read")+ .mockImplementationOnce(async function (+ this: FileHandle,+ ...args: Parameters<FileHandle["read"]>+ ) {+ release = this.close.bind(this);+ this.close = async () => {+ attempts += 1;+ if (attempts === 1) {+ controller.abort(reason);+ throw cleanup;+ }+ await release!();+ };+ if (readFails) throw primary;+ return Reflect.apply(original, this, args);+ });+ onTestFinished(async () => {+ read.mockRestore();+ await release?.();+ });+ const result = await client.execute(+ "inspect_plist",+ { path },+ { signal: controller.signal },+ );+ expect(result.ok).toBe(false);+ if (result.ok) throw new Error("Expected retained close failure");+ const failure = result.error.cause;+ expect(failure).toBeInstanceOf(ArtifactFileCleanupFailure);+ if (!(failure instanceof ArtifactFileCleanupFailure))+ throw new Error("Expected physical owner");+ expect(failure.fileCleanupFailure.outcome).toEqual(+ readFails+ ? { kind: "failed", cause: primary }+ : { kind: "completed", value: "xml" },+ );+ expect(result.error.cleanupIncomplete).toBe(true);+ expect((await client.close()).ok).toBe(true);+ expect(result.error.cleanupIncomplete).toBe(false);+ expect(resolvedAnalysisError(result.error).cause).toBe(+ readFails ? primary : reason,+ );+ });++it.each([null, 0, new ProviderCleanupError("foreign", ["unowned"], {})])(+ "preserves pre-admission abort reason %s without adopting its resource authority",+ async (reason) => {+ const { client, path, runner } = await fixture();+ const run = vi.spyOn(runner, "run");+ onTestFinished(() => run.mockRestore());+ const controller = new AbortController();+ controller.abort(reason);+ const result = await client.execute(+ "inspect_plist",+ { path },+ { signal: controller.signal },+ );+ expect(result.ok).toBe(false);+ if (result.ok) throw new Error("Expected pre-admission cancellation");+ expect(result.error.cause).toBe(reason);+ expect(result.error.cleanupIncomplete).toBe(false);+ expect(result.error.cleanupResources).toEqual([]);+ expect(run).not.toHaveBeenCalled();+ },+);++it("retains a failed admission close before any native command", async () => {+ const { client, path, runner } = await fixture();+ const run = vi.spyOn(runner, "run");+ const close = vi+ .spyOn(OwnedFileHandle.prototype, "close")+ .mockRejectedValueOnce(new Error("controlled admission close failure"));+ onTestFinished(() => {+ close.mockRestore();+ run.mockRestore();+ });+ const result = await client.execute("inspect_plist", { path });+ expect(result.ok).toBe(false);+ if (result.ok) throw new Error("Expected failed admission close");+ expect(result.error.cleanupResources).toContain(path);+ expect(result.error.cleanupIncomplete).toBe(true);+ expect(run).not.toHaveBeenCalled();+ expect((await client.close()).ok).toBe(true);+ expect(result.error.cleanupIncomplete).toBe(false);+});++it("preserves an opaque cancellation observed during successful prefix close", async () => {+ const { client, path, prototype } = await fixture();+ const controller = new AbortController();+ const reason = new ProviderCleanupError("foreign", ["unowned-resource"], {});+ const original = prototype.read;+ const read = vi+ .spyOn(prototype, "read")+ .mockImplementationOnce(async function (+ this: FileHandle,+ ...args: Parameters<FileHandle["read"]>+ ) {+ const closed = this.close.bind(this);+ this.close = async () => {+ await closed();+ controller.abort(reason);+ };+ return Reflect.apply(original, this, args);+ });+ onTestFinished(() => read.mockRestore());+ const result = await client.execute(+ "inspect_plist",+ { path },+ { signal: controller.signal },+ );+ expect(result.ok).toBe(false);+ if (result.ok) throw new Error("Expected late cancellation");+ expect(result.error).toMatchObject({+ operation: "inspect_plist",+ cause: reason,+ cleanupIncomplete: false,+ });+ expect(result.error.cleanupResources).not.toContain("unowned-resource");+ expect((await client.close()).ok).toBe(true);+});++it("joins an admitted prefix read when client close starts concurrently", async () => {+ const { client, path, prototype } = await fixture();+ let enter!: () => void;+ let resume!: () => void;+ const entered = new Promise<void>((resolve) => {+ enter = resolve;+ });+ const gate = new Promise<void>((resolve) => {+ resume = resolve;+ });+ const original = prototype.read;+ const read = vi+ .spyOn(prototype, "read")+ .mockImplementationOnce(async function (+ this: FileHandle,+ ...args: Parameters<FileHandle["read"]>+ ) {+ enter();+ await gate;+ return Reflect.apply(original, this, args);+ });+ onTestFinished(() => {+ resume();+ read.mockRestore();+ });+ const inspecting = client.execute("inspect_plist", { path });+ await entered;+ let finished = false;+ const closing = client.close().then((result) => {+ finished = true;+ return result;+ });+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(finished).toBe(false);+ resume();+ expect((await inspecting).ok).toBe(true);+ expect((await closing).ok).toBe(true);+});