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(uninstall): retain configuration publication ownership through recovery
morluto2fb5e204a357
diff --git a/docs/installation.md b/docs/installation.mdindex 0d4d0b6e9..b4cfc25b3 100644--- a/docs/installation.md+++ b/docs/installation.md@@ -67,8 +67,8 @@ setup readback or rollback, name the backup path that holds the bytes from justbefore that edit.If setup cannot verify a newly created configuration, it retains the file andreports manual recovery instead of deleting a pathname that may have changed.-For an existing configuration, rollback refuses a detected replacement or edit-and names its recovery backup. Quit clients before editing their configuration;+For an existing configuration, setup and uninstall recovery refuse a detected+replacement or edit and name the recovery backup. Quit clients before editing their configuration;these checks do not lock out another writer modifying the same file in place.Setup also retains valid environment overrides in REA's existing server entry,such as `REA_MCP_INPUT_SCHEMA_PROFILE`, `REA_MCP_OUTPUT_SCHEMA_PROFILE`, anddiff --git a/src/application/ClientConfigurationPublication.ts b/src/application/ClientConfigurationPublication.tsindex 454fb8253..147de0afb 100644--- a/src/application/ClientConfigurationPublication.ts+++ b/src/application/ClientConfigurationPublication.ts@@ -4,7 +4,10 @@ import writeFileAtomic from "write-file-atomic";import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";import { withOwnedFileHandle } from "../filesystem/OwnedRegularFile.js";-import { sameRegularFileState } from "../filesystem/RegularFile.js";+import {+ RegularFileChangedError,+ sameRegularFileState,+} from "../filesystem/RegularFile.js";/** The exact staged file retained through publication, verification and recovery. */export class ClientConfigurationPublication {@@ -17,21 +20,57 @@ export class ClientConfigurationPublication {static async write(path: string,contents: string,+ mode?: number,): Promise<ClientConfigurationPublication> {let owner: OwnedFileHandle | undefined;try {await writeFileAtomic(path, contents, {encoding: "utf8",- mode: 0o600,+ ...(mode === undefined ? {} : { mode }),tmpfileCreated: async (stagedPath) => {- owner = new OwnedFileHandle(- await open(+ const writableFlags =+ constants.O_RDWR |+ (constants.O_NONBLOCK ?? 0) |+ (constants.O_NOFOLLOW ?? 0);+ if (((await lstat(stagedPath)).mode & 0o200) !== 0) {+ owner = new OwnedFileHandle(await open(stagedPath, writableFlags));+ } else {+ // The atomic writer already owns a writable creation descriptor.+ // Retain ours before restoring the staged file's final read-only mode.+ const readable = new StagedConfigurationPermissions(+ await open(+ stagedPath,+ constants.O_RDONLY |+ (constants.O_NONBLOCK ?? 0) |+ (constants.O_NOFOLLOW ?? 0),+ ),+ );+ await withOwnedFileHandle(stagedPath,- constants.O_RDWR |- (constants.O_NONBLOCK ?? 0) |- (constants.O_NOFOLLOW ?? 0),- ),- );+ readable,+ {},+ async (handle) => {+ const staged = await handle.stat();+ if (!staged.isFile())+ throw new Error("Staged configuration is not a regular file");+ readable.restoreMode(staged.mode & 0o7777);+ await handle.chmod((staged.mode & 0o7777) | 0o600);+ owner = new OwnedFileHandle(+ await open(stagedPath, writableFlags),+ );+ const writable = await owner.handle.stat();+ if (+ staged.ino === 0 ||+ !writable.isFile() ||+ writable.dev !== staged.dev ||+ writable.ino !== staged.ino+ )+ throw new RegularFileChangedError(stagedPath);+ },+ );+ }+ if (owner === undefined)+ throw new Error("Staged configuration has no file owner");if (!(await owner.handle.stat()).isFile())throw new Error("Staged configuration is not a regular file");},@@ -120,3 +159,28 @@ export class ClientConfigurationPublication {return true;}}++/** Restore temporary staging permissions before releasing their exact descriptor. */+class StagedConfigurationPermissions extends OwnedFileHandle {+ #mode: number | undefined;+ #restoring: Promise<void> | undefined;++ restoreMode(mode: number): void {+ this.#mode = mode;+ }++ override async close(): Promise<void> {+ if (this.#mode !== undefined) {+ this.#restoring ??= this.handle+ .chmod(this.#mode)+ .then(() => {+ this.#mode = undefined;+ })+ .finally(() => {+ this.#restoring = undefined;+ });+ await this.#restoring;+ }+ await super.close();+ }+}diff --git a/src/application/RegularFileRead.ts b/src/application/RegularFileRead.tsindex da4585762..199264ec7 100644--- a/src/application/RegularFileRead.ts+++ b/src/application/RegularFileRead.ts@@ -69,6 +69,46 @@ export const retryRegularFileCleanup = async <Value>(};};+/** Retry every explicit nested operation owner; close rejection values grant no authority. */+export const retryRegularFileCleanupFailures = async (+ failure: RegularFileCleanupFailure,+ resources: ArtifactResourceScope,+): Promise<{+ readonly primary: unknown;+ readonly failures: readonly RegularFileCleanupFailure[];+ readonly cleanup?: AnalysisCleanupObservation;+}> => {+ const failures: RegularFileCleanupFailure[] = [];+ const observations: AnalysisCleanupObservation[] = [];+ let current = failure;+ let primary: unknown;+ for (;;) {+ failures.push(current);+ const retried = await retryRegularFileCleanup(current, resources);+ if (retried.cleanup !== undefined) observations.push(retried.cleanup);+ primary =+ retried.outcome.kind === "failed"+ ? retried.outcome.cause+ : current.cleanupCause;+ const nested =+ current.outcome.kind === "failed" ? current.outcome.cause : undefined;+ if (!(nested instanceof RegularFileCleanupFailure)) break;+ current = nested;+ }+ return {+ primary,+ failures,+ ...(observations.length === 0+ ? {}+ : {+ cleanup: {+ reason: observations.map(({ reason }) => reason).join("; "),+ resources: observations.flatMap(({ resources }) => resources),+ },+ }),+ };+};+const failureMessage = (cause: unknown): string =>cause instanceof Error ? cause.message : String(cause);diff --git a/src/application/SetupClientConfiguration.ts b/src/application/SetupClientConfiguration.tsindex 306695628..ec5608e52 100644--- a/src/application/SetupClientConfiguration.ts+++ b/src/application/SetupClientConfiguration.ts@@ -304,6 +304,7 @@ const persistClientConfiguration = async ({...(legacyPath === undefined ? [] : [legacyPath]),...(enableOmp ? [[OMP_DISABLED_SERVERS_KEY]] : []),]),+ 0o600,);} catch (cause: unknown) {if (cause instanceof RegularFileCleanupFailure) throw cause;diff --git a/src/application/SetupHost.ts b/src/application/SetupHost.tsindex 48670d8f3..8e4b702f4 100644--- a/src/application/SetupHost.ts+++ b/src/application/SetupHost.ts@@ -45,7 +45,7 @@ import { failedConfigurationMessage } from "./SetupClients.js";import { setupInstallFailure } from "./SetupInstallFailure.js";import {RegularFileCleanupFailure,- retryRegularFileCleanup,+ retryRegularFileCleanupFailures,} from "./RegularFileRead.js";import {explicitSetupRegistrationEnvironment,@@ -404,42 +404,19 @@ const runClientConfigurationOperation = async <Value>(return await operation();} catch (cause: unknown) {if (!(cause instanceof RegularFileCleanupFailure)) throw cause;- let retained = cause;- let primary: unknown;- const observations: {- readonly reason: string;- readonly resources: readonly string[];- }[] = [];- let rollbackMessage = "";- // Nested descriptor operations can each fail close. Only walk explicit- // owned-operation outcomes; an arbitrary cause is not an ownership grant.- for (;;) {- const cleanup = await retryRegularFileCleanup(retained, resources);- if (cleanup.cleanup !== undefined) observations.push(cleanup.cleanup);- if (retained instanceof ClientConfigurationCleanupRollbackFailure)- rollbackMessage = ` ${failedConfigurationMessage(retained.configurationFailure)}`;- primary =- cleanup.outcome.kind === "failed"- ? cleanup.outcome.cause- : retained.cleanupCause;- if (- cleanup.outcome.kind !== "failed" ||- !(primary instanceof RegularFileCleanupFailure)- )- break;- retained = primary;- }- const cleanup =- observations.length === 0- ? undefined- : {- reason: observations.map(({ reason }) => reason).join("; "),- resources: observations.flatMap(({ resources }) => resources),- };+ const cleanup = await retryRegularFileCleanupFailures(cause, resources);+ const rollback = cleanup.failures.find(+ (failure) =>+ failure instanceof ClientConfigurationCleanupRollbackFailure,+ );+ const rollbackMessage =+ rollback instanceof ClientConfigurationCleanupRollbackFailure+ ? ` ${failedConfigurationMessage(rollback.configurationFailure)}`+ : "";throw configurationCleanupError(- `Could not safely access client configuration at ${cause.path}: ${errorMessage(primary)}.${rollbackMessage}`,+ `Could not safely access client configuration at ${cause.path}: ${errorMessage(cleanup.primary)}.${rollbackMessage}`,cause,- cleanup,+ cleanup.cleanup,);}});diff --git a/src/application/Uninstall.ts b/src/application/Uninstall.tsindex 5e4dc6de1..e48392540 100644--- a/src/application/Uninstall.ts+++ b/src/application/Uninstall.ts@@ -12,7 +12,7 @@ import { constants as fsConstants } from "node:fs";import { homeDirectoryFromEnvironment } from "../config/homeDirectory.js";import { join } from "node:path";-import writeFileAtomic from "write-file-atomic";+import { ClientConfigurationPublication } from "./ClientConfigurationPublication.js";import { z } from "zod";import { PRODUCT_IDENTITY } from "../identity.js";@@ -34,6 +34,7 @@ import {InvalidUtf8FileError,RegularFileCleanupFailure,readRegularFileText,+ retryRegularFileCleanupFailures,} from "./RegularFileRead.js";import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";import {@@ -62,7 +63,12 @@ export interface UninstallFileSystem {readRegularText?(path: string): Promise<string>;/** Preserve the first backup; reject an existing destination with EEXIST. */copy(source: string, destination: string): Promise<void>;- writeText(path: string, contents: string): Promise<void>;+ publishConfiguration(+ path: string,+ contents: string,+ ): Promise<+ Pick<ClientConfigurationPublication, "verify" | "assertCurrent" | "restore">+ >;stat(path: string): Promise<ManagedPathStats>;realpath?(path: string): Promise<string>;remove(path: string, recursive?: boolean): Promise<void>;@@ -77,8 +83,8 @@ const systemFileSystem = (readRegularText: (path) => readSkillFile(path, resources),copy: (source, destination) =>copyFile(source, destination, fsConstants.COPYFILE_EXCL),- writeText: (path, contents) =>- writeFileAtomic(path, contents, { encoding: "utf8" }),+ publishConfiguration: (path, contents) =>+ ClientConfigurationPublication.write(path, contents),stat: (path) => lstat(path),realpath: (path) => realpath(path),remove: (path, recursive = true) => rm(path, { recursive }),@@ -222,6 +228,9 @@ export const systemUninstallHost = (const home =selectedHome ?? homeDirectoryFromEnvironment(environment, platform);const resources = new ArtifactResourceScope();+ // Whole-operation admission must not share a gate with its nested file reads:+ // a peer's pending cleanup otherwise waits for the operation requesting it.+ const configurationOperations = new ArtifactResourceScope();const fileSystem = selectedFileSystem ?? systemFileSystem(resources);// Set with the client list: the package view that redirects this// process's AppData writes, if any.@@ -253,23 +262,30 @@ export const systemUninstallHost = (]),);},- inspectClient: async (client) => {- const read = await readClientConfiguration(client, fileSystem);- if (read.kind === "item")- return read.item.status === "failed" ? read.item : undefined;- const removal = clientRegistrationRemoval(read.parsed, client);- if (!removal.removeNative && removal.legacyPath === undefined)- return undefined;- // A removal the running package would revert, or redirect into its- // private storage, would leave the registration in place.- const blocker = clientWriteBlocker(client);- return blocker === undefined- ? undefined- : item(client.name, "failed", blocker);- },+ inspectClient: (client) =>+ configurationOperations.run(async () => {+ const read = await readClientConfiguration(+ client,+ fileSystem,+ resources,+ );+ if (read.kind === "item")+ return read.item.status === "failed" ? read.item : undefined;+ const removal = clientRegistrationRemoval(read.parsed, client);+ if (!removal.removeNative && removal.legacyPath === undefined)+ return undefined;+ // A removal the running package would revert, or redirect into its+ // private storage, would leave the registration in place.+ const blocker = clientWriteBlocker(client);+ return blocker === undefined+ ? undefined+ : item(client.name, "failed", blocker);+ }),removeClient: (client) =>- removeClient(client, fileSystem, resources, () =>- clientWriteBlocker(client),+ configurationOperations.run(() =>+ removeClient(client, fileSystem, resources, () =>+ clientWriteBlocker(client),+ ),),inspectSkill: async () => {for (const destination of skillDestinations(@@ -301,6 +317,7 @@ export const systemUninstallHost = (purgeData: () => purgeManagedData(join(home, ".rea"), fileSystem),close: async () => {try {+ await configurationOperations.close();await resources.close();return undefined;} catch (cause: unknown) {@@ -352,6 +369,7 @@ type ClientConfigurationRead =const readClientConfiguration = async (client: SetupClient,fileSystem: UninstallFileSystem,+ resources: ArtifactResourceScope,): Promise<ClientConfigurationRead> => {if (client.configPathError !== undefined)return itemRead(item(client.name, "failed", client.configPathError));@@ -371,11 +389,17 @@ const readClientConfiguration = async (try {original = await fileSystem.readText(transactionPath);} catch (cause: unknown) {- const readFailure =- cause instanceof RegularFileCleanupFailure &&- cause.outcome.kind === "failed"- ? cause.outcome.cause- : cause;+ if (cause instanceof RegularFileCleanupFailure) {+ await retryRegularFileCleanupFailures(cause, resources);+ return itemRead(+ item(+ client.name,+ "failed",+ "Configuration could not be read or its resources could not be released. Check file permissions, then rerun uninstall.",+ ),+ );+ }+ const readFailure = cause;return itemRead(isMissing(readFailure)? item(client.name, "skipped", "Configuration does not exist.")@@ -479,7 +503,7 @@ const removeClient = async (resources: ArtifactResourceScope,writeBlocker?: () => string | undefined,): Promise<UninstallItem> => {- const read = await readClientConfiguration(client, fileSystem);+ const read = await readClientConfiguration(client, fileSystem, resources);if (read.kind === "item") return read.item;const { transactionPath, original, parsed } = read;const name = PRODUCT_IDENTITY.mcpServerKey;@@ -528,8 +552,17 @@ const removeClient = async (},);if (typeof backupPath !== "string") return backupPath;+ const manualRecovery = () =>+ item(+ client.name,+ "failed",+ `Configuration could not be updated or restored. Restore the backup at ${backupPath} manually, then rerun uninstall.`,+ );+ let publication: Awaited<+ ReturnType<UninstallFileSystem["publishConfiguration"]>+ >;try {- await fileSystem.writeText(+ publication = await fileSystem.publishConfiguration(transactionPath,serializeClientConfiguration(document,@@ -538,39 +571,53 @@ const removeClient = async (editedPaths,),);- const readback = parseClientConfiguration(- await fileSystem.readText(transactionPath),- client.format,- );- if (- (removeNative && Object.hasOwn(readback.servers, name)) ||- (readback.dialect === "dsh" &&- dshDocument(readback.document).carriesEntry) ||- (removeLegacy && Object.hasOwn(readback.legacyServers, name))- )- throw new Error("registration readback mismatch");- return item(- client.name,- "removed",- `Removed registration from ${client.configPath}.`,- );} catch (cause: unknown) {- // Update failure attempts a restore before reporting; cause is preserved below.- void cause;- try {- await fileSystem.writeText(transactionPath, original);- } catch (restoreCause: unknown) {- void restoreCause;- return item(- client.name,- "failed",- `Configuration could not be updated or restored. Restore the backup at ${backupPath} manually, then rerun uninstall.`,- );- }+ if (cause instanceof RegularFileCleanupFailure)+ await retryRegularFileCleanupFailures(cause, resources);+ return manualRecovery();+ }+ try {+ return await publication.verify(async () => {+ try {+ const readback = parseClientConfiguration(+ await fileSystem.readText(transactionPath),+ client.format,+ );+ await publication.assertCurrent();+ if (+ (removeNative && Object.hasOwn(readback.servers, name)) ||+ (readback.dialect === "dsh" &&+ dshDocument(readback.document).carriesEntry) ||+ (removeLegacy && Object.hasOwn(readback.legacyServers, name))+ )+ throw new Error("registration readback mismatch");+ return item(+ client.name,+ "removed",+ `Removed registration from ${client.configPath}.`,+ );+ } catch (cause: unknown) {+ if (cause instanceof RegularFileCleanupFailure)+ await retryRegularFileCleanupFailures(cause, resources);+ try {+ await publication.restore(original);+ } catch {+ return manualRecovery();+ }+ return item(+ client.name,+ "failed",+ `Configuration could not be updated. The original was restored and its backup at ${backupPath} was retained. Repair the configuration or restore that backup, then rerun uninstall.`,+ );+ }+ });+ } catch (cause: unknown) {+ if (cause instanceof RegularFileCleanupFailure)+ await retryRegularFileCleanupFailures(cause, resources);return item(client.name,"failed",- `Configuration could not be updated. The original was restored and its backup at ${backupPath} was retained. Repair the configuration or restore that backup, then rerun uninstall.`,+ `Configuration verification or resource cleanup failed. The backup at ${backupPath} was retained. Check the configuration and rerun uninstall.`,);}};diff --git a/tests/boundary/filesystem/clientConfigurationTransactions.test.ts b/tests/boundary/filesystem/clientConfigurationTransactions.test.tsindex 70cbbbd08..cb2b51a29 100644--- a/tests/boundary/filesystem/clientConfigurationTransactions.test.ts+++ b/tests/boundary/filesystem/clientConfigurationTransactions.test.ts@@ -23,6 +23,34 @@ import {type UninstallFileSystem,} from "../../../src/application/Uninstall.js";import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";+import { ClientConfigurationPublication } from "../../../src/application/ClientConfigurationPublication.js";++const failedVerificationFileSystem = (+ failure: "verification" | "recovery",+): UninstallFileSystem => {+ return {+ readText: (path) => readFile(path, "utf8"),+ copy: (source, destination) =>+ copyFile(source, destination, fsConstants.COPYFILE_EXCL),+ publishConfiguration: async (path, contents) => {+ const publication = await ClientConfigurationPublication.write(+ path,+ contents,+ );+ publication.assertCurrent = async () => {+ throw new Error("verification failed");+ };+ if (failure === "recovery")+ publication.restore = async () => {+ throw new Error("restore failed");+ };+ return publication;+ },+ stat: (path) => lstat(path),+ realpath: (path) => realpath(path),+ remove: (path) => rm(path, { recursive: true }),+ };+};describe("uninstall backups after edits made since setup", () => {const editedSinceSetup = async (prefix: string) => {@@ -53,24 +81,6 @@ describe("uninstall backups after edits made since setup", () => {};};- const fileSystem = (failWrites: "update" | "always"): UninstallFileSystem => {- let writes = 0;- return {- readText: (path) => readFile(path, "utf8"),- copy: (source, destination) =>- copyFile(source, destination, fsConstants.COPYFILE_EXCL),- writeText: async (path, contents) => {- writes += 1;- if (failWrites === "always" || writes === 1)- throw new Error("write failed");- await writeFile(path, contents);- },- stat: (path) => lstat(path),- realpath: (path) => realpath(path),- remove: (path) => rm(path, { recursive: true }),- };- };-it("preserves the pre-uninstall bytes when removal succeeds", async () => {const {root,@@ -91,18 +101,18 @@ describe("uninstall backups after edits made since setup", () => {it.each([[- "update",+ "verification",(path: string) =>`Configuration could not be updated. The original was restored and its backup at ${path} was retained. Repair the configuration or restore that backup, then rerun uninstall.`,],[- "always",+ "recovery",(path: string) =>`Configuration could not be updated or restored. Restore the backup at ${path} manually, then rerun uninstall.`,],] as const)(- "names the backup holding the pre-uninstall bytes when %s writes fail",- async (failWrites, message) => {+ "names the backup holding the pre-uninstall bytes when %s fails",+ async (failure, message) => {const {root,configPath,@@ -112,15 +122,22 @@ describe("uninstall backups after edits made since setup", () => {recoveryPath,} = await editedSinceSetup("rea-uninstall-current-backup-failure-");expect(- await systemUninstallHost(root, fileSystem(failWrites)).removeClient(- client,- ),+ await systemUninstallHost(+ root,+ failedVerificationFileSystem(failure),+ ).removeClient(client),).toEqual({name: "cursor",status: "failed",detail: message(recoveryPath),});- expect(await readFile(configPath, "utf8")).toBe(beforeUninstall);+ if (failure === "verification")+ expect(await readFile(configPath, "utf8")).toBe(beforeUninstall);+ else+ expect(JSON.parse(await readFile(configPath, "utf8"))).toEqual({+ keep: "edited after setup",+ mcpServers: {},+ });expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(beforeSetup,);@@ -155,10 +172,11 @@ describe("uninstall backups after edits made since setup", () => {await editedSinceSetup("rea-uninstall-current-backup-unverified-");let writes = 0;const result = await systemUninstallHost(root, {- ...fileSystem("update"),+ ...failedVerificationFileSystem("verification"),copy,- writeText: async () => {+ publishConfiguration: async () => {writes += 1;+ throw new Error("unexpected publication before verified backup");},}).removeClient(client);expect(result.status).toBe("failed");@@ -431,3 +449,37 @@ describe("Codex configuration text preservation", () => {).rejects.toMatchObject({ code: "ENOENT" });});});++it+ .skipIf(process.platform === "win32" || process.getuid?.() === 0)+ .each([0o400, 0o640])(+ "uninstall preserves configuration mode %s while retaining recovery authority",+ async (mode) => {+ const root = await createTestTempDirectory("rea-uninstall-file-mode-");+ const configPath = join(root, "config.json");+ await writeFile(+ configPath,+ '{"mcpServers":{"rea":{"command":"rea","args":["mcp"]}},"keep":true}\n',+ );+ await chmod(configPath, mode);+ const host = systemUninstallHost(root);+ try {+ expect(+ (+ await host.removeClient({+ name: "cursor",+ format: "json",+ configPath,+ })+ ).status,+ ).toBe("removed");+ expect((await lstat(configPath)).mode & 0o777).toBe(mode);+ expect(JSON.parse(await readFile(configPath, "utf8"))).toEqual({+ mcpServers: {},+ keep: true,+ });+ } finally {+ await host.close?.();+ }+ },+);diff --git a/tests/boundary/filesystem/clientLifecycle.test.ts b/tests/boundary/filesystem/clientLifecycle.test.tsindex e80bd000d..2659bde3a 100644--- a/tests/boundary/filesystem/clientLifecycle.test.ts+++ b/tests/boundary/filesystem/clientLifecycle.test.ts@@ -16,6 +16,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { parse as parseJsonc, type ParseError } from "jsonc-parser";import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";+import { ClientConfigurationPublication } from "../../../src/application/ClientConfigurationPublication.js";import { clearClientLocationEnvironment } from "../../fixtures/clientEnvironment.js";import { supportedClients } from "../../../src/application/SupportedClients.js";import { PRODUCT_IDENTITY } from "../../../src/identity.js";@@ -1876,6 +1877,11 @@ describe("client configuration filesystem failure reporting", () => {(config: string) =>`Configuration could not be updated. The original was restored and its backup at ${config}.rea.backup was retained. Repair the configuration or restore that backup, then rerun uninstall.`,],+ [+ "publication",+ (config: string) =>+ `Configuration could not be updated or restored. Restore the backup at ${config}.rea.backup manually, then rerun uninstall.`,+ ],["restore",(config: string) =>@@ -1886,7 +1892,6 @@ describe("client configuration filesystem failure reporting", () => {async (failure, expectedDetail) => {const { home, config } = await uninstallFixture();const detail = expectedDetail(config);- let writes = 0;const fileSystem: UninstallFileSystem = {...testFileSystem,readText: (path) =>@@ -1897,11 +1902,22 @@ describe("client configuration filesystem failure reporting", () => {failure === "backup"? Promise.reject(new Error("SECRET backup failure")): copyFile(source, destination, fsConstants.COPYFILE_EXCL),- writeText: async (path, contents) => {- writes += 1;- if ((failure === "update" && writes === 1) || failure === "restore")- throw new Error("SECRET write failure");- await writeFile(path, contents);+ publishConfiguration: async (path, contents) => {+ if (failure === "publication")+ throw new Error("SECRET publication failure");+ const publication = await ClientConfigurationPublication.write(+ path,+ contents,+ );+ if (failure === "update" || failure === "restore")+ publication.assertCurrent = async () => {+ throw new Error("SECRET verification failure");+ };+ if (failure === "restore")+ publication.restore = async () => {+ throw new Error("SECRET restore failure");+ };+ return publication;},};const result = await runUninstall(@@ -1921,13 +1937,17 @@ describe("client configuration filesystem failure reporting", () => {const current = await readFile(config, "utf8");const initial = '{"existing":true}\n';await writeFile(`${config}.rea.backup`, initial);- let writes = 0;const result = await systemUninstallHost(home, {...testFileSystem,- writeText: async (path, contents) => {- writes += 1;- await writeFile(path, contents);- if (writes === 1) throw new Error("update failed after writing");+ publishConfiguration: async (path, contents) => {+ const publication = await ClientConfigurationPublication.write(+ path,+ contents,+ );+ publication.assertCurrent = async () => {+ throw new Error("verification failed after writing");+ };+ return publication;},}).removeClient({ name: "cursor", format: "json", configPath: config });expect(result.status).toBe("failed");@@ -2034,7 +2054,8 @@ const testFileSystem: UninstallFileSystem = {readText: (path) => readFile(path, "utf8"),copy: (source, destination) =>copyFile(source, destination, fsConstants.COPYFILE_EXCL),- writeText: (path, contents) => writeFile(path, contents),+ publishConfiguration: (path, contents) =>+ ClientConfigurationPublication.write(path, contents),stat: (path) => lstat(path),realpath: (path) => realpath(path),remove: (path) => rm(path, { recursive: true }),diff --git a/tests/process-global/setupConfigurationRollback.test.ts b/tests/process-global/setupConfigurationRollback.test.tsindex eb6ed91cb..4471e9437 100644--- a/tests/process-global/setupConfigurationRollback.test.ts+++ b/tests/process-global/setupConfigurationRollback.test.ts@@ -10,6 +10,12 @@ const state = vi.hoisted(() => ({rejectPublicationClose: false,publicationCloseFailure: undefined as unknown,publicationHandles: [] as FileHandle[],+ beforePublicationOpen: undefined as+ | ((path: string) => Promise<void>)+ | undefined,+ stagingPrefix: undefined as string | undefined,+ readOnlyStageHandles: [] as FileHandle[],+ rejectStageModeRestore: false,afterPublication: undefined as ((path: string) => Promise<void>) | undefined,rejectRestore: false,removeCopiedRecovery: false,@@ -23,6 +29,10 @@ afterEach(() => {state.rejectPublicationClose = false;state.publicationCloseFailure = undefined;state.publicationHandles = [];+ state.beforePublicationOpen = undefined;+ state.stagingPrefix = undefined;+ state.readOnlyStageHandles = [];+ state.rejectStageModeRestore = false;state.afterPublication = undefined;state.rejectRestore = false;state.removeCopiedRecovery = false;@@ -35,7 +45,26 @@ vi.mock("node:fs/promises", async (importOriginal) => {return {...original,open: async (...arguments_: Parameters<typeof original.open>) => {+ const writable =+ typeof arguments_[1] === "number" && (arguments_[1] & 3) === 2;+ if (writable && typeof arguments_[0] === "string")+ await state.beforePublicationOpen?.(arguments_[0]);const handle = await original.open(...arguments_);+ if (+ typeof arguments_[0] === "string" &&+ state.stagingPrefix !== undefined &&+ arguments_[0].startsWith(state.stagingPrefix) &&+ typeof arguments_[1] === "number" &&+ (arguments_[1] & 3) === 0+ ) {+ state.readOnlyStageHandles.push(handle);+ const chmod = handle.chmod.bind(handle);+ handle.chmod = async (mode) => {+ if (state.rejectStageModeRestore && mode === 0o400)+ throw new Error("staging mode restoration denied");+ await chmod(mode);+ };+ }if (typeof arguments_[1] === "number" && (arguments_[1] & 3) === 2) {state.publicationHandles.push(handle);const close = handle.close.bind(handle);@@ -119,8 +148,10 @@ import { RegularFileCleanupFailure } from "../../src/application/RegularFileReadimport { OwnedFileHandle } from "../../src/filesystem/OwnedFileHandle.js";import type { DoctorHost } from "../../src/application/Doctor.js";import { systemSetupHost } from "../../src/application/SetupHost.js";+import { systemUninstallHost } from "../../src/application/Uninstall.js";import { ConfigurationError } from "../../src/domain/configurationErrors.js";import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";+import { createDeferred } from "../fixtures/binarySession.js";const ownReadHandle = async (path: string) => {const owner = new OwnedFileHandle(await open(path, "r"));@@ -547,3 +578,443 @@ it("does not adopt a descriptor named by an opaque publication close rejection",if (handle.fd >= 0) await handle.close();}});++it.each(["symlink", "regular", "valid-readback"] as const)(+ "uninstall retains a %s replacement instead of restoring through its name",+ async (kind) => {+ const root = await createTestTempDirectory(+ "rea-uninstall-replaced-rollback-",+ );+ const path = join(root, "client.json");+ const replacement = join(root, "replacement.json");+ const fs =+ await vi.importActual<typeof import("node:fs/promises")>(+ "node:fs/promises",+ );+ const original =+ '{"mcpServers":{"rea":{"command":"rea","args":["mcp"]}},"keep":"original"}\n';+ const foreign = '{"keep":"replacement"}\n';+ await fs.writeFile(path, original);+ await fs.writeFile(replacement, foreign);+ state.failReadback = kind !== "valid-readback";+ state.afterPublication = async (publishedPath) => {+ state.afterPublication = undefined;+ if (kind === "symlink") {+ await fs.unlink(publishedPath);+ await fs.symlink(replacement, publishedPath);+ } else await fs.rename(replacement, publishedPath);+ };+ const host = systemUninstallHost(root);+ try {+ const result = await host.removeClient({+ name: "cursor",+ configPath: path,+ format: "json",+ });+ expect(await fs.readFile(path, "utf8")).toBe(foreign);+ if (kind === "symlink") {+ expect((await fs.lstat(path)).isSymbolicLink()).toBe(true);+ expect(await fs.readFile(replacement, "utf8")).toBe(foreign);+ }+ expect(result.status).toBe("failed");+ expect(result.detail).not.toContain("The original was restored");+ expect(await fs.readFile(`${path}.rea.backup`, "utf8")).toBe(original);+ } finally {+ await host.close?.();+ }+ },+);++it("uninstall retains both readback and publication owners until cleanup retry", async () => {+ const root = await createTestTempDirectory("rea-uninstall-two-close-owners-");+ const path = join(root, "client.json");+ const fs =+ await vi.importActual<typeof import("node:fs/promises")>(+ "node:fs/promises",+ );+ await fs.writeFile(+ path,+ '{"mcpServers":{"rea":{"command":"rea","args":["mcp"]}}}\n',+ );+ const readOwner = await ownReadHandle(path);+ const closeRead = readOwner.handle.close.bind(readOwner.handle);+ let rejectReadClose = true;+ readOwner.handle.close = async () => {+ if (rejectReadClose) throw new Error("injected readback close failure");+ await closeRead();+ };+ state.readbackCleanupFailure = new RegularFileCleanupFailure(+ path,+ readOwner,+ { kind: "completed", value: "" },+ new Error("readback close failed"),+ );+ state.rejectPublicationClose = true;+ const host = systemUninstallHost(root);+ try {+ const result = await host.removeClient({+ name: "cursor",+ configPath: path,+ format: "json",+ });+ expect(result.status).toBe("failed");+ expect(state.publicationHandles).toHaveLength(1);+ expect(readOwner.handle.fd).toBeGreaterThanOrEqual(0);+ expect(state.publicationHandles[0]!.fd).toBeGreaterThanOrEqual(0);+ rejectReadClose = false;+ state.rejectPublicationClose = false;+ expect(await host.close?.()).toBeUndefined();+ expect(readOwner.handle.fd).toBe(-1);+ expect(state.publicationHandles[0]!.fd).toBe(-1);+ } finally {+ rejectReadClose = false;+ state.rejectPublicationClose = false;+ await host.close?.();+ await readOwner.close();+ for (const handle of state.publicationHandles)+ if (handle.fd >= 0) await handle.close();+ }+});++it("uninstall retains the exact owner of a failed initial config read", async () => {+ const root = await createTestTempDirectory(+ "rea-uninstall-initial-read-owner-",+ );+ const path = join(root, "client.json");+ const fs =+ await vi.importActual<typeof import("node:fs/promises")>(+ "node:fs/promises",+ );+ const original = '{"mcpServers":{"rea":{"command":"rea","args":["mcp"]}}}\n';+ await fs.writeFile(path, original);+ const owner = await ownReadHandle(path);+ const close = owner.handle.close.bind(owner.handle);+ let rejectClose = true;+ owner.handle.close = async () => {+ if (rejectClose) throw new Error("initial close denied");+ await close();+ };+ state.initialCleanupFailure = new RegularFileCleanupFailure(+ path,+ owner,+ { kind: "completed", value: original },+ new Error("initial close denied"),+ );+ const host = systemUninstallHost(root);+ try {+ expect(+ await host.inspectClient({+ name: "cursor",+ configPath: path,+ format: "json",+ }),+ ).toMatchObject({ status: "failed" });+ expect(state.publicationHandles).toHaveLength(0);+ expect(owner.handle.fd).toBeGreaterThanOrEqual(0);+ rejectClose = false;+ expect(await host.close?.()).toBeUndefined();+ expect(owner.handle.fd).toBe(-1);+ expect(await fs.readFile(path, "utf8")).toBe(original);+ await expect(fs.readFile(`${path}.rea.backup`)).rejects.toMatchObject({+ code: "ENOENT",+ });+ } finally {+ rejectClose = false;+ await host.close?.();+ await owner.close();+ }+});++it("uninstall close joins a publication already admitted by its host", async () => {+ const root = await createTestTempDirectory(+ "rea-uninstall-close-publication-",+ );+ const path = join(root, "client.json");+ const fs =+ await vi.importActual<typeof import("node:fs/promises")>(+ "node:fs/promises",+ );+ await fs.writeFile(+ path,+ '{"mcpServers":{"rea":{"command":"rea","args":["mcp"]}}}\n',+ );+ const arrived = createDeferred<void>();+ const release = createDeferred<void>();+ state.afterPublication = async () => {+ arrived.resolve();+ await release.promise;+ };+ const host = systemUninstallHost(root);+ const removal = host.removeClient({+ name: "cursor",+ configPath: path,+ format: "json",+ });+ await arrived.promise;+ let closed = false;+ const closing = host.close?.().then((result) => {+ closed = true;+ return result;+ });+ try {+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(closed).toBe(false);+ expect(state.publicationHandles[0]!.fd).toBeGreaterThanOrEqual(0);+ } finally {+ release.resolve();+ }+ expect((await removal).status).toBe("failed");+ expect(await closing).toBeUndefined();+ expect(state.publicationHandles[0]!.fd).toBe(-1);+ await expect(+ host.removeClient({ name: "cursor", configPath: path, format: "json" }),+ ).rejects.toThrow("closed");+});++it("cleanup retry never adopts an opaque cancellation reason as another owner", async () => {+ const root = await createTestTempDirectory(+ "rea-cleanup-cancellation-authority-",+ );+ const path = join(root, "owned.json");+ const other = join(root, "other.json");+ const fs =+ await vi.importActual<typeof import("node:fs/promises")>(+ "node:fs/promises",+ );+ await fs.writeFile(path, "owned");+ await fs.writeFile(other, "other");+ const owned = await ownReadHandle(path);+ const foreign = await ownReadHandle(other);+ const opaque = new RegularFileCleanupFailure(+ other,+ foreign,+ { kind: "completed", value: "other" },+ new Error("opaque reason"),+ );+ const { RegularFileOperationCancelled } =+ await import("../../src/filesystem/RegularFile.js");+ const { ArtifactResourceScope } =+ await import("../../src/artifacts/ArtifactResourceScope.js");+ const { retryRegularFileCleanupFailures } =+ await import("../../src/application/RegularFileRead.js");+ const resources = new ArtifactResourceScope();+ const outcome = await retryRegularFileCleanupFailures(+ new RegularFileCleanupFailure(+ path,+ owned,+ { kind: "failed", cause: new RegularFileOperationCancelled(opaque) },+ new Error("owned close failed"),+ ),+ resources,+ );+ expect(outcome.primary).toBe(opaque);+ expect(outcome.failures).toHaveLength(1);+ expect(owned.handle.fd).toBe(-1);+ await resources.close();+ expect(foreign.handle.fd).toBeGreaterThanOrEqual(0);+});++it("uninstall progresses when a peer leaves a denied-close descriptor pending", async () => {+ const root = await createTestTempDirectory("rea-uninstall-peer-cleanup-");+ const path = join(root, "client.json");+ const other = join(root, "other.json");+ const fs =+ await vi.importActual<typeof import("node:fs/promises")>(+ "node:fs/promises",+ );+ await fs.writeFile(+ path,+ '{"mcpServers":{"rea":{"command":"rea","args":["mcp"]}}}\n',+ );+ await fs.writeFile(other, "{}");+ const owner = await ownReadHandle(other);+ const close = owner.handle.close.bind(owner.handle);+ let rejectClose = true;+ owner.handle.close = async () => {+ if (rejectClose) throw new Error("peer close denied");+ await close();+ };+ const arrived = createDeferred<void>();+ const release = createDeferred<void>();+ state.failReadback = false;+ state.afterPublication = async () => {+ arrived.resolve();+ await release.promise;+ };+ const host = systemUninstallHost(root);+ const removal = host.removeClient({+ name: "cursor",+ configPath: path,+ format: "json",+ });+ let timeout: ReturnType<typeof setTimeout> | undefined;+ try {+ await arrived.promise;+ state.initialCleanupFailure = new RegularFileCleanupFailure(+ other,+ owner,+ { kind: "completed", value: "{}" },+ new Error("peer close denied"),+ );+ expect(+ await host.inspectClient({+ name: "other",+ configPath: other,+ format: "json",+ }),+ ).toMatchObject({ status: "failed" });+ state.initialCleanupFailure = undefined;+ release.resolve();+ const result = await Promise.race([+ removal,+ new Promise<never>((_resolve, reject) => {+ timeout = setTimeout(+ () =>+ reject(+ new Error("configuration admission deadlocked with file cleanup"),+ ),+ 5000,+ );+ }),+ ]);+ expect(result.status).toBe("failed");+ expect(owner.handle.fd).toBeGreaterThanOrEqual(0);+ rejectClose = false;+ expect(await host.close?.()).toBeUndefined();+ expect(owner.handle.fd).toBe(-1);+ expect(state.publicationHandles[0]!.fd).toBe(-1);+ } finally {+ if (timeout !== undefined) clearTimeout(timeout);+ state.initialCleanupFailure = undefined;+ rejectClose = false;+ release.resolve();+ await owner.close();+ for (const handle of state.publicationHandles)+ if (handle.fd >= 0) await handle.close();+ }+});++it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(+ "read-only staging never changes permissions on a substituted writable descriptor",+ async () => {+ const root = await createTestTempDirectory(+ "rea-uninstall-staging-handoff-",+ );+ const path = join(root, "client.json");+ const foreign = join(root, "foreign.json");+ const fs =+ await vi.importActual<typeof import("node:fs/promises")>(+ "node:fs/promises",+ );+ const original =+ '{"mcpServers":{"rea":{"command":"rea","args":["mcp"]}}}\n';+ await fs.writeFile(path, original);+ await fs.chmod(path, 0o400);+ await fs.writeFile(foreign, "foreign");+ await fs.chmod(foreign, 0o640);+ state.beforePublicationOpen = async (stagedPath) => {+ state.beforePublicationOpen = undefined;+ await fs.unlink(stagedPath);+ await fs.link(foreign, stagedPath);+ };+ const host = systemUninstallHost(root);+ try {+ expect(+ (+ await host.removeClient({+ name: "cursor",+ configPath: path,+ format: "json",+ })+ ).status,+ ).toBe("failed");+ expect(await fs.readFile(foreign, "utf8")).toBe("foreign");+ expect((await fs.lstat(foreign)).mode & 0o777).toBe(0o640);+ expect(await fs.readFile(path, "utf8")).toBe(original);+ expect((await fs.lstat(path)).mode & 0o777).toBe(0o400);+ expect(state.publicationHandles).toHaveLength(1);+ expect(state.publicationHandles[0]!.fd).toBe(-1);+ } finally {+ await host.close?.();+ }+ },+);++it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(+ "uninstall retains permission restoration ownership until the staged descriptor releases",+ async () => {+ const root = await createTestTempDirectory(+ "rea-uninstall-staging-mode-retry-",+ );+ const path = join(root, "client.json");+ const fs =+ await vi.importActual<typeof import("node:fs/promises")>(+ "node:fs/promises",+ );+ const original =+ '{"mcpServers":{"rea":{"command":"rea","args":["mcp"]}}}\n';+ await fs.writeFile(path, original);+ await fs.chmod(path, 0o400);+ state.stagingPrefix = `${path}.`;+ state.rejectStageModeRestore = true;+ const host = systemUninstallHost(root);+ try {+ expect(+ (+ await host.removeClient({+ name: "cursor",+ configPath: path,+ format: "json",+ })+ ).status,+ ).toBe("failed");+ const pending = state.readOnlyStageHandles.filter(({ fd }) => fd >= 0);+ expect(pending).toHaveLength(1);+ expect(await host.close?.()).toContain("cleanup failed");+ state.rejectStageModeRestore = false;+ expect(await host.close?.()).toBeUndefined();+ expect(pending[0]!.fd).toBe(-1);+ expect(await fs.readFile(path, "utf8")).toBe(original);+ expect((await fs.lstat(path)).mode & 0o777).toBe(0o400);+ } finally {+ state.rejectStageModeRestore = false;+ await host.close?.();+ for (const handle of state.readOnlyStageHandles)+ if (handle.fd >= 0) await handle.close();+ }+ },+);++it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(+ "uninstall restores a read-only configuration through its retained writable descriptor",+ async () => {+ const root = await createTestTempDirectory(+ "rea-uninstall-readonly-restore-",+ );+ const path = join(root, "client.json");+ const fs =+ await vi.importActual<typeof import("node:fs/promises")>(+ "node:fs/promises",+ );+ const original =+ '{"mcpServers":{"rea":{"command":"rea","args":["mcp"]}},"keep":true}\n';+ await fs.writeFile(path, original);+ await fs.chmod(path, 0o400);+ const host = systemUninstallHost(root);+ try {+ const result = await host.removeClient({+ name: "cursor",+ configPath: path,+ format: "json",+ });+ expect(result.status).toBe("failed");+ expect(result.detail).toContain("The original was restored");+ expect(await fs.readFile(path, "utf8")).toBe(original);+ expect((await fs.lstat(path)).mode & 0o777).toBe(0o400);+ expect(await fs.readFile(`${path}.rea.backup`, "utf8")).toBe(original);+ expect(state.publicationHandles[0]!.fd).toBe(-1);+ } finally {+ await host.close?.();+ }+ },+);